_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/src/ngtsc/incremental/README.md_4835_13810
## Reuse of emit results In plain TypeScript programs, the compiled JavaScript code for any given input file (e.g. `foo.ts`) depends only on the code within that input file. That is, only the contents of `foo.ts` can affect the generated contents written to `foo.js`. The TypeScript compiler can therefore perform a very simple optimization, and avoid generating and emitting code for any input files which do not change. This is important for good incremental build performance, as emitting a file is a very expensive operation. (in practice, the TypeScript feature of `const enum` declarations breaks this overly simple model) In Angular applications, however, this optimization is not nearly so simple. The emit of a `.js` file in Angular is affected in four main ways: * Just as in plain TS, it depends on the contents of the input `.ts` file. * It can be affected by expressions that were statically evaluated during analysis of any decorated classes in the input, and these expressions can depend on other files. For example, the directive with its selector specified via the imported `DIR_SELECTOR` constant above has compilation output which depends on the value of `DIR_SELECTOR`. Therefore, the `dir.js` file needs to be emitted whenever the value of the selector constant in `selectors.ts` changes, even if `dir.ts` itself is unchanged. The compiler therefore will re-emit `dir.js` if the `dir.ts` file is determined to have _logically_ changed, using the same dependency graph that powers analysis reuse. * Components can have external templates and CSS stylesheets which influence their compilation. These are incorporated into a component's analysis dependencies. * Components (and NgModules) are influenced by the NgModule graph, which controls which directives and pipes are "in scope" for each component's template. This last relationship is the most difficult, as there is no import relationship between a component and the directives and pipes it uses in its template. That means that a component file can be logically unchanged, but still require re-emit if one of its dependencies has been updated in a way that influences the compilation of the component. ### Example For example, the output of a compiled component includes an array called `directiveDefs`, listing all of the directives and components actually used within the component's template. This array is built by combining the template (from analysis) with the "scope" of the component - the set of directives and pipes which are available for use in its template. This scope is synthesized from the analysis of not just the component's NgModule, but other NgModules which might be imported, and the components/directives that those NgModules export, and their analysis data as well. These dependencies of a component on the directives/pipes it consumes, and the NgModule structures that made them visible, are not captured in the file-level dependency graph. This is due to the peculiar nature of NgModule and component relationships: NgModules import components, so there is never a reference from a component to its NgModule, or any of its directive or pipe dependencies. In code, this looks like: ```typescript // dir.ts @Directive({selector: '[dir]'}) export class Dir {} // cmp.ts @Component({ selector: 'cmp', template: '<div dir></div>', // Matches the `[dir]` selector }) export class Cmp {} // mod.ts import {Dir} from './dir'; import {Cmp} from './cmp'; @NgModule({declarations: [Dir, Cmp]}) export class Mod {} ``` Here, `Cmp` never directly imports or refers to `Dir`, but it _does_ consume the directive in its template. During emit, `Cmp` would receive a `directiveDefs` array: ```typescript // cmp.js import * as i1 from './dir'; export class Cmp { static cmp = defineComponent({ ... directiveDefs: [i1.Dir], }); } ``` If `Dir`'s selector were to change to `[other]` in an incremental step, it might no longer match `Cmp`'s template, in which case `cmp.js` would need to be re-emitted. ### SemanticSymbols For each decorated class being processed, the compiler creates a `SemanticSymbol` representing the data regarding that class that's involved in these "indirect" relationships. During the compiler's `resolve` phase, these `SemanticSymbol`s are connected together to form a "semantic dependency graph". Two classes of data are recorded: * Information about the public shape API of the class. For example, directives have a public API which includes their selector, any inputs or outputs, and their `exportAs` name if any. * Information about the emit shape of the class, including any dependencies on other `SemanticSymbol`s. This information allows the compiler to determine which classes have been semantically affected by other changes in the program (and therefore need to be re-emitted) according to a simple algorithm: 1. Determine the set of `SemanticSymbol`s which have had their public API changed. 2. For each `SemanticSymbol`, determine if its emit shape was affected by any of the public API changes (that is, if it depends on a symbol with public API changes). ### Determination of public API changes The first step of this algorithm is to determine, for each `SemanticSymbol`, if its public API has been affected. Doing this requires knowing which `SemanticSymbol` in the previous program corresponds to the current version of the symbol. There are two ways that symbols can be "matched": * The old and new symbols share the same `ts.ClassDeclaration`. This is true whenever the `ts.SourceFile` declaring the class has not changed between the old and new programs. The public API of the symbol may still have changed (such as when a directive's selector is determined by a constant imported from another file, like in one of the examples above). But if the declaration file itself has not changed, then the previous symbol can be directly found this way. * By its unique path and name. If the file _has_ changed, then symbols can be located by their declaration path plus their name, if they have a name that's guaranteed to be unique. Currently, this means that the classes are declared at the top level of the source file, so their names are in the module's scope. If this is the case, then a symbol can be matched to its ancestor even if the declaration itself has changed in the meantime. Note that there is no guarantee the symbol will be of the same type - an incremental step may change a directive into a component, or even into a pipe or injectable. Once a previous symbol is located, its public API can be compared against the current version of the symbol. Symbols without a valid ancestor are assumed to have changed in their public API. The compiler processes all `SemanticSymbol`s and determines the `Set` of them which have experienced public API changes. In the example above, this `Set` would include the `DirectiveSymbol` for `Dir`, since its selector would have changed. ### Determination of emit requirements For each potential output file, the compiler then looks at all declared `SemanticSymbol`s and uses their ancestor symbol (if present) as well as the `Set` of public API changes to make a determination if that file needs be emitted. In the case of a `ComponentSymbol`, for example, the symbol tracks the dependencies of the component which will go into the `directiveDefs` array. If that array is different, the component needs to be re-emitted. Even if the same directives are referenced, if one of those directives has changed in its public API, the emitted output (especially when generating prelink library code) may be affected, and the component needs to be re-emitted. ### `SemanticReference`s `ComponentSymbol`s track their dependencies via an intermediate type, a `SemanticReference`. Such references track not only the `SemanticSymbol` of the dependency, but also the name by which it was imported previously. Even if a dependency's identity and public API remain the same, changes in how it was exported can affect the import which needs to be emitted within the component consuming it, and thus would require a re-emit. ## Reuse of template type-checking results Since type-checking block (TCB) generation for template type-checking is a form of emit, `SemanticSymbol`s also track the type-checking shape of decorated classes. This includes any data which is not public API, but upon which the TCB generation for components might depend. Such data includes: * Type-checking API shape from any base classes, since TCB generation uses information from the full inheritance chain of a directive/pipe. * The generic signature shape of the class. * Private field names for `@Input`s and `@Output`s. Using a similar algorithm to the `emit` optimization, the compiler can determine which files need their type-checking code regenerated, and which can continue to use TCB code from the previous program, even if some dependencies have unrelated changes.
{ "end_byte": 13810, "start_byte": 4835, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/README.md" }
angular/packages/compiler-cli/src/ngtsc/incremental/README.md_13810_15519
## Unsuccessful compilation attempts Often, incremental compilations will fail. The user's input program may contain incomplete changes, typos, semantic errors, or other problems which prevent the compiler from fully analyzing or emitting it. Such errors create problems for incremental build correctness, as the compiler relies on information extracted from the previous program to correctly optimize the next compilation. If the previous compilation failed, such information may be unreliable. In theory, the compiler could simply not perform incremental compilation on top of a broken build, and assume that it must redo all analysis and re-emit all files, but this would result in devastatingly poor performance for common developer workflows that rely on automatically running builds and/or tests on every change. The compiler must deal with such scenarios more gracefully. ngtsc solves this problem by always performing its incremental steps from a "last known good" compilation. Thus, if compilation A succeeds, and a subsequent compilation B fails, compilation C will begin using the state of compilation A as a starting point. This requires tracking of two important pieces of state: * Reusable information, such as analysis results, from the last known good compilation. * The accumulated set of files which have physically changed since the last known good compilation. Using this information, ngtsc is able to "forget" about the intermediate failed attempts and begin each new compilation as if it were a single step from the last successful build. It can then ensure complete correctness of its reuse optimization, since it has reliable data extracted from the " previous" successful build.
{ "end_byte": 15519, "start_byte": 13810, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/README.md" }
angular/packages/compiler-cli/src/ngtsc/incremental/BUILD.bazel_0_1160
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "incremental", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ ":api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental/semantic_graph", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/program_driver", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], ) ts_library( name = "api", srcs = ["api.ts"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/reflection", "@npm//typescript", ], )
{ "end_byte": 1160, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/incremental/index.ts_0_499
/** * @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 {IncrementalCompilation} from './src/incremental'; export {NOOP_INCREMENTAL_BUILD} from './src/noop'; export { AnalyzedIncrementalState, DeltaIncrementalState, FreshIncrementalState, IncrementalState, IncrementalStateKind, } from './src/state'; export * from './src/strategy';
{ "end_byte": 499, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/index.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/test/BUILD.bazel_0_802
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/transform", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 802, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/incremental/test/incremental_spec.ts_0_1681
/** * @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, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {NOOP_PERF_RECORDER} from '../../perf'; import {makeProgram} from '../../testing'; import {TraitCompiler} from '../../transform'; import {IncrementalCompilation} from '../src/incremental'; runInEachFileSystem(() => { describe('incremental reconciliation', () => { it('should treat source files with changed versions as changed', () => { const FOO_PATH = absoluteFrom('/foo.ts'); const {program} = makeProgram([{name: FOO_PATH, contents: `export const FOO = true;`}]); const fooSf = getSourceFileOrError(program, FOO_PATH); const traitCompiler = {getAnalyzedRecords: () => new Map()} as TraitCompiler; const versionMapFirst = new Map([[FOO_PATH, 'version.1']]); const firstCompilation = IncrementalCompilation.fresh(program, versionMapFirst); firstCompilation.recordSuccessfulAnalysis(traitCompiler); firstCompilation.recordSuccessfulEmit(fooSf); const versionMapSecond = new Map([[FOO_PATH, 'version.2']]); const secondCompilation = IncrementalCompilation.incremental( program, versionMapSecond, program, firstCompilation.state, new Set(), NOOP_PERF_RECORDER, ); secondCompilation.recordSuccessfulAnalysis(traitCompiler); expect(secondCompilation.safeToSkipEmit(fooSf)).toBeFalse(); }); }); });
{ "end_byte": 1681, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/test/incremental_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/BUILD.bazel_0_398
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "semantic_graph", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/reflection", "@npm//typescript", ], )
{ "end_byte": 398, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/index.ts_0_547
/** * @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 {SemanticReference, SemanticSymbol} from './src/api'; export {SemanticDepGraph, SemanticDepGraphUpdater} from './src/graph'; export { areTypeParametersEqual, extractSemanticTypeParameters, SemanticTypeParameter, } from './src/type_parameters'; export {isArrayEqual, isReferenceEqual, isSetEqual, isSymbolEqual} from './src/util';
{ "end_byte": 547, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/index.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/api.ts_0_5443
/** * @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 {absoluteFromSourceFile, AbsoluteFsPath} from '../../../file_system'; import {ClassDeclaration} from '../../../reflection'; /** * Represents a symbol that is recognizable across incremental rebuilds, which enables the captured * metadata to be compared to the prior compilation. This allows for semantic understanding of * the changes that have been made in a rebuild, which potentially enables more reuse of work * from the prior compilation. */ export abstract class SemanticSymbol { /** * The path of the file that declares this symbol. */ public readonly path: AbsoluteFsPath; /** * The identifier of this symbol, or null if no identifier could be determined. It should * uniquely identify the symbol relative to `file`. This is typically just the name of a * top-level class declaration, as that uniquely identifies the class within the file. * * If the identifier is null, then this symbol cannot be recognized across rebuilds. In that * case, the symbol is always assumed to have semantically changed to guarantee a proper * rebuild. */ public readonly identifier: string | null; constructor( /** * The declaration for this symbol. */ public readonly decl: ClassDeclaration, ) { this.path = absoluteFromSourceFile(decl.getSourceFile()); this.identifier = getSymbolIdentifier(decl); } /** * Allows the symbol to be compared to the equivalent symbol in the previous compilation. The * return value indicates whether the symbol has been changed in a way such that its public API * is affected. * * This method determines whether a change to _this_ symbol require the symbols that * use to this symbol to be re-emitted. * * Note: `previousSymbol` is obtained from the most recently succeeded compilation. Symbols of * failed compilations are never provided. * * @param previousSymbol The symbol from a prior compilation. */ abstract isPublicApiAffected(previousSymbol: SemanticSymbol): boolean; /** * Allows the symbol to determine whether its emit is affected. The equivalent symbol from a prior * build is given, in addition to the set of symbols of which the public API has changed. * * This method determines whether a change to _other_ symbols, i.e. those present in * `publicApiAffected`, should cause _this_ symbol to be re-emitted. * * @param previousSymbol The equivalent symbol from a prior compilation. Note that it may be a * different type of symbol, if e.g. a Component was changed into a Directive with the same name. * @param publicApiAffected The set of symbols of which the public API has changed. */ isEmitAffected?(previousSymbol: SemanticSymbol, publicApiAffected: Set<SemanticSymbol>): boolean; /** * Similar to `isPublicApiAffected`, but here equivalent symbol from a prior compilation needs * to be compared to see if the type-check block of components that use this symbol is affected. * * This method determines whether a change to _this_ symbol require the symbols that * use to this symbol to have their type-check block regenerated. * * Note: `previousSymbol` is obtained from the most recently succeeded compilation. Symbols of * failed compilations are never provided. * * @param previousSymbol The symbol from a prior compilation. */ abstract isTypeCheckApiAffected(previousSymbol: SemanticSymbol): boolean; /** * Similar to `isEmitAffected`, but focused on the type-check block of this symbol. This method * determines whether a change to _other_ symbols, i.e. those present in `typeCheckApiAffected`, * should cause _this_ symbol's type-check block to be regenerated. * * @param previousSymbol The equivalent symbol from a prior compilation. Note that it may be a * different type of symbol, if e.g. a Component was changed into a Directive with the same name. * @param typeCheckApiAffected The set of symbols of which the type-check API has changed. */ isTypeCheckBlockAffected?( previousSymbol: SemanticSymbol, typeCheckApiAffected: Set<SemanticSymbol>, ): boolean; } /** * Represents a reference to a semantic symbol that has been emitted into a source file. The * reference may refer to the symbol using a different name than the semantic symbol's declared * name, e.g. in case a re-export under a different name was chosen by a reference emitter. * Consequently, to know that an emitted reference is still valid not only requires that the * semantic symbol is still valid, but also that the path by which the symbol is imported has not * changed. */ export interface SemanticReference { symbol: SemanticSymbol; /** * The path by which the symbol has been referenced. */ importPath: string | null; } function getSymbolIdentifier(decl: ClassDeclaration): string | null { if (!ts.isSourceFile(decl.parent)) { return null; } // If this is a top-level class declaration, the class name is used as unique identifier. // Other scenarios are currently not supported and causes the symbol not to be identified // across rebuilds, unless the declaration node has not changed. return decl.name.text; }
{ "end_byte": 5443, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/api.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/type_parameters.ts_0_2904
/** * @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 {ClassDeclaration} from '../../../reflection'; import {isArrayEqual} from './util'; /** * Describes a generic type parameter of a semantic symbol. A class declaration with type parameters * needs special consideration in certain contexts. For example, template type-check blocks may * contain type constructors of used directives which include the type parameters of the directive. * As a consequence, if a change is made that affects the type parameters of said directive, any * template type-check blocks that use the directive need to be regenerated. * * This type represents a single generic type parameter. It currently only tracks whether the * type parameter has a constraint, i.e. has an `extends` clause. When a constraint is present, we * currently assume that the type parameter is affected in each incremental rebuild; proving that * a type parameter with constraint is not affected is non-trivial as it requires full semantic * understanding of the type constraint. */ export interface SemanticTypeParameter { /** * Whether a type constraint, i.e. an `extends` clause is present on the type parameter. */ hasGenericTypeBound: boolean; } /** * Converts the type parameters of the given class into their semantic representation. If the class * does not have any type parameters, then `null` is returned. */ export function extractSemanticTypeParameters( node: ClassDeclaration, ): SemanticTypeParameter[] | null { if (!ts.isClassDeclaration(node) || node.typeParameters === undefined) { return null; } return node.typeParameters.map((typeParam) => ({ hasGenericTypeBound: typeParam.constraint !== undefined, })); } /** * Compares the list of type parameters to determine if they can be considered equal. */ export function areTypeParametersEqual( current: SemanticTypeParameter[] | null, previous: SemanticTypeParameter[] | null, ): boolean { // First compare all type parameters one-to-one; any differences mean that the list of type // parameters has changed. if (!isArrayEqual(current, previous, isTypeParameterEqual)) { return false; } // If there is a current list of type parameters and if any of them has a generic type constraint, // then the meaning of that type parameter may have changed without us being aware; as such we // have to assume that the type parameters have in fact changed. if (current !== null && current.some((typeParam) => typeParam.hasGenericTypeBound)) { return false; } return true; } function isTypeParameterEqual(a: SemanticTypeParameter, b: SemanticTypeParameter): boolean { return a.hasGenericTypeBound === b.hasGenericTypeBound; }
{ "end_byte": 2904, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/type_parameters.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/graph.ts_0_4751
/** * @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 {Expression, ExternalExpr} from '@angular/compiler'; import {AbsoluteFsPath} from '../../../file_system'; import {ClassDeclaration} from '../../../reflection'; import {SemanticReference, SemanticSymbol} from './api'; export interface SemanticDependencyResult { /** * The files that need to be re-emitted. */ needsEmit: Set<AbsoluteFsPath>; /** * The files for which the type-check block should be regenerated. */ needsTypeCheckEmit: Set<AbsoluteFsPath>; /** * The newly built graph that represents the current compilation. */ newGraph: SemanticDepGraph; } /** * Represents a declaration for which no semantic symbol has been registered. For example, * declarations from external dependencies have not been explicitly registered and are represented * by this symbol. This allows the unresolved symbol to still be compared to a symbol from a prior * compilation. */ class OpaqueSymbol extends SemanticSymbol { override isPublicApiAffected(): false { return false; } override isTypeCheckApiAffected(): false { return false; } } /** * The semantic dependency graph of a single compilation. */ export class SemanticDepGraph { readonly files = new Map<AbsoluteFsPath, Map<string, SemanticSymbol>>(); // Note: the explicit type annotation is used to work around a CI failure on Windows: // error TS2742: The inferred type of 'symbolByDecl' cannot be named without a reference to // '../../../../../../../external/npm/node_modules/typescript/lib/typescript'. This is likely // not portable. A type annotation is necessary. readonly symbolByDecl: Map<ClassDeclaration, SemanticSymbol> = new Map< ClassDeclaration, SemanticSymbol >(); /** * Registers a symbol in the graph. The symbol is given a unique identifier if possible, such that * its equivalent symbol can be obtained from a prior graph even if its declaration node has * changed across rebuilds. Symbols without an identifier are only able to find themselves in a * prior graph if their declaration node is identical. */ registerSymbol(symbol: SemanticSymbol): void { this.symbolByDecl.set(symbol.decl, symbol); if (symbol.identifier !== null) { // If the symbol has a unique identifier, record it in the file that declares it. This enables // the symbol to be requested by its unique name. if (!this.files.has(symbol.path)) { this.files.set(symbol.path, new Map<string, SemanticSymbol>()); } this.files.get(symbol.path)!.set(symbol.identifier, symbol); } } /** * Attempts to resolve a symbol in this graph that represents the given symbol from another graph. * If no matching symbol could be found, null is returned. * * @param symbol The symbol from another graph for which its equivalent in this graph should be * found. */ getEquivalentSymbol(symbol: SemanticSymbol): SemanticSymbol | null { // First lookup the symbol by its declaration. It is typical for the declaration to not have // changed across rebuilds, so this is likely to find the symbol. Using the declaration also // allows to diff symbols for which no unique identifier could be determined. let previousSymbol = this.getSymbolByDecl(symbol.decl); if (previousSymbol === null && symbol.identifier !== null) { // The declaration could not be resolved to a symbol in a prior compilation, which may // happen because the file containing the declaration has changed. In that case we want to // lookup the symbol based on its unique identifier, as that allows us to still compare the // changed declaration to the prior compilation. previousSymbol = this.getSymbolByName(symbol.path, symbol.identifier); } return previousSymbol; } /** * Attempts to find the symbol by its identifier. */ private getSymbolByName(path: AbsoluteFsPath, identifier: string): SemanticSymbol | null { if (!this.files.has(path)) { return null; } const file = this.files.get(path)!; if (!file.has(identifier)) { return null; } return file.get(identifier)!; } /** * Attempts to resolve the declaration to its semantic symbol. */ getSymbolByDecl(decl: ClassDeclaration): SemanticSymbol | null { if (!this.symbolByDecl.has(decl)) { return null; } return this.symbolByDecl.get(decl)!; } } /** * Implements the logic to go from a previous dependency graph to a new one, along with information * on which files have been affected. */
{ "end_byte": 4751, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/graph.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/graph.ts_4752_10665
export class SemanticDepGraphUpdater { private readonly newGraph = new SemanticDepGraph(); /** * Contains opaque symbols that were created for declarations for which there was no symbol * registered, which happens for e.g. external declarations. */ private readonly opaqueSymbols = new Map<ClassDeclaration, OpaqueSymbol>(); constructor( /** * The semantic dependency graph of the most recently succeeded compilation, or null if this * is the initial build. */ private priorGraph: SemanticDepGraph | null, ) {} /** * Registers the symbol in the new graph that is being created. */ registerSymbol(symbol: SemanticSymbol): void { this.newGraph.registerSymbol(symbol); } /** * Takes all facts that have been gathered to create a new semantic dependency graph. In this * process, the semantic impact of the changes is determined which results in a set of files that * need to be emitted and/or type-checked. */ finalize(): SemanticDependencyResult { if (this.priorGraph === null) { // If no prior dependency graph is available then this was the initial build, in which case // we don't need to determine the semantic impact as everything is already considered // logically changed. return { needsEmit: new Set<AbsoluteFsPath>(), needsTypeCheckEmit: new Set<AbsoluteFsPath>(), newGraph: this.newGraph, }; } const needsEmit = this.determineInvalidatedFiles(this.priorGraph); const needsTypeCheckEmit = this.determineInvalidatedTypeCheckFiles(this.priorGraph); return { needsEmit, needsTypeCheckEmit, newGraph: this.newGraph, }; } private determineInvalidatedFiles(priorGraph: SemanticDepGraph): Set<AbsoluteFsPath> { const isPublicApiAffected = new Set<SemanticSymbol>(); // The first phase is to collect all symbols which have their public API affected. Any symbols // that cannot be matched up with a symbol from the prior graph are considered affected. for (const symbol of this.newGraph.symbolByDecl.values()) { const previousSymbol = priorGraph.getEquivalentSymbol(symbol); if (previousSymbol === null || symbol.isPublicApiAffected(previousSymbol)) { isPublicApiAffected.add(symbol); } } // The second phase is to find all symbols for which the emit result is affected, either because // their used declarations have changed or any of those used declarations has had its public API // affected as determined in the first phase. const needsEmit = new Set<AbsoluteFsPath>(); for (const symbol of this.newGraph.symbolByDecl.values()) { if (symbol.isEmitAffected === undefined) { continue; } const previousSymbol = priorGraph.getEquivalentSymbol(symbol); if (previousSymbol === null || symbol.isEmitAffected(previousSymbol, isPublicApiAffected)) { needsEmit.add(symbol.path); } } return needsEmit; } private determineInvalidatedTypeCheckFiles(priorGraph: SemanticDepGraph): Set<AbsoluteFsPath> { const isTypeCheckApiAffected = new Set<SemanticSymbol>(); // The first phase is to collect all symbols which have their public API affected. Any symbols // that cannot be matched up with a symbol from the prior graph are considered affected. for (const symbol of this.newGraph.symbolByDecl.values()) { const previousSymbol = priorGraph.getEquivalentSymbol(symbol); if (previousSymbol === null || symbol.isTypeCheckApiAffected(previousSymbol)) { isTypeCheckApiAffected.add(symbol); } } // The second phase is to find all symbols for which the emit result is affected, either because // their used declarations have changed or any of those used declarations has had its public API // affected as determined in the first phase. const needsTypeCheckEmit = new Set<AbsoluteFsPath>(); for (const symbol of this.newGraph.symbolByDecl.values()) { if (symbol.isTypeCheckBlockAffected === undefined) { continue; } const previousSymbol = priorGraph.getEquivalentSymbol(symbol); if ( previousSymbol === null || symbol.isTypeCheckBlockAffected(previousSymbol, isTypeCheckApiAffected) ) { needsTypeCheckEmit.add(symbol.path); } } return needsTypeCheckEmit; } /** * Creates a `SemanticReference` for the reference to `decl` using the expression `expr`. See * the documentation of `SemanticReference` for details. */ getSemanticReference(decl: ClassDeclaration, expr: Expression): SemanticReference { return { symbol: this.getSymbol(decl), importPath: getImportPath(expr), }; } /** * Gets the `SemanticSymbol` that was registered for `decl` during the current compilation, or * returns an opaque symbol that represents `decl`. */ getSymbol(decl: ClassDeclaration): SemanticSymbol { const symbol = this.newGraph.getSymbolByDecl(decl); if (symbol === null) { // No symbol has been recorded for the provided declaration, which would be the case if the // declaration is external. Return an opaque symbol in that case, to allow the external // declaration to be compared to a prior compilation. return this.getOpaqueSymbol(decl); } return symbol; } /** * Gets or creates an `OpaqueSymbol` for the provided class declaration. */ private getOpaqueSymbol(decl: ClassDeclaration): OpaqueSymbol { if (this.opaqueSymbols.has(decl)) { return this.opaqueSymbols.get(decl)!; } const symbol = new OpaqueSymbol(decl); this.opaqueSymbols.set(decl, symbol); return symbol; } } function getImportPath(expr: Expression): string | null { if (expr instanceof ExternalExpr) { return `${expr.value.moduleName}\$${expr.value.name}`; } else { return null; } }
{ "end_byte": 10665, "start_byte": 4752, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/graph.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/util.ts_0_2584
/** * @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 {SemanticReference, SemanticSymbol} from './api'; /** * Determines whether the provided symbols represent the same declaration. */ export function isSymbolEqual(a: SemanticSymbol, b: SemanticSymbol): boolean { if (a.decl === b.decl) { // If the declaration is identical then it must represent the same symbol. return true; } if (a.identifier === null || b.identifier === null) { // Unidentifiable symbols are assumed to be different. return false; } return a.path === b.path && a.identifier === b.identifier; } /** * Determines whether the provided references to a semantic symbol are still equal, i.e. represent * the same symbol and are imported by the same path. */ export function isReferenceEqual(a: SemanticReference, b: SemanticReference): boolean { if (!isSymbolEqual(a.symbol, b.symbol)) { // If the reference's target symbols are different, the reference itself is different. return false; } // The reference still corresponds with the same symbol, now check that the path by which it is // imported has not changed. return a.importPath === b.importPath; } export function referenceEquality<T>(a: T, b: T): boolean { return a === b; } /** * Determines if the provided arrays are equal to each other, using the provided equality tester * that is called for all entries in the array. */ export function isArrayEqual<T>( a: readonly T[] | null, b: readonly T[] | null, equalityTester: (a: T, b: T) => boolean = referenceEquality, ): boolean { if (a === null || b === null) { return a === b; } if (a.length !== b.length) { return false; } return !a.some((item, index) => !equalityTester(item, b[index])); } /** * Determines if the provided sets are equal to each other, using the provided equality tester. * Sets that only differ in ordering are considered equal. */ export function isSetEqual<T>( a: ReadonlySet<T> | null, b: ReadonlySet<T> | null, equalityTester: (a: T, b: T) => boolean = referenceEquality, ): boolean { if (a === null || b === null) { return a === b; } if (a.size !== b.size) { return false; } for (const itemA of a) { let found = false; for (const itemB of b) { if (equalityTester(itemA, itemB)) { found = true; break; } } if (!found) { return false; } } return true; }
{ "end_byte": 2584, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/util.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts_0_2140
/** * @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 {absoluteFromSourceFile, AbsoluteFsPath, resolve} from '../../file_system'; import {PerfPhase, PerfRecorder} from '../../perf'; import {MaybeSourceFileWithOriginalFile, NgOriginalFile} from '../../program_driver'; import {ClassRecord, TraitCompiler} from '../../transform'; import {FileTypeCheckingData} from '../../typecheck'; import {toUnredirectedSourceFile} from '../../util/src/typescript'; import {IncrementalBuild} from '../api'; import {SemanticDepGraphUpdater} from '../semantic_graph'; import {FileDependencyGraph} from './dependency_tracking'; import { AnalyzedIncrementalState, DeltaIncrementalState, IncrementalState, IncrementalStateKind, } from './state'; /** * Information about the previous compilation being used as a starting point for the current one, * including the delta of files which have logically changed and need to be reanalyzed. */ interface IncrementalStep { priorState: AnalyzedIncrementalState; logicallyChangedTsFiles: Set<AbsoluteFsPath>; } /** * Discriminant of the `Phase` type union. */ enum PhaseKind { Analysis, TypeCheckAndEmit, } /** * An incremental compilation undergoing analysis, and building a semantic dependency graph. */ interface AnalysisPhase { kind: PhaseKind.Analysis; semanticDepGraphUpdater: SemanticDepGraphUpdater; } /** * An incremental compilation that completed analysis and is undergoing template type-checking and * emit. */ interface TypeCheckAndEmitPhase { kind: PhaseKind.TypeCheckAndEmit; needsEmit: Set<AbsoluteFsPath>; needsTypeCheckEmit: Set<AbsoluteFsPath>; } /** * Represents the current phase of a compilation. */ type Phase = AnalysisPhase | TypeCheckAndEmitPhase; /** * Manages the incremental portion of an Angular compilation, allowing for reuse of a prior * compilation if available, and producing an output state for reuse of the current compilation in a * future one. */
{ "end_byte": 2140, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts_2141_11164
export class IncrementalCompilation implements IncrementalBuild<ClassRecord, FileTypeCheckingData> { private phase: Phase; /** * `IncrementalState` of this compilation if it were to be reused in a subsequent incremental * compilation at the current moment. * * Exposed via the `state` read-only getter. */ private _state: IncrementalState; private constructor( state: IncrementalState, readonly depGraph: FileDependencyGraph, private versions: Map<AbsoluteFsPath, string> | null, private step: IncrementalStep | null, ) { this._state = state; // The compilation begins in analysis phase. this.phase = { kind: PhaseKind.Analysis, semanticDepGraphUpdater: new SemanticDepGraphUpdater( step !== null ? step.priorState.semanticDepGraph : null, ), }; } /** * Begin a fresh `IncrementalCompilation`. */ static fresh( program: ts.Program, versions: Map<AbsoluteFsPath, string> | null, ): IncrementalCompilation { const state: IncrementalState = { kind: IncrementalStateKind.Fresh, }; return new IncrementalCompilation(state, new FileDependencyGraph(), versions, /* reuse */ null); } static incremental( program: ts.Program, newVersions: Map<AbsoluteFsPath, string> | null, oldProgram: ts.Program, oldState: IncrementalState, modifiedResourceFiles: Set<AbsoluteFsPath> | null, perf: PerfRecorder, ): IncrementalCompilation { return perf.inPhase(PerfPhase.Reconciliation, () => { const physicallyChangedTsFiles = new Set<AbsoluteFsPath>(); const changedResourceFiles = new Set<AbsoluteFsPath>(modifiedResourceFiles ?? []); let priorAnalysis: AnalyzedIncrementalState; switch (oldState.kind) { case IncrementalStateKind.Fresh: // Since this line of program has never been successfully analyzed to begin with, treat // this as a fresh compilation. return IncrementalCompilation.fresh(program, newVersions); case IncrementalStateKind.Analyzed: // The most recent program was analyzed successfully, so we can use that as our prior // state and don't need to consider any other deltas except changes in the most recent // program. priorAnalysis = oldState; break; case IncrementalStateKind.Delta: // There is an ancestor program which was analyzed successfully and can be used as a // starting point, but we need to determine what's changed since that program. priorAnalysis = oldState.lastAnalyzedState; for (const sfPath of oldState.physicallyChangedTsFiles) { physicallyChangedTsFiles.add(sfPath); } for (const resourcePath of oldState.changedResourceFiles) { changedResourceFiles.add(resourcePath); } break; } const oldVersions = priorAnalysis.versions; const oldFilesArray = oldProgram.getSourceFiles().map(toOriginalSourceFile); const oldFiles = new Set(oldFilesArray); const deletedTsFiles = new Set(oldFilesArray.map((sf) => absoluteFromSourceFile(sf))); for (const possiblyRedirectedNewFile of program.getSourceFiles()) { const sf = toOriginalSourceFile(possiblyRedirectedNewFile); const sfPath = absoluteFromSourceFile(sf); // Since we're seeing a file in the incoming program with this name, it can't have been // deleted. deletedTsFiles.delete(sfPath); if (oldFiles.has(sf)) { // This source file has the same object identity as in the previous program. We need to // determine if it's really the same file, or if it might have changed versions since the // last program without changing its identity. // If there's no version information available, then this is the same file, and we can // skip it. if (oldVersions === null || newVersions === null) { continue; } // If a version is available for the file from both the prior and the current program, and // that version is the same, then this is the same file, and we can skip it. if ( oldVersions.has(sfPath) && newVersions.has(sfPath) && oldVersions.get(sfPath)! === newVersions.get(sfPath)! ) { continue; } // Otherwise, assume that the file has changed. Either its versions didn't match, or we // were missing version information about it on one side for some reason. } // Bail out if a .d.ts file changes - the semantic dep graph is not able to process such // changes correctly yet. if (sf.isDeclarationFile) { return IncrementalCompilation.fresh(program, newVersions); } // The file has changed physically, so record it. physicallyChangedTsFiles.add(sfPath); } // Remove any files that have been deleted from the list of physical changes. for (const deletedFileName of deletedTsFiles) { physicallyChangedTsFiles.delete(resolve(deletedFileName)); } // Use the prior dependency graph to project physical changes into a set of logically changed // files. const depGraph = new FileDependencyGraph(); const logicallyChangedTsFiles = depGraph.updateWithPhysicalChanges( priorAnalysis.depGraph, physicallyChangedTsFiles, deletedTsFiles, changedResourceFiles, ); // Physically changed files aren't necessarily counted as logically changed by the dependency // graph (files do not have edges to themselves), so add them to the logical changes // explicitly. for (const sfPath of physicallyChangedTsFiles) { logicallyChangedTsFiles.add(sfPath); } // Start off in a `DeltaIncrementalState` as a delta against the previous successful analysis, // until this compilation completes its own analysis. const state: DeltaIncrementalState = { kind: IncrementalStateKind.Delta, physicallyChangedTsFiles, changedResourceFiles, lastAnalyzedState: priorAnalysis, }; return new IncrementalCompilation(state, depGraph, newVersions, { priorState: priorAnalysis, logicallyChangedTsFiles, }); }); } get state(): IncrementalState { return this._state; } get semanticDepGraphUpdater(): SemanticDepGraphUpdater { if (this.phase.kind !== PhaseKind.Analysis) { throw new Error( `AssertionError: Cannot update the SemanticDepGraph after analysis completes`, ); } return this.phase.semanticDepGraphUpdater; } recordSuccessfulAnalysis(traitCompiler: TraitCompiler): void { if (this.phase.kind !== PhaseKind.Analysis) { throw new Error( `AssertionError: Incremental compilation in phase ${ PhaseKind[this.phase.kind] }, expected Analysis`, ); } const {needsEmit, needsTypeCheckEmit, newGraph} = this.phase.semanticDepGraphUpdater.finalize(); // Determine the set of files which have already been emitted. let emitted: Set<AbsoluteFsPath>; if (this.step === null) { // Since there is no prior compilation, no files have yet been emitted. emitted = new Set(); } else { // Begin with the files emitted by the prior successful compilation, but remove those which we // know need to bee re-emitted. emitted = new Set(this.step.priorState.emitted); // Files need re-emitted if they've logically changed. for (const sfPath of this.step.logicallyChangedTsFiles) { emitted.delete(sfPath); } // Files need re-emitted if they've semantically changed. for (const sfPath of needsEmit) { emitted.delete(sfPath); } } // Transition to a successfully analyzed compilation. At this point, a subsequent compilation // could use this state as a starting point. this._state = { kind: IncrementalStateKind.Analyzed, versions: this.versions, depGraph: this.depGraph, semanticDepGraph: newGraph, priorAnalysis: traitCompiler.getAnalyzedRecords(), typeCheckResults: null, emitted, }; // We now enter the type-check and emit phase of compilation. this.phase = { kind: PhaseKind.TypeCheckAndEmit, needsEmit, needsTypeCheckEmit, }; } recordSuccessfulTypeCheck(results: Map<AbsoluteFsPath, FileTypeCheckingData>): void { if (this._state.kind !== IncrementalStateKind.Analyzed) { throw new Error(`AssertionError: Expected successfully analyzed compilation.`); } else if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) { throw new Error( `AssertionError: Incremental compilation in phase ${ PhaseKind[this.phase.kind] }, expected TypeCheck`, ); } this._state.typeCheckResults = results; }
{ "end_byte": 11164, "start_byte": 2141, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts_11168_15366
recordSuccessfulEmit(sf: ts.SourceFile): void { if (this._state.kind !== IncrementalStateKind.Analyzed) { throw new Error(`AssertionError: Expected successfully analyzed compilation.`); } this._state.emitted.add(absoluteFromSourceFile(sf)); } priorAnalysisFor(sf: ts.SourceFile): ClassRecord[] | null { if (this.step === null) { return null; } const sfPath = absoluteFromSourceFile(sf); // If the file has logically changed, its previous analysis cannot be reused. if (this.step.logicallyChangedTsFiles.has(sfPath)) { return null; } const priorAnalysis = this.step.priorState.priorAnalysis; if (!priorAnalysis.has(sf)) { return null; } return priorAnalysis.get(sf)!; } priorTypeCheckingResultsFor(sf: ts.SourceFile): FileTypeCheckingData | null { if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) { throw new Error(`AssertionError: Expected successfully analyzed compilation.`); } if (this.step === null) { return null; } const sfPath = absoluteFromSourceFile(sf); // If the file has logically changed, or its template type-checking results have semantically // changed, then past type-checking results cannot be reused. if ( this.step.logicallyChangedTsFiles.has(sfPath) || this.phase.needsTypeCheckEmit.has(sfPath) ) { return null; } // Past results also cannot be reused if they're not available. if ( this.step.priorState.typeCheckResults === null || !this.step.priorState.typeCheckResults.has(sfPath) ) { return null; } const priorResults = this.step.priorState.typeCheckResults.get(sfPath)!; // If the past results relied on inlining, they're not safe for reuse. if (priorResults.hasInlines) { return null; } return priorResults; } safeToSkipEmit(sf: ts.SourceFile): boolean { // If this is a fresh compilation, it's never safe to skip an emit. if (this.step === null) { return false; } const sfPath = absoluteFromSourceFile(sf); // If the file has itself logically changed, it must be emitted. if (this.step.logicallyChangedTsFiles.has(sfPath)) { return false; } if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) { throw new Error( `AssertionError: Expected successful analysis before attempting to emit files`, ); } // If during analysis it was determined that this file has semantically changed, it must be // emitted. if (this.phase.needsEmit.has(sfPath)) { return false; } // Generally it should be safe to assume here that the file was previously emitted by the last // successful compilation. However, as a defense-in-depth against incorrectness, we explicitly // check that the last emit included this file, and re-emit it otherwise. return this.step.priorState.emitted.has(sfPath); } } /** * To accurately detect whether a source file was affected during an incremental rebuild, the * "original" source file needs to be consistently used. * * First, TypeScript may have created source file redirects when declaration files of the same * version of a library are included multiple times. The non-redirected source file should be used * to detect changes, as otherwise the redirected source files cause a mismatch when compared to * a prior program. * * Second, the program that is used for template type checking may contain mutated source files, if * inline type constructors or inline template type-check blocks had to be used. Such source files * store their original, non-mutated source file from the original program in a symbol. For * computing the affected files in an incremental build this original source file should be used, as * the mutated source file would always be considered affected. */ function toOriginalSourceFile(sf: ts.SourceFile): ts.SourceFile { const unredirectedSf = toUnredirectedSourceFile(sf); const originalFile = (unredirectedSf as MaybeSourceFileWithOriginalFile)[NgOriginalFile]; if (originalFile !== undefined) { return originalFile; } else { return unredirectedSf; } }
{ "end_byte": 15366, "start_byte": 11168, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/incremental.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/state.ts_0_3658
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {AbsoluteFsPath} from '../../file_system'; import {ClassRecord} from '../../transform'; import {FileTypeCheckingData} from '../../typecheck/src/checker'; import {SemanticDepGraph} from '../semantic_graph'; import {FileDependencyGraph} from './dependency_tracking'; /** * Discriminant of the `IncrementalState` union. */ export enum IncrementalStateKind { Fresh, Delta, Analyzed, } /** * Placeholder state for a fresh compilation that has never been successfully analyzed. */ export interface FreshIncrementalState { kind: IncrementalStateKind.Fresh; } /** * State captured from a compilation that completed analysis successfully, that can serve as a * starting point for a future incremental build. */ export interface AnalyzedIncrementalState { kind: IncrementalStateKind.Analyzed; /** * Dependency graph extracted from the build, to be used to determine the logical impact of * physical file changes. */ depGraph: FileDependencyGraph; /** * The semantic dependency graph from the build. * * This is used to perform in-depth comparison of Angular decorated classes, to determine * which files have to be re-emitted and/or re-type-checked. */ semanticDepGraph: SemanticDepGraph; /** * The analysis data from a prior compilation. This stores the trait information for all source * files that was present in a prior compilation. */ priorAnalysis: Map<ts.SourceFile, ClassRecord[]>; /** * All generated template type-checking files produced as part of this compilation, or `null` if * type-checking was not (yet) performed. */ typeCheckResults: Map<AbsoluteFsPath, FileTypeCheckingData> | null; /** * Cumulative set of source file paths which were definitively emitted by this compilation or * carried forward from a prior one. */ emitted: Set<AbsoluteFsPath>; /** * Map of source file paths to the version of this file as seen in the compilation. */ versions: Map<AbsoluteFsPath, string> | null; } /** * Incremental state for a compilation that has not been successfully analyzed, but that can be * based on a previous compilation which was. * * This is the state produced by an incremental compilation until its own analysis succeeds. If * analysis fails, this state carries forward information about which files have changed since the * last successful build (the `lastAnalyzedState`), so that the next incremental build can consider * the total delta between the `lastAnalyzedState` and the current program in its incremental * analysis. */ export interface DeltaIncrementalState { kind: IncrementalStateKind.Delta; /** * If available, the `AnalyzedIncrementalState` for the most recent ancestor of the current * program which was successfully analyzed. */ lastAnalyzedState: AnalyzedIncrementalState; /** * Set of file paths which have changed since the `lastAnalyzedState` compilation. */ physicallyChangedTsFiles: Set<AbsoluteFsPath>; /** * Set of resource file paths which have changed since the `lastAnalyzedState` compilation. */ changedResourceFiles: Set<AbsoluteFsPath>; } /** * State produced by a compilation that's usable as the starting point for a subsequent compilation. * * Discriminated by the `IncrementalStateKind` enum. */ export type IncrementalState = | AnalyzedIncrementalState | DeltaIncrementalState | FreshIncrementalState;
{ "end_byte": 3658, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/state.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts_0_4632
/** * @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 {absoluteFromSourceFile, AbsoluteFsPath} from '../../file_system'; import {DependencyTracker} from '../api'; /** * An implementation of the `DependencyTracker` dependency graph API. * * The `FileDependencyGraph`'s primary job is to determine whether a given file has "logically" * changed, given the set of physical changes (direct changes to files on disk). * * A file is logically changed if at least one of three conditions is met: * * 1. The file itself has physically changed. * 2. One of its dependencies has physically changed. * 3. One of its resource dependencies has physically changed. */ export class FileDependencyGraph<T extends {fileName: string} = ts.SourceFile> implements DependencyTracker<T> { private nodes = new Map<T, FileNode>(); addDependency(from: T, on: T): void { this.nodeFor(from).dependsOn.add(absoluteFromSourceFile(on)); } addResourceDependency(from: T, resource: AbsoluteFsPath): void { this.nodeFor(from).usesResources.add(resource); } recordDependencyAnalysisFailure(file: T): void { this.nodeFor(file).failedAnalysis = true; } getResourceDependencies(from: T): AbsoluteFsPath[] { const node = this.nodes.get(from); return node ? [...node.usesResources] : []; } /** * Update the current dependency graph from a previous one, incorporating a set of physical * changes. * * This method performs two tasks: * * 1. For files which have not logically changed, their dependencies from `previous` are added to * `this` graph. * 2. For files which have logically changed, they're added to a set of logically changed files * which is eventually returned. * * In essence, for build `n`, this method performs: * * G(n) + L(n) = G(n - 1) + P(n) * * where: * * G(n) = the dependency graph of build `n` * L(n) = the logically changed files from build n - 1 to build n. * P(n) = the physically changed files from build n - 1 to build n. */ updateWithPhysicalChanges( previous: FileDependencyGraph<T>, changedTsPaths: Set<AbsoluteFsPath>, deletedTsPaths: Set<AbsoluteFsPath>, changedResources: Set<AbsoluteFsPath>, ): Set<AbsoluteFsPath> { const logicallyChanged = new Set<AbsoluteFsPath>(); for (const sf of previous.nodes.keys()) { const sfPath = absoluteFromSourceFile(sf); const node = previous.nodeFor(sf); if (isLogicallyChanged(sf, node, changedTsPaths, deletedTsPaths, changedResources)) { logicallyChanged.add(sfPath); } else if (!deletedTsPaths.has(sfPath)) { this.nodes.set(sf, { dependsOn: new Set(node.dependsOn), usesResources: new Set(node.usesResources), failedAnalysis: false, }); } } return logicallyChanged; } private nodeFor(sf: T): FileNode { if (!this.nodes.has(sf)) { this.nodes.set(sf, { dependsOn: new Set<AbsoluteFsPath>(), usesResources: new Set<AbsoluteFsPath>(), failedAnalysis: false, }); } return this.nodes.get(sf)!; } } /** * Determine whether `sf` has logically changed, given its dependencies and the set of physically * changed files and resources. */ function isLogicallyChanged<T extends {fileName: string}>( sf: T, node: FileNode, changedTsPaths: ReadonlySet<AbsoluteFsPath>, deletedTsPaths: ReadonlySet<AbsoluteFsPath>, changedResources: ReadonlySet<AbsoluteFsPath>, ): boolean { // A file is assumed to have logically changed if its dependencies could not be determined // accurately. if (node.failedAnalysis) { return true; } const sfPath = absoluteFromSourceFile(sf); // A file is logically changed if it has physically changed itself (including being deleted). if (changedTsPaths.has(sfPath) || deletedTsPaths.has(sfPath)) { return true; } // A file is logically changed if one of its dependencies has physically changed. for (const dep of node.dependsOn) { if (changedTsPaths.has(dep) || deletedTsPaths.has(dep)) { return true; } } // A file is logically changed if one of its resources has physically changed. for (const dep of node.usesResources) { if (changedResources.has(dep)) { return true; } } return false; } interface FileNode { dependsOn: Set<AbsoluteFsPath>; usesResources: Set<AbsoluteFsPath>; failedAnalysis: boolean; }
{ "end_byte": 4632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/noop.ts_0_431
/** * @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 {IncrementalBuild} from '../api'; export const NOOP_INCREMENTAL_BUILD: IncrementalBuild<any, any> = { priorAnalysisFor: () => null, priorTypeCheckingResultsFor: () => null, recordSuccessfulTypeCheck: () => {}, };
{ "end_byte": 431, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/noop.ts" }
angular/packages/compiler-cli/src/ngtsc/incremental/src/strategy.ts_0_3829
/** * @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 {IncrementalState} from './state'; /** * Strategy used to manage the association between a `ts.Program` and the `IncrementalState` which * represents the reusable Angular part of its compilation. */ export interface IncrementalBuildStrategy { /** * Determine the Angular `IncrementalState` for the given `ts.Program`, if one is available. */ getIncrementalState(program: ts.Program): IncrementalState | null; /** * Associate the given `IncrementalState` with the given `ts.Program` and make it available to * future compilations. */ setIncrementalState(driver: IncrementalState, program: ts.Program): void; /** * Convert this `IncrementalBuildStrategy` into a possibly new instance to be used in the next * incremental compilation (may be a no-op if the strategy is not stateful). */ toNextBuildStrategy(): IncrementalBuildStrategy; } /** * A noop implementation of `IncrementalBuildStrategy` which neither returns nor tracks any * incremental data. */ export class NoopIncrementalBuildStrategy implements IncrementalBuildStrategy { getIncrementalState(): null { return null; } setIncrementalState(): void {} toNextBuildStrategy(): IncrementalBuildStrategy { return this; } } /** * Tracks an `IncrementalState` within the strategy itself. */ export class TrackedIncrementalBuildStrategy implements IncrementalBuildStrategy { private state: IncrementalState | null = null; private isSet: boolean = false; getIncrementalState(): IncrementalState | null { return this.state; } setIncrementalState(state: IncrementalState): void { this.state = state; this.isSet = true; } toNextBuildStrategy(): TrackedIncrementalBuildStrategy { const strategy = new TrackedIncrementalBuildStrategy(); // Only reuse state that was explicitly set via `setIncrementalState`. strategy.state = this.isSet ? this.state : null; return strategy; } } /** * Manages the `IncrementalState` associated with a `ts.Program` by monkey-patching it onto the * program under `SYM_INCREMENTAL_STATE`. */ export class PatchedProgramIncrementalBuildStrategy implements IncrementalBuildStrategy { getIncrementalState(program: ts.Program): IncrementalState | null { const state = (program as MayHaveIncrementalState)[SYM_INCREMENTAL_STATE]; if (state === undefined) { return null; } return state; } setIncrementalState(state: IncrementalState, program: ts.Program): void { (program as MayHaveIncrementalState)[SYM_INCREMENTAL_STATE] = state; } toNextBuildStrategy(): IncrementalBuildStrategy { return this; } } /** * Symbol under which the `IncrementalState` is stored on a `ts.Program`. * * The TS model of incremental compilation is based around reuse of a previous `ts.Program` in the * construction of a new one. The `NgCompiler` follows this abstraction - passing in a previous * `ts.Program` is sufficient to trigger incremental compilation. This previous `ts.Program` need * not be from an Angular compilation (that is, it need not have been created from `NgCompiler`). * * If it is, though, Angular can benefit from reusing previous analysis work. This reuse is managed * by the `IncrementalState`, which is inherited from the old program to the new program. To * support this behind the API of passing an old `ts.Program`, the `IncrementalState` is stored on * the `ts.Program` under this symbol. */ const SYM_INCREMENTAL_STATE = Symbol('NgIncrementalState'); interface MayHaveIncrementalState { [SYM_INCREMENTAL_STATE]?: IncrementalState; }
{ "end_byte": 3829, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/incremental/src/strategy.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/BUILD.bazel_0_620
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "entry_point", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), module_name = "@angular/compiler-cli/src/ngtsc/entry_point", deps = [ "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/shims:api", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 620, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/entry_point/index.ts_0_432
/** * @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 {FlatIndexGenerator} from './src/generator'; export {findFlatIndexEntryPoint} from './src/logic'; export {checkForPrivateExports} from './src/private_export_checker'; export {ReferenceGraph} from './src/reference_graph';
{ "end_byte": 432, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/index.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts_0_1640
/** * @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 {ReferenceGraph} from '../src/reference_graph'; describe('entry_point reference graph', () => { let graph: ReferenceGraph<string>; const refs = (target: string) => { return Array.from(graph.transitiveReferencesOf(target)).sort(); }; beforeEach(() => { graph = new ReferenceGraph(); graph.add('origin', 'alpha'); graph.add('alpha', 'beta'); graph.add('beta', 'gamma'); }); it('should track a simple chain of references', () => { // origin -> alpha -> beta -> gamma expect(refs('origin')).toEqual(['alpha', 'beta', 'gamma']); expect(refs('beta')).toEqual(['gamma']); }); it('should not crash on a cycle', () => { // origin -> alpha -> beta -> gamma // ^---------------/ graph.add('beta', 'origin'); expect(refs('origin')).toEqual(['alpha', 'beta', 'gamma', 'origin']); }); it('should report a path between two nodes in the graph', () => { // ,------------------------\ // origin -> alpha -> beta -> gamma -> delta // \----------------^ graph.add('beta', 'delta'); graph.add('delta', 'alpha'); expect(graph.pathFrom('origin', 'gamma')).toEqual(['origin', 'alpha', 'beta', 'gamma']); expect(graph.pathFrom('beta', 'alpha')).toEqual(['beta', 'delta', 'alpha']); }); it("should not report a path that doesn't exist", () => { expect(graph.pathFrom('gamma', 'beta')).toBeNull(); }); });
{ "end_byte": 1640, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/test/reference_graph_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts_0_1017
/** * @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 '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {findFlatIndexEntryPoint} from '../src/logic'; runInEachFileSystem(() => { describe('entry_point logic', () => { let _: typeof absoluteFrom; beforeEach(() => (_ = absoluteFrom)); describe('findFlatIndexEntryPoint', () => { it('should use the only source file if only a single one is specified', () => { expect(findFlatIndexEntryPoint([_('/src/index.ts')])).toBe(_('/src/index.ts')); }); it('should use the shortest source file ending with "index.ts" for multiple files', () => { expect( findFlatIndexEntryPoint([_('/src/deep/index.ts'), _('/src/index.ts'), _('/index.ts')]), ).toBe(_('/index.ts')); }); }); }); });
{ "end_byte": 1017, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/test/entry_point_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/test/BUILD.bazel_0_613
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/entry_point", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 613, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts_0_6007
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {DeclarationNode} from '../../reflection'; import {ReferenceGraph} from './reference_graph'; /** * Produce `ts.Diagnostic`s for classes that are visible from exported types (e.g. directives * exposed by exported `NgModule`s) that are not themselves exported. * * This function reconciles two concepts: * * A class is Exported if it's exported from the main library `entryPoint` file. * A class is Visible if, via Angular semantics, a downstream consumer can import an Exported class * and be affected by the class in question. For example, an Exported NgModule may expose a * directive class to its consumers. Consumers that import the NgModule may have the directive * applied to elements in their templates. In this case, the directive is considered Visible. * * `checkForPrivateExports` attempts to verify that all Visible classes are Exported, and report * `ts.Diagnostic`s for those that aren't. * * @param entryPoint `ts.SourceFile` of the library's entrypoint, which should export the library's * public API. * @param checker `ts.TypeChecker` for the current program. * @param refGraph `ReferenceGraph` tracking the visibility of Angular types. * @returns an array of `ts.Diagnostic`s representing errors when visible classes are not exported * properly. */ export function checkForPrivateExports( entryPoint: ts.SourceFile, checker: ts.TypeChecker, refGraph: ReferenceGraph, ): ts.Diagnostic[] { const diagnostics: ts.Diagnostic[] = []; // Firstly, compute the exports of the entry point. These are all the Exported classes. const topLevelExports = new Set<DeclarationNode>(); // Do this via `ts.TypeChecker.getExportsOfModule`. const moduleSymbol = checker.getSymbolAtLocation(entryPoint); if (moduleSymbol === undefined) { throw new Error(`Internal error: failed to get symbol for entrypoint`); } const exportedSymbols = checker.getExportsOfModule(moduleSymbol); // Loop through the exported symbols, de-alias if needed, and add them to `topLevelExports`. // TODO(alxhub): use proper iteration when build.sh is removed. (#27762) exportedSymbols.forEach((symbol) => { if (symbol.flags & ts.SymbolFlags.Alias) { symbol = checker.getAliasedSymbol(symbol); } const decl = symbol.valueDeclaration; if (decl !== undefined) { topLevelExports.add(decl); } }); // Next, go through each exported class and expand it to the set of classes it makes Visible, // using the `ReferenceGraph`. For each Visible class, verify that it's also Exported, and queue // an error if it isn't. `checkedSet` ensures only one error is queued per class. const checkedSet = new Set<DeclarationNode>(); // Loop through each Exported class. // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762) topLevelExports.forEach((mainExport) => { // Loop through each class made Visible by the Exported class. refGraph.transitiveReferencesOf(mainExport).forEach((transitiveReference) => { // Skip classes which have already been checked. if (checkedSet.has(transitiveReference)) { return; } checkedSet.add(transitiveReference); // Verify that the Visible class is also Exported. if (!topLevelExports.has(transitiveReference)) { // This is an error, `mainExport` makes `transitiveReference` Visible, but // `transitiveReference` is not Exported from the entrypoint. Construct a diagnostic to // give to the user explaining the situation. const descriptor = getDescriptorOfDeclaration(transitiveReference); const name = getNameOfDeclaration(transitiveReference); // Construct the path of visibility, from `mainExport` to `transitiveReference`. let visibleVia = 'NgModule exports'; const transitivePath = refGraph.pathFrom(mainExport, transitiveReference); if (transitivePath !== null) { visibleVia = transitivePath.map((seg) => getNameOfDeclaration(seg)).join(' -> '); } const diagnostic: ts.Diagnostic = { category: ts.DiagnosticCategory.Error, code: ngErrorCode(ErrorCode.SYMBOL_NOT_EXPORTED), file: transitiveReference.getSourceFile(), ...getPosOfDeclaration(transitiveReference), messageText: `Unsupported private ${descriptor} ${name}. This ${descriptor} is visible to consumers via ${visibleVia}, but is not exported from the top-level library entrypoint.`, }; diagnostics.push(diagnostic); } }); }); return diagnostics; } function getPosOfDeclaration(decl: DeclarationNode): {start: number; length: number} { const node: ts.Node = getIdentifierOfDeclaration(decl) || decl; return { start: node.getStart(), length: node.getEnd() + 1 - node.getStart(), }; } function getIdentifierOfDeclaration(decl: DeclarationNode): ts.Identifier | null { if ( (ts.isClassDeclaration(decl) || ts.isVariableDeclaration(decl) || ts.isFunctionDeclaration(decl)) && decl.name !== undefined && ts.isIdentifier(decl.name) ) { return decl.name; } else { return null; } } function getNameOfDeclaration(decl: DeclarationNode): string { const id = getIdentifierOfDeclaration(decl); return id !== null ? id.text : '(unnamed)'; } function getDescriptorOfDeclaration(decl: DeclarationNode): string { switch (decl.kind) { case ts.SyntaxKind.ClassDeclaration: return 'class'; case ts.SyntaxKind.FunctionDeclaration: return 'function'; case ts.SyntaxKind.VariableDeclaration: return 'variable'; case ts.SyntaxKind.EnumDeclaration: return 'enum'; default: return 'declaration'; } }
{ "end_byte": 6007, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts_0_1336
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import ts from 'typescript'; import {AbsoluteFsPath, dirname, join} from '../../file_system'; import {TopLevelShimGenerator} from '../../shims/api'; import {relativePathBetween} from '../../util/src/path'; export class FlatIndexGenerator implements TopLevelShimGenerator { readonly flatIndexPath: string; readonly shouldEmit = true; constructor( readonly entryPoint: AbsoluteFsPath, relativeFlatIndexPath: string, readonly moduleName: string | null, ) { this.flatIndexPath = join(dirname(entryPoint), relativeFlatIndexPath).replace(/\.js$/, '') + '.ts'; } makeTopLevelShim(): ts.SourceFile { const relativeEntryPoint = relativePathBetween(this.flatIndexPath, this.entryPoint); const contents = `/** * Generated bundle index. Do not edit. */ export * from '${relativeEntryPoint}'; `; const genFile = ts.createSourceFile( this.flatIndexPath, contents, ts.ScriptTarget.ES2015, true, ts.ScriptKind.TS, ); if (this.moduleName !== null) { genFile.moduleName = this.moduleName; } return genFile; } }
{ "end_byte": 1336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/src/generator.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts_0_2470
/** * @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 {DeclarationNode} from '../../reflection'; export class ReferenceGraph<T = DeclarationNode> { private references = new Map<T, Set<T>>(); add(from: T, to: T): void { if (!this.references.has(from)) { this.references.set(from, new Set()); } this.references.get(from)!.add(to); } transitiveReferencesOf(target: T): Set<T> { const set = new Set<T>(); this.collectTransitiveReferences(set, target); return set; } pathFrom(source: T, target: T): T[] | null { return this.collectPathFrom(source, target, new Set()); } private collectPathFrom(source: T, target: T, seen: Set<T>): T[] | null { if (source === target) { // Looking for a path from the target to itself - that path is just the target. This is the // "base case" of the search. return [target]; } else if (seen.has(source)) { // The search has already looked through this source before. return null; } // Consider outgoing edges from `source`. seen.add(source); if (!this.references.has(source)) { // There are no outgoing edges from `source`. return null; } else { // Look through the outgoing edges of `source`. // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762) let candidatePath: T[] | null = null; this.references.get(source)!.forEach((edge) => { // Early exit if a path has already been found. if (candidatePath !== null) { return; } // Look for a path from this outgoing edge to `target`. const partialPath = this.collectPathFrom(edge, target, seen); if (partialPath !== null) { // A path exists from `edge` to `target`. Insert `source` at the beginning. candidatePath = [source, ...partialPath]; } }); return candidatePath; } } private collectTransitiveReferences(set: Set<T>, decl: T): void { if (this.references.has(decl)) { // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762) this.references.get(decl)!.forEach((ref) => { if (!set.has(ref)) { set.add(ref); this.collectTransitiveReferences(set, ref); } }); } } }
{ "end_byte": 2470, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.ts" }
angular/packages/compiler-cli/src/ngtsc/entry_point/src/logic.ts_0_1523
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {AbsoluteFsPath, getFileSystem} from '../../file_system'; import {isNonDeclarationTsPath} from '../../util/src/typescript'; export function findFlatIndexEntryPoint( rootFiles: ReadonlyArray<AbsoluteFsPath>, ): AbsoluteFsPath | null { // There are two ways for a file to be recognized as the flat module index: // 1) if it's the only file!!!!!! // 2) (deprecated) if it's named 'index.ts' and has the shortest path of all such files. const tsFiles = rootFiles.filter((file) => isNonDeclarationTsPath(file)); let resolvedEntryPoint: AbsoluteFsPath | null = null; if (tsFiles.length === 1) { // There's only one file - this is the flat module index. resolvedEntryPoint = tsFiles[0]; } else { // In the event there's more than one TS file, one of them can still be selected as the // flat module index if it's named 'index.ts'. If there's more than one 'index.ts', the one // with the shortest path wins. // // This behavior is DEPRECATED and only exists to support existing usages. for (const tsFile of tsFiles) { if ( getFileSystem().basename(tsFile) === 'index.ts' && (resolvedEntryPoint === null || tsFile.length <= resolvedEntryPoint.length) ) { resolvedEntryPoint = tsFile; } } } return resolvedEntryPoint; }
{ "end_byte": 1523, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/entry_point/src/logic.ts" }
angular/packages/compiler-cli/src/ngtsc/util/BUILD.bazel_0_460
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "util", srcs = glob([ "src/**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/reflection", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 460, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/util/test/typescript_spec.ts_0_908
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {FileSystem, getFileSystem} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {getRootDirs} from '../src/typescript'; runInEachFileSystem(() => { let fs: FileSystem; beforeEach(() => { fs = getFileSystem(); }); describe('typescript', () => { it('should allow relative root directories', () => { const mockCompilerHost = { getCanonicalFileName: (val: string) => val, getCurrentDirectory: () => '/fs-root/projects', }; const result = getRootDirs(mockCompilerHost, {rootDir: './test-project-root'}); expect(result).toEqual([fs.resolve('/fs-root/projects/test-project-root')]); }); }); });
{ "end_byte": 908, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/test/typescript_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/util/test/BUILD.bazel_0_659
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 659, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts_0_3525
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {makeProgram} from '../../testing'; import {visit, VisitListEntryResult, Visitor} from '../src/visitor'; class TestAstVisitor extends Visitor { override visitClassDeclaration( node: ts.ClassDeclaration, ): VisitListEntryResult<ts.Statement, ts.ClassDeclaration> { const name = node.name!.text; const statics = node.members.filter((member) => { const modifiers = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined; return (modifiers || []).some((mod) => mod.kind === ts.SyntaxKind.StaticKeyword); }); const idStatic = statics.find( (el) => ts.isPropertyDeclaration(el) && ts.isIdentifier(el.name) && el.name.text === 'id', ) as ts.PropertyDeclaration | undefined; if (idStatic !== undefined) { return { node, before: [ ts.factory.createVariableStatement(undefined, [ ts.factory.createVariableDeclaration( `${name}_id`, undefined, undefined, idStatic.initializer, ), ]), ], }; } return {node}; } } function testTransformerFactory(context: ts.TransformationContext): ts.Transformer<ts.SourceFile> { return (file: ts.SourceFile) => visit(file, new TestAstVisitor(), context); } runInEachFileSystem(() => { describe('AST Visitor', () => { let _: typeof absoluteFrom; beforeEach(() => (_ = absoluteFrom)); it('should add a statement before class in plain file', () => { const {program, host} = makeProgram([ {name: _('/main.ts'), contents: `class A { static id = 3; }`}, ]); const sf = getSourceFileOrError(program, _('/main.ts')); program.emit(sf, undefined, undefined, undefined, {before: [testTransformerFactory]}); const main = host.readFile('/main.js'); expect(main).toMatch(/^var A_id = 3;/); }); it('should add a statement before class inside function definition', () => { const {program, host} = makeProgram([ { name: _('/main.ts'), contents: ` export function foo() { var x = 3; class A { static id = 2; } return A; } `, }, ]); const sf = getSourceFileOrError(program, _('/main.ts')); program.emit(sf, undefined, undefined, undefined, {before: [testTransformerFactory]}); const main = host.readFile(_('/main.js')); expect(main).toMatch(/var x = 3;\s+var A_id = 2;\s+var A =/); }); it('handles nested statements', () => { const {program, host} = makeProgram([ { name: _('/main.ts'), contents: ` export class A { static id = 3; foo() { class B { static id = 4; } return B; } }`, }, ]); const sf = getSourceFileOrError(program, _('/main.ts')); program.emit(sf, undefined, undefined, undefined, {before: [testTransformerFactory]}); const main = host.readFile(_('/main.js')); expect(main).toMatch(/var A_id = 3;\s+var A = /); expect(main).toMatch(/var B_id = 4;\s+var B = /); }); }); });
{ "end_byte": 3525, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/test/visitor_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/util/src/path.ts_0_1683
/** * @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 {dirname, relative, resolve, toRelativeImport} from '../../file_system'; import {stripExtension} from '../../file_system/src/util'; import ts from 'typescript'; export function relativePathBetween(from: string, to: string): string | null { const relativePath = stripExtension(relative(dirname(resolve(from)), resolve(to))); return relativePath !== '' ? toRelativeImport(relativePath) : null; } export function normalizeSeparators(path: string): string { // TODO: normalize path only for OS that need it. return path.replace(/\\/g, '/'); } /** * Attempts to generate a project-relative path * @param sourceFile * @param rootDirs * @param compilerHost * @returns */ export function getProjectRelativePath( sourceFile: ts.SourceFile, rootDirs: readonly string[], compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, ): string | null { // Note: we need to pass both the file name and the root directories through getCanonicalFileName, // because the root directories might've been passed through it already while the source files // definitely have not. This can break the relative return value, because in some platforms // getCanonicalFileName lowercases the path. const filePath = compilerHost.getCanonicalFileName(sourceFile.fileName); for (const rootDir of rootDirs) { const rel = relative(compilerHost.getCanonicalFileName(rootDir), filePath); if (!rel.startsWith('..')) { return rel; } } return null; }
{ "end_byte": 1683, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/src/path.ts" }
angular/packages/compiler-cli/src/ngtsc/util/src/visitor.ts_0_4561
/** * @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'; /** * Result type of visiting a node that's typically an entry in a list, which allows specifying that * nodes should be added before the visited node in the output. */ export type VisitListEntryResult<B extends ts.Node, T extends B> = { node: T; before?: B[]; after?: B[]; }; /** * Visit a node with the given visitor and return a transformed copy. */ export function visit<T extends ts.Node>( node: T, visitor: Visitor, context: ts.TransformationContext, ): T { return visitor._visit(node, context); } /** * Abstract base class for visitors, which processes certain nodes specially to allow insertion * of other nodes before them. */ export abstract class Visitor { /** * Maps statements to an array of statements that should be inserted before them. */ private _before = new Map<ts.Node, ts.Statement[]>(); /** * Maps statements to an array of statements that should be inserted after them. */ private _after = new Map<ts.Node, ts.Statement[]>(); /** * Visit a class declaration, returning at least the transformed declaration and optionally other * nodes to insert before the declaration. */ abstract visitClassDeclaration( node: ts.ClassDeclaration, ): VisitListEntryResult<ts.Statement, ts.ClassDeclaration>; private _visitListEntryNode<T extends ts.Statement>( node: T, visitor: (node: T) => VisitListEntryResult<ts.Statement, T>, ): T { const result = visitor(node); if (result.before !== undefined) { // Record that some nodes should be inserted before the given declaration. The declaration's // parent's _visit call is responsible for performing this insertion. this._before.set(result.node, result.before); } if (result.after !== undefined) { // Same with nodes that should be inserted after. this._after.set(result.node, result.after); } return result.node; } /** * Visit types of nodes which don't have their own explicit visitor. */ visitOtherNode<T extends ts.Node>(node: T): T { return node; } /** * @internal */ _visit<T extends ts.Node>(node: T, context: ts.TransformationContext): T { // First, visit the node. visitedNode starts off as `null` but should be set after visiting // is completed. let visitedNode: T | null = null; node = ts.visitEachChild(node, (child) => child && this._visit(child, context), context) as T; if (ts.isClassDeclaration(node)) { visitedNode = this._visitListEntryNode(node, (node: ts.ClassDeclaration) => this.visitClassDeclaration(node), ) as typeof node; } else { visitedNode = this.visitOtherNode(node); } // If the visited node has a `statements` array then process them, maybe replacing the visited // node and adding additional statements. if (visitedNode && (ts.isBlock(visitedNode) || ts.isSourceFile(visitedNode))) { visitedNode = this._maybeProcessStatements(visitedNode); } return visitedNode; } private _maybeProcessStatements<T extends ts.Block | ts.SourceFile>(node: T): T { // Shortcut - if every statement doesn't require nodes to be prepended or appended, // this is a no-op. if (node.statements.every((stmt) => !this._before.has(stmt) && !this._after.has(stmt))) { return node; } // Build a new list of statements and patch it onto the clone. const newStatements: ts.Statement[] = []; node.statements.forEach((stmt) => { if (this._before.has(stmt)) { newStatements.push(...(this._before.get(stmt)! as ts.Statement[])); this._before.delete(stmt); } newStatements.push(stmt); if (this._after.has(stmt)) { newStatements.push(...(this._after.get(stmt)! as ts.Statement[])); this._after.delete(stmt); } }); const statementsArray = ts.factory.createNodeArray( newStatements, node.statements.hasTrailingComma, ); if (ts.isBlock(node)) { return ts.factory.updateBlock(node, statementsArray) as T; } else { return ts.factory.updateSourceFile( node, statementsArray, node.isDeclarationFile, node.referencedFiles, node.typeReferenceDirectives, node.hasNoDefaultLib, node.libReferenceDirectives, ) as T; } } }
{ "end_byte": 4561, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/src/visitor.ts" }
angular/packages/compiler-cli/src/ngtsc/util/src/typescript.ts_0_7683
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const TS = /\.tsx?$/i; const D_TS = /\.d\.ts$/i; import ts from 'typescript'; import {AbsoluteFsPath, getFileSystem} from '../../file_system'; import {DeclarationNode} from '../../reflection'; /** * Type describing a symbol that is guaranteed to have a value declaration. */ export type SymbolWithValueDeclaration = ts.Symbol & { valueDeclaration: ts.Declaration; declarations: ts.Declaration[]; }; export function isSymbolWithValueDeclaration( symbol: ts.Symbol | null | undefined, ): symbol is SymbolWithValueDeclaration { // If there is a value declaration set, then the `declarations` property is never undefined. We // still check for the property to exist as this matches with the type that `symbol` is narrowed // to. return ( symbol != null && symbol.valueDeclaration !== undefined && symbol.declarations !== undefined ); } export function isDtsPath(filePath: string): boolean { return D_TS.test(filePath); } export function isNonDeclarationTsPath(filePath: string): boolean { return TS.test(filePath) && !D_TS.test(filePath); } export function isFromDtsFile(node: ts.Node): boolean { let sf: ts.SourceFile | undefined = node.getSourceFile(); if (sf === undefined) { sf = ts.getOriginalNode(node).getSourceFile(); } return sf !== undefined && sf.isDeclarationFile; } export function nodeNameForError(node: ts.Node & {name?: ts.Node}): string { if (node.name !== undefined && ts.isIdentifier(node.name)) { return node.name.text; } else { const kind = ts.SyntaxKind[node.kind]; const {line, character} = ts.getLineAndCharacterOfPosition( node.getSourceFile(), node.getStart(), ); return `${kind}@${line}:${character}`; } } export function getSourceFile(node: ts.Node): ts.SourceFile { // In certain transformation contexts, `ts.Node.getSourceFile()` can actually return `undefined`, // despite the type signature not allowing it. In that event, get the `ts.SourceFile` via the // original node instead (which works). const directSf = node.getSourceFile() as ts.SourceFile | undefined; return directSf !== undefined ? directSf : ts.getOriginalNode(node).getSourceFile(); } export function getSourceFileOrNull( program: ts.Program, fileName: AbsoluteFsPath, ): ts.SourceFile | null { return program.getSourceFile(fileName) || null; } export function getTokenAtPosition(sf: ts.SourceFile, pos: number): ts.Node { // getTokenAtPosition is part of TypeScript's private API. return (ts as any).getTokenAtPosition(sf, pos); } export function identifierOfNode(decl: ts.Node & {name?: ts.Node}): ts.Identifier | null { if (decl.name !== undefined && ts.isIdentifier(decl.name)) { return decl.name; } else { return null; } } export function isDeclaration(node: ts.Node): node is ts.Declaration { return isValueDeclaration(node) || isTypeDeclaration(node); } export function isValueDeclaration( node: ts.Node, ): node is ts.ClassDeclaration | ts.FunctionDeclaration | ts.VariableDeclaration { return ( ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node) ); } export function isTypeDeclaration( node: ts.Node, ): node is ts.EnumDeclaration | ts.TypeAliasDeclaration | ts.InterfaceDeclaration { return ( ts.isEnumDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node) ); } export function isNamedDeclaration(node: ts.Node): node is ts.Declaration & {name: ts.Identifier} { const namedNode = node as {name?: ts.Identifier}; return namedNode.name !== undefined && ts.isIdentifier(namedNode.name); } export function isExported(node: DeclarationNode): boolean { let topLevel: ts.Node = node; if (ts.isVariableDeclaration(node) && ts.isVariableDeclarationList(node.parent)) { topLevel = node.parent.parent; } const modifiers = ts.canHaveModifiers(topLevel) ? ts.getModifiers(topLevel) : undefined; return ( modifiers !== undefined && modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ); } export function getRootDirs( host: Pick<ts.CompilerHost, 'getCurrentDirectory' | 'getCanonicalFileName'>, options: ts.CompilerOptions, ): AbsoluteFsPath[] { const rootDirs: string[] = []; const cwd = host.getCurrentDirectory(); const fs = getFileSystem(); if (options.rootDirs !== undefined) { rootDirs.push(...options.rootDirs); } else if (options.rootDir !== undefined) { rootDirs.push(options.rootDir); } else { rootDirs.push(cwd); } // In Windows the above might not always return posix separated paths // See: // https://github.com/Microsoft/TypeScript/blob/3f7357d37f66c842d70d835bc925ec2a873ecfec/src/compiler/sys.ts#L650 // Also compiler options might be set via an API which doesn't normalize paths return rootDirs.map((rootDir) => fs.resolve(cwd, host.getCanonicalFileName(rootDir))); } export function nodeDebugInfo(node: ts.Node): string { const sf = getSourceFile(node); const {line, character} = ts.getLineAndCharacterOfPosition(sf, node.pos); return `[${sf.fileName}: ${ts.SyntaxKind[node.kind]} @ ${line}:${character}]`; } /** * Resolve the specified `moduleName` using the given `compilerOptions` and `compilerHost`. * * This helper will attempt to use the `CompilerHost.resolveModuleNames()` method if available. * Otherwise it will fallback on the `ts.ResolveModuleName()` function. */ export function resolveModuleName( moduleName: string, containingFile: string, compilerOptions: ts.CompilerOptions, compilerHost: ts.ModuleResolutionHost & Pick<ts.CompilerHost, 'resolveModuleNames'>, moduleResolutionCache: ts.ModuleResolutionCache | null, ): ts.ResolvedModule | undefined { if (compilerHost.resolveModuleNames) { return compilerHost.resolveModuleNames( [moduleName], containingFile, undefined, // reusedNames undefined, // redirectedReference compilerOptions, )[0]; } else { return ts.resolveModuleName( moduleName, containingFile, compilerOptions, compilerHost, moduleResolutionCache !== null ? moduleResolutionCache : undefined, ).resolvedModule; } } /** Returns true if the node is an assignment expression. */ export function isAssignment(node: ts.Node): node is ts.BinaryExpression { return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken; } /** * Asserts that the keys `K` form a subset of the keys of `T`. */ export type SubsetOfKeys<T, K extends keyof T> = K; /** * Represents the type `T`, with a transformation applied that turns all methods (even optional * ones) into required fields (which may be `undefined`, if the method was optional). */ export type RequiredDelegations<T> = { [M in keyof Required<T>]: T[M]; }; /** * Source files may become redirects to other source files when their package name and version are * identical. TypeScript creates a proxy source file for such source files which has an internal * `redirectInfo` property that refers to the original source file. */ interface RedirectedSourceFile extends ts.SourceFile { redirectInfo?: {unredirected: ts.SourceFile}; } /** * Obtains the non-redirected source file for `sf`. */ export function toUnredirectedSourceFile(sf: ts.SourceFile): ts.SourceFile { const redirectInfo = (sf as RedirectedSourceFile).redirectInfo; if (redirectInfo === undefined) { return sf; } return redirectInfo.unredirected; }
{ "end_byte": 7683, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/util/src/typescript.ts" }
angular/packages/compiler-cli/src/ngtsc/hmr/BUILD.bazel_0_520
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "hmr", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 520, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/hmr/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/hmr/index.ts_0_278
/*! * @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 './src/metadata'; export * from './src/update_declaration';
{ "end_byte": 278, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/hmr/index.ts" }
angular/packages/compiler-cli/src/ngtsc/hmr/src/update_declaration.ts_0_2283
/*! * @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 {compileHmrUpdateCallback, R3HmrMetadata, outputAst as o} from '@angular/compiler'; import {CompileResult} from '../../transform'; import { ImportManager, presetImportManagerForceNamespaceImports, translateStatement, } from '../../translator'; import ts from 'typescript'; /** * Gets the declaration for the function that replaces the metadata of a class during HMR. * @param compilationResults Code generated for the class during compilation. * @param meta HMR metadata about the class. * @param sourceFile File in which the class is defined. */ export function getHmrUpdateDeclaration( compilationResults: CompileResult[], constantStatements: o.Statement[], meta: R3HmrMetadata, sourceFile: ts.SourceFile, ): ts.FunctionDeclaration { const importRewriter = new HmrModuleImportRewriter(meta.coreName); const importManager = new ImportManager({ ...presetImportManagerForceNamespaceImports, rewriter: importRewriter, }); const callback = compileHmrUpdateCallback(compilationResults, constantStatements, meta); const node = translateStatement(sourceFile, callback, importManager) as ts.FunctionDeclaration; // The output AST doesn't support modifiers so we have to emit to // TS and then update the declaration to add `export default`. return ts.factory.updateFunctionDeclaration( node, [ ts.factory.createToken(ts.SyntaxKind.ExportKeyword), ts.factory.createToken(ts.SyntaxKind.DefaultKeyword), ], node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body, ); } /** Rewriter that replaces namespace imports to `@angular/core` with a specifier identifier. */ class HmrModuleImportRewriter { constructor(private readonly coreName: string) {} rewriteNamespaceImportIdentifier(specifier: string, moduleName: string): string { return moduleName === '@angular/core' ? this.coreName : specifier; } rewriteSymbol(symbol: string): string { return symbol; } rewriteSpecifier(specifier: string): string { return specifier; } }
{ "end_byte": 2283, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/hmr/src/update_declaration.ts" }
angular/packages/compiler-cli/src/ngtsc/hmr/src/metadata.ts_0_1905
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {R3CompiledExpression, R3HmrMetadata, outputAst as o} from '@angular/compiler'; import {DeclarationNode, ReflectionHost} from '../../reflection'; import {getProjectRelativePath} from '../../util/src/path'; import {CompileResult} from '../../transform'; import {extractHmrLocals} from './extract_locals'; import ts from 'typescript'; /** * Extracts the HMR metadata for a class declaration. * @param clazz Class being analyzed. * @param reflection Reflection host. * @param compilerHost Compiler host to use when resolving file names. * @param rootDirs Root directories configured by the user. * @param definition Analyzed component definition. * @param factory Analyzed component factory. * @param classMetadata Analyzed `setClassMetadata` expression, if any. * @param debugInfo Analyzed `setClassDebugInfo` expression, if any. */ export function extractHmrMetatadata( clazz: DeclarationNode, reflection: ReflectionHost, compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, rootDirs: readonly string[], definition: R3CompiledExpression, factory: CompileResult, classMetadata: o.Statement | null, debugInfo: o.Statement | null, ): R3HmrMetadata | null { if (!reflection.isClass(clazz)) { return null; } const sourceFile = clazz.getSourceFile(); const filePath = getProjectRelativePath(sourceFile, rootDirs, compilerHost) || compilerHost.getCanonicalFileName(sourceFile.fileName); const meta: R3HmrMetadata = { type: new o.WrappedNodeExpr(clazz.name), className: clazz.name.text, filePath, locals: extractHmrLocals(clazz, definition, factory, classMetadata, debugInfo), coreName: '__ngCore__', }; return meta; }
{ "end_byte": 1905, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/hmr/src/metadata.ts" }
angular/packages/compiler-cli/src/ngtsc/hmr/src/extract_locals.ts_0_8029
/*! * @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 {R3CompiledExpression, outputAst as o} from '@angular/compiler'; import {DeclarationNode} from '../../reflection'; import {CompileResult} from '../../transform'; import ts from 'typescript'; /** * Determines the names of the file-level locals that the HMR * initializer needs to capture and pass along. * @param sourceFile File in which the file is being compiled. * @param definition Compiled component definition. * @param factory Compiled component factory. * @param classMetadata Compiled `setClassMetadata` expression, if any. * @param debugInfo Compiled `setClassDebugInfo` expression, if any. */ export function extractHmrLocals( node: DeclarationNode, definition: R3CompiledExpression, factory: CompileResult, classMetadata: o.Statement | null, debugInfo: o.Statement | null, ): string[] { const name = ts.isClassDeclaration(node) && node.name ? node.name.text : null; const visitor = new PotentialTopLevelReadsVisitor(); const sourceFile = node.getSourceFile(); // Visit all of the compiled expression to look for potential // local references that would have to be retained. definition.expression.visitExpression(visitor, null); definition.statements.forEach((statement) => statement.visitStatement(visitor, null)); factory.initializer?.visitExpression(visitor, null); factory.statements.forEach((statement) => statement.visitStatement(visitor, null)); classMetadata?.visitStatement(visitor, null); debugInfo?.visitStatement(visitor, null); // Filter out only the references to defined top-level symbols. This allows us to ignore local // variables inside of functions. Note that we filter out the class name since it is always // defined and it saves us having to repeat this logic wherever the locals are consumed. const availableTopLevel = getTopLevelDeclarationNames(sourceFile); return Array.from(visitor.allReads).filter((r) => r !== name && availableTopLevel.has(r)); } /** * Gets the names of all top-level declarations within the file (imports, declared classes etc). * @param sourceFile File in which to search for locals. */ function getTopLevelDeclarationNames(sourceFile: ts.SourceFile): Set<string> { const results = new Set<string>(); // Only look through the top-level statements. for (const node of sourceFile.statements) { // Class, function and const enum declarations need to be captured since they correspond // to runtime code. Intentionally excludes interfaces and type declarations. if ( ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node) || (ts.isEnumDeclaration(node) && !node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ConstKeyword)) ) { if (node.name) { results.add(node.name.text); } continue; } // Variable declarations. if (ts.isVariableStatement(node)) { for (const decl of node.declarationList.declarations) { trackBindingName(decl.name, results); } continue; } // Import declarations. if (ts.isImportDeclaration(node) && node.importClause) { const importClause = node.importClause; // Skip over type-only imports since they won't be emitted to JS. if (importClause.isTypeOnly) { continue; } // import foo from 'foo' if (importClause.name) { results.add(importClause.name.text); } if (importClause.namedBindings) { const namedBindings = importClause.namedBindings; if (ts.isNamespaceImport(namedBindings)) { // import * as foo from 'foo'; results.add(namedBindings.name.text); } else { // import {foo} from 'foo'; namedBindings.elements.forEach((el) => { if (!el.isTypeOnly) { results.add(el.name.text); } }); } } continue; } } return results; } /** * Adds all the variables declared through a `ts.BindingName` to a set of results. * @param node Node from which to start searching for variables. * @param results Set to which to add the matches. */ function trackBindingName(node: ts.BindingName, results: Set<string>): void { if (ts.isIdentifier(node)) { results.add(node.text); } else { for (const el of node.elements) { if (!ts.isOmittedExpression(el)) { trackBindingName(el.name, results); } } } } /** * Visitor that will traverse an AST looking for potential top-level variable reads. * The reads are "potential", because the visitor doesn't account for local variables * inside functions. */ class PotentialTopLevelReadsVisitor extends o.RecursiveAstVisitor { readonly allReads = new Set<string>(); override visitReadVarExpr(ast: o.ReadVarExpr, context: any) { this.allReads.add(ast.name); super.visitReadVarExpr(ast, context); } override visitWrappedNodeExpr(ast: o.WrappedNodeExpr<unknown>, context: any) { if (this.isTypeScriptNode(ast.node)) { this.addAllTopLevelIdentifiers(ast.node); } super.visitWrappedNodeExpr(ast, context); } /** * Traverses a TypeScript AST and tracks all the top-level reads. * @param node Node from which to start the traversal. */ private addAllTopLevelIdentifiers = (node: ts.Node) => { if (ts.isIdentifier(node) && this.isTopLevelIdentifierReference(node)) { this.allReads.add(node.text); } else { ts.forEachChild(node, this.addAllTopLevelIdentifiers); } }; /** * TypeScript identifiers are used both when referring to a variable (e.g. `console.log(foo)`) * and for names (e.g. `{foo: 123}`). This function determines if the identifier is a top-level * variable read, rather than a nested name. * @param node Identifier to check. */ private isTopLevelIdentifierReference(node: ts.Identifier): boolean { const parent = node.parent; // The parent might be undefined for a synthetic node or if `setParentNodes` is set to false // when the SourceFile was created. We can account for such cases using the type checker, at // the expense of performance. At the moment of writing, we're keeping it simple since the // compiler sets `setParentNodes: true`. if (!parent) { return false; } // Identifier referenced at the top level. Unlikely. if ( ts.isSourceFile(parent) || (ts.isExpressionStatement(parent) && parent.expression === node) ) { return true; } // Identifier used inside a call is only top-level if it's an argument. // This also covers decorators since their expression is usually a call. if (ts.isCallExpression(parent)) { return parent.expression === node || parent.arguments.includes(node); } // Identifier used in a property read is only top-level if it's the expression. if (ts.isPropertyAccessExpression(parent)) { return parent.expression === node; } // Identifier used in an array is only top-level if it's one of the elements. if (ts.isArrayLiteralExpression(parent)) { return parent.elements.includes(node); } // Identifier in a property assignment is only top level if it's the initializer. if (ts.isPropertyAssignment(parent)) { return parent.initializer === node; } // Identifier in a class is only top level if it's the name. if (ts.isClassDeclaration(parent)) { return parent.name === node; } // Otherwise it's not top-level. return false; } /** Checks if a value is a TypeScript AST node. */ private isTypeScriptNode(value: any): value is ts.Node { // If this is too permissive, we can also check for `getSourceFile`. This code runs // on a narrow set of use cases so checking for `kind` should be enough. return !!value && typeof value.kind === 'number'; } }
{ "end_byte": 8029, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/hmr/src/extract_locals.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/BUILD.bazel_0_690
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "partial_evaluator", srcs = ["index.ts"] + glob([ "src/*.ts", ]), module_name = "@angular/compiler-cli/src/ngtsc/partial_evaluator", deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 690, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/index.ts_0_614
/** * @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 {describeResolvedType, traceDynamicValue} from './src/diagnostics'; export {DynamicValue} from './src/dynamic'; export {ForeignFunctionResolver, PartialEvaluator} from './src/interface'; export {StaticInterpreter} from './src/interpreter'; export { EnumValue, KnownFn, ResolvedValue, ResolvedValueArray, ResolvedValueMap, } from './src/result'; export {SyntheticValue} from './src/synthetic';
{ "end_byte": 614, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/index.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts_0_4231
/** * @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 {platform} from 'os'; import ts from 'typescript'; import {absoluteFrom as _, absoluteFromSourceFile} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {Reference} from '../../imports'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {StringConcatBuiltinFn} from '../src/builtin'; import {describeResolvedType, traceDynamicValue} from '../src/diagnostics'; import {DynamicValue} from '../src/dynamic'; import {PartialEvaluator} from '../src/interface'; import {EnumValue, ResolvedModule} from '../src/result'; runInEachFileSystem((os) => { describe('partial evaluator', () => { describe('describeResolvedType()', () => { it('should describe primitives', () => { expect(describeResolvedType(0)).toBe('number'); expect(describeResolvedType(true)).toBe('boolean'); expect(describeResolvedType(false)).toBe('boolean'); expect(describeResolvedType(null)).toBe('null'); expect(describeResolvedType(undefined)).toBe('undefined'); expect(describeResolvedType('text')).toBe('string'); }); it('should describe objects limited to a single level', () => { expect(describeResolvedType(new Map())).toBe('{}'); expect( describeResolvedType( new Map<string, any>([ ['a', 0], ['b', true], ]), ), ).toBe('{ a: number; b: boolean }'); expect(describeResolvedType(new Map([['a', new Map()]]))).toBe('{ a: object }'); expect(describeResolvedType(new Map([['a', [1, 2, 3]]]))).toBe('{ a: Array }'); }); it('should describe arrays limited to a single level', () => { expect(describeResolvedType([])).toBe('[]'); expect(describeResolvedType([1, 2, 3])).toBe('[number, number, number]'); expect( describeResolvedType([ [1, 2], [3, 4], ]), ).toBe('[Array, Array]'); expect(describeResolvedType([new Map([['a', 0]])])).toBe('[object]'); }); it('should describe references', () => { const namedFn = ts.factory.createFunctionDeclaration( /* modifiers */ undefined, /* asteriskToken */ undefined, /* name */ 'test', /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, /* body */ undefined, ); expect(describeResolvedType(new Reference(namedFn))).toBe('test'); const anonymousFn = ts.factory.createFunctionDeclaration( /* modifiers */ undefined, /* asteriskToken */ undefined, /* name */ undefined, /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, /* body */ undefined, ); expect(describeResolvedType(new Reference(anonymousFn))).toBe('(anonymous)'); }); it('should describe enum values', () => { const decl = ts.factory.createEnumDeclaration( /* modifiers */ undefined, /* name */ 'MyEnum', /* members */ [ts.factory.createEnumMember('member', ts.factory.createNumericLiteral(1))], ); const ref = new Reference(decl); expect(describeResolvedType(new EnumValue(ref, 'member', 1))).toBe('MyEnum'); }); it('should describe dynamic values', () => { const node = ts.factory.createObjectLiteralExpression(); expect(describeResolvedType(DynamicValue.fromUnsupportedSyntax(node))).toBe( '(not statically analyzable)', ); }); it('should describe known functions', () => { expect(describeResolvedType(new StringConcatBuiltinFn('foo'))).toBe('Function'); }); it('should describe external modules', () => { expect(describeResolvedType(new ResolvedModule(new Map(), () => undefined))).toBe( '(module)', ); }); });
{ "end_byte": 4231, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts_4237_12528
if (os !== 'Windows' && platform() !== 'win32') { describe('traceDynamicValue()', () => { it('should not include the origin node if points to a different dynamic node.', () => { // In the below expression, the read of "value" is evaluated to be dynamic, but it's also // the exact node for which the diagnostic is produced. Therefore, this node is not part // of the trace. const trace = traceExpression('const value = nonexistent;', 'value'); expect(trace.length).toBe(1); expect(trace[0].messageText).toBe(`Unknown reference.`); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('nonexistent'); }); it('should include the origin node if it is dynamic by itself', () => { const trace = traceExpression('', 'nonexistent;'); expect(trace.length).toBe(1); expect(trace[0].messageText).toBe(`Unknown reference.`); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('nonexistent'); }); it('should include a trace for a dynamic subexpression in the origin expression', () => { const trace = traceExpression('const value = nonexistent;', 'value.property'); expect(trace.length).toBe(2); expect(trace[0].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('value'); expect(trace[1].messageText).toBe('Unknown reference.'); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[1])).toBe('nonexistent'); }); it('should reduce the granularity to a single entry per statement', () => { // Dynamic values exist for each node that has been visited, but only the initial dynamic // value within a statement is included in the trace. const trace = traceExpression( `const firstChild = document.body.childNodes[0]; const child = firstChild.firstChild;`, 'child !== undefined', ); expect(trace.length).toBe(4); expect(trace[0].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('child'); expect(trace[1].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[1])).toBe('firstChild'); expect(trace[2].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[2].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[2])).toBe('document.body'); expect(trace[3].messageText).toBe( `A value for 'document' cannot be determined statically, as it is an external declaration.`, ); expect(absoluteFromSourceFile(trace[3].file!)).toBe(_('/lib.d.ts')); expect(getSourceCode(trace[3])).toBe('document: any'); }); it('should trace dynamic strings', () => { const trace = traceExpression('', '`${document}`'); expect(trace.length).toBe(1); expect(trace[0].messageText).toBe('A string value could not be determined statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('document'); }); it('should trace invalid expression types', () => { const trace = traceExpression('', 'true()'); expect(trace.length).toBe(1); expect(trace[0].messageText).toBe('Unable to evaluate an invalid expression.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('true'); }); it('should trace unknown syntax', () => { const trace = traceExpression('', `new String('test')`); expect(trace.length).toBe(1); expect(trace[0].messageText).toBe('This syntax is not supported.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe("new String('test')"); }); it('should trace complex function invocations', () => { const trace = traceExpression( ` function complex() { console.log('test'); return true; }`, 'complex()', ); expect(trace.length).toBe(2); expect(trace[0].messageText).toBe( 'Unable to evaluate function call of complex function. A function must have exactly one return statement.', ); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('complex()'); expect(trace[1].messageText).toBe('Function is declared here.'); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[1])).toContain(`console.log('test');`); }); it('should trace object destructuring of external reference', () => { const trace = traceExpression('const {body: {firstChild}} = document;', 'firstChild'); expect(trace.length).toBe(2); expect(trace[0].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('body: {firstChild}'); expect(trace[1].messageText).toBe( `A value for 'document' cannot be determined statically, as it is an external declaration.`, ); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/lib.d.ts')); expect(getSourceCode(trace[1])).toBe('document: any'); }); it('should trace deep object destructuring of external reference', () => { const trace = traceExpression( 'const {doc: {body: {firstChild}}} = {doc: document};', 'firstChild', ); expect(trace.length).toBe(2); expect(trace[0].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('body: {firstChild}'); expect(trace[1].messageText).toBe( `A value for 'document' cannot be determined statically, as it is an external declaration.`, ); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/lib.d.ts')); expect(getSourceCode(trace[1])).toBe('document: any'); }); it('should trace array destructuring of dynamic value', () => { const trace = traceExpression( 'const [firstChild] = document.body.childNodes;', 'firstChild', ); expect(trace.length).toBe(3); expect(trace[0].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[0].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[0])).toBe('firstChild'); expect(trace[1].messageText).toBe('Unable to evaluate this expression statically.'); expect(absoluteFromSourceFile(trace[1].file!)).toBe(_('/entry.ts')); expect(getSourceCode(trace[1])).toBe('document.body'); expect(trace[2].messageText).toBe( `A value for 'document' cannot be determined statically, as it is an external declaration.`, ); expect(absoluteFromSourceFile(trace[2].file!)).toBe(_('/lib.d.ts')); expect(getSourceCode(trace[2])).toBe('document: any'); }); }); } }); }); function getSourceCode(diag: ts.DiagnosticRelatedInformation): string { const text = diag.file!.text; return text.slice(diag.start!, diag.start! + diag.length!); }
{ "end_byte": 12528, "start_byte": 4237, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts_12530_13432
function traceExpression(code: string, expr: string): ts.DiagnosticRelatedInformation[] { const {program} = makeProgram( [ {name: _('/entry.ts'), contents: `${code}; const target$ = ${expr};`}, {name: _('/lib.d.ts'), contents: `declare const document: any;`}, ], /* options */ undefined, /* host */ undefined, /* checkForErrors */ false, ); const checker = program.getTypeChecker(); const decl = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration); const valueExpr = decl.initializer!; const reflectionHost = new TypeScriptReflectionHost(checker); const evaluator = new PartialEvaluator(reflectionHost, checker, /* dependencyTracker */ null); const value = evaluator.evaluate(valueExpr); if (!(value instanceof DynamicValue)) { throw new Error('Expected DynamicValue'); } return traceDynamicValue(valueExpr, value); }
{ "end_byte": 13432, "start_byte": 12530, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/utils.ts_0_2911
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom} from '../../file_system'; import {TestFile} from '../../file_system/testing'; import {Reference} from '../../imports'; import {DependencyTracker} from '../../incremental/api'; import {TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {ForeignFunctionResolver, PartialEvaluator} from '../src/interface'; import {ResolvedValue} from '../src/result'; export function makeExpression( code: string, expr: string, supportingFiles: TestFile[] = [], ): { expression: ts.Expression; host: ts.CompilerHost; checker: ts.TypeChecker; program: ts.Program; options: ts.CompilerOptions; } { const {program, options, host} = makeProgram([ {name: absoluteFrom('/entry.ts'), contents: `${code}; const target$ = ${expr};`}, ...supportingFiles, ]); const checker = program.getTypeChecker(); const decl = getDeclaration( program, absoluteFrom('/entry.ts'), 'target$', ts.isVariableDeclaration, ); return { expression: decl.initializer!, host, options, checker, program, }; } export function makeEvaluator( checker: ts.TypeChecker, tracker?: DependencyTracker, ): PartialEvaluator { const reflectionHost = new TypeScriptReflectionHost(checker); return new PartialEvaluator(reflectionHost, checker, tracker !== undefined ? tracker : null); } export function evaluate<T extends ResolvedValue>( code: string, expr: string, supportingFiles: TestFile[] = [], foreignFunctionResolver?: ForeignFunctionResolver, ): T { const {expression, checker} = makeExpression(code, expr, supportingFiles); const evaluator = makeEvaluator(checker); return evaluator.evaluate(expression, foreignFunctionResolver) as T; } export function owningModuleOf(ref: Reference): string | null { return ref.bestGuessOwningModule !== null ? ref.bestGuessOwningModule.specifier : null; } export function firstArgFfr( fn: Reference<ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression>, expr: ts.CallExpression, resolve: (expr: ts.Expression) => ResolvedValue, ): ResolvedValue { return resolve(expr.arguments[0]); } export const arrowReturnValueFfr: ForeignFunctionResolver = (_fn, node, resolve) => { // Extracts the `Foo` from `() => Foo`. return resolve((node.arguments[0] as ts.ArrowFunction).body as ts.Expression); }; export const returnTypeFfr: ForeignFunctionResolver = (fn, node, resolve) => { // Extract the `Foo` from the return type of the `external` function declaration. return resolve( ((fn.node as ts.FunctionDeclaration).type as ts.TypeReferenceNode).typeName as ts.Identifier, ); };
{ "end_byte": 2911, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/utils.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/BUILD.bazel_0_873
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 873, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_0_756
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {Reference} from '../../imports'; import {DependencyTracker} from '../../incremental/api'; import {getDeclaration, makeProgram} from '../../testing'; import {DynamicValue} from '../src/dynamic'; import {EnumValue} from '../src/result'; import { arrowReturnValueFfr, evaluate, firstArgFfr, makeEvaluator, makeExpression, owningModuleOf, returnTypeFfr, } from './utils';
{ "end_byte": 756, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_758_6771
runInEachFileSystem(() => { describe('ngtsc metadata', () => { let _: typeof absoluteFrom; beforeEach(() => (_ = absoluteFrom)); it('reads a file correctly', () => { const value = evaluate( ` import {Y} from './other'; const A = Y; `, 'A', [ { name: _('/other.ts'), contents: ` export const Y = 'test'; `, }, ], ); expect(value).toEqual('test'); }); it('map access works', () => { expect(evaluate('const obj = {a: "test"};', 'obj.a')).toEqual('test'); }); it('resolves undefined property access', () => { expect(evaluate('const obj: any = {}', 'obj.bar')).toEqual(undefined); }); it('function calls work', () => { expect(evaluate(`function foo(bar) { return bar; }`, 'foo("test")')).toEqual('test'); }); it('function call default value works', () => { expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo()')).toEqual(1); expect(evaluate(`function foo(bar = 1) { return bar; }`, 'foo(2)')).toEqual(2); expect(evaluate(`function foo(a, c = a) { return c; }; const a = 1;`, 'foo(2)')).toEqual(2); }); it('function call spread works', () => { expect(evaluate(`function foo(a, ...b) { return [a, b]; }`, 'foo(1, ...[2, 3])')).toEqual([ 1, [2, 3], ]); }); it('conditionals work', () => { expect(evaluate(`const x = false; const y = x ? 'true' : 'false';`, 'y')).toEqual('false'); }); it('addition works', () => { expect(evaluate(`const x = 1 + 2;`, 'x')).toEqual(3); }); it('static property on class works', () => { expect(evaluate(`class Foo { static bar = 'test'; }`, 'Foo.bar')).toEqual('test'); }); it('static property call works', () => { expect( evaluate(`class Foo { static bar(test) { return test; } }`, 'Foo.bar("test")'), ).toEqual('test'); }); it('indirected static property call works', () => { expect( evaluate( `class Foo { static bar(test) { return test; } }; const fn = Foo.bar;`, 'fn("test")', ), ).toEqual('test'); }); it('array works', () => { expect(evaluate(`const x = 'test'; const y = [1, x, 2];`, 'y')).toEqual([1, 'test', 2]); }); it('array spread works', () => { expect( evaluate(`const a = [1, 2]; const b = [4, 5]; const c = [...a, 3, ...b];`, 'c'), ).toEqual([1, 2, 3, 4, 5]); }); it('&& operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a && b')).toEqual('world'); expect(evaluate(`const a = false, b = 'world';`, 'a && b')).toEqual(false); expect(evaluate(`const a = 'hello', b = 0;`, 'a && b')).toEqual(0); }); it('|| operations work', () => { expect(evaluate(`const a = 'hello', b = 'world';`, 'a || b')).toEqual('hello'); expect(evaluate(`const a = false, b = 'world';`, 'a || b')).toEqual('world'); expect(evaluate(`const a = 'hello', b = 0;`, 'a || b')).toEqual('hello'); }); it('evaluates arithmetic operators', () => { expect(evaluate('const a = 6, b = 3;', 'a + b')).toEqual(9); expect(evaluate('const a = 6, b = 3;', 'a - b')).toEqual(3); expect(evaluate('const a = 6, b = 3;', 'a * b')).toEqual(18); expect(evaluate('const a = 6, b = 3;', 'a / b')).toEqual(2); expect(evaluate('const a = 6, b = 3;', 'a % b')).toEqual(0); expect(evaluate('const a = 6, b = 3;', 'a & b')).toEqual(2); expect(evaluate('const a = 6, b = 3;', 'a | b')).toEqual(7); expect(evaluate('const a = 6, b = 3;', 'a ^ b')).toEqual(5); expect(evaluate('const a = 6, b = 3;', 'a ** b')).toEqual(216); expect(evaluate('const a = 6, b = 3;', 'a << b')).toEqual(48); expect(evaluate('const a = -6, b = 2;', 'a >> b')).toEqual(-2); expect(evaluate('const a = -6, b = 2;', 'a >>> b')).toEqual(1073741822); }); it('evaluates comparison operators', () => { expect(evaluate('const a = 2, b = 3;', 'a < b')).toEqual(true); expect(evaluate('const a = 3, b = 3;', 'a < b')).toEqual(false); expect(evaluate('const a = 3, b = 3;', 'a <= b')).toEqual(true); expect(evaluate('const a = 4, b = 3;', 'a <= b')).toEqual(false); expect(evaluate('const a = 4, b = 3;', 'a > b')).toEqual(true); expect(evaluate('const a = 3, b = 3;', 'a > b')).toEqual(false); expect(evaluate('const a = 3, b = 3;', 'a >= b')).toEqual(true); expect(evaluate('const a = 2, b = 3;', 'a >= b')).toEqual(false); expect(evaluate('const a: any = 3, b = "3";', 'a == b')).toEqual(true); expect(evaluate('const a: any = 2, b = "3";', 'a == b')).toEqual(false); expect(evaluate('const a: any = 2, b = "3";', 'a != b')).toEqual(true); expect(evaluate('const a: any = 3, b = "3";', 'a != b')).toEqual(false); expect(evaluate('const a: any = 3, b = 3;', 'a === b')).toEqual(true); expect(evaluate('const a: any = 3, b = "3";', 'a === b')).toEqual(false); expect(evaluate('const a: any = 3, b = "3";', 'a !== b')).toEqual(true); expect(evaluate('const a: any = 3, b = 3;', 'a !== b')).toEqual(false); }); it('parentheticals work', () => { expect(evaluate(`const a = 3, b = 4;`, 'a * (a + b)')).toEqual(21); }); it('array access works', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[1] + a[0]')).toEqual(3); }); it('array access out of bounds is `undefined`', () => { expect(evaluate(`const a = [1, 2, 3];`, 'a[-1]')).toEqual(undefined); expect(evaluate(`const a = [1, 2, 3];`, 'a[3]')).toEqual(undefined); }); it('array `length` property access works', () => { expect(evaluate(`const a = [1, 2, 3];`, "a['length'] + 1")).toEqual(4); }); it('array `slice` function works', () => { expect(evaluate(`const a = [1, 2, 3];`, "a['slice']()")).toEqual([1, 2, 3]); });
{ "end_byte": 6771, "start_byte": 758, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_6777_14320
it('array `concat` function works', () => { expect(evaluate(`const a = [1, 2], b = [3, 4];`, "a['concat'](b)")).toEqual([1, 2, 3, 4]); expect(evaluate(`const a = [1, 2], b = 3;`, "a['concat'](b)")).toEqual([1, 2, 3]); expect(evaluate(`const a = [1, 2], b = 3, c = [4, 5];`, "a['concat'](b, c)")).toEqual([ 1, 2, 3, 4, 5, ]); expect(evaluate(`const a = [1, 2], b = [3, 4]`, "a['concat'](...b)")).toEqual([1, 2, 3, 4]); }); it('negation works', () => { expect(evaluate(`const x = 3;`, '!x')).toEqual(false); expect(evaluate(`const x = 3;`, '!!x')).toEqual(true); }); it('supports boolean literals', () => { expect(evaluate('const a = true;', 'a')).toEqual(true); expect(evaluate('const a = false;', 'a')).toEqual(false); }); it('supports undefined', () => { expect(evaluate('const a = undefined;', 'a')).toEqual(undefined); }); it('supports null', () => { expect(evaluate('const a = null;', 'a')).toEqual(null); }); it('supports negative numbers', () => { expect(evaluate('const a = -123;', 'a')).toEqual(-123); }); it('supports destructuring array variable declarations', () => { const code = ` const [a, b, c, d] = [0, 1, 2, 3]; const e = c; `; expect(evaluate(code, 'a')).toBe(0); expect(evaluate(code, 'b')).toBe(1); expect(evaluate(code, 'c')).toBe(2); expect(evaluate(code, 'd')).toBe(3); expect(evaluate(code, 'e')).toBe(2); }); it('supports destructuring object variable declaration', () => { const code = ` const {a, b, c, d} = {a: 0, b: 1, c: 2, d: 3}; const e = c; `; expect(evaluate(code, 'a')).toBe(0); expect(evaluate(code, 'b')).toBe(1); expect(evaluate(code, 'c')).toBe(2); expect(evaluate(code, 'd')).toBe(3); expect(evaluate(code, 'e')).toBe(2); }); it('supports destructuring object variable declaration with an alias', () => { expect(evaluate(`const {a: value} = {a: 5}; const e = value;`, 'e')).toBe(5); }); it('supports nested destructuring object variable declarations', () => { expect(evaluate(`const {a: {b: {c}}} = {a: {b: {c: 0}}};`, 'c')).toBe(0); }); it('supports nested destructuring array variable declarations', () => { expect(evaluate(`const [[[a]]] = [[[1]]];`, 'a')).toBe(1); }); it('supports nested destructuring variable declarations mixing arrays and objects', () => { expect(evaluate(`const {a: {b: [[c]]}} = {a: {b: [[1337]]}};`, 'c')).toBe(1337); }); it('resolves unknown values in a destructured variable declaration as dynamic values', () => { const value = evaluate(`const {a: {body}} = {a: window};`, 'body', [ {name: _('/window.ts'), contents: `declare const window: any;`}, ]); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toBe('body'); }); it('resolves unknown binary operators as dynamic value', () => { const value = evaluate('declare const window: any;', '"location" in window'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('"location" in window'); expect(value.isFromUnsupportedSyntax()).toBe(true); }); it('resolves unknown unary operators as dynamic value', () => { const value = evaluate('let index = 0;', '++index'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('++index'); expect(value.isFromUnsupportedSyntax()).toBe(true); }); it('resolves invalid element accesses as dynamic value', () => { const value = evaluate('const a = {}; const index: any = true;', 'a[index]'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('a[index]'); if (!value.isFromInvalidExpressionType()) { return fail('Should have an invalid expression type as reason'); } expect(value.reason).toEqual(true); }); it('resolves invalid array accesses as dynamic value', () => { const value = evaluate('const a = []; const index = 1.5;', 'a[index]'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('a[index]'); if (!value.isFromInvalidExpressionType()) { return fail('Should have an invalid expression type as reason'); } expect(value.reason).toEqual(1.5); }); it('resolves binary operator on non-literals as dynamic value', () => { const value = evaluate('const a: any = []; const b: any = [];', 'a + b'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('a + b'); if (!(value.reason instanceof DynamicValue)) { return fail(`Should have a DynamicValue as reason`); } if (!value.reason.isFromInvalidExpressionType()) { return fail('Should have an invalid expression type as reason'); } expect(value.reason.node.getText()).toEqual('a'); expect(value.reason.reason).toEqual([]); }); it('resolves invalid spreads in array literals as dynamic value', () => { const array = evaluate('const a: any = true;', '[1, ...a]'); if (!Array.isArray(array)) { return fail(`Should have resolved to an array`); } expect(array[0]).toBe(1); const value = array[1]; if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('...a'); if (!value.isFromInvalidExpressionType()) { return fail('Should have an invalid spread element as reason'); } expect(value.reason).toEqual(true); }); it('resolves invalid spreads in object literals as dynamic value', () => { const value = evaluate('const a: any = true;', '{b: true, ...a}'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('{b: true, ...a}'); if (!value.isFromDynamicInput()) { return fail('Should have a dynamic input as reason'); } expect(value.reason.node.getText()).toEqual('...a'); if (!value.reason.isFromInvalidExpressionType()) { return fail('Should have an invalid spread element as reason'); } expect(value.reason.reason).toEqual(true); }); it('resolves access from external variable declarations as dynamic value', () => { const value = evaluate('declare const window: any;', 'window.location'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.isFromDynamicInput()).toEqual(true); expect(value.node.getText()).toEqual('window.location'); if (!(value.reason instanceof DynamicValue)) { return fail(`Should have a DynamicValue as reason`); } expect(value.reason.isFromExternalReference()).toEqual(true); expect(value.reason.node.getText()).toEqual('window: any'); });
{ "end_byte": 14320, "start_byte": 6777, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_14326_22162
it('supports declarations of primitive constant types', () => { expect(evaluate(`declare const x: 'foo';`, `x`)).toEqual('foo'); expect(evaluate(`declare const x: 42;`, `x`)).toEqual(42); expect(evaluate(`declare const x: null;`, `x`)).toEqual(null); expect(evaluate(`declare const x: true;`, `x`)).toEqual(true); }); it('supports declarations of tuples', () => { expect(evaluate(`declare const x: ['foo', 42, null, true];`, `x`)).toEqual([ 'foo', 42, null, true, ]); expect(evaluate(`declare const x: ['bar'];`, `[...x]`)).toEqual(['bar']); }); // https://github.com/angular/angular/issues/48089 it('supports declarations of readonly tuples with class references', () => { const tuple = evaluate( ` import {External} from 'external'; declare class Local {} declare const x: readonly [typeof External, typeof Local];`, `x`, [ { name: _('/node_modules/external/index.d.ts'), contents: 'export declare class External {}', }, ], ); if (!Array.isArray(tuple)) { return fail('Should have evaluated tuple as an array'); } const [external, local] = tuple; if (!(external instanceof Reference)) { return fail('Should have evaluated `typeof A` to a Reference'); } expect(ts.isClassDeclaration(external.node)).toBe(true); expect(external.debugName).toBe('External'); expect(external.ownedByModuleGuess).toBe('external'); if (!(local instanceof Reference)) { return fail('Should have evaluated `typeof B` to a Reference'); } expect(ts.isClassDeclaration(local.node)).toBe(true); expect(local.debugName).toBe('Local'); expect(local.ownedByModuleGuess).toBeNull(); }); it('evaluates tuple elements it cannot understand to DynamicValue', () => { const value = evaluate(`declare const x: ['foo', string];`, `x`) as [string, DynamicValue]; expect(Array.isArray(value)).toBeTrue(); expect(value[0]).toEqual('foo'); expect(value[1] instanceof DynamicValue).toBeTrue(); expect(value[1].isFromDynamicType()).toBe(true); }); it('imports work', () => { const {program} = makeProgram([ {name: _('/second.ts'), contents: 'export function foo(bar) { return bar; }'}, { name: _('/entry.ts'), contents: ` import {foo} from './second'; const target$ = foo; `, }, ]); const checker = program.getTypeChecker(); const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration); const expr = result.initializer!; const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(getSourceFileOrError(program, _('/entry.ts'))); if (reference === null) { return fail('Expected to get an identifier'); } expect(reference.getSourceFile()).toEqual(getSourceFileOrError(program, _('/entry.ts'))); }); it('absolute imports work', () => { const {program} = makeProgram([ { name: _('/node_modules/some_library/index.d.ts'), contents: 'export declare function foo(bar);', }, { name: _('/entry.ts'), contents: ` import {foo} from 'some_library'; const target$ = foo; `, }, ]); const checker = program.getTypeChecker(); const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration); const expr = result.initializer!; const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to an absolute reference'); } expect(owningModuleOf(resolved)).toBe('some_library'); expect(ts.isFunctionDeclaration(resolved.node)).toBe(true); const reference = resolved.getIdentityIn(getSourceFileOrError(program, _('/entry.ts'))); expect(reference).not.toBeNull(); expect(reference!.getSourceFile()).toEqual(getSourceFileOrError(program, _('/entry.ts'))); }); it('reads values from default exports', () => { const value = evaluate( ` import mod from './second'; `, 'mod.property', [{name: _('/second.ts'), contents: 'export default {property: "test"}'}], ); expect(value).toEqual('test'); }); it('reads values from named exports', () => { const value = evaluate(`import * as mod from './second';`, 'mod.a.property', [ {name: _('/second.ts'), contents: 'export const a = {property: "test"};'}, ]); expect(value).toEqual('test'); }); it('chain of re-exports works', () => { const value = evaluate(`import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: _('/const.ts'), contents: 'export const value = {property: "test"};'}, {name: _('/def.ts'), contents: `import {value} from './const'; export default value;`}, {name: _('/indirect-reexport.ts'), contents: `import value from './def'; export {value};`}, {name: _('/direct-reexport.ts'), contents: `export {value} from './indirect-reexport';`}, ]); expect(value).toEqual('test'); }); it('map spread works', () => { const map: Map<string, number> = evaluate<Map<string, number>>( `const a = {a: 1}; const b = {b: 2, c: 1}; const c = {...a, ...b, c: 3};`, 'c', ); const obj: {[key: string]: number} = {}; map.forEach((value, key) => (obj[key] = value)); expect(obj).toEqual({ a: 1, b: 2, c: 3, }); }); it('module spread works', () => { const map = evaluate<Map<string, number>>( `import * as mod from './module'; const c = {...mod, c: 3};`, 'c', [{name: _('/module.ts'), contents: `export const a = 1; export const b = 2;`}], ); const obj: {[key: string]: number} = {}; map.forEach((value, key) => (obj[key] = value)); expect(obj).toEqual({ a: 1, b: 2, c: 3, }); }); it('evaluates module exports lazily to avoid infinite recursion', () => { const value = evaluate(`import * as mod1 from './mod1';`, 'mod1.primary', [ { name: _('/mod1.ts'), contents: ` import * as mod2 from './mod2'; export const primary = mod2.indirection; export const secondary = 2;`, }, { name: _('/mod2.ts'), contents: `import * as mod1 from './mod1'; export const indirection = mod1.secondary;`, }, ]); expect(value).toEqual(2); }); it('indirected-via-object function call works', () => { expect( evaluate( ` function fn(res) { return res; } const obj = {fn}; `, 'obj.fn("test")', ), ).toEqual('test'); }); it('template expressions work', () => { expect(evaluate('const a = 2, b = 4;', '`1${a}3${b}5`')).toEqual('12345'); }); it('template expressions should resolve enums', () => { expect(evaluate('enum Test { VALUE = "test" };', '`a.${Test.VALUE}.b`')).toBe('a.test.b'); }); it('string concatenation should resolve enums', () => { expect(evaluate('enum Test { VALUE = "test" };', '"a." + Test.VALUE + ".b"')).toBe( 'a.test.b', ); });
{ "end_byte": 22162, "start_byte": 14326, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_22168_30771
it('string `concat` function works', () => { expect(evaluate(`const a = '12', b = '34';`, "a['concat'](b)")).toBe('1234'); expect(evaluate(`const a = '12', b = '3';`, "a['concat'](b)")).toBe('123'); expect(evaluate(`const a = '12', b = '3', c = '45';`, "a['concat'](b,c)")).toBe('12345'); expect( evaluate(`const a = '1', b = 2, c = '3', d = true, e = null;`, "a['concat'](b,c,d,e)"), ).toBe('123truenull'); expect(evaluate('enum Test { VALUE = "test" };', '"a."[\'concat\'](Test.VALUE, ".b")')).toBe( 'a.test.b', ); }); it('should resolve non-literals as dynamic string', () => { const value = evaluate(`const a: any = [];`, '`a.${a}.b`'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } expect(value.node.getText()).toEqual('`a.${a}.b`'); if (!value.isFromDynamicInput()) { return fail('Should originate from dynamic input'); } else if (!value.reason.isFromDynamicString()) { return fail('Should refer to a dynamic string part'); } expect(value.reason.node.getText()).toEqual('a'); }); it('enum resolution works', () => { const result = evaluate( ` enum Foo { A, B, C, } const r = Foo.B; `, 'r', ); if (!(result instanceof EnumValue)) { return fail(`result is not an EnumValue`); } expect((result.enumRef.node as ts.EnumDeclaration).name.text).toBe('Foo'); expect(result.name).toBe('B'); }); it('variable declaration resolution works', () => { const value = evaluate(`import {value} from './decl';`, 'value', [ {name: _('/decl.d.ts'), contents: 'export declare let value: number;'}, ]); expect(value instanceof Reference).toBe(true); }); it('should resolve shorthand properties to values', () => { const {program} = makeProgram([ {name: _('/entry.ts'), contents: `const prop = 42; const target$ = {prop};`}, ]); const checker = program.getTypeChecker(); const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration); const expr = result.initializer! as ts.ObjectLiteralExpression; const prop = expr.properties[0] as ts.ShorthandPropertyAssignment; const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(prop.name); expect(resolved).toBe(42); }); it('should resolve dynamic values in object literals', () => { const {program} = makeProgram([ {name: _('/decl.d.ts'), contents: 'export declare const fn: any;'}, { name: _('/entry.ts'), contents: `import {fn} from './decl'; const prop = fn.foo(); const target$ = {value: prop};`, }, ]); const checker = program.getTypeChecker(); const result = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration); const expr = result.initializer! as ts.ObjectLiteralExpression; const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(expr); if (!(resolved instanceof Map)) { return fail('Should have resolved to a Map'); } const value = resolved.get('value')!; if (!(value instanceof DynamicValue)) { return fail(`Should have resolved 'value' to a DynamicValue`); } const prop = expr.properties[0] as ts.PropertyAssignment; expect(value.node).toBe(prop.initializer); }); it('should not attach identifiers to FFR-resolved values', () => { const value = evaluate( ` declare function foo(arg: any): any; class Target {} const indir = foo(Target); const value = indir; `, 'value', [], firstArgFfr, ); if (!(value instanceof Reference)) { return fail('Expected value to be a Reference'); } const id = value.getIdentityIn(value.node.getSourceFile()); if (id === null) { return fail('Expected value to have an identity'); } expect(id.text).toEqual('Target'); }); it('should not associate an owning module when a FFR-resolved expression is within the originating source file', () => { const resolved = evaluate( `import {forwardRef} from 'forward'; class Foo {}`, 'forwardRef(() => Foo)', [ { name: _('/node_modules/forward/index.d.ts'), contents: `export declare function forwardRef<T>(fn: () => T): T;`, }, ], arrowReturnValueFfr, ); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect((resolved.node as ts.ClassDeclaration).name!.text).toBe('Foo'); expect(resolved.bestGuessOwningModule).toBeNull(); }); it('should not associate an owning module when a FFR-resolved expression is imported using a relative import', () => { const resolved = evaluate( `import {forwardRef} from 'forward'; import {Foo} from './foo';`, 'forwardRef(() => Foo)', [ { name: _('/node_modules/forward/index.d.ts'), contents: `export declare function forwardRef<T>(fn: () => T): T;`, }, { name: _('/foo.ts'), contents: `export class Foo {}`, }, ], arrowReturnValueFfr, ); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect((resolved.node as ts.ClassDeclaration).name!.text).toBe('Foo'); expect(resolved.bestGuessOwningModule).toBeNull(); }); it('should associate an owning module when a FFR-resolved expression is imported using an absolute import', () => { const {expression, checker} = makeExpression( `import {forwardRef} from 'forward'; import {Foo} from 'external';`, `forwardRef(() => Foo)`, [ { name: _('/node_modules/forward/index.d.ts'), contents: `export declare function forwardRef<T>(fn: () => T): T;`, }, { name: _('/node_modules/external/index.d.ts'), contents: `export declare class Foo {}`, }, ], ); const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(expression, arrowReturnValueFfr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect((resolved.node as ts.ClassDeclaration).name!.text).toBe('Foo'); expect(resolved.bestGuessOwningModule).toEqual({ specifier: 'external', resolutionContext: expression.getSourceFile().fileName, }); }); it('should associate an owning module when a FFR-resolved expression is within the foreign file', () => { const {expression, checker} = makeExpression( `import {external} from 'external';`, `external()`, [ { name: _('/node_modules/external/index.d.ts'), contents: ` export declare class Foo {} export declare function external(): Foo; `, }, ], ); const evaluator = makeEvaluator(checker); const resolved = evaluator.evaluate(expression, returnTypeFfr); if (!(resolved instanceof Reference)) { return fail('Expected expression to resolve to a reference'); } expect((resolved.node as ts.ClassDeclaration).name!.text).toBe('Foo'); expect(resolved.bestGuessOwningModule).toEqual({ specifier: 'external', resolutionContext: expression.getSourceFile().fileName, }); }); it('should resolve functions with more than one statement to a complex function call', () => { const value = evaluate(`function foo(bar) { const b = bar; return b; }`, 'foo("test")'); if (!(value instanceof DynamicValue)) { return fail(`Should have resolved to a DynamicValue`); } if (!value.isFromComplexFunctionCall()) { return fail('Expected DynamicValue to be from complex function call'); } expect((value.node as ts.CallExpression).expression.getText()).toBe('foo'); expect((value.reason.node as ts.FunctionDeclaration).getText()).toContain( 'const b = bar; return b;', ); });
{ "end_byte": 30771, "start_byte": 22168, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts_30777_34824
describe('(visited file tracking)', () => { it('should track each time a source file is visited', () => { const addDependency = jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker'); const {expression, checker, program} = makeExpression( `class A { static foo = 42; } function bar() { return A.foo; }`, 'bar()', ); const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName; const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency}); evaluator.evaluate(expression); expect(addDependency).toHaveBeenCalledTimes(2); // two declaration visited expect( addDependency.calls .allArgs() .map((args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]), ).toEqual([ [entryPath, entryPath], [entryPath, entryPath], ]); }); it('should track imported source files', () => { const addDependency = jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker'); const {expression, checker, program} = makeExpression( `import {Y} from './other'; const A = Y;`, 'A', [ {name: _('/other.ts'), contents: `export const Y = 'test';`}, {name: _('/not-visited.ts'), contents: `export const Z = 'nope';`}, ], ); const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName; const otherPath = getSourceFileOrError(program, _('/other.ts')).fileName; const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency}); evaluator.evaluate(expression); expect(addDependency).toHaveBeenCalledTimes(2); expect( addDependency.calls .allArgs() .map((args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]), ).toEqual([ [entryPath, entryPath], [entryPath, otherPath], ]); }); it('should track files passed through during re-exports', () => { const addDependency = jasmine.createSpy<DependencyTracker['addDependency']>('DependencyTracker'); const {expression, checker, program} = makeExpression( `import * as mod from './direct-reexport';`, 'mod.value.property', [ {name: _('/const.ts'), contents: 'export const value = {property: "test"};'}, { name: _('/def.ts'), contents: `import {value} from './const'; export default value;`, }, { name: _('/indirect-reexport.ts'), contents: `import value from './def'; export {value};`, }, { name: _('/direct-reexport.ts'), contents: `export {value} from './indirect-reexport';`, }, ], ); const evaluator = makeEvaluator(checker, {...fakeDepTracker, addDependency}); const entryPath = getSourceFileOrError(program, _('/entry.ts')).fileName; const directReexportPath = getSourceFileOrError(program, _('/direct-reexport.ts')).fileName; const constPath = getSourceFileOrError(program, _('/const.ts')).fileName; evaluator.evaluate(expression); expect(addDependency).toHaveBeenCalledTimes(2); expect( addDependency.calls .allArgs() .map((args: Parameters<typeof addDependency>) => [args[0].fileName, args[1].fileName]), ).toEqual([ [entryPath, directReexportPath], // Not '/indirect-reexport.ts' or '/def.ts'. // TS skips through them when finding the original symbol for `value` [entryPath, constPath], ]); }); }); }); }); const fakeDepTracker: DependencyTracker = { addDependency: () => undefined, addResourceDependency: () => undefined, recordDependencyAnalysisFailure: () => undefined, };
{ "end_byte": 34824, "start_byte": 30777, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/test/evaluator_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/builtin.ts_0_1986
/** * @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 {DynamicValue} from './dynamic'; import {EnumValue, KnownFn, ResolvedValue, ResolvedValueArray} from './result'; export class ArraySliceBuiltinFn extends KnownFn { constructor(private lhs: ResolvedValueArray) { super(); } override evaluate(node: ts.CallExpression, args: ResolvedValueArray): ResolvedValue { if (args.length === 0) { return this.lhs; } else { return DynamicValue.fromUnknown(node); } } } export class ArrayConcatBuiltinFn extends KnownFn { constructor(private lhs: ResolvedValueArray) { super(); } override evaluate(node: ts.CallExpression, args: ResolvedValueArray): ResolvedValue { const result: ResolvedValueArray = [...this.lhs]; for (const arg of args) { if (arg instanceof DynamicValue) { result.push(DynamicValue.fromDynamicInput(node, arg)); } else if (Array.isArray(arg)) { result.push(...arg); } else { result.push(arg); } } return result; } } export class StringConcatBuiltinFn extends KnownFn { constructor(private lhs: string) { super(); } override evaluate(node: ts.CallExpression, args: ResolvedValueArray): ResolvedValue { let result = this.lhs; for (const arg of args) { const resolved = arg instanceof EnumValue ? arg.resolved : arg; if ( typeof resolved === 'string' || typeof resolved === 'number' || typeof resolved === 'boolean' || resolved == null ) { // Cast to `any`, because `concat` will convert // anything to a string, but TS only allows strings. result = result.concat(resolved as any); } else { return DynamicValue.fromUnknown(node); } } return result; } }
{ "end_byte": 1986, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/builtin.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts_0_3725
/** * @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 {Reference} from '../../imports'; import {OwningModule} from '../../imports/src/references'; import {DependencyTracker} from '../../incremental/api'; import {Declaration, DeclarationNode, FunctionDefinition, ReflectionHost} from '../../reflection'; import {isDeclaration} from '../../util/src/typescript'; import {ArrayConcatBuiltinFn, ArraySliceBuiltinFn, StringConcatBuiltinFn} from './builtin'; import {DynamicValue} from './dynamic'; import {ForeignFunctionResolver} from './interface'; import { EnumValue, KnownFn, ResolvedModule, ResolvedValue, ResolvedValueArray, ResolvedValueMap, } from './result'; import {SyntheticValue} from './synthetic'; /** * Tracks the scope of a function body, which includes `ResolvedValue`s for the parameters of that * body. */ type Scope = Map<ts.ParameterDeclaration, ResolvedValue>; interface BinaryOperatorDef { literal: boolean; op: (a: any, b: any) => ResolvedValue; } function literalBinaryOp(op: (a: any, b: any) => any): BinaryOperatorDef { return {op, literal: true}; } function referenceBinaryOp(op: (a: any, b: any) => any): BinaryOperatorDef { return {op, literal: false}; } const BINARY_OPERATORS = new Map<ts.SyntaxKind, BinaryOperatorDef>([ [ts.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)], [ts.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)], [ts.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)], [ts.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)], [ts.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)], [ts.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)], [ts.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)], [ts.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)], [ts.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)], [ts.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)], [ts.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)], [ts.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)], [ts.SyntaxKind.EqualsEqualsToken, literalBinaryOp((a, b) => a == b)], [ts.SyntaxKind.EqualsEqualsEqualsToken, literalBinaryOp((a, b) => a === b)], [ts.SyntaxKind.ExclamationEqualsToken, literalBinaryOp((a, b) => a != b)], [ts.SyntaxKind.ExclamationEqualsEqualsToken, literalBinaryOp((a, b) => a !== b)], [ts.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)], [ts.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)], [ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)], [ts.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))], [ts.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)], [ts.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)], ]); const UNARY_OPERATORS = new Map<ts.SyntaxKind, (a: any) => any>([ [ts.SyntaxKind.TildeToken, (a) => ~a], [ts.SyntaxKind.MinusToken, (a) => -a], [ts.SyntaxKind.PlusToken, (a) => +a], [ts.SyntaxKind.ExclamationToken, (a) => !a], ]); interface Context { originatingFile: ts.SourceFile; /** * The module name (if any) which was used to reach the currently resolving symbols. */ absoluteModuleName: string | null; /** * A file name representing the context in which the current `absoluteModuleName`, if any, was * resolved. */ resolutionContext: string; scope: Scope; foreignFunctionResolver?: ForeignFunctionResolver; }
{ "end_byte": 3725, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts_3726_11911
export class StaticInterpreter { constructor( private host: ReflectionHost, private checker: ts.TypeChecker, private dependencyTracker: DependencyTracker | null, ) {} visit(node: ts.Expression, context: Context): ResolvedValue { return this.visitExpression(node, context); } private visitExpression(node: ts.Expression, context: Context): ResolvedValue { let result: ResolvedValue; if (node.kind === ts.SyntaxKind.TrueKeyword) { return true; } else if (node.kind === ts.SyntaxKind.FalseKeyword) { return false; } else if (node.kind === ts.SyntaxKind.NullKeyword) { return null; } else if (ts.isStringLiteral(node)) { return node.text; } else if (ts.isNoSubstitutionTemplateLiteral(node)) { return node.text; } else if (ts.isTemplateExpression(node)) { result = this.visitTemplateExpression(node, context); } else if (ts.isNumericLiteral(node)) { return parseFloat(node.text); } else if (ts.isObjectLiteralExpression(node)) { result = this.visitObjectLiteralExpression(node, context); } else if (ts.isIdentifier(node)) { result = this.visitIdentifier(node, context); } else if (ts.isPropertyAccessExpression(node)) { result = this.visitPropertyAccessExpression(node, context); } else if (ts.isCallExpression(node)) { result = this.visitCallExpression(node, context); } else if (ts.isConditionalExpression(node)) { result = this.visitConditionalExpression(node, context); } else if (ts.isPrefixUnaryExpression(node)) { result = this.visitPrefixUnaryExpression(node, context); } else if (ts.isBinaryExpression(node)) { result = this.visitBinaryExpression(node, context); } else if (ts.isArrayLiteralExpression(node)) { result = this.visitArrayLiteralExpression(node, context); } else if (ts.isParenthesizedExpression(node)) { result = this.visitParenthesizedExpression(node, context); } else if (ts.isElementAccessExpression(node)) { result = this.visitElementAccessExpression(node, context); } else if (ts.isAsExpression(node)) { result = this.visitExpression(node.expression, context); } else if (ts.isNonNullExpression(node)) { result = this.visitExpression(node.expression, context); } else if (this.host.isClass(node)) { result = this.visitDeclaration(node, context); } else { return DynamicValue.fromUnsupportedSyntax(node); } if (result instanceof DynamicValue && result.node !== node) { return DynamicValue.fromDynamicInput(node, result); } return result; } private visitArrayLiteralExpression( node: ts.ArrayLiteralExpression, context: Context, ): ResolvedValue { const array: ResolvedValueArray = []; for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (ts.isSpreadElement(element)) { array.push(...this.visitSpreadElement(element, context)); } else { array.push(this.visitExpression(element, context)); } } return array; } protected visitObjectLiteralExpression( node: ts.ObjectLiteralExpression, context: Context, ): ResolvedValue { const map: ResolvedValueMap = new Map<string, ResolvedValue>(); for (let i = 0; i < node.properties.length; i++) { const property = node.properties[i]; if (ts.isPropertyAssignment(property)) { const name = this.stringNameFromPropertyName(property.name, context); // Check whether the name can be determined statically. if (name === undefined) { return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property.name)); } map.set(name, this.visitExpression(property.initializer, context)); } else if (ts.isShorthandPropertyAssignment(property)) { const symbol = this.checker.getShorthandAssignmentValueSymbol(property); if (symbol === undefined || symbol.valueDeclaration === undefined) { map.set(property.name.text, DynamicValue.fromUnknown(property)); } else { map.set(property.name.text, this.visitDeclaration(symbol.valueDeclaration, context)); } } else if (ts.isSpreadAssignment(property)) { const spread = this.visitExpression(property.expression, context); if (spread instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, spread); } else if (spread instanceof Map) { spread.forEach((value, key) => map.set(key, value)); } else if (spread instanceof ResolvedModule) { spread.getExports().forEach((value, key) => map.set(key, value)); } else { return DynamicValue.fromDynamicInput( node, DynamicValue.fromInvalidExpressionType(property, spread), ); } } else { return DynamicValue.fromUnknown(node); } } return map; } private visitTemplateExpression(node: ts.TemplateExpression, context: Context): ResolvedValue { const pieces: string[] = [node.head.text]; for (let i = 0; i < node.templateSpans.length; i++) { const span = node.templateSpans[i]; const value = literal(this.visit(span.expression, context), () => DynamicValue.fromDynamicString(span.expression), ); if (value instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, value); } pieces.push(`${value}`, span.literal.text); } return pieces.join(''); } private visitIdentifier(node: ts.Identifier, context: Context): ResolvedValue { const decl = this.host.getDeclarationOfIdentifier(node); if (decl === null) { if (ts.identifierToKeywordKind(node) === ts.SyntaxKind.UndefinedKeyword) { return undefined; } else { // Check if the symbol here is imported. if (this.dependencyTracker !== null && this.host.getImportOfIdentifier(node) !== null) { // It was, but no declaration for the node could be found. This means that the dependency // graph for the current file cannot be properly updated to account for this (broken) // import. Instead, the originating file is reported as failing dependency analysis, // ensuring that future compilations will always attempt to re-resolve the previously // broken identifier. this.dependencyTracker.recordDependencyAnalysisFailure(context.originatingFile); } return DynamicValue.fromUnknownIdentifier(node); } } const declContext = {...context, ...joinModuleContext(context, node, decl)}; const result = this.visitDeclaration(decl.node, declContext); if (result instanceof Reference) { // Only record identifiers to non-synthetic references. Synthetic references may not have the // same value at runtime as they do at compile time, so it's not legal to refer to them by the // identifier here. if (!result.synthetic) { result.addIdentifier(node); } } else if (result instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, result); } return result; } private visitDeclaration(node: DeclarationNode, context: Context): ResolvedValue { if (this.dependencyTracker !== null) { this.dependencyTracker.addDependency(context.originatingFile, node.getSourceFile()); } if (this.host.isClass(node)) { return this.getReference(node, context); } else if (ts.isVariableDeclaration(node)) { return this.visitVariableDeclaration(node, context); } else if (ts.isParameter(node) && context.scope.has(node)) { return context.scope.get(node)!; } else if (ts.isExportAssignment(node)) { return this.visitExpression(node.expression, context); } else if (ts.isEnumDeclaration(node)) { return this.visitEnumDeclaration(node, context); } else if (ts.isSourceFile(node)) { return this.visitSourceFile(node, context); } else if (ts.isBindingElement(node)) { return this.visitBindingElement(node, context); } else { return this.getReference(node, context); } }
{ "end_byte": 11911, "start_byte": 3726, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts_11914_20532
private visitVariableDeclaration(node: ts.VariableDeclaration, context: Context): ResolvedValue { const value = this.host.getVariableValue(node); if (value !== null) { return this.visitExpression(value, context); } else if (isVariableDeclarationDeclared(node)) { // If the declaration has a literal type that can be statically reduced to a value, resolve to // that value. If not, the historical behavior for variable declarations is to return a // `Reference` to the variable, as the consumer could use it in a context where knowing its // static value is not necessary. // // Arguably, since the value cannot be statically determined, we should return a // `DynamicValue`. This returns a `Reference` because it's the same behavior as before // `visitType` was introduced. // // TODO(zarend): investigate switching to a `DynamicValue` and verify this won't break any // use cases, especially in ngcc if (node.type !== undefined) { const evaluatedType = this.visitType(node.type, context); if (!(evaluatedType instanceof DynamicValue)) { return evaluatedType; } } return this.getReference(node, context); } else { return undefined; } } private visitEnumDeclaration(node: ts.EnumDeclaration, context: Context): ResolvedValue { const enumRef = this.getReference(node, context); const map = new Map<string, EnumValue>(); node.members.forEach((member) => { const name = this.stringNameFromPropertyName(member.name, context); if (name !== undefined) { const resolved = member.initializer && this.visit(member.initializer, context); map.set(name, new EnumValue(enumRef, name, resolved)); } }); return map; } private visitElementAccessExpression( node: ts.ElementAccessExpression, context: Context, ): ResolvedValue { const lhs = this.visitExpression(node.expression, context); if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } const rhs = this.visitExpression(node.argumentExpression, context); if (rhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, rhs); } if (typeof rhs !== 'string' && typeof rhs !== 'number') { return DynamicValue.fromInvalidExpressionType(node, rhs); } return this.accessHelper(node, lhs, rhs, context); } private visitPropertyAccessExpression( node: ts.PropertyAccessExpression, context: Context, ): ResolvedValue { const lhs = this.visitExpression(node.expression, context); const rhs = node.name.text; // TODO: handle reference to class declaration. if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } return this.accessHelper(node, lhs, rhs, context); } private visitSourceFile(node: ts.SourceFile, context: Context): ResolvedValue { const declarations = this.host.getExportsOfModule(node); if (declarations === null) { return DynamicValue.fromUnknown(node); } return new ResolvedModule(declarations, (decl) => { const declContext = { ...context, ...joinModuleContext(context, node, decl), }; // Visit both concrete and inline declarations. return this.visitDeclaration(decl.node, declContext); }); } private accessHelper( node: ts.Node, lhs: ResolvedValue, rhs: string | number, context: Context, ): ResolvedValue { const strIndex = `${rhs}`; if (lhs instanceof Map) { if (lhs.has(strIndex)) { return lhs.get(strIndex)!; } else { return undefined; } } else if (lhs instanceof ResolvedModule) { return lhs.getExport(strIndex); } else if (Array.isArray(lhs)) { if (rhs === 'length') { return lhs.length; } else if (rhs === 'slice') { return new ArraySliceBuiltinFn(lhs); } else if (rhs === 'concat') { return new ArrayConcatBuiltinFn(lhs); } if (typeof rhs !== 'number' || !Number.isInteger(rhs)) { return DynamicValue.fromInvalidExpressionType(node, rhs); } return lhs[rhs]; } else if (typeof lhs === 'string' && rhs === 'concat') { return new StringConcatBuiltinFn(lhs); } else if (lhs instanceof Reference) { const ref = lhs.node; if (this.host.isClass(ref)) { const module = owningModule(context, lhs.bestGuessOwningModule); let value: ResolvedValue = undefined; const member = this.host .getMembersOfClass(ref) .find((member) => member.isStatic && member.name === strIndex); if (member !== undefined) { if (member.value !== null) { value = this.visitExpression(member.value, context); } else if (member.implementation !== null) { value = new Reference(member.implementation, module); } else if (member.node) { value = new Reference(member.node, module); } } return value; } else if (isDeclaration(ref)) { return DynamicValue.fromDynamicInput( node, DynamicValue.fromExternalReference(ref, lhs as Reference<ts.Declaration>), ); } } else if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } else if (lhs instanceof SyntheticValue) { return DynamicValue.fromSyntheticInput(node, lhs); } return DynamicValue.fromUnknown(node); } private visitCallExpression(node: ts.CallExpression, context: Context): ResolvedValue { const lhs = this.visitExpression(node.expression, context); if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } // If the call refers to a builtin function, attempt to evaluate the function. if (lhs instanceof KnownFn) { return lhs.evaluate(node, this.evaluateFunctionArguments(node, context)); } if (!(lhs instanceof Reference)) { return DynamicValue.fromInvalidExpressionType(node.expression, lhs); } const fn = this.host.getDefinitionOfFunction(lhs.node); if (fn === null) { return DynamicValue.fromInvalidExpressionType(node.expression, lhs); } if (!isFunctionOrMethodReference(lhs)) { return DynamicValue.fromInvalidExpressionType(node.expression, lhs); } const resolveFfrExpr = (expr: ts.Expression) => { let contextExtension: { absoluteModuleName?: string | null; resolutionContext?: string; } = {}; // TODO(alxhub): the condition `fn.body === null` here is vestigial - we probably _do_ want to // change the context like this even for non-null function bodies. But, this is being // redesigned as a refactoring with no behavior changes so that should be done as a follow-up. if ( fn.body === null && expr.getSourceFile() !== node.expression.getSourceFile() && lhs.bestGuessOwningModule !== null ) { contextExtension = { absoluteModuleName: lhs.bestGuessOwningModule.specifier, resolutionContext: lhs.bestGuessOwningModule.resolutionContext, }; } return this.visitFfrExpression(expr, {...context, ...contextExtension}); }; // If the function is foreign (declared through a d.ts file), attempt to resolve it with the // foreignFunctionResolver, if one is specified. if (fn.body === null && context.foreignFunctionResolver !== undefined) { const unresolvable = DynamicValue.fromDynamicInput( node, DynamicValue.fromExternalReference(node.expression, lhs), ); return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable); } const res: ResolvedValue = this.visitFunctionBody(node, fn, context); // If the result of attempting to resolve the function body was a DynamicValue, attempt to use // the foreignFunctionResolver if one is present. This could still potentially yield a usable // value. if (res instanceof DynamicValue && context.foreignFunctionResolver !== undefined) { const unresolvable = DynamicValue.fromComplexFunctionCall(node, fn); return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable); } return res; } /** * Visit an expression which was extracted from a foreign-function resolver. * * This will process the result and ensure it's correct for FFR-resolved values, including marking * `Reference`s as synthetic. */
{ "end_byte": 20532, "start_byte": 11914, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts_20535_29197
private visitFfrExpression(expr: ts.Expression, context: Context): ResolvedValue { const res = this.visitExpression(expr, context); if (res instanceof Reference) { // This Reference was created synthetically, via a foreign function resolver. The real // runtime value of the function expression may be different than the foreign function // resolved value, so mark the Reference as synthetic to avoid it being misinterpreted. res.synthetic = true; } return res; } private visitFunctionBody( node: ts.CallExpression, fn: FunctionDefinition, context: Context, ): ResolvedValue { if (fn.body === null) { return DynamicValue.fromUnknown(node); } else if (fn.body.length !== 1 || !ts.isReturnStatement(fn.body[0])) { return DynamicValue.fromComplexFunctionCall(node, fn); } const ret = fn.body[0] as ts.ReturnStatement; const args = this.evaluateFunctionArguments(node, context); const newScope: Scope = new Map<ts.ParameterDeclaration, ResolvedValue>(); const calleeContext = {...context, scope: newScope}; fn.parameters.forEach((param, index) => { let arg = args[index]; if (param.node.dotDotDotToken !== undefined) { arg = args.slice(index); } if (arg === undefined && param.initializer !== null) { arg = this.visitExpression(param.initializer, calleeContext); } newScope.set(param.node, arg); }); return ret.expression !== undefined ? this.visitExpression(ret.expression, calleeContext) : undefined; } private visitConditionalExpression( node: ts.ConditionalExpression, context: Context, ): ResolvedValue { const condition = this.visitExpression(node.condition, context); if (condition instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, condition); } if (condition) { return this.visitExpression(node.whenTrue, context); } else { return this.visitExpression(node.whenFalse, context); } } private visitPrefixUnaryExpression( node: ts.PrefixUnaryExpression, context: Context, ): ResolvedValue { const operatorKind = node.operator; if (!UNARY_OPERATORS.has(operatorKind)) { return DynamicValue.fromUnsupportedSyntax(node); } const op = UNARY_OPERATORS.get(operatorKind)!; const value = this.visitExpression(node.operand, context); if (value instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, value); } else { return op(value); } } private visitBinaryExpression(node: ts.BinaryExpression, context: Context): ResolvedValue { const tokenKind = node.operatorToken.kind; if (!BINARY_OPERATORS.has(tokenKind)) { return DynamicValue.fromUnsupportedSyntax(node); } const opRecord = BINARY_OPERATORS.get(tokenKind)!; let lhs: ResolvedValue, rhs: ResolvedValue; if (opRecord.literal) { lhs = literal(this.visitExpression(node.left, context), (value) => DynamicValue.fromInvalidExpressionType(node.left, value), ); rhs = literal(this.visitExpression(node.right, context), (value) => DynamicValue.fromInvalidExpressionType(node.right, value), ); } else { lhs = this.visitExpression(node.left, context); rhs = this.visitExpression(node.right, context); } if (lhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, lhs); } else if (rhs instanceof DynamicValue) { return DynamicValue.fromDynamicInput(node, rhs); } else { return opRecord.op(lhs, rhs); } } private visitParenthesizedExpression( node: ts.ParenthesizedExpression, context: Context, ): ResolvedValue { return this.visitExpression(node.expression, context); } private evaluateFunctionArguments(node: ts.CallExpression, context: Context): ResolvedValueArray { const args: ResolvedValueArray = []; for (const arg of node.arguments) { if (ts.isSpreadElement(arg)) { args.push(...this.visitSpreadElement(arg, context)); } else { args.push(this.visitExpression(arg, context)); } } return args; } private visitSpreadElement(node: ts.SpreadElement, context: Context): ResolvedValueArray { const spread = this.visitExpression(node.expression, context); if (spread instanceof DynamicValue) { return [DynamicValue.fromDynamicInput(node, spread)]; } else if (!Array.isArray(spread)) { return [DynamicValue.fromInvalidExpressionType(node, spread)]; } else { return spread; } } private visitBindingElement(node: ts.BindingElement, context: Context): ResolvedValue { const path: ts.BindingElement[] = []; let closestDeclaration: ts.Node = node; while ( ts.isBindingElement(closestDeclaration) || ts.isArrayBindingPattern(closestDeclaration) || ts.isObjectBindingPattern(closestDeclaration) ) { if (ts.isBindingElement(closestDeclaration)) { path.unshift(closestDeclaration); } closestDeclaration = closestDeclaration.parent; } if ( !ts.isVariableDeclaration(closestDeclaration) || closestDeclaration.initializer === undefined ) { return DynamicValue.fromUnknown(node); } let value = this.visit(closestDeclaration.initializer, context); for (const element of path) { let key: number | string; if (ts.isArrayBindingPattern(element.parent)) { key = element.parent.elements.indexOf(element); } else { const name = element.propertyName || element.name; if (ts.isIdentifier(name)) { key = name.text; } else { return DynamicValue.fromUnknown(element); } } value = this.accessHelper(element, value, key, context); if (value instanceof DynamicValue) { return value; } } return value; } private stringNameFromPropertyName(node: ts.PropertyName, context: Context): string | undefined { if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) { return node.text; } else if (ts.isComputedPropertyName(node)) { const literal = this.visitExpression(node.expression, context); return typeof literal === 'string' ? literal : undefined; } else { return undefined; } } private getReference<T extends DeclarationNode>(node: T, context: Context): Reference<T> { return new Reference(node, owningModule(context)); } private visitType(node: ts.TypeNode, context: Context): ResolvedValue { if (ts.isLiteralTypeNode(node)) { return this.visitExpression(node.literal, context); } else if (ts.isTupleTypeNode(node)) { return this.visitTupleType(node, context); } else if (ts.isNamedTupleMember(node)) { return this.visitType(node.type, context); } else if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) { return this.visitType(node.type, context); } else if (ts.isTypeQueryNode(node)) { return this.visitTypeQuery(node, context); } return DynamicValue.fromDynamicType(node); } private visitTupleType(node: ts.TupleTypeNode, context: Context): ResolvedValueArray { const res: ResolvedValueArray = []; for (const elem of node.elements) { res.push(this.visitType(elem, context)); } return res; } private visitTypeQuery(node: ts.TypeQueryNode, context: Context): ResolvedValue { if (!ts.isIdentifier(node.exprName)) { return DynamicValue.fromUnknown(node); } const decl = this.host.getDeclarationOfIdentifier(node.exprName); if (decl === null) { return DynamicValue.fromUnknownIdentifier(node.exprName); } const declContext: Context = {...context, ...joinModuleContext(context, node, decl)}; return this.visitDeclaration(decl.node, declContext); } } function isFunctionOrMethodReference( ref: Reference<ts.Node>, ): ref is Reference<ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression> { return ( ts.isFunctionDeclaration(ref.node) || ts.isMethodDeclaration(ref.node) || ts.isFunctionExpression(ref.node) ); } function literal( value: ResolvedValue, reject: (value: ResolvedValue) => ResolvedValue, ): ResolvedValue { if (value instanceof EnumValue) { value = value.resolved; } if ( value instanceof DynamicValue || value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { return value; } return reject(value); }
{ "end_byte": 29197, "start_byte": 20535, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts_29199_30505
function isVariableDeclarationDeclared(node: ts.VariableDeclaration): boolean { if (node.parent === undefined || !ts.isVariableDeclarationList(node.parent)) { return false; } const declList = node.parent; if (declList.parent === undefined || !ts.isVariableStatement(declList.parent)) { return false; } const varStmt = declList.parent; const modifiers = ts.getModifiers(varStmt); return ( modifiers !== undefined && modifiers.some((mod) => mod.kind === ts.SyntaxKind.DeclareKeyword) ); } const EMPTY = {}; function joinModuleContext( existing: Context, node: ts.Node, decl: Declaration, ): { absoluteModuleName?: string; resolutionContext?: string; } { if (typeof decl.viaModule === 'string' && decl.viaModule !== existing.absoluteModuleName) { return { absoluteModuleName: decl.viaModule, resolutionContext: node.getSourceFile().fileName, }; } else { return EMPTY; } } function owningModule(context: Context, override: OwningModule | null = null): OwningModule | null { let specifier = context.absoluteModuleName; if (override !== null) { specifier = override.specifier; } if (specifier !== null) { return { specifier, resolutionContext: context.resolutionContext, }; } else { return null; } }
{ "end_byte": 30505, "start_byte": 29199, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/result.ts_0_2683
/** * @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 {Reference} from '../../imports'; import {Declaration} from '../../reflection'; import {DynamicValue} from './dynamic'; import {SyntheticValue} from './synthetic'; /** * A value resulting from static resolution. * * This could be a primitive, collection type, reference to a `ts.Node` that declares a * non-primitive value, or a special `DynamicValue` type which indicates the value was not * available statically. */ export type ResolvedValue = | number | boolean | string | null | undefined | Reference | EnumValue | ResolvedValueArray | ResolvedValueMap | ResolvedModule | KnownFn | SyntheticValue<unknown> | DynamicValue<unknown>; /** * An array of `ResolvedValue`s. * * This is a reified type to allow the circular reference of `ResolvedValue` -> `ResolvedValueArray` * -> `ResolvedValue`. */ export interface ResolvedValueArray extends Array<ResolvedValue> {} /** * A map of strings to `ResolvedValue`s. * * This is a reified type to allow the circular reference of `ResolvedValue` -> `ResolvedValueMap` * -> `ResolvedValue`. */ export interface ResolvedValueMap extends Map<string, ResolvedValue> {} /** * A collection of publicly exported declarations from a module. Each declaration is evaluated * lazily upon request. */ export class ResolvedModule { constructor( private exports: Map<string, Declaration>, private evaluate: (decl: Declaration) => ResolvedValue, ) {} getExport(name: string): ResolvedValue { if (!this.exports.has(name)) { return undefined; } return this.evaluate(this.exports.get(name)!); } getExports(): ResolvedValueMap { const map = new Map<string, ResolvedValue>(); this.exports.forEach((decl, name) => { map.set(name, this.evaluate(decl)); }); return map; } } /** * A value member of an enumeration. * * Contains a `Reference` to the enumeration itself, and the name of the referenced member. */ export class EnumValue { constructor( readonly enumRef: Reference<ts.Declaration>, readonly name: string, readonly resolved: ResolvedValue, ) {} } /** * An implementation of a known function that can be statically evaluated. * It could be a built-in function or method (such as `Array.prototype.slice`) or a TypeScript * helper (such as `__spread`). */ export abstract class KnownFn { abstract evaluate(node: ts.CallExpression, args: ResolvedValueArray): ResolvedValue; }
{ "end_byte": 2683, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/result.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/dynamic.ts_0_8152
/** * @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 {Reference} from '../../imports'; import {FunctionDefinition} from '../../reflection'; import {SyntheticValue} from './synthetic'; /** * The reason why a value cannot be determined statically. */ export const enum DynamicValueReason { /** * A value could not be determined statically, because it contains a term that could not be * determined statically. * (E.g. a property assignment or call expression where the lhs is a `DynamicValue`, a template * literal with a dynamic expression, an object literal with a spread assignment which could not * be determined statically, etc.) */ DYNAMIC_INPUT, /** * A string could not be statically evaluated. * (E.g. a dynamically constructed object property name or a template literal expression that * could not be statically resolved to a primitive value.) */ DYNAMIC_STRING, /** * An external reference could not be resolved to a value which can be evaluated. * For example a call expression for a function declared in `.d.ts`, or accessing native globals * such as `window`. */ EXTERNAL_REFERENCE, /** * Syntax that `StaticInterpreter` doesn't know how to evaluate, for example a type of * `ts.Expression` that is not supported. */ UNSUPPORTED_SYNTAX, /** * A declaration of a `ts.Identifier` could not be found. */ UNKNOWN_IDENTIFIER, /** * A value could be resolved, but is not an acceptable type for the operation being performed. * * For example, attempting to call a non-callable expression. */ INVALID_EXPRESSION_TYPE, /** * A function call could not be evaluated as the function's body is not a single return statement. */ COMPLEX_FUNCTION_CALL, /** * A value that could not be determined because it contains type information that cannot be * statically evaluated. This happens when producing a value from type information, but the value * of the given type cannot be determined statically. * * E.g. evaluating a tuple. * * `declare const foo: [string];` * * Evaluating `foo` gives a DynamicValue wrapped in an array with a reason of DYNAMIC_TYPE. This * is because the static evaluator has a `string` type for the first element of this tuple, and * the value of that string cannot be determined statically. The type `string` permits it to be * 'foo', 'bar' or any arbitrary string, so we evaluate it to a DynamicValue. */ DYNAMIC_TYPE, /** * A value could not be determined because one of the inputs to its evaluation is a synthetically * produced value. */ SYNTHETIC_INPUT, /** * A value could not be determined statically for any reason other the above. */ UNKNOWN, } /** * Represents a value which cannot be determined statically. */ export class DynamicValue<R = unknown> { private constructor( readonly node: ts.Node, readonly reason: R, private code: DynamicValueReason, ) {} static fromDynamicInput(node: ts.Node, input: DynamicValue): DynamicValue<DynamicValue> { return new DynamicValue(node, input, DynamicValueReason.DYNAMIC_INPUT); } static fromDynamicString(node: ts.Node): DynamicValue { return new DynamicValue(node, undefined, DynamicValueReason.DYNAMIC_STRING); } static fromExternalReference( node: ts.Node, ref: Reference<ts.Declaration>, ): DynamicValue<Reference<ts.Declaration>> { return new DynamicValue(node, ref, DynamicValueReason.EXTERNAL_REFERENCE); } static fromUnsupportedSyntax(node: ts.Node): DynamicValue { return new DynamicValue(node, undefined, DynamicValueReason.UNSUPPORTED_SYNTAX); } static fromUnknownIdentifier(node: ts.Identifier): DynamicValue { return new DynamicValue(node, undefined, DynamicValueReason.UNKNOWN_IDENTIFIER); } static fromInvalidExpressionType(node: ts.Node, value: unknown): DynamicValue<unknown> { return new DynamicValue(node, value, DynamicValueReason.INVALID_EXPRESSION_TYPE); } static fromComplexFunctionCall( node: ts.Node, fn: FunctionDefinition, ): DynamicValue<FunctionDefinition> { return new DynamicValue(node, fn, DynamicValueReason.COMPLEX_FUNCTION_CALL); } static fromDynamicType(node: ts.TypeNode): DynamicValue { return new DynamicValue(node, undefined, DynamicValueReason.DYNAMIC_TYPE); } static fromSyntheticInput( node: ts.Node, value: SyntheticValue<unknown>, ): DynamicValue<SyntheticValue<unknown>> { return new DynamicValue(node, value, DynamicValueReason.SYNTHETIC_INPUT); } static fromUnknown(node: ts.Node): DynamicValue { return new DynamicValue(node, undefined, DynamicValueReason.UNKNOWN); } isFromDynamicInput(this: DynamicValue<R>): this is DynamicValue<DynamicValue> { return this.code === DynamicValueReason.DYNAMIC_INPUT; } isFromDynamicString(this: DynamicValue<R>): this is DynamicValue { return this.code === DynamicValueReason.DYNAMIC_STRING; } isFromExternalReference(this: DynamicValue<R>): this is DynamicValue<Reference<ts.Declaration>> { return this.code === DynamicValueReason.EXTERNAL_REFERENCE; } isFromUnsupportedSyntax(this: DynamicValue<R>): this is DynamicValue { return this.code === DynamicValueReason.UNSUPPORTED_SYNTAX; } isFromUnknownIdentifier(this: DynamicValue<R>): this is DynamicValue { return this.code === DynamicValueReason.UNKNOWN_IDENTIFIER; } isFromInvalidExpressionType(this: DynamicValue<R>): this is DynamicValue<unknown> { return this.code === DynamicValueReason.INVALID_EXPRESSION_TYPE; } isFromComplexFunctionCall(this: DynamicValue<R>): this is DynamicValue<FunctionDefinition> { return this.code === DynamicValueReason.COMPLEX_FUNCTION_CALL; } isFromDynamicType(this: DynamicValue<R>): this is DynamicValue { return this.code === DynamicValueReason.DYNAMIC_TYPE; } isFromUnknown(this: DynamicValue<R>): this is DynamicValue { return this.code === DynamicValueReason.UNKNOWN; } accept<R>(visitor: DynamicValueVisitor<R>): R { switch (this.code) { case DynamicValueReason.DYNAMIC_INPUT: return visitor.visitDynamicInput(this as unknown as DynamicValue<DynamicValue>); case DynamicValueReason.DYNAMIC_STRING: return visitor.visitDynamicString(this); case DynamicValueReason.EXTERNAL_REFERENCE: return visitor.visitExternalReference( this as unknown as DynamicValue<Reference<ts.Declaration>>, ); case DynamicValueReason.UNSUPPORTED_SYNTAX: return visitor.visitUnsupportedSyntax(this); case DynamicValueReason.UNKNOWN_IDENTIFIER: return visitor.visitUnknownIdentifier(this); case DynamicValueReason.INVALID_EXPRESSION_TYPE: return visitor.visitInvalidExpressionType(this); case DynamicValueReason.COMPLEX_FUNCTION_CALL: return visitor.visitComplexFunctionCall( this as unknown as DynamicValue<FunctionDefinition>, ); case DynamicValueReason.DYNAMIC_TYPE: return visitor.visitDynamicType(this); case DynamicValueReason.SYNTHETIC_INPUT: return visitor.visitSyntheticInput( this as unknown as DynamicValue<SyntheticValue<unknown>>, ); case DynamicValueReason.UNKNOWN: return visitor.visitUnknown(this); } } } export interface DynamicValueVisitor<R> { visitDynamicInput(value: DynamicValue<DynamicValue>): R; visitDynamicString(value: DynamicValue): R; visitExternalReference(value: DynamicValue<Reference<ts.Declaration>>): R; visitUnsupportedSyntax(value: DynamicValue): R; visitUnknownIdentifier(value: DynamicValue): R; visitInvalidExpressionType(value: DynamicValue): R; visitComplexFunctionCall(value: DynamicValue<FunctionDefinition>): R; visitDynamicType(value: DynamicValue): R; visitSyntheticInput(value: DynamicValue<SyntheticValue<unknown>>): R; visitUnknown(value: DynamicValue): R; }
{ "end_byte": 8152, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/dynamic.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interface.ts_0_1456
/** * @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 {Reference} from '../../imports'; import {DependencyTracker} from '../../incremental/api'; import {ReflectionHost} from '../../reflection'; import {DynamicValue} from './dynamic'; import {StaticInterpreter} from './interpreter'; import {ResolvedValue} from './result'; export type ForeignFunctionResolver = ( fn: Reference<ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression>, callExpr: ts.CallExpression, resolve: (expr: ts.Expression) => ResolvedValue, unresolvable: DynamicValue, ) => ResolvedValue; export class PartialEvaluator { constructor( private host: ReflectionHost, private checker: ts.TypeChecker, private dependencyTracker: DependencyTracker | null, ) {} evaluate(expr: ts.Expression, foreignFunctionResolver?: ForeignFunctionResolver): ResolvedValue { const interpreter = new StaticInterpreter(this.host, this.checker, this.dependencyTracker); const sourceFile = expr.getSourceFile(); return interpreter.visit(expr, { originatingFile: sourceFile, absoluteModuleName: null, resolutionContext: sourceFile.fileName, scope: new Map<ts.ParameterDeclaration, ResolvedValue>(), foreignFunctionResolver, }); } }
{ "end_byte": 1456, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interface.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/diagnostics.ts_0_7305
/** * @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 {makeRelatedInformation} from '../../diagnostics'; import {Reference} from '../../imports'; import {FunctionDefinition} from '../../reflection'; import {DynamicValue, DynamicValueVisitor} from './dynamic'; import {EnumValue, KnownFn, ResolvedModule, ResolvedValue} from './result'; import {SyntheticValue} from './synthetic'; /** * Derives a type representation from a resolved value to be reported in a diagnostic. * * @param value The resolved value for which a type representation should be derived. * @param maxDepth The maximum nesting depth of objects and arrays, defaults to 1 level. */ export function describeResolvedType(value: ResolvedValue, maxDepth: number = 1): string { if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string') { return typeof value; } else if (value instanceof Map) { if (maxDepth === 0) { return 'object'; } const entries = Array.from(value.entries()).map(([key, v]) => { return `${quoteKey(key)}: ${describeResolvedType(v, maxDepth - 1)}`; }); return entries.length > 0 ? `{ ${entries.join('; ')} }` : '{}'; } else if (value instanceof ResolvedModule) { return '(module)'; } else if (value instanceof EnumValue) { return value.enumRef.debugName ?? '(anonymous)'; } else if (value instanceof Reference) { return value.debugName ?? '(anonymous)'; } else if (Array.isArray(value)) { if (maxDepth === 0) { return 'Array'; } return `[${value.map((v) => describeResolvedType(v, maxDepth - 1)).join(', ')}]`; } else if (value instanceof DynamicValue) { return '(not statically analyzable)'; } else if (value instanceof KnownFn) { return 'Function'; } else { return 'unknown'; } } function quoteKey(key: string): string { if (/^[a-z0-9_]+$/i.test(key)) { return key; } else { return `'${key.replace(/'/g, "\\'")}'`; } } /** * Creates an array of related information diagnostics for a `DynamicValue` that describe the trace * of why an expression was evaluated as dynamic. * * @param node The node for which a `ts.Diagnostic` is to be created with the trace. * @param value The dynamic value for which a trace should be created. */ export function traceDynamicValue( node: ts.Node, value: DynamicValue, ): ts.DiagnosticRelatedInformation[] { return value.accept(new TraceDynamicValueVisitor(node)); } class TraceDynamicValueVisitor implements DynamicValueVisitor<ts.DiagnosticRelatedInformation[]> { private currentContainerNode: ts.Node | null = null; constructor(private node: ts.Node) {} visitDynamicInput(value: DynamicValue<DynamicValue>): ts.DiagnosticRelatedInformation[] { const trace = value.reason.accept(this); if (this.shouldTrace(value.node)) { const info = makeRelatedInformation( value.node, 'Unable to evaluate this expression statically.', ); trace.unshift(info); } return trace; } visitSyntheticInput( value: DynamicValue<SyntheticValue<unknown>>, ): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'Unable to evaluate this expression further.')]; } visitDynamicString(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [ makeRelatedInformation(value.node, 'A string value could not be determined statically.'), ]; } visitExternalReference( value: DynamicValue<Reference<ts.Declaration>>, ): ts.DiagnosticRelatedInformation[] { const name = value.reason.debugName; const description = name !== null ? `'${name}'` : 'an anonymous declaration'; return [ makeRelatedInformation( value.node, `A value for ${description} cannot be determined statically, as it is an external declaration.`, ), ]; } visitComplexFunctionCall( value: DynamicValue<FunctionDefinition>, ): ts.DiagnosticRelatedInformation[] { return [ makeRelatedInformation( value.node, 'Unable to evaluate function call of complex function. A function must have exactly one return statement.', ), makeRelatedInformation(value.reason.node, 'Function is declared here.'), ]; } visitInvalidExpressionType(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'Unable to evaluate an invalid expression.')]; } visitUnknown(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'Unable to evaluate statically.')]; } visitUnknownIdentifier(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'Unknown reference.')]; } visitDynamicType(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'Dynamic type.')]; } visitUnsupportedSyntax(value: DynamicValue): ts.DiagnosticRelatedInformation[] { return [makeRelatedInformation(value.node, 'This syntax is not supported.')]; } /** * Determines whether the dynamic value reported for the node should be traced, i.e. if it is not * part of the container for which the most recent trace was created. */ private shouldTrace(node: ts.Node): boolean { if (node === this.node) { // Do not include a dynamic value for the origin node, as the main diagnostic is already // reported on that node. return false; } const container = getContainerNode(node); if (container === this.currentContainerNode) { // The node is part of the same container as the previous trace entry, so this dynamic value // should not become part of the trace. return false; } this.currentContainerNode = container; return true; } } /** * Determines the closest parent node that is to be considered as container, which is used to reduce * the granularity of tracing the dynamic values to a single entry per container. Currently, full * statements and destructuring patterns are considered as container. */ function getContainerNode(node: ts.Node): ts.Node { let currentNode: ts.Node | undefined = node; while (currentNode !== undefined) { switch (currentNode.kind) { case ts.SyntaxKind.ExpressionStatement: case ts.SyntaxKind.VariableStatement: case ts.SyntaxKind.ReturnStatement: case ts.SyntaxKind.IfStatement: case ts.SyntaxKind.SwitchStatement: case ts.SyntaxKind.DoStatement: case ts.SyntaxKind.WhileStatement: case ts.SyntaxKind.ForStatement: case ts.SyntaxKind.ForInStatement: case ts.SyntaxKind.ForOfStatement: case ts.SyntaxKind.ContinueStatement: case ts.SyntaxKind.BreakStatement: case ts.SyntaxKind.ThrowStatement: case ts.SyntaxKind.ObjectBindingPattern: case ts.SyntaxKind.ArrayBindingPattern: return currentNode; } currentNode = currentNode.parent; } return node.getSourceFile(); }
{ "end_byte": 7305, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/diagnostics.ts" }
angular/packages/compiler-cli/src/ngtsc/partial_evaluator/src/synthetic.ts_0_507
/** * @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 */ /** * A value produced which originated in a `ForeignFunctionResolver` and doesn't come from the * template itself. * * Synthetic values cannot be further evaluated, and attempts to do so produce `DynamicValue`s * instead. */ export class SyntheticValue<T> { constructor(readonly value: T) {} }
{ "end_byte": 507, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/partial_evaluator/src/synthetic.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/README.md_0_2752
# Virtual file-system layer To improve cross platform support, all file access (and path manipulation) is now done through a well known interface (`FileSystem`). Note that `FileSystem` extends `ReadonlyFileSystem`, which itself extends `PathManipulation`. If you are using a file-system object you should only ask for the type that supports all the methods that you require. For example, if you have a function (`foo()`) that only needs to resolve paths then it should only require `PathManipulation`: `foo(fs: PathManipulation)`. This allows the caller to avoid implementing unneeded functionality. For testing, a number of `MockFileSystem` implementations are supplied. These provide an in-memory file-system which emulates operating systems like OS/X, Unix and Windows. The current file system is always available via the helper method, `getFileSystem()`. This is also used by a number of helper methods to avoid having to pass `FileSystem` objects around all the time. The result of this is that one must be careful to ensure that the file-system has been initialized before using any of these helper methods. To prevent this happening accidentally the current file system always starts out as an instance of `InvalidFileSystem`, which will throw an error if any of its methods are called. Generally it is safer to explicitly pass file-system objects to constructors or free-standing functions if possible. This avoids confusing bugs where the global file-system has not been set-up correctly before calling functions that expect there to be a file-system configured globally. You can set the current file-system by calling `setFileSystem()`. During testing you can call the helper function `initMockFileSystem(os)` which takes a string name of the OS to emulate, and will also monkey-patch aspects of the TypeScript library to ensure that TS is also using the current file-system. Finally there is the `NgtscCompilerHost` to be used for any TypeScript compilation, which uses a given file-system. All tests that interact with the file-system should be tested against each of the mock file-systems. A series of helpers have been provided to support such tests: * `runInEachFileSystem()` - wrap your tests in this helper to run all the wrapped tests in each of the mock file-systems, it calls `initMockFileSystem()` for each OS to emulate. * `loadTestFiles()` - use this to add files and their contents to the mock file system for testing. * `loadStandardTestFiles()` - use this to load a mirror image of Angular test files on disk into the in-memory mock file-system. * `loadAngularCore()` - use this to load the npm package of `@angular/core` into the mock file-system. All ngtsc source and tests now use this virtual file-system setup.
{ "end_byte": 2752, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/README.md" }
angular/packages/compiler-cli/src/ngtsc/file_system/BUILD.bazel_0_280
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "file_system", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 280, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/file_system/index.ts_0_902
/** * @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 {NgtscCompilerHost} from './src/compiler_host'; export { absoluteFrom, absoluteFromSourceFile, basename, dirname, getFileSystem, isLocalRelativePath, isRoot, isRooted, join, relative, relativeFrom, resolve, setFileSystem, toRelativeImport, } from './src/helpers'; export {LogicalFileSystem, LogicalProjectPath} from './src/logical'; export {NodeJSFileSystem} from './src/node_js_file_system'; export { AbsoluteFsPath, FileStats, FileSystem, PathManipulation, PathSegment, PathString, ReadonlyFileSystem, } from './src/types'; export {getSourceFileOrError} from './src/util'; export {createFileSystemTsReadDirectoryFn} from './src/ts_read_directory';
{ "end_byte": 902, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/index.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/test/compiler_host_spec.ts_0_2417
/** * @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 {NgtscCompilerHost} from '../src/compiler_host'; import {absoluteFrom, getFileSystem} from '../src/helpers'; import {runInEachFileSystem} from '../testing'; runInEachFileSystem(() => { describe('NgtscCompilerHost', () => { describe('fileExists()', () => { it('should return `false` for an existing directory', () => { const directory = absoluteFrom('/a/b/c'); const fs = getFileSystem(); fs.ensureDir(directory); const host = new NgtscCompilerHost(fs); expect(host.fileExists(directory)).toBe(false); }); }); describe('readFile()', () => { it('should return `undefined` for an existing directory', () => { const directory = absoluteFrom('/a/b/c'); const fs = getFileSystem(); fs.ensureDir(directory); const host = new NgtscCompilerHost(fs); expect(host.readFile(directory)).toBe(undefined); }); }); describe('getSourceFile()', () => { it('should return `undefined` for an existing directory', () => { const directory = absoluteFrom('/a/b/c'); const fs = getFileSystem(); fs.ensureDir(directory); const host = new NgtscCompilerHost(fs); expect(host.getSourceFile(directory, ts.ScriptTarget.ES2015)).toBe(undefined); }); }); describe('useCaseSensitiveFileNames()', () => { it('should return the same as `FileSystem.isCaseSensitive()', () => { const directory = absoluteFrom('/a/b/c'); const fs = getFileSystem(); fs.ensureDir(directory); const host = new NgtscCompilerHost(fs); expect(host.useCaseSensitiveFileNames()).toEqual(fs.isCaseSensitive()); }); }); describe('getCanonicalFileName()', () => { it('should return the original filename if FS is case-sensitive or lower case otherwise', () => { const directory = absoluteFrom('/a/b/c'); const fs = getFileSystem(); fs.ensureDir(directory); const host = new NgtscCompilerHost(fs); expect(host.getCanonicalFileName('AbCd.ts')).toEqual( fs.isCaseSensitive() ? 'AbCd.ts' : 'abcd.ts', ); }); }); }); });
{ "end_byte": 2417, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/test/compiler_host_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts_0_2018
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as os from 'os'; import {absoluteFrom, relativeFrom, setFileSystem} from '../src/helpers'; import {NodeJSFileSystem} from '../src/node_js_file_system'; describe('path types', () => { beforeEach(() => { setFileSystem(new NodeJSFileSystem()); }); describe('absoluteFrom', () => { it('should not throw when creating one from an absolute path', () => { expect(() => absoluteFrom('/test.txt')).not.toThrow(); }); if (os.platform() === 'win32') { it('should not throw when creating one from a windows absolute path', () => { expect(absoluteFrom('C:\\test.txt')).toEqual('C:/test.txt'); }); it('should not throw when creating one from a windows absolute path with POSIX separators', () => { expect(absoluteFrom('C:/test.txt')).toEqual('C:/test.txt'); }); it('should support windows drive letters', () => { expect(absoluteFrom('D:\\foo\\test.txt')).toEqual('D:/foo/test.txt'); }); it('should convert Windows path separators to POSIX separators', () => { expect(absoluteFrom('C:\\foo\\test.txt')).toEqual('C:/foo/test.txt'); }); } it('should throw when creating one from a non-absolute path', () => { expect(() => absoluteFrom('test.txt')).toThrow(); }); }); describe('relativeFrom', () => { it('should not throw when creating one from a relative path', () => { expect(() => relativeFrom('a/b/c.txt')).not.toThrow(); }); it('should throw when creating one from an absolute path', () => { expect(() => relativeFrom('/a/b/c.txt')).toThrow(); }); if (os.platform() === 'win32') { it('should throw when creating one from a Windows absolute path', () => { expect(() => relativeFrom('C:/a/b/c.txt')).toThrow(); }); } }); });
{ "end_byte": 2018, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/test/helpers_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/test/logical_spec.ts_0_4252
/** * @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 {NgtscCompilerHost} from '../src/compiler_host'; import {absoluteFrom, getFileSystem} from '../src/helpers'; import {LogicalFileSystem, LogicalProjectPath} from '../src/logical'; import {runInEachFileSystem} from '../testing'; runInEachFileSystem(() => { describe('logical paths', () => { let _: typeof absoluteFrom; let host: NgtscCompilerHost; beforeEach(() => { _ = absoluteFrom; host = new NgtscCompilerHost(getFileSystem()); }); describe('LogicalFileSystem', () => { it('should determine logical paths in a single root file system', () => { const fs = new LogicalFileSystem([_('/test')], host); expect(fs.logicalPathOfFile(_('/test/foo/foo.ts'))).toEqual( '/foo/foo' as LogicalProjectPath, ); expect(fs.logicalPathOfFile(_('/test/bar/bar.ts'))).toEqual( '/bar/bar' as LogicalProjectPath, ); expect(fs.logicalPathOfFile(_('/not-test/bar.ts'))).toBeNull(); }); it('should determine logical paths in a multi-root file system', () => { const fs = new LogicalFileSystem([_('/test/foo'), _('/test/bar')], host); expect(fs.logicalPathOfFile(_('/test/foo/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(_('/test/bar/bar.ts'))).toEqual('/bar' as LogicalProjectPath); }); it('should continue to work when one root is a child of another', () => { const fs = new LogicalFileSystem([_('/test'), _('/test/dist')], host); expect(fs.logicalPathOfFile(_('/test/foo.ts'))).toEqual('/foo' as LogicalProjectPath); expect(fs.logicalPathOfFile(_('/test/dist/foo.ts'))).toEqual('/foo' as LogicalProjectPath); }); it('should always return `/` prefixed logical paths', () => { const rootFs = new LogicalFileSystem([_('/')], host); expect(rootFs.logicalPathOfFile(_('/foo/foo.ts'))).toEqual( '/foo/foo' as LogicalProjectPath, ); const nonRootFs = new LogicalFileSystem([_('/test/')], host); expect(nonRootFs.logicalPathOfFile(_('/test/foo/foo.ts'))).toEqual( '/foo/foo' as LogicalProjectPath, ); }); it('should maintain casing of logical paths', () => { const fs = new LogicalFileSystem([_('/Test')], host); expect(fs.logicalPathOfFile(_('/Test/foo/Foo.ts'))).toEqual( '/foo/Foo' as LogicalProjectPath, ); expect(fs.logicalPathOfFile(_('/Test/foo/foo.ts'))).toEqual( '/foo/foo' as LogicalProjectPath, ); expect(fs.logicalPathOfFile(_('/Test/bar/bAR.ts'))).toEqual( '/bar/bAR' as LogicalProjectPath, ); }); it('should use case-sensitivity when matching rootDirs', () => { const fs = new LogicalFileSystem([_('/Test')], host); if (host.useCaseSensitiveFileNames()) { expect(fs.logicalPathOfFile(_('/test/car/CAR.ts'))).toBe(null); } else { expect(fs.logicalPathOfFile(_('/test/car/CAR.ts'))).toEqual( '/car/CAR' as LogicalProjectPath, ); } }); }); describe('utilities', () => { it('should give a relative path between two adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo' as LogicalProjectPath, '/bar' as LogicalProjectPath, ); expect(res).toEqual('./bar'); }); it('should give a relative path between two non-adjacent logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/foo/index' as LogicalProjectPath, '/bar/index' as LogicalProjectPath, ); expect(res).toEqual('../bar/index'); }); it('should maintain casing in relative path between logical files', () => { const res = LogicalProjectPath.relativePathBetween( '/fOO' as LogicalProjectPath, '/bAR' as LogicalProjectPath, ); expect(res).toEqual('./bAR'); }); }); }); });
{ "end_byte": 4252, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/test/logical_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/test/node_js_file_system_spec.ts_0_6547
/** * @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: We do not use a namespace import here because this will result in the // named exports being modified if we apply jasmine spies on `realFs`. Using // the default export gives us an object where we can patch properties on. import realFs from 'fs'; import os from 'os'; import url from 'url'; import { NodeJSFileSystem, NodeJSPathManipulation, NodeJSReadonlyFileSystem, } from '../src/node_js_file_system'; import {AbsoluteFsPath, PathSegment} from '../src/types'; describe('NodeJSPathManipulation', () => { let fs: NodeJSPathManipulation; let abcPath: AbsoluteFsPath; let xyzPath: AbsoluteFsPath; beforeEach(() => { fs = new NodeJSPathManipulation(); abcPath = fs.resolve('/a/b/c'); xyzPath = fs.resolve('/x/y/z'); }); describe('pwd()', () => { it('should delegate to process.cwd()', () => { const spy = spyOn(process, 'cwd').and.returnValue(abcPath); const result = fs.pwd(); expect(result).toEqual(abcPath); expect(spy).toHaveBeenCalledWith(); }); }); if (os.platform() === 'win32') { // Only relevant on Windows describe('relative', () => { it('should handle Windows paths on different drives', () => { expect(fs.relative('C:\\a\\b\\c', 'D:\\a\\b\\d')).toEqual(fs.resolve('D:\\a\\b\\d')); }); }); } }); describe('NodeJSReadonlyFileSystem', () => { let fs: NodeJSReadonlyFileSystem; let abcPath: AbsoluteFsPath; let xyzPath: AbsoluteFsPath; beforeEach(() => { fs = new NodeJSReadonlyFileSystem(); abcPath = fs.resolve('/a/b/c'); xyzPath = fs.resolve('/x/y/z'); }); describe('isCaseSensitive()', () => { it('should return true if the FS is case-sensitive', () => { const currentFilename = url.fileURLToPath(import.meta.url); const isCaseSensitive = !realFs.existsSync(currentFilename.toUpperCase()); expect(fs.isCaseSensitive()).toEqual(isCaseSensitive); }); }); describe('exists()', () => { it('should delegate to fs.existsSync()', () => { const spy = spyOn(realFs, 'existsSync').and.returnValues(true, false); expect(fs.exists(abcPath)).toBe(true); expect(spy).toHaveBeenCalledWith(abcPath); expect(fs.exists(xyzPath)).toBe(false); expect(spy).toHaveBeenCalledWith(xyzPath); }); }); describe('readFile()', () => { it('should delegate to fs.readFileSync()', () => { const spy = spyOn(realFs, 'readFileSync').and.returnValue('Some contents'); const result = fs.readFile(abcPath); expect(result).toBe('Some contents'); expect(spy).toHaveBeenCalledWith(abcPath, 'utf8'); }); }); describe('readFileBuffer()', () => { it('should delegate to fs.readFileSync()', () => { const buffer = new Buffer('Some contents'); const spy = spyOn(realFs, 'readFileSync').and.returnValue(buffer); const result = fs.readFileBuffer(abcPath); expect(result).toBe(buffer); expect(spy).toHaveBeenCalledWith(abcPath); }); }); describe('readdir()', () => { it('should delegate to fs.readdirSync()', () => { const spy = spyOn(realFs, 'readdirSync').and.returnValue(['x', 'y/z'] as any); const result = fs.readdir(abcPath); expect(result).toEqual(['x' as PathSegment, 'y/z' as PathSegment]); // TODO: @JiaLiPassion need to wait for @types/jasmine update to handle optional parameters. // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43486 expect(spy as any).toHaveBeenCalledWith(abcPath); }); }); describe('lstat()', () => { it('should delegate to fs.lstatSync()', () => { const stats = new realFs.Stats(); const spy = spyOn(realFs, 'lstatSync').and.returnValue(stats); const result = fs.lstat(abcPath); expect(result).toBe(stats); expect(spy).toHaveBeenCalledWith(abcPath); }); }); describe('stat()', () => { it('should delegate to fs.statSync()', () => { const stats = new realFs.Stats(); const spy = spyOn(realFs, 'statSync').and.returnValue(stats); const result = fs.stat(abcPath); expect(result).toBe(stats); // TODO: @JiaLiPassion need to wait for @types/jasmine update to handle optional parameters. // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43486 expect(spy as any).toHaveBeenCalledWith(abcPath); }); }); }); describe('NodeJSFileSystem', () => { let fs: NodeJSFileSystem; let abcPath: AbsoluteFsPath; let xyzPath: AbsoluteFsPath; beforeEach(() => { fs = new NodeJSFileSystem(); abcPath = fs.resolve('/a/b/c'); xyzPath = fs.resolve('/x/y/z'); }); describe('writeFile()', () => { it('should delegate to fs.writeFileSync()', () => { const spy = spyOn(realFs, 'writeFileSync'); fs.writeFile(abcPath, 'Some contents'); expect(spy).toHaveBeenCalledWith(abcPath, 'Some contents', undefined); spy.calls.reset(); fs.writeFile(abcPath, 'Some contents', /* exclusive */ true); expect(spy).toHaveBeenCalledWith(abcPath, 'Some contents', {flag: 'wx'}); }); }); describe('removeFile()', () => { it('should delegate to fs.unlink()', () => { const spy = spyOn(realFs, 'unlinkSync'); fs.removeFile(abcPath); expect(spy).toHaveBeenCalledWith(abcPath); }); }); describe('copyFile()', () => { it('should delegate to fs.copyFileSync()', () => { const spy = spyOn(realFs, 'copyFileSync'); fs.copyFile(abcPath, xyzPath); expect(spy).toHaveBeenCalledWith(abcPath, xyzPath); }); }); describe('moveFile()', () => { it('should delegate to fs.renameSync()', () => { const spy = spyOn(realFs, 'renameSync'); fs.moveFile(abcPath, xyzPath); expect(spy).toHaveBeenCalledWith(abcPath, xyzPath); }); }); describe('ensureDir()', () => { it('should delegate to fs.mkdirSync()', () => { const mkdirCalls: string[] = []; spyOn(realFs, 'mkdirSync').and.callFake(((path: string) => mkdirCalls.push(path)) as any); fs.ensureDir(abcPath); expect(mkdirCalls).toEqual([abcPath]); }); }); describe('removeDeep()', () => { it('should delegate to rmdirSync()', () => { const spy = spyOn(realFs, 'rmdirSync'); fs.removeDeep(abcPath); expect(spy).toHaveBeenCalledWith(abcPath, {recursive: true}); }); }); });
{ "end_byte": 6547, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/test/node_js_file_system_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/test/BUILD.bazel_0_528
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 528, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/BUILD.bazel_0_374
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "@npm//@types/jasmine", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 374, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts_0_556
/** * @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 {Folder, MockFileSystem} from './src/mock_file_system'; export {MockFileSystemNative} from './src/mock_file_system_native'; export {MockFileSystemPosix} from './src/mock_file_system_posix'; export {MockFileSystemWindows} from './src/mock_file_system_windows'; export {initMockFileSystem, runInEachFileSystem, TestFile} from './src/test_helper';
{ "end_byte": 556, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/test/mock_file_system_spec.ts_0_1626
/** * @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 {getFileSystem} from '../../src/helpers'; import {FileSystem} from '../../src/types'; import {runInEachFileSystem} from '../src/test_helper'; runInEachFileSystem(() => { describe('MockFileSystem', () => { let fs: FileSystem; beforeEach(() => { fs = getFileSystem(); }); it('should support symlinks', () => { const targetPath = fs.resolve('/link/target'); const symlinkPath = fs.resolve('/src/symlink'); const packageJsonInTarget = fs.resolve(targetPath, 'package.json'); const packageJsonUsingSymlink = fs.resolve(symlinkPath, 'package.json'); fs.ensureDir(targetPath); fs.ensureDir(fs.resolve('/src')); fs.writeFile(packageJsonInTarget, '{}'); fs.symlink(targetPath, symlinkPath); expect(fs.exists(packageJsonUsingSymlink)).toBe(true); expect(fs.exists(fs.resolve(symlinkPath, 'unknown.json'))).toBe(false); expect(fs.readFile(packageJsonInTarget)).toBe('{}'); expect(fs.realpath(packageJsonUsingSymlink)).toBe(packageJsonInTarget); expect(fs.realpath(packageJsonInTarget)).toBe(packageJsonInTarget); expect(fs.stat(symlinkPath).isSymbolicLink()).toBe(false); expect(fs.lstat(symlinkPath).isSymbolicLink()).toBe(true); expect(fs.stat(packageJsonUsingSymlink).isSymbolicLink()).toBe(false); expect(fs.lstat(packageJsonUsingSymlink).isSymbolicLink()).toBe(false); }); }); });
{ "end_byte": 1626, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/test/mock_file_system_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/test/BUILD.bazel_0_500
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 500, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts_0_1544
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import * as p from 'path'; import {AbsoluteFsPath, PathSegment, PathString} from '../../src/types'; import {MockFileSystem} from './mock_file_system'; export class MockFileSystemWindows extends MockFileSystem { override resolve(...paths: string[]): AbsoluteFsPath { const resolved = p.win32.resolve(this.pwd(), ...paths); return this.normalize(resolved as AbsoluteFsPath); } override dirname<T extends string>(path: T): T { return this.normalize(p.win32.dirname(path) as T); } override join<T extends string>(basePath: T, ...paths: string[]): T { return this.normalize(p.win32.join(basePath, ...paths)) as T; } override relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return this.normalize(p.win32.relative(from, to)) as PathSegment | AbsoluteFsPath; } override basename(filePath: string, extension?: string): PathSegment { return p.win32.basename(filePath, extension) as PathSegment; } override isRooted(path: string): boolean { return /^([A-Z]:)?([\\\/]|$)/i.test(path); } protected override splitPath<T extends PathString>(path: T): string[] { return path.split(/[\\\/]/); } override normalize<T extends PathString>(path: T): T { return path.replace(/^[\/\\]/i, 'C:/').replace(/\\/g, '/') as T; } }
{ "end_byte": 1544, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_windows.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts_0_430
/** * @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 {basename, dirname, resolve} from '../../src/helpers'; import {AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString} from '../../src/types'; /** * An in-memory file system that can be used in unit tests. */
{ "end_byte": 430, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts_431_8517
export abstract class MockFileSystem implements FileSystem { private _fileTree: Folder = {}; private _cwd: AbsoluteFsPath; constructor( private _isCaseSensitive = false, cwd: AbsoluteFsPath = '/' as AbsoluteFsPath, ) { this._cwd = this.normalize(cwd); } isCaseSensitive() { return this._isCaseSensitive; } exists(path: AbsoluteFsPath): boolean { return this.findFromPath(path).entity !== null; } readFile(path: AbsoluteFsPath): string { const {entity} = this.findFromPath(path); if (isFile(entity)) { return entity.toString(); } else { throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`); } } readFileBuffer(path: AbsoluteFsPath): Uint8Array { const {entity} = this.findFromPath(path); if (isFile(entity)) { return entity instanceof Uint8Array ? entity : new Buffer(entity); } else { throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`); } } writeFile(path: AbsoluteFsPath, data: string | Uint8Array, exclusive: boolean = false): void { const [folderPath, basename] = this.splitIntoFolderAndFile(path); const {entity} = this.findFromPath(folderPath); if (entity === null || !isFolder(entity)) { throw new MockFileSystemError( 'ENOENT', path, `Unable to write file "${path}". The containing folder does not exist.`, ); } if (exclusive && entity[basename] !== undefined) { throw new MockFileSystemError( 'EEXIST', path, `Unable to exclusively write file "${path}". The file already exists.`, ); } entity[basename] = data; } removeFile(path: AbsoluteFsPath): void { const [folderPath, basename] = this.splitIntoFolderAndFile(path); const {entity} = this.findFromPath(folderPath); if (entity === null || !isFolder(entity)) { throw new MockFileSystemError( 'ENOENT', path, `Unable to remove file "${path}". The containing folder does not exist.`, ); } if (isFolder(entity[basename])) { throw new MockFileSystemError( 'EISDIR', path, `Unable to remove file "${path}". The path to remove is a folder.`, ); } delete entity[basename]; } symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { const [folderPath, basename] = this.splitIntoFolderAndFile(path); const {entity} = this.findFromPath(folderPath); if (entity === null || !isFolder(entity)) { throw new MockFileSystemError( 'ENOENT', path, `Unable to create symlink at "${path}". The containing folder does not exist.`, ); } entity[basename] = new SymLink(target); } readdir(path: AbsoluteFsPath): PathSegment[] { const {entity} = this.findFromPath(path); if (entity === null) { throw new MockFileSystemError( 'ENOENT', path, `Unable to read directory "${path}". It does not exist.`, ); } if (isFile(entity)) { throw new MockFileSystemError( 'ENOTDIR', path, `Unable to read directory "${path}". It is a file.`, ); } return Object.keys(entity) as PathSegment[]; } lstat(path: AbsoluteFsPath): FileStats { const {entity} = this.findFromPath(path); if (entity === null) { throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`); } return new MockFileStats(entity); } stat(path: AbsoluteFsPath): FileStats { const {entity} = this.findFromPath(path, {followSymLinks: true}); if (entity === null) { throw new MockFileSystemError('ENOENT', path, `File "${path}" does not exist.`); } return new MockFileStats(entity); } copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { this.writeFile(to, this.readFile(from)); } moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { this.writeFile(to, this.readFile(from)); const result = this.findFromPath(dirname(from)); const folder = result.entity as Folder; const name = basename(from); delete folder[name]; } ensureDir(path: AbsoluteFsPath): Folder { const segments = this.splitPath(path).map((segment) => this.getCanonicalPath(segment)); // Convert the root folder to a canonical empty string `''` (on Windows it would be `'C:'`). segments[0] = ''; if (segments.length > 1 && segments[segments.length - 1] === '') { // Remove a trailing slash (unless the path was only `/`) segments.pop(); } let current: Folder = this._fileTree; for (const segment of segments) { if (isFile(current[segment])) { throw new Error(`Folder already exists as a file.`); } if (!current[segment]) { current[segment] = {}; } current = current[segment] as Folder; } return current; } removeDeep(path: AbsoluteFsPath): void { const [folderPath, basename] = this.splitIntoFolderAndFile(path); const {entity} = this.findFromPath(folderPath); if (entity === null || !isFolder(entity)) { throw new MockFileSystemError( 'ENOENT', path, `Unable to remove folder "${path}". The containing folder does not exist.`, ); } delete entity[basename]; } isRoot(path: AbsoluteFsPath): boolean { return this.dirname(path) === path; } extname(path: AbsoluteFsPath | PathSegment): string { const match = /.+(\.[^.]*)$/.exec(path); return match !== null ? match[1] : ''; } realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { const result = this.findFromPath(filePath, {followSymLinks: true}); if (result.entity === null) { throw new MockFileSystemError( 'ENOENT', filePath, `Unable to find the real path of "${filePath}". It does not exist.`, ); } else { return result.path; } } pwd(): AbsoluteFsPath { return this._cwd; } chdir(path: AbsoluteFsPath): void { this._cwd = this.normalize(path); } getDefaultLibLocation(): AbsoluteFsPath { // Mimic the node module resolution algorithm and start in the current directory, then look // progressively further up the tree until reaching the FS root. // E.g. if the current directory is /foo/bar, look in /foo/bar/node_modules, then // /foo/node_modules, then /node_modules. let path = 'node_modules/typescript/lib'; let resolvedPath = this.resolve(path); // Construct a path for the top-level node_modules to identify the stopping point. const topLevelNodeModules = this.resolve('/' + path); while (resolvedPath !== topLevelNodeModules) { if (this.exists(resolvedPath)) { return resolvedPath; } // Not here, look one level higher. path = '../' + path; resolvedPath = this.resolve(path); } // The loop exits before checking the existence of /node_modules/typescript at the top level. // This is intentional - if no /node_modules/typescript exists anywhere in the tree, there's // nothing this function can do about it, and TS may error later if it looks for a lib.d.ts file // within this directory. It might be okay, though, if TS never checks for one. return topLevelNodeModules; } abstract resolve(...paths: string[]): AbsoluteFsPath; abstract dirname<T extends string>(file: T): T; abstract join<T extends string>(basePath: T, ...paths: string[]): T; abstract relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath; abstract basename(filePath: string, extension?: string): PathSegment; abstract isRooted(path: string): boolean; abstract normalize<T extends PathString>(path: T): T; protected abstract splitPath<T extends PathString>(path: T): string[]; dump(): Folder { const {entity} = this.findFromPath(this.resolve('/')); if (entity === null || !isFolder(entity)) { return {}; } return this.cloneFolder(entity); } init(folder: Folder): void { this.mount(this.resolve('/'), folder); }
{ "end_byte": 8517, "start_byte": 431, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts_8521_12449
mount(path: AbsoluteFsPath, folder: Folder): void { if (this.exists(path)) { throw new Error(`Unable to mount in '${path}' as it already exists.`); } const mountFolder = this.ensureDir(path); this.copyInto(folder, mountFolder); } private cloneFolder(folder: Folder): Folder { const clone: Folder = {}; this.copyInto(folder, clone); return clone; } private copyInto(from: Folder, to: Folder): void { for (const path in from) { const item = from[path]; const canonicalPath = this.getCanonicalPath(path); if (isSymLink(item)) { to[canonicalPath] = new SymLink(this.getCanonicalPath(item.path)); } else if (isFolder(item)) { to[canonicalPath] = this.cloneFolder(item); } else { to[canonicalPath] = from[path]; } } } protected findFromPath(path: AbsoluteFsPath, options?: {followSymLinks: boolean}): FindResult { const followSymLinks = !!options && options.followSymLinks; const segments = this.splitPath(path); if (segments.length > 1 && segments[segments.length - 1] === '') { // Remove a trailing slash (unless the path was only `/`) segments.pop(); } // Convert the root folder to a canonical empty string `""` (on Windows it would be `C:`). segments[0] = ''; let current: Entity | null = this._fileTree; while (segments.length) { current = current[this.getCanonicalPath(segments.shift()!)]; if (current === undefined) { return {path, entity: null}; } if (segments.length > 0) { if (isFile(current)) { // Reaching a file when there's still remaining segments means that the requested path // does not actually exist. current = null; break; } if (isSymLink(current)) { // Intermediate directories that are themselves symlinks should always be followed // regardless of `followSymLinks`, as otherwise the remaining segments would not be found. return this.findFromPath(resolve(current.path, ...segments), {followSymLinks}); } } if (isFile(current)) { break; } if (isSymLink(current)) { if (followSymLinks) { return this.findFromPath(resolve(current.path, ...segments), {followSymLinks}); } else { break; } } } return {path, entity: current}; } protected splitIntoFolderAndFile(path: AbsoluteFsPath): [AbsoluteFsPath, string] { const segments = this.splitPath(this.getCanonicalPath(path)); const file = segments.pop()!; return [path.substring(0, path.length - file.length - 1) as AbsoluteFsPath, file]; } protected getCanonicalPath<T extends string>(p: T): T { return this.isCaseSensitive() ? p : (p.toLowerCase() as T); } } export interface FindResult { path: AbsoluteFsPath; entity: Entity | null; } export type Entity = Folder | File | SymLink; export interface Folder { [pathSegments: string]: Entity; } export type File = string | Uint8Array; export class SymLink { constructor(public path: AbsoluteFsPath) {} } class MockFileStats implements FileStats { constructor(private entity: Entity) {} isFile(): boolean { return isFile(this.entity); } isDirectory(): boolean { return isFolder(this.entity); } isSymbolicLink(): boolean { return isSymLink(this.entity); } } class MockFileSystemError extends Error { constructor( public code: string, public path: string, message: string, ) { super(message); } } export function isFile(item: Entity | null): item is File { return Buffer.isBuffer(item) || typeof item === 'string'; } export function isSymLink(item: Entity | null): item is SymLink { return item instanceof SymLink; } export function isFolder(item: Entity | null): item is Folder { return item !== null && !isFile(item) && !isSymLink(item); }
{ "end_byte": 12449, "start_byte": 8521, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts_0_2541
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import * as os from 'os'; import {NodeJSFileSystem} from '../../src/node_js_file_system'; import {AbsoluteFsPath, PathSegment, PathString} from '../../src/types'; import {MockFileSystem} from './mock_file_system'; const isWindows = os.platform() === 'win32'; export class MockFileSystemNative extends MockFileSystem { constructor(cwd: AbsoluteFsPath = '/' as AbsoluteFsPath) { super(undefined, cwd); } // Delegate to the real NodeJSFileSystem for these path related methods override resolve(...paths: string[]): AbsoluteFsPath { return NodeJSFileSystem.prototype.resolve.call(this, this.pwd(), ...paths); } override dirname<T extends string>(file: T): T { return NodeJSFileSystem.prototype.dirname.call(this, file) as T; } override join<T extends string>(basePath: T, ...paths: string[]): T { return NodeJSFileSystem.prototype.join.call(this, basePath, ...paths) as T; } override relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return NodeJSFileSystem.prototype.relative.call(this, from, to); } override basename(filePath: string, extension?: string): PathSegment { return NodeJSFileSystem.prototype.basename.call(this, filePath, extension); } override isCaseSensitive() { return NodeJSFileSystem.prototype.isCaseSensitive.call(this); } override isRooted(path: string): boolean { return NodeJSFileSystem.prototype.isRooted.call(this, path); } override isRoot(path: AbsoluteFsPath): boolean { return NodeJSFileSystem.prototype.isRoot.call(this, path); } override normalize<T extends PathString>(path: T): T { // When running in Windows, absolute paths are normalized to always include a drive letter. This // ensures that rooted posix paths used in tests will be normalized to real Windows paths, i.e. // including a drive letter. Note that the same normalization is done in emulated Windows mode // (see `MockFileSystemWindows`) so that the behavior is identical between native Windows and // emulated Windows mode. if (isWindows) { path = path.replace(/^[\/\\]/i, 'C:/') as T; } return NodeJSFileSystem.prototype.normalize.call(this, path) as T; } protected override splitPath<T>(path: string): string[] { return path.split(/[\\\/]/); } }
{ "end_byte": 2541, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_native.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts_0_5647
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="jasmine"/> import ts from 'typescript'; import {absoluteFrom, setFileSystem} from '../../src/helpers'; import {InvalidFileSystem} from '../../src/invalid_file_system'; import {AbsoluteFsPath} from '../../src/types'; import {MockFileSystem} from './mock_file_system'; import {MockFileSystemNative} from './mock_file_system_native'; import {MockFileSystemPosix} from './mock_file_system_posix'; import {MockFileSystemWindows} from './mock_file_system_windows'; export interface TestFile { name: AbsoluteFsPath; contents: string; isRoot?: boolean | undefined; } export interface RunInEachFileSystemFn { (callback: (os: string) => void): void; windows(callback: (os: string) => void): void; unix(callback: (os: string) => void): void; native(callback: (os: string) => void): void; osX(callback: (os: string) => void): void; } const FS_NATIVE = 'Native'; const FS_OS_X = 'OS/X'; const FS_UNIX = 'Unix'; const FS_WINDOWS = 'Windows'; const FS_ALL = [FS_OS_X, FS_WINDOWS, FS_UNIX, FS_NATIVE]; function runInEachFileSystemFn(callback: (os: string) => void) { FS_ALL.forEach((os) => runInFileSystem(os, callback, false)); } function runInFileSystem(os: string, callback: (os: string) => void, error: boolean) { describe(`<<FileSystem: ${os}>>`, () => { beforeEach(() => initMockFileSystem(os)); afterEach(() => setFileSystem(new InvalidFileSystem())); callback(os); if (error) { afterAll(() => { throw new Error(`runInFileSystem limited to ${os}, cannot pass`); }); } }); } export const runInEachFileSystem: RunInEachFileSystemFn = runInEachFileSystemFn as RunInEachFileSystemFn; runInEachFileSystem.native = (callback: (os: string) => void) => runInFileSystem(FS_NATIVE, callback, true); runInEachFileSystem.osX = (callback: (os: string) => void) => runInFileSystem(FS_OS_X, callback, true); runInEachFileSystem.unix = (callback: (os: string) => void) => runInFileSystem(FS_UNIX, callback, true); runInEachFileSystem.windows = (callback: (os: string) => void) => runInFileSystem(FS_WINDOWS, callback, true); export function initMockFileSystem(os: string, cwd?: AbsoluteFsPath): MockFileSystem { const fs = createMockFileSystem(os, cwd); setFileSystem(fs); monkeyPatchTypeScript(fs); return fs; } function createMockFileSystem(os: string, cwd?: AbsoluteFsPath): MockFileSystem { switch (os) { case 'OS/X': return new MockFileSystemPosix(/* isCaseSensitive */ false, cwd); case 'Unix': return new MockFileSystemPosix(/* isCaseSensitive */ true, cwd); case 'Windows': return new MockFileSystemWindows(/* isCaseSensitive*/ false, cwd); case 'Native': return new MockFileSystemNative(cwd); default: throw new Error('FileSystem not supported'); } } function monkeyPatchTypeScript(fs: MockFileSystem) { ts.sys.fileExists = (path) => { const absPath = fs.resolve(path); return fs.exists(absPath) && fs.stat(absPath).isFile(); }; ts.sys.getCurrentDirectory = () => fs.pwd(); ts.sys.getDirectories = getDirectories; ts.sys.readFile = fs.readFile.bind(fs); ts.sys.resolvePath = fs.resolve.bind(fs); ts.sys.writeFile = fs.writeFile.bind(fs); ts.sys.directoryExists = directoryExists; ts.sys.readDirectory = readDirectory; function getDirectories(path: string): string[] { return fs.readdir(absoluteFrom(path)).filter((p) => fs.stat(fs.resolve(path, p)).isDirectory()); } function getFileSystemEntries(path: string): FileSystemEntries { const files: string[] = []; const directories: string[] = []; const absPath = fs.resolve(path); const entries = fs.readdir(absPath); for (const entry of entries) { if (entry == '.' || entry === '..') { continue; } const absPath = fs.resolve(path, entry); const stat = fs.stat(absPath); if (stat.isDirectory()) { directories.push(absPath); } else if (stat.isFile()) { files.push(absPath); } } return {files, directories}; } function realPath(path: string): string { return fs.realpath(fs.resolve(path)); } function directoryExists(path: string) { const absPath = fs.resolve(path); return fs.exists(absPath) && fs.stat(absPath).isDirectory(); } // Rather than completely re-implementing we are using the `ts.matchFiles` function, // which is internal to the `ts` namespace. const tsMatchFiles: ( path: string, extensions: ReadonlyArray<string> | undefined, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string, directoryExists: (path: string) => boolean, ) => string[] = (ts as any).matchFiles; function readDirectory( path: string, extensions?: ReadonlyArray<string>, excludes?: ReadonlyArray<string>, includes?: ReadonlyArray<string>, depth?: number, ): string[] { return tsMatchFiles( path, extensions, excludes, includes, fs.isCaseSensitive(), fs.pwd(), depth, getFileSystemEntries, realPath, directoryExists, ); } } interface FileSystemEntries { readonly files: ReadonlyArray<string>; readonly directories: ReadonlyArray<string>; }
{ "end_byte": 5647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/test_helper.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts_0_1523
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import * as p from 'path'; import {AbsoluteFsPath, PathSegment, PathString} from '../../src/types'; import {MockFileSystem} from './mock_file_system'; export class MockFileSystemPosix extends MockFileSystem { override resolve(...paths: string[]): AbsoluteFsPath { const resolved = p.posix.resolve(this.pwd(), ...paths); return this.normalize(resolved) as AbsoluteFsPath; } override dirname<T extends string>(file: T): T { return this.normalize(p.posix.dirname(file)) as T; } override join<T extends string>(basePath: T, ...paths: string[]): T { return this.normalize(p.posix.join(basePath, ...paths)) as T; } override relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return this.normalize(p.posix.relative(from, to)) as PathSegment | AbsoluteFsPath; } override basename(filePath: string, extension?: string): PathSegment { return p.posix.basename(filePath, extension) as PathSegment; } override isRooted(path: string): boolean { return path.startsWith('/'); } protected override splitPath<T extends PathString>(path: T): string[] { return path.split('/'); } override normalize<T extends PathString>(path: T): T { return path.replace(/^[a-z]:\//i, '/').replace(/\\/g, '/') as T; } }
{ "end_byte": 1523, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/helpers.ts_0_3636
/** * @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 {InvalidFileSystem} from './invalid_file_system'; import {AbsoluteFsPath, FileSystem, PathSegment, PathString} from './types'; import {normalizeSeparators} from './util'; let fs: FileSystem = new InvalidFileSystem(); export function getFileSystem(): FileSystem { return fs; } export function setFileSystem(fileSystem: FileSystem) { fs = fileSystem; } /** * Convert the path `path` to an `AbsoluteFsPath`, throwing an error if it's not an absolute path. */ export function absoluteFrom(path: string): AbsoluteFsPath { if (!fs.isRooted(path)) { throw new Error(`Internal Error: absoluteFrom(${path}): path is not absolute`); } return fs.resolve(path); } const ABSOLUTE_PATH = Symbol('AbsolutePath'); /** * Extract an `AbsoluteFsPath` from a `ts.SourceFile`-like object. */ export function absoluteFromSourceFile(sf: {fileName: string}): AbsoluteFsPath { const sfWithPatch = sf as {fileName: string; [ABSOLUTE_PATH]?: AbsoluteFsPath}; if (sfWithPatch[ABSOLUTE_PATH] === undefined) { sfWithPatch[ABSOLUTE_PATH] = fs.resolve(sfWithPatch.fileName); } // Non-null assertion needed since TS doesn't narrow the type of fields that use a symbol as a key // apparently. return sfWithPatch[ABSOLUTE_PATH]!; } /** * Convert the path `path` to a `PathSegment`, throwing an error if it's not a relative path. */ export function relativeFrom(path: string): PathSegment { const normalized = normalizeSeparators(path); if (fs.isRooted(normalized)) { throw new Error(`Internal Error: relativeFrom(${path}): path is not relative`); } return normalized as PathSegment; } /** * Static access to `dirname`. */ export function dirname<T extends PathString>(file: T): T { return fs.dirname(file); } /** * Static access to `join`. */ export function join<T extends PathString>(basePath: T, ...paths: string[]): T { return fs.join(basePath, ...paths); } /** * Static access to `resolve`s. */ export function resolve(basePath: string, ...paths: string[]): AbsoluteFsPath { return fs.resolve(basePath, ...paths); } /** Returns true when the path provided is the root path. */ export function isRoot(path: AbsoluteFsPath): boolean { return fs.isRoot(path); } /** * Static access to `isRooted`. */ export function isRooted(path: string): boolean { return fs.isRooted(path); } /** * Static access to `relative`. */ export function relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return fs.relative(from, to); } /** * Static access to `basename`. */ export function basename(filePath: PathString, extension?: string): PathSegment { return fs.basename(filePath, extension) as PathSegment; } /** * Returns true if the given path is locally relative. * * This is used to work out if the given path is relative (i.e. not absolute) but also is not * escaping the current directory. */ export function isLocalRelativePath(relativePath: string): boolean { return !isRooted(relativePath) && !relativePath.startsWith('..'); } /** * Converts a path to a form suitable for use as a relative module import specifier. * * In other words it adds the `./` to the path if it is locally relative. */ export function toRelativeImport( relativePath: PathSegment | AbsoluteFsPath, ): PathSegment | AbsoluteFsPath { return isLocalRelativePath(relativePath) ? (`./${relativePath}` as PathSegment) : relativePath; }
{ "end_byte": 3636, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/helpers.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts_0_4805
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import fs from 'fs'; import {createRequire} from 'module'; import * as p from 'path'; import {fileURLToPath} from 'url'; import { AbsoluteFsPath, FileStats, FileSystem, PathManipulation, PathSegment, PathString, ReadonlyFileSystem, } from './types'; /** * A wrapper around the Node.js file-system that supports path manipulation. */ export class NodeJSPathManipulation implements PathManipulation { pwd(): AbsoluteFsPath { return this.normalize(process.cwd()) as AbsoluteFsPath; } chdir(dir: AbsoluteFsPath): void { process.chdir(dir); } resolve(...paths: string[]): AbsoluteFsPath { return this.normalize(p.resolve(...paths)) as AbsoluteFsPath; } dirname<T extends string>(file: T): T { return this.normalize(p.dirname(file)) as T; } join<T extends string>(basePath: T, ...paths: string[]): T { return this.normalize(p.join(basePath, ...paths)) as T; } isRoot(path: AbsoluteFsPath): boolean { return this.dirname(path) === this.normalize(path); } isRooted(path: string): boolean { return p.isAbsolute(path); } relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return this.normalize(p.relative(from, to)) as PathSegment | AbsoluteFsPath; } basename(filePath: string, extension?: string): PathSegment { return p.basename(filePath, extension) as PathSegment; } extname(path: AbsoluteFsPath | PathSegment): string { return p.extname(path); } normalize<T extends string>(path: T): T { // Convert backslashes to forward slashes return path.replace(/\\/g, '/') as T; } } // G3-ESM-MARKER: G3 uses CommonJS, but externally everything in ESM. // CommonJS/ESM interop for determining the current file name and containing dir. const isCommonJS = typeof __filename !== 'undefined'; const currentFileUrl = isCommonJS ? null : import.meta.url; const currentFileName = isCommonJS ? __filename : fileURLToPath(currentFileUrl!); /** * A wrapper around the Node.js file-system that supports readonly operations and path manipulation. */ export class NodeJSReadonlyFileSystem extends NodeJSPathManipulation implements ReadonlyFileSystem { private _caseSensitive: boolean | undefined = undefined; isCaseSensitive(): boolean { if (this._caseSensitive === undefined) { // Note the use of the real file-system is intentional: // `this.exists()` relies upon `isCaseSensitive()` so that would cause an infinite recursion. this._caseSensitive = !fs.existsSync(this.normalize(toggleCase(currentFileName))); } return this._caseSensitive; } exists(path: AbsoluteFsPath): boolean { return fs.existsSync(path); } readFile(path: AbsoluteFsPath): string { return fs.readFileSync(path, 'utf8'); } readFileBuffer(path: AbsoluteFsPath): Uint8Array { return fs.readFileSync(path); } readdir(path: AbsoluteFsPath): PathSegment[] { return fs.readdirSync(path) as PathSegment[]; } lstat(path: AbsoluteFsPath): FileStats { return fs.lstatSync(path); } stat(path: AbsoluteFsPath): FileStats { return fs.statSync(path); } realpath(path: AbsoluteFsPath): AbsoluteFsPath { return this.resolve(fs.realpathSync(path)); } getDefaultLibLocation(): AbsoluteFsPath { // G3-ESM-MARKER: G3 uses CommonJS, but externally everything in ESM. const requireFn = isCommonJS ? require : createRequire(currentFileUrl!); return this.resolve(requireFn.resolve('typescript'), '..'); } } /** * A wrapper around the Node.js file-system (i.e. the `fs` package). */ export class NodeJSFileSystem extends NodeJSReadonlyFileSystem implements FileSystem { writeFile(path: AbsoluteFsPath, data: string | Uint8Array, exclusive: boolean = false): void { fs.writeFileSync(path, data, exclusive ? {flag: 'wx'} : undefined); } removeFile(path: AbsoluteFsPath): void { fs.unlinkSync(path); } symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { fs.symlinkSync(target, path); } copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { fs.copyFileSync(from, to); } moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { fs.renameSync(from, to); } ensureDir(path: AbsoluteFsPath): void { fs.mkdirSync(path, {recursive: true}); } removeDeep(path: AbsoluteFsPath): void { fs.rmdirSync(path, {recursive: true}); } } /** * Toggle the case of each character in a string. */ function toggleCase(str: string): string { return str.replace(/\w/g, (ch) => ch.toUpperCase() === ch ? ch.toLowerCase() : ch.toUpperCase(), ); }
{ "end_byte": 4805, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/types.ts_0_3371
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * A `string` representing a specific type of path, with a particular brand `B`. * * A `string` is not assignable to a `BrandedPath`, but a `BrandedPath` is assignable to a `string`. * Two `BrandedPath`s with different brands are not mutually assignable. */ export type BrandedPath<B extends string> = string & { _brand: B; }; /** * A fully qualified path in the file system, in POSIX form. */ export type AbsoluteFsPath = BrandedPath<'AbsoluteFsPath'>; /** * A path that's relative to another (unspecified) root. * * This does not necessarily have to refer to a physical file. */ export type PathSegment = BrandedPath<'PathSegment'>; /** * An abstraction over the path manipulation aspects of a file-system. */ export interface PathManipulation { extname(path: AbsoluteFsPath | PathSegment): string; isRoot(path: AbsoluteFsPath): boolean; isRooted(path: string): boolean; dirname<T extends PathString>(file: T): T; extname(path: AbsoluteFsPath | PathSegment): string; join<T extends PathString>(basePath: T, ...paths: string[]): T; /** * Compute the relative path between `from` and `to`. * * In file-systems that can have multiple file trees the returned path may not actually be * "relative" (i.e. `PathSegment`). For example, Windows can have multiple drives : * `relative('c:/a/b', 'd:/a/c')` would be `d:/a/c'. */ relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath; basename(filePath: string, extension?: string): PathSegment; normalize<T extends PathString>(path: T): T; resolve(...paths: string[]): AbsoluteFsPath; pwd(): AbsoluteFsPath; chdir(path: AbsoluteFsPath): void; } /** * An abstraction over the read-only aspects of a file-system. */ export interface ReadonlyFileSystem extends PathManipulation { isCaseSensitive(): boolean; exists(path: AbsoluteFsPath): boolean; readFile(path: AbsoluteFsPath): string; readFileBuffer(path: AbsoluteFsPath): Uint8Array; readdir(path: AbsoluteFsPath): PathSegment[]; lstat(path: AbsoluteFsPath): FileStats; stat(path: AbsoluteFsPath): FileStats; realpath(filePath: AbsoluteFsPath): AbsoluteFsPath; getDefaultLibLocation(): AbsoluteFsPath; } /** * A basic interface to abstract the underlying file-system. * * This makes it easier to provide mock file-systems in unit tests, * but also to create clever file-systems that have features such as caching. */ export interface FileSystem extends ReadonlyFileSystem { writeFile(path: AbsoluteFsPath, data: string | Uint8Array, exclusive?: boolean): void; removeFile(path: AbsoluteFsPath): void; symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void; copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void; moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void; ensureDir(path: AbsoluteFsPath): void; removeDeep(path: AbsoluteFsPath): void; } export type PathString = string | AbsoluteFsPath | PathSegment; /** * Information about an object in the FileSystem. * This is analogous to the `fs.Stats` class in Node.js. */ export interface FileStats { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean; }
{ "end_byte": 3371, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/types.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts_0_2902
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString} from './types'; /** * The default `FileSystem` that will always fail. * * This is a way of ensuring that the developer consciously chooses and * configures the `FileSystem` before using it; particularly important when * considering static functions like `absoluteFrom()` which rely on * the `FileSystem` under the hood. */ export class InvalidFileSystem implements FileSystem { exists(path: AbsoluteFsPath): boolean { throw makeError(); } readFile(path: AbsoluteFsPath): string { throw makeError(); } readFileBuffer(path: AbsoluteFsPath): Uint8Array { throw makeError(); } writeFile(path: AbsoluteFsPath, data: string | Uint8Array, exclusive?: boolean): void { throw makeError(); } removeFile(path: AbsoluteFsPath): void { throw makeError(); } symlink(target: AbsoluteFsPath, path: AbsoluteFsPath): void { throw makeError(); } readdir(path: AbsoluteFsPath): PathSegment[] { throw makeError(); } lstat(path: AbsoluteFsPath): FileStats { throw makeError(); } stat(path: AbsoluteFsPath): FileStats { throw makeError(); } pwd(): AbsoluteFsPath { throw makeError(); } chdir(path: AbsoluteFsPath): void { throw makeError(); } extname(path: AbsoluteFsPath | PathSegment): string { throw makeError(); } copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { throw makeError(); } moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { throw makeError(); } ensureDir(path: AbsoluteFsPath): void { throw makeError(); } removeDeep(path: AbsoluteFsPath): void { throw makeError(); } isCaseSensitive(): boolean { throw makeError(); } resolve(...paths: string[]): AbsoluteFsPath { throw makeError(); } dirname<T extends PathString>(file: T): T { throw makeError(); } join<T extends PathString>(basePath: T, ...paths: string[]): T { throw makeError(); } isRoot(path: AbsoluteFsPath): boolean { throw makeError(); } isRooted(path: string): boolean { throw makeError(); } relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { throw makeError(); } basename(filePath: string, extension?: string): PathSegment { throw makeError(); } realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { throw makeError(); } getDefaultLibLocation(): AbsoluteFsPath { throw makeError(); } normalize<T extends PathString>(path: T): T { throw makeError(); } } function makeError() { return new Error( 'FileSystem has not been configured. Please call `setFileSystem()` before calling this method.', ); }
{ "end_byte": 2902, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/util.ts_0_1123
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {AbsoluteFsPath, PathString} from './types'; const TS_DTS_JS_EXTENSION = /(?:\.d)?\.ts$|\.js$/; /** * Convert Windows-style separators to POSIX separators. */ export function normalizeSeparators(path: string): string { // TODO: normalize path only for OS that need it. return path.replace(/\\/g, '/'); } /** * Remove a .ts, .d.ts, or .js extension from a file name. */ export function stripExtension<T extends PathString>(path: T): T { return path.replace(TS_DTS_JS_EXTENSION, '') as T; } export function getSourceFileOrError(program: ts.Program, fileName: AbsoluteFsPath): ts.SourceFile { const sf = program.getSourceFile(fileName); if (sf === undefined) { throw new Error( `Program does not contain "${fileName}" - available files are ${program .getSourceFiles() .map((sf) => sf.fileName) .join(', ')}`, ); } return sf; }
{ "end_byte": 1123, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/util.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts_0_4642
/** * @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 { absoluteFromSourceFile, dirname, isLocalRelativePath, relative, resolve, toRelativeImport, } from './helpers'; import {AbsoluteFsPath, BrandedPath, PathSegment} from './types'; import {stripExtension} from './util'; /** * A path that's relative to the logical root of a TypeScript project (one of the project's * rootDirs). * * Paths in the type system use POSIX format. */ export type LogicalProjectPath = BrandedPath<'LogicalProjectPath'>; export const LogicalProjectPath = { /** * Get the relative path between two `LogicalProjectPath`s. * * This will return a `PathSegment` which would be a valid module specifier to use in `from` when * importing from `to`. */ relativePathBetween: function (from: LogicalProjectPath, to: LogicalProjectPath): PathSegment { const relativePath = relative(dirname(resolve(from)), resolve(to)); return toRelativeImport(relativePath) as PathSegment; }, }; /** * A utility class which can translate absolute paths to source files into logical paths in * TypeScript's logical file system, based on the root directories of the project. */ export class LogicalFileSystem { /** * The root directories of the project, sorted with the longest path first. */ private rootDirs: AbsoluteFsPath[]; /** * The same root directories as `rootDirs` but with each one converted to its * canonical form for matching in case-insensitive file-systems. */ private canonicalRootDirs: AbsoluteFsPath[]; /** * A cache of file paths to project paths, because computation of these paths is slightly * expensive. */ private cache: Map<AbsoluteFsPath, LogicalProjectPath | null> = new Map(); constructor( rootDirs: AbsoluteFsPath[], private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, ) { // Make a copy and sort it by length in reverse order (longest first). This speeds up lookups, // since there's no need to keep going through the array once a match is found. this.rootDirs = rootDirs.concat([]).sort((a, b) => b.length - a.length); this.canonicalRootDirs = this.rootDirs.map( (dir) => this.compilerHost.getCanonicalFileName(dir) as AbsoluteFsPath, ); } /** * Get the logical path in the project of a `ts.SourceFile`. * * This method is provided as a convenient alternative to calling * `logicalPathOfFile(absoluteFromSourceFile(sf))`. */ logicalPathOfSf(sf: ts.SourceFile): LogicalProjectPath | null { return this.logicalPathOfFile(absoluteFromSourceFile(sf)); } /** * Get the logical path in the project of a source file. * * @returns A `LogicalProjectPath` to the source file, or `null` if the source file is not in any * of the TS project's root directories. */ logicalPathOfFile(physicalFile: AbsoluteFsPath): LogicalProjectPath | null { if (!this.cache.has(physicalFile)) { const canonicalFilePath = this.compilerHost.getCanonicalFileName( physicalFile, ) as AbsoluteFsPath; let logicalFile: LogicalProjectPath | null = null; for (let i = 0; i < this.rootDirs.length; i++) { const rootDir = this.rootDirs[i]; const canonicalRootDir = this.canonicalRootDirs[i]; if (isWithinBasePath(canonicalRootDir, canonicalFilePath)) { // Note that we match against canonical paths but then create the logical path from // original paths. logicalFile = this.createLogicalProjectPath(physicalFile, rootDir); // The logical project does not include any special "node_modules" nested directories. if (logicalFile.indexOf('/node_modules/') !== -1) { logicalFile = null; } else { break; } } } this.cache.set(physicalFile, logicalFile); } return this.cache.get(physicalFile)!; } private createLogicalProjectPath( file: AbsoluteFsPath, rootDir: AbsoluteFsPath, ): LogicalProjectPath { const logicalPath = stripExtension(file.slice(rootDir.length)); return (logicalPath.startsWith('/') ? logicalPath : '/' + logicalPath) as LogicalProjectPath; } } /** * Is the `path` a descendant of the `base`? * E.g. `foo/bar/zee` is within `foo/bar` but not within `foo/car`. */ function isWithinBasePath(base: AbsoluteFsPath, path: AbsoluteFsPath): boolean { return isLocalRelativePath(relative(base, path)); }
{ "end_byte": 4642, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/logical.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts_0_2350
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import * as os from 'os'; import ts from 'typescript'; import {absoluteFrom} from './helpers'; import {FileSystem} from './types'; export class NgtscCompilerHost implements ts.CompilerHost { constructor( protected fs: FileSystem, protected options: ts.CompilerOptions = {}, ) {} getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile | undefined { const text = this.readFile(fileName); return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, true) : undefined; } getDefaultLibFileName(options: ts.CompilerOptions): string { return this.fs.join(this.getDefaultLibLocation(), ts.getDefaultLibFileName(options)); } getDefaultLibLocation(): string { return this.fs.getDefaultLibLocation(); } writeFile( fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray<ts.SourceFile>, ): void { const path = absoluteFrom(fileName); this.fs.ensureDir(this.fs.dirname(path)); this.fs.writeFile(path, data); } getCurrentDirectory(): string { return this.fs.pwd(); } getCanonicalFileName(fileName: string): string { return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase(); } useCaseSensitiveFileNames(): boolean { return this.fs.isCaseSensitive(); } getNewLine(): string { switch (this.options.newLine) { case ts.NewLineKind.CarriageReturnLineFeed: return '\r\n'; case ts.NewLineKind.LineFeed: return '\n'; default: return os.EOL; } } fileExists(fileName: string): boolean { const absPath = this.fs.resolve(fileName); return this.fs.exists(absPath) && this.fs.stat(absPath).isFile(); } readFile(fileName: string): string | undefined { const absPath = this.fs.resolve(fileName); if (!this.fileExists(absPath)) { return undefined; } return this.fs.readFile(absPath); } realpath(path: string): string { return this.fs.realpath(this.fs.resolve(path)); } }
{ "end_byte": 2350, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.ts" }
angular/packages/compiler-cli/src/ngtsc/file_system/src/ts_read_directory.ts_0_3450
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // We use TypeScript's native `ts.matchFiles` utility for the virtual file systems // and their TypeScript compiler host `readDirectory` implementation. TypeScript's // function implements complex logic for matching files with respect to root // directory, extensions, excludes, includes etc. The function is currently // internal but we can use it as the API most likely will not change any time soon, // nor does it seem like this is being made public any time soon. // Related issue for tracking: https://github.com/microsoft/TypeScript/issues/13793. import ts from 'typescript'; import {FileSystem} from './types'; // https://github.com/microsoft/TypeScript/blob/b397d1fd4abd0edef85adf0afd91c030bb0b4955/src/compiler/utilities.ts#L6192 declare module 'typescript' { export interface FileSystemEntries { readonly files: readonly string[]; readonly directories: readonly string[]; } export const matchFiles: | undefined | (( path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string, directoryExists: (path: string) => boolean, ) => string[]); } /** * Creates a {@link ts.CompilerHost#readDirectory} implementation function, * that leverages the specified file system (that may be e.g. virtual). */ export function createFileSystemTsReadDirectoryFn( fs: FileSystem, ): NonNullable<ts.CompilerHost['readDirectory']> { if (ts.matchFiles === undefined) { throw Error( 'Unable to read directory in configured file system. This means that ' + 'TypeScript changed its file matching internals.\n\nPlease consider downgrading your ' + 'TypeScript version, and report an issue in the Angular framework repository.', ); } const matchFilesFn = ts.matchFiles.bind(ts); return ( rootDir: string, extensions: string[], excludes: string[] | undefined, includes: string[], depth?: number, ): string[] => { const directoryExists = (p: string) => { const resolvedPath = fs.resolve(p); return fs.exists(resolvedPath) && fs.stat(resolvedPath).isDirectory(); }; return matchFilesFn( rootDir, extensions, excludes, includes, fs.isCaseSensitive(), fs.pwd(), depth, (p) => { const resolvedPath = fs.resolve(p); // TS also gracefully returns an empty file set. if (!directoryExists(resolvedPath)) { return {directories: [], files: []}; } const children = fs.readdir(resolvedPath); const files: string[] = []; const directories: string[] = []; for (const child of children) { if (fs.stat(fs.join(resolvedPath, child))?.isDirectory()) { directories.push(child); } else { files.push(child); } } return {files, directories}; }, (p) => fs.resolve(p), (p) => directoryExists(p), ); }; }
{ "end_byte": 3450, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/file_system/src/ts_read_directory.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/BUILD.bazel_0_546
package(default_visibility = ["//visibility:public"]) load("//tools:defaults.bzl", "ts_library") ts_library( name = "scope", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], )
{ "end_byte": 546, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/scope/index.ts_0_759
/** * @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 { ComponentScopeKind, ComponentScopeReader, ExportScope, LocalModuleScope, ScopeData, StandaloneScope, } from './src/api'; export {CompoundComponentScopeReader} from './src/component_scope'; export {DtsModuleScopeResolver, MetadataDtsModuleScopeResolver} from './src/dependency'; export {DeclarationData, LocalModuleScopeRegistry, LocalNgModuleData} from './src/local'; export {TypeCheckScope, TypeCheckScopeRegistry} from './src/typecheck'; export {makeNotStandaloneDiagnostic, makeUnknownComponentImportDiagnostic} from './src/util';
{ "end_byte": 759, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/index.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts_0_3037
/** * @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 {ExternalExpr, ExternalReference} from '@angular/compiler'; import ts from 'typescript'; import {UnifiedModulesHost} from '../../core/api'; import {absoluteFrom} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {AliasingHost, Reference, UnifiedModulesAliasingHost} from '../../imports'; import {DtsMetadataReader} from '../../metadata'; import {ClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {makeProgram} from '../../testing'; import {ExportScope} from '../src/api'; import {MetadataDtsModuleScopeResolver} from '../src/dependency'; const MODULE_FROM_NODE_MODULES_PATH = /.*node_modules\/(\w+)\/index\.d\.ts$/; const testHost: UnifiedModulesHost = { fileNameToModuleName: function (imported: string): string { const res = MODULE_FROM_NODE_MODULES_PATH.exec(imported)!; return 'root/' + res[1]; }, }; /** * Simple metadata types are added to the top of each testing file, for convenience. */ const PROLOG = ` export declare type ModuleMeta<A, B, C, D> = never; export declare type ComponentMeta<A, B, C, D, E, F> = never; export declare type DirectiveMeta<A, B, C, D, E, F> = never; export declare type PipeMeta<A, B> = never; `; /** * Construct the testing environment with a given set of absolute modules and their contents. * * This returns both the `MetadataDtsModuleScopeResolver` and a `refs` object which can be * destructured to retrieve references to specific declared classes. */ function makeTestEnv( modules: {[module: string]: string}, aliasGenerator: AliasingHost | null = null, ): { refs: {[name: string]: Reference<ClassDeclaration>}; resolver: MetadataDtsModuleScopeResolver; } { // Map the modules object to an array of files for `makeProgram`. const files = Object.keys(modules).map((moduleName) => { return { name: absoluteFrom(`/node_modules/${moduleName}/index.d.ts`), contents: PROLOG + (modules as any)[moduleName], }; }); const {program} = makeProgram(files); const checker = program.getTypeChecker(); const reflector = new TypeScriptReflectionHost(checker); const resolver = new MetadataDtsModuleScopeResolver( new DtsMetadataReader(checker, reflector), aliasGenerator, ); // Resolver for the refs object. const get = (target: {}, name: string): Reference<ts.ClassDeclaration> => { for (const sf of program.getSourceFiles()) { const symbol = checker.getSymbolAtLocation(sf)!; const exportedSymbol = symbol.exports!.get(name as ts.__String); if (exportedSymbol !== undefined) { const decl = exportedSymbol.valueDeclaration as ts.ClassDeclaration; return new Reference(decl); } } throw new Error('Class not found: ' + name); }; return { resolver, refs: new Proxy({}, {get}), }; }
{ "end_byte": 3037, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts_3039_10576
runInEachFileSystem(() => { describe('MetadataDtsModuleScopeResolver', () => { it('should produce an accurate scope for a basic NgModule', () => { const {resolver, refs} = makeTestEnv({ 'test': ` export declare class Dir { static ɵdir: DirectiveMeta<Dir, '[dir]', ['exportAs'], {'input': 'input2'}, {'output': 'output2'}, ['query']>; } export declare class Module { static ɵmod: ModuleMeta<Module, [typeof Dir], never, [typeof Dir]>; } `, }); const {Dir, Module} = refs; const scope = resolver.resolve(Module)!; expect(scopeToRefs(scope)).toEqual([Dir]); }); it('should produce an accurate scope when a module is exported', () => { const {resolver, refs} = makeTestEnv({ 'test': ` export declare class Dir { static ɵdir: DirectiveMeta<Dir, '[dir]', never, never, never, never>; } export declare class ModuleA { static ɵmod: ModuleMeta<ModuleA, [typeof Dir], never, [typeof Dir]>; } export declare class ModuleB { static ɵmod: ModuleMeta<ModuleB, never, never, [typeof ModuleA]>; } `, }); const {Dir, ModuleB} = refs; const scope = resolver.resolve(ModuleB)!; expect(scopeToRefs(scope)).toEqual([Dir]); }); it('should resolve correctly across modules', () => { const {resolver, refs} = makeTestEnv({ 'declaration': ` export declare class Dir { static ɵdir: DirectiveMeta<Dir, '[dir]', never, never, never, never>; } export declare class ModuleA { static ɵmod: ModuleMeta<ModuleA, [typeof Dir], never, [typeof Dir]>; } `, 'exported': ` import * as d from 'declaration'; export declare class ModuleB { static ɵmod: ModuleMeta<ModuleB, never, never, [typeof d.ModuleA]>; } `, }); const {Dir, ModuleB} = refs; const scope = resolver.resolve(ModuleB)!; expect(scopeToRefs(scope).map((ref) => ref.node)).toEqual([Dir.node]); // Explicitly verify that the directive has the correct owning module. expect(scope.exported.dependencies[0].ref.bestGuessOwningModule).toEqual({ specifier: 'declaration', resolutionContext: ModuleB.node.getSourceFile().fileName, }); }); it('should write correct aliases for deep dependencies', () => { const {resolver, refs} = makeTestEnv( { 'deep': ` export declare class DeepDir { static ɵdir: DirectiveMeta<DeepDir, '[deep]', never, never, never, never>; } export declare class DeepModule { static ɵmod: ModuleMeta<DeepModule, [typeof DeepDir], never, [typeof DeepDir]>; } `, 'middle': ` import * as deep from 'deep'; export declare class MiddleDir { static ɵdir: DirectiveMeta<MiddleDir, '[middle]', never, never, never, never>; } export declare class MiddleModule { static ɵmod: ModuleMeta<MiddleModule, [typeof MiddleDir], never, [typeof MiddleDir, typeof deep.DeepModule]>; } `, 'shallow': ` import * as middle from 'middle'; export declare class ShallowDir { static ɵdir: DirectiveMeta<ShallowDir, '[middle]', never, never, never, never>; } export declare class ShallowModule { static ɵmod: ModuleMeta<ShallowModule, [typeof ShallowDir], never, [typeof ShallowDir, typeof middle.MiddleModule]>; } `, }, new UnifiedModulesAliasingHost(testHost), ); const {ShallowModule} = refs; const scope = resolver.resolve(ShallowModule)!; const [DeepDir, MiddleDir, ShallowDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toEqual({ moduleName: 'root/shallow', name: 'ɵng$root$deep$$DeepDir', }); expect(getAlias(MiddleDir)).toEqual({ moduleName: 'root/shallow', name: 'ɵng$root$middle$$MiddleDir', }); expect(getAlias(ShallowDir)).toBeNull(); }); it('should write correct aliases for bare directives in exports', () => { const {resolver, refs} = makeTestEnv( { 'deep': ` export declare class DeepDir { static ɵdir: DirectiveMeta<DeepDir, '[deep]', never, never, never, never>; } export declare class DeepModule { static ɵmod: ModuleMeta<DeepModule, [typeof DeepDir], never, [typeof DeepDir]>; } `, 'middle': ` import * as deep from 'deep'; export declare class MiddleDir { static ɵdir: DirectiveMeta<MiddleDir, '[middle]', never, never, never, never>; } export declare class MiddleModule { static ɵmod: ModuleMeta<MiddleModule, [typeof MiddleDir], [typeof deep.DeepModule], [typeof MiddleDir, typeof deep.DeepDir]>; } `, 'shallow': ` import * as middle from 'middle'; export declare class ShallowDir { static ɵdir: DirectiveMeta<ShallowDir, '[middle]', never, never, never, never>; } export declare class ShallowModule { static ɵmod: ModuleMeta<ShallowModule, [typeof ShallowDir], never, [typeof ShallowDir, typeof middle.MiddleModule]>; } `, }, new UnifiedModulesAliasingHost(testHost), ); const {ShallowModule} = refs; const scope = resolver.resolve(ShallowModule)!; const [DeepDir, MiddleDir, ShallowDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toEqual({ moduleName: 'root/shallow', name: 'ɵng$root$deep$$DeepDir', }); expect(getAlias(MiddleDir)).toEqual({ moduleName: 'root/shallow', name: 'ɵng$root$middle$$MiddleDir', }); expect(getAlias(ShallowDir)).toBeNull(); }); it('should not use an alias if a directive is declared in the same file as the re-exporting module', () => { const {resolver, refs} = makeTestEnv( { 'module': ` export declare class DeepDir { static ɵdir: DirectiveMeta<DeepDir, '[deep]', never, never, never, never>; } export declare class DeepModule { static ɵmod: ModuleMeta<DeepModule, [typeof DeepDir], never, [typeof DeepDir]>; } export declare class DeepExportModule { static ɵmod: ModuleMeta<DeepExportModule, never, never, [typeof DeepModule]>; } `, }, new UnifiedModulesAliasingHost(testHost), ); const {DeepExportModule} = refs; const scope = resolver.resolve(DeepExportModule)!; const [DeepDir] = scopeToRefs(scope); expect(getAlias(DeepDir)).toBeNull(); }); }); function scopeToRefs(scope: ExportScope): Reference<ClassDeclaration>[] { return scope.exported.dependencies .map((dep) => dep.ref) .sort((a, b) => a.debugName!.localeCompare(b.debugName!)); } function getAlias(ref: Reference<ClassDeclaration>): ExternalReference | null { if (ref.alias === null) { return null; } else { return (ref.alias as ExternalExpr).value; } } });
{ "end_byte": 10576, "start_byte": 3039, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/dependency_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/test/BUILD.bazel_0_908
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "test_lib", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 908, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts_0_1426
/** * @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 {Reference, ReferenceEmitter} from '../../imports'; import { ClassPropertyMapping, CompoundMetadataRegistry, DirectiveMeta, LocalMetadataRegistry, MatchSource, MetadataRegistry, MetaKind, PipeMeta, } from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {LocalModuleScope, ScopeData} from '../src/api'; import {DtsModuleScopeResolver} from '../src/dependency'; import {LocalModuleScopeRegistry} from '../src/local'; function registerFakeRefs(registry: MetadataRegistry): { [name: string]: Reference<ClassDeclaration>; } { const get = (target: {}, name: string): Reference<ClassDeclaration> => { const sf = ts.createSourceFile( name + '.ts', `export class ${name} {}`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS, ); const clazz = sf.statements[0] as unknown as ClassDeclaration; const ref = new Reference(clazz); if (name.startsWith('Dir') || name.startsWith('Cmp')) { registry.registerDirectiveMetadata(fakeDirective(ref)); } else if (name.startsWith('Pipe')) { registry.registerPipeMetadata(fakePipe(ref)); } return ref; }; return new Proxy({}, {get}); }
{ "end_byte": 1426, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts_1428_10019
describe('LocalModuleScopeRegistry', () => { const refEmitter = new ReferenceEmitter([]); let scopeRegistry!: LocalModuleScopeRegistry; let metaRegistry!: MetadataRegistry; beforeEach(() => { const localRegistry = new LocalMetadataRegistry(); scopeRegistry = new LocalModuleScopeRegistry( localRegistry, localRegistry, new MockDtsModuleScopeResolver(), refEmitter, null, ); metaRegistry = new CompoundMetadataRegistry([localRegistry, scopeRegistry]); }); it('should produce an accurate LocalModuleScope for a basic NgModule', () => { const {Dir1, Dir2, Pipe1, Module} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(Module.node), imports: [], declarations: [Dir1, Dir2, Pipe1], exports: [Dir1, Pipe1], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scope = scopeRegistry.getScopeOfModule(Module.node) as LocalModuleScope; expect(scopeToRefs(scope.compilation)).toEqual([Dir1, Dir2, Pipe1]); expect(scopeToRefs(scope.exported)).toEqual([Dir1, Pipe1]); }); it('should produce accurate LocalModuleScopes for a complex module chain', () => { const {DirA, DirB, DirCI, DirCE, ModuleA, ModuleB, ModuleC} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleA.node), imports: [ModuleB], declarations: [DirA], exports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleB.node), exports: [ModuleC, DirB], declarations: [DirB], imports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleC.node), declarations: [DirCI, DirCE], exports: [DirCE], imports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scopeA = scopeRegistry.getScopeOfModule(ModuleA.node) as LocalModuleScope; expect(scopeToRefs(scopeA.compilation)).toEqual([DirA, DirB, DirCE]); expect(scopeToRefs(scopeA.exported)).toEqual([]); }); it('should not treat exported modules as imported', () => { const {Dir, ModuleA, ModuleB} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleA.node), exports: [ModuleB], imports: [], declarations: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleB.node), declarations: [Dir], exports: [Dir], imports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scopeA = scopeRegistry.getScopeOfModule(ModuleA.node) as LocalModuleScope; expect(scopeToRefs(scopeA.compilation)).toEqual([]); expect(scopeToRefs(scopeA.exported)).toEqual([Dir]); }); it('should deduplicate declarations and exports', () => { const {DirA, ModuleA, DirB, ModuleB, ModuleC} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleA.node), declarations: [DirA, DirA], imports: [ModuleB, ModuleC], exports: [DirA, DirA, DirB, ModuleB], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleB.node), declarations: [DirB], imports: [], exports: [DirB], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleC.node), declarations: [], imports: [], exports: [ModuleB], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scope = scopeRegistry.getScopeOfModule(ModuleA.node) as LocalModuleScope; expect(scopeToRefs(scope.compilation)).toEqual([DirA, DirB]); expect(scopeToRefs(scope.exported)).toEqual([DirA, DirB]); }); it('should preserve reference identities in module metadata', () => { const {Dir, Module} = registerFakeRefs(metaRegistry); const idSf = ts.createSourceFile('id.ts', 'var id;', ts.ScriptTarget.Latest, true); // Create a new Reference to Dir, with a special `ts.Identifier`, and register the directive // using it. This emulates what happens when an NgModule declares a Directive. const idVar = idSf.statements[0] as ts.VariableStatement; const id = idVar.declarationList.declarations[0].name as ts.Identifier; const DirInModule = new Reference(Dir.node); DirInModule.addIdentifier(id); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(Module.node), exports: [], imports: [], declarations: [DirInModule], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scope = scopeRegistry.getScopeOfModule(Module.node) as LocalModuleScope; expect(scope.compilation.dependencies[0].ref.getIdentityIn(idSf)).toBe(id); }); it("should allow directly exporting a directive that's not imported", () => { const {Dir, ModuleA, ModuleB} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleA.node), exports: [Dir], imports: [ModuleB], declarations: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleB.node), declarations: [Dir], exports: [Dir], imports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); const scopeA = scopeRegistry.getScopeOfModule(ModuleA.node) as LocalModuleScope; expect(scopeToRefs(scopeA.exported)).toEqual([Dir]); }); it("should not allow directly exporting a directive that's not imported", () => { const {Dir, ModuleA, ModuleB} = registerFakeRefs(metaRegistry); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleA.node), exports: [Dir], imports: [], declarations: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); metaRegistry.registerNgModuleMetadata({ kind: MetaKind.NgModule, ref: new Reference(ModuleB.node), declarations: [Dir], exports: [Dir], imports: [], schemas: [], rawDeclarations: null, rawImports: null, rawExports: null, decorator: null, mayDeclareProviders: false, }); expect(scopeRegistry.getScopeOfModule(ModuleA.node)!.compilation.isPoisoned).toBeTrue(); // ModuleA should have associated diagnostics as it exports `Dir` without declaring it. expect(scopeRegistry.getDiagnosticsOfModule(ModuleA.node)).not.toBeNull(); // ModuleB should have no diagnostics as it correctly declares `Dir`. expect(scopeRegistry.getDiagnosticsOfModule(ModuleB.node)).toBeNull(); }); });
{ "end_byte": 10019, "start_byte": 1428, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts_10021_11787
function fakeDirective(ref: Reference<ClassDeclaration>): DirectiveMeta { const name = ref.debugName!; return { kind: MetaKind.Directive, matchSource: MatchSource.Selector, ref, name, selector: `[${ref.debugName}]`, isComponent: name.startsWith('Cmp'), inputs: ClassPropertyMapping.fromMappedObject({}), outputs: ClassPropertyMapping.fromMappedObject({}), exportAs: null, queries: [], hasNgTemplateContextGuard: false, ngTemplateGuards: [], coercedInputFields: new Set<string>(), restrictedInputFields: new Set<string>(), stringLiteralInputFields: new Set<string>(), undeclaredInputFields: new Set<string>(), isGeneric: false, baseClass: null, isPoisoned: false, isStructural: false, animationTriggerNames: null, isStandalone: false, isSignal: false, imports: null, rawImports: null, schemas: null, decorator: null, hostDirectives: null, assumedToExportProviders: false, ngContentSelectors: null, preserveWhitespaces: false, isExplicitlyDeferred: false, deferredImports: null, inputFieldNamesFromMetadataArray: null, }; } function fakePipe(ref: Reference<ClassDeclaration>): PipeMeta { const name = ref.debugName!; return { kind: MetaKind.Pipe, ref, name, nameExpr: null, isStandalone: false, decorator: null, isExplicitlyDeferred: false, }; } class MockDtsModuleScopeResolver implements DtsModuleScopeResolver { resolve(ref: Reference<ClassDeclaration>): null { return null; } } function scopeToRefs(scopeData: ScopeData): Reference<ClassDeclaration>[] { return scopeData.dependencies .map((dep) => dep.ref) .sort((a, b) => a.debugName!.localeCompare(b.debugName!)); }
{ "end_byte": 11787, "start_byte": 10021, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/scope/test/local_spec.ts" }