The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code:   DatasetGenerationCastError
Exception:    DatasetGenerationCastError
Message:      An error occurred while generating the dataset

All the data files must have the same columns, but at some point there are 1 new columns ({'tags'})

This happened while the json dataset builder was generating data using

hf://datasets/sylvester-francis/slm-typescript/validation.jsonl (at revision 47ea960125f8768ea2f862c14612ba75f7a663a8)

Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1831, in _prepare_split_single
                  writer.write_table(table)
                File "/usr/local/lib/python3.12/site-packages/datasets/arrow_writer.py", line 714, in write_table
                  pa_table = table_cast(pa_table, self._schema)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/table.py", line 2272, in table_cast
                  return cast_table_to_schema(table, schema)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/table.py", line 2218, in cast_table_to_schema
                  raise CastError(
              datasets.table.CastError: Couldn't cast
              text: string
              source: string
              repo: string
              path: string
              tags: list<item: string>
                child 0, item: string
              to
              {'text': Value('string'), 'source': Value('string'), 'repo': Value('string'), 'path': Value('string')}
              because column names don't match
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1339, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 972, in convert_to_parquet
                  builder.download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 894, in download_and_prepare
                  self._download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 970, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1702, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1833, in _prepare_split_single
                  raise DatasetGenerationCastError.from_cast_error(
              datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset
              
              All the data files must have the same columns, but at some point there are 1 new columns ({'tags'})
              
              This happened while the json dataset builder was generating data using
              
              hf://datasets/sylvester-francis/slm-typescript/validation.jsonl (at revision 47ea960125f8768ea2f862c14612ba75f7a663a8)
              
              Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
source
string
repo
string
path
string
/** * @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 {ProfilerFrame} from '../../../../../../protocol'; export type Filter = (nodes: ProfilerFrame) => boolean; export const noopFilter = (_: ProfilerFrame) => true; interface Query<Arguments = unknown> { readonly name: QueryType; parseArguments(args: string[]): Arguments | undefined; apply(node: ProfilerFrame, args: Arguments): boolean; } type Operator = '>' | '<' | '=' | '<=' | '>='; const ops: {[operator in Operator]: (a: number, b: number) => boolean} = { '>'(a: number, b: number): boolean { return a > b; }, '<'(a: number, b: number): boolean { return a < b; }, '='(a: number, b: number): boolean { return a === b; }, '<='(a: number, b: number): boolean { return a <= b; }, '>='(a: number, b: number): boolean { return a >= b; }, }; type DurationArgument = [Operator, number]; type SourceArgument = string; const enum QueryType { Duration = 'duration', Source = 'source', } type QueryArguments = DurationArgument | SourceArgument; const operatorRe = /^(>=|<=|=|<|>|)/; class DurationQuery implements Query<DurationArgument> { readonly name = QueryType.Duration; parseArguments([arg]: string[]): DurationArgument | undefined { arg = arg.trim(); const operator = (arg.match(operatorRe) ?? [null])[0]; if (!operator) { return undefined; } const num = parseFloat(arg.replace(operatorRe, '').trim()); if (isNaN(num)) { return undefined; } return [operator as Operator, num] as DurationArgument; } apply(node: ProfilerFrame, args: DurationArgument): boolean { return ops[args[0]](node.duration, args[1]); } } class SourceQuery implements Query<SourceArgument> { readonly name = QueryType.Source; parseArguments([arg]: string[]): SourceArgument { return arg; } apply(node: ProfilerFrame, args: SourceArgument): boolean { return node.source.indexOf(args) >= 0; } } const queryMap: {[query in QueryType]: Query} = [new DurationQuery(), new SourceQuery()].reduce( (map, query) => { map[query.name] = query; return map; }, {} as {[query in QueryType]: Query}, ); const queryRe = new RegExp(`!?s*(${QueryType.Duration}|${QueryType.Source})$`, 'g'); type Predicate = true | false; type QueryAST = [Predicate, QueryType, QueryArguments]; /** * Parses a query in the form: * filter := ('!'? query)* * query := 'sort': [a-z]* | 'duration': operator duration * operator := '=' | '>' | '<' | '>=' | '<=' * duration := [0-9]* 'ms'? * * @param query string that represents the search query * @returns tuples representing the query type and its arguments */ export const parseFilter = (query: string): QueryAST[] => { const parts = query.split(':').map((part) => part.trim()); if (parts.length <= 1) { return []; } const result: QueryAST[] = []; for (let i = 0; i < parts.length - 1; i++) { const part = parts[i]; if (!queryRe.test(part)) { continue; } const match = part.match(/(\w+)$/); if (!match) { continue; } const operator = queryMap[match[0] as QueryType]; if (!operator) { continue; } const operandString = parts[i + 1].replace(queryRe, '').trim(); const operand = operator.parseArguments([operandString]) as QueryArguments; if (!operand) { continue; } const hasNegation = /^(.*?)\s*!\s*\w+/.test(part); result.push([!hasNegation, operator.name, operand]); } return result; }; export const createFilter = (query: string) => { const queries = parseFilter(query); return (frame: ProfilerFrame) => { return queries.every(([predicate, queryName, args]) => { const currentQuery = queryMap[queryName]; if (!currentQuery) { return true; } const result = currentQuery.apply(frame, args); return predicate ? result : !result; }); }; };
github
angular/angular
devtools/projects/ng-devtools/src/lib/devtools-tabs/profiler/recording-timeline/filter.ts
/** * @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'; /** Possible alias import declarations */ export type AliasImportDeclaration = ts.ImportSpecifier | ts.NamespaceImport | ts.ImportClause; /** * Describes a TypeScript transformation context with the internal emit * resolver exposed. There are requests upstream in TypeScript to expose * that as public API: https://github.com/microsoft/TypeScript/issues/17516. */ interface TransformationContextWithResolver extends ts.TransformationContext { getEmitResolver: () => EmitResolver | undefined; } const patchedReferencedAliasesSymbol = Symbol('patchedReferencedAliases'); /** Describes a subset of the TypeScript internal emit resolver. */ interface EmitResolver { isReferencedAliasDeclaration?(node: ts.Node, ...args: unknown[]): void; [patchedReferencedAliasesSymbol]?: Set<AliasImportDeclaration>; } /** * Patches the alias declaration reference resolution for a given transformation context * so that TypeScript knows about the specified alias declarations being referenced. * * This exists because TypeScript performs analysis of import usage before transformers * run and doesn't refresh its state after transformations. This means that imports * for symbols used as constructor types are elided due to their original type-only usage. * * In reality though, since we downlevel decorators and constructor parameters, we want * these symbols to be retained in the JavaScript output as they will be used as values * at runtime. We can instruct TypeScript to preserve imports for such identifiers by * creating a mutable clone of a given import specifier/clause or namespace, but that * has the downside of preserving the full import in the JS output. See: * https://github.com/microsoft/TypeScript/blob/3eaa7c65f6f076a08a5f7f1946fd0df7c7430259/src/compiler/transformers/ts.ts#L242-L250. * * This is a trick the CLI used in the past for constructor parameter downleveling in JIT: * https://github.com/angular/angular-cli/blob/b3f84cc5184337666ce61c07b7b9df418030106f/packages/ngtools/webpack/src/transformers/ctor-parameters.ts#L323-L325 * The trick is not ideal though as it preserves the full import (as outlined before), and it * results in a slow-down due to the type checker being involved multiple times. The CLI worked * around this import preserving issue by having another complex post-process step that detects and * elides unused imports. Note that these unused imports could cause unused chunks being generated * by webpack if the application or library is not marked as side-effect free. * * This is not ideal though, as we basically re-implement the complex import usage resolution * from TypeScript. We can do better by letting TypeScript do the import eliding, but providing * information about the alias declarations (e.g. import specifiers) that should not be elided * because they are actually referenced (as they will now appear in static properties). * * More information about these limitations with transformers can be found in: * 1. https://github.com/Microsoft/TypeScript/issues/17552. * 2. https://github.com/microsoft/TypeScript/issues/17516. * 3. https://github.com/angular/tsickle/issues/635. * * The patch we apply to tell TypeScript about actual referenced aliases (i.e. imported symbols), * matches conceptually with the logic that runs internally in TypeScript when the * `emitDecoratorMetadata` flag is enabled. TypeScript basically surfaces the same problem and * solves it conceptually the same way, but obviously doesn't need to access an internal API. * * The set that is returned by this function is meant to be filled with import declaration nodes * that have been referenced in a value-position by the transform, such the installed patch can * ensure that those import declarations are not elided. * * If `null` is returned then the transform operates in an isolated context, i.e. using the * `ts.transform` API. In such scenario there is no information whether an alias declaration * is referenced, so all alias declarations are naturally preserved and explicitly registering * an alias declaration as used isn't necessary. * * See below. Note that this uses sourcegraph as the TypeScript checker file doesn't display on * Github. * https://sourcegraph.com/github.com/microsoft/TypeScript@3eaa7c65f6f076a08a5f7f1946fd0df7c7430259/-/blob/src/compiler/checker.ts#L31219-31257 */ export function loadIsReferencedAliasDeclarationPatch( context: ts.TransformationContext, ): Set<ts.Declaration> | null { // If the `getEmitResolver` method is not available, TS most likely changed the // internal structure of the transformation context. We will abort gracefully. if (!isTransformationContextWithEmitResolver(context)) { throwIncompatibleTransformationContextError(); } const emitResolver = context.getEmitResolver(); if (emitResolver === undefined) { // In isolated `ts.transform` operations no emit resolver is present, return null as `isReferencedAliasDeclaration` // will never be invoked. return null; } // The emit resolver may have been patched already, in which case we return the set of referenced // aliases that was created when the patch was first applied. // See https://github.com/angular/angular/issues/40276. const existingReferencedAliases = emitResolver[patchedReferencedAliasesSymbol]; if (existingReferencedAliases !== undefined) { return existingReferencedAliases; } const originalIsReferencedAliasDeclaration = emitResolver.isReferencedAliasDeclaration; // If the emit resolver does not have a function called `isReferencedAliasDeclaration`, then // we abort gracefully as most likely TS changed the internal structure of the emit resolver. if (originalIsReferencedAliasDeclaration === undefined) { throwIncompatibleTransformationContextError(); } const referencedAliases = new Set<AliasImportDeclaration>(); emitResolver.isReferencedAliasDeclaration = function (node, ...args) { if (isAliasImportDeclaration(node) && (referencedAliases as Set<ts.Node>).has(node)) { return true; } return originalIsReferencedAliasDeclaration.call(emitResolver, node, ...args); }; return (emitResolver[patchedReferencedAliasesSymbol] = referencedAliases); } /** * Gets whether a given node corresponds to an import alias declaration. Alias * declarations can be import specifiers, namespace imports or import clauses * as these do not declare an actual symbol but just point to a target declaration. */ export function isAliasImportDeclaration(node: ts.Node): node is AliasImportDeclaration { return ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node); } /** Whether the transformation context exposes its emit resolver. */ function isTransformationContextWithEmitResolver( context: ts.TransformationContext, ): context is TransformationContextWithResolver { return (context as Partial<TransformationContextWithResolver>).getEmitResolver !== undefined; } /** * Throws an error about an incompatible TypeScript version for which the alias * declaration reference resolution could not be monkey-patched. The error will * also propose potential solutions that can be applied by developers. */ function throwIncompatibleTransformationContextError(): never { throw Error( 'Angular compiler is incompatible with this version of the TypeScript compiler.\n\n' + 'If you recently updated TypeScript and this issue surfaces now, consider downgrading.\n\n' + 'Please report an issue on the Angular repositories when this issue ' + 'surfaces and you are using a supposedly compatible TypeScript version.', ); }
github
angular/angular
packages/compiler-cli/src/ngtsc/imports/src/patch_alias_reference_resolution.ts
/** * @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 {ComponentRef, inject, Injectable} from '@angular/core'; import {OutletContext} from './router_outlet_context'; import {ActivatedRoute, ActivatedRouteSnapshot} from './router_state'; import {TreeNode} from './utils/tree'; /** * @description * * Represents the detached route tree. * * This is an opaque value the router will give to a custom route reuse strategy * to store and retrieve later on. * * @publicApi */ export type DetachedRouteHandle = {}; /** @internal */ export type DetachedRouteHandleInternal = { contexts: Map<string, OutletContext>; componentRef: ComponentRef<any>; route: TreeNode<ActivatedRoute>; }; /** * @description * * Provides a way to customize when activated routes get reused. * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy)}) export abstract class RouteReuseStrategy { /** Determines if this route (and its subtree) should be detached to be reused later */ abstract shouldDetach(route: ActivatedRouteSnapshot): boolean; /** * Stores the detached route. * * Storing a `null` value should erase the previously stored value. */ abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void; /** Determines if this route (and its subtree) should be reattached */ abstract shouldAttach(route: ActivatedRouteSnapshot): boolean; /** Retrieves the previously stored route */ abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null; /** Determines if a route should be reused */ abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean; } /** * @description * * This base route reuse strategy only reuses routes when the matched router configs are * identical. This prevents components from being destroyed and recreated * when just the route parameters, query parameters or fragment change * (that is, the existing component is _reused_). * * This strategy does not store any routes for later reuse. * * Angular uses this strategy by default. * * * It can be used as a base class for custom route reuse strategies, i.e. you can create your own * class that extends the `BaseRouteReuseStrategy` one. * @publicApi */ export abstract class BaseRouteReuseStrategy implements RouteReuseStrategy { /** * Whether the given route should detach for later reuse. * Always returns false for `BaseRouteReuseStrategy`. * */ shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } /** * A no-op; the route is never stored since this strategy never detaches routes for later re-use. */ store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} /** Returns `false`, meaning the route (and its subtree) is never reattached */ shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } /** Returns `null` because this strategy does not store routes for later re-use. */ retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { return null; } /** * Determines if a route should be reused. * This strategy returns `true` when the future route config and current route config are * identical. */ shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } @Injectable({providedIn: 'root'}) export class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {}
github
angular/angular
packages/router/src/route_reuse_strategy.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // NOTE: This file contains derived code from original sources // created by Microsoft, licensed under an Apache License. // This is the formal `NOTICE` for the modified/copied code. // Original license: https://github.com/microsoft/TypeScript/blob/main/LICENSE.txt. // Original ref: https://github.com/microsoft/TypeScript/pull/58036 import ts from 'typescript'; /** @internal */ export enum FlowFlags { Unreachable = 1 << 0, // Unreachable code Start = 1 << 1, // Start of flow graph BranchLabel = 1 << 2, // Non-looping junction LoopLabel = 1 << 3, // Looping junction Assignment = 1 << 4, // Assignment TrueCondition = 1 << 5, // Condition known to be true FalseCondition = 1 << 6, // Condition known to be false SwitchClause = 1 << 7, // Switch statement clause ArrayMutation = 1 << 8, // Potential array mutation Call = 1 << 9, // Potential assertion call ReduceLabel = 1 << 10, // Temporarily reduce antecedents of label Referenced = 1 << 11, // Referenced as antecedent once Shared = 1 << 12, // Referenced as antecedent more than once Label = BranchLabel | LoopLabel, Condition = TrueCondition | FalseCondition, } /** @internal */ export type FlowNode = | FlowUnreachable | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation | FlowCall | FlowReduceLabel; /** @internal */ export interface FlowNodeBase { flags: FlowFlags; id: number; // Node id used by flow type cache in checker node: unknown; // Node or other data antecedent: FlowNode | FlowNode[] | undefined; } /** @internal */ export interface FlowUnreachable extends FlowNodeBase { node: undefined; antecedent: undefined; } // FlowStart represents the start of a control flow. For a function expression or arrow // function, the node property references the function (which in turn has a flowNode // property for the containing control flow). /** @internal */ export interface FlowStart extends FlowNodeBase { node: | ts.FunctionExpression | ts.ArrowFunction | ts.MethodDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | undefined; antecedent: undefined; } // FlowLabel represents a junction with multiple possible preceding control flows. /** @internal */ export interface FlowLabel extends FlowNodeBase { node: undefined; antecedent: FlowNode[] | undefined; } // FlowAssignment represents a node that assigns a value to a narrowable reference, // i.e. an identifier or a dotted name that starts with an identifier or 'this'. /** @internal */ export interface FlowAssignment extends FlowNodeBase { node: ts.Expression | ts.VariableDeclaration | ts.BindingElement; antecedent: FlowNode; } /** @internal */ export interface FlowCall extends FlowNodeBase { node: ts.CallExpression; antecedent: FlowNode; } // FlowCondition represents a condition that is known to be true or false at the // node's location in the control flow. /** @internal */ export interface FlowCondition extends FlowNodeBase { node: ts.Expression; antecedent: FlowNode; } // dprint-ignore /** @internal */ export interface FlowSwitchClause extends FlowNodeBase { node: FlowSwitchClauseData; antecedent: FlowNode; } /** @internal */ export interface FlowSwitchClauseData { switchStatement: ts.SwitchStatement; clauseStart: number; // Start index of case/default clause range clauseEnd: number; // End index of case/default clause range } // FlowArrayMutation represents a node potentially mutates an array, i.e. an // operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'. /** @internal */ export interface FlowArrayMutation extends FlowNodeBase { node: ts.CallExpression | ts.BinaryExpression; antecedent: FlowNode; } /** @internal */ export interface FlowReduceLabel extends FlowNodeBase { node: FlowReduceLabelData; antecedent: FlowNode; } /** @internal */ export interface FlowReduceLabelData { target: FlowLabel; antecedents: FlowNode[]; }
github
angular/angular
packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_node_internals.ts
/** * @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 {MessageId, ɵparseTranslation, ɵSourceMessage} from '../../../../../index'; import {Diagnostics} from '../../../diagnostics'; import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser'; export interface ArbJsonObject extends Record<MessageId, ɵSourceMessage | ArbMetadata> { '@@locale': string; } export interface ArbMetadata { type?: 'text' | 'image' | 'css'; description?: string; ['x-locations']?: ArbLocation[]; } export interface ArbLocation { start: {line: number; column: number}; end: {line: number; column: number}; file: string; } /** * A translation parser that can parse JSON formatted as an Application Resource Bundle (ARB). * * See https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification * * ```json * { * "@@locale": "en-US", * "message-id": "Target message string", * "@message-id": { * "type": "text", * "description": "Some description text", * "x-locations": [ * { * "start": {"line": 23, "column": 145}, * "end": {"line": 24, "column": 53}, * "file": "some/file.ts" * }, * ... * ] * }, * ... * } * ``` */ export class ArbTranslationParser implements TranslationParser<ArbJsonObject> { analyze(_filePath: string, contents: string): ParseAnalysis<ArbJsonObject> { const diagnostics = new Diagnostics(); if (!contents.includes('"@@locale"')) { return {canParse: false, diagnostics}; } try { // We can parse this file if it is valid JSON and contains the `"@@locale"` property. return {canParse: true, diagnostics, hint: this.tryParseArbFormat(contents)}; } catch { diagnostics.warn('File is not valid JSON.'); return {canParse: false, diagnostics}; } } parse( _filePath: string, contents: string, arb: ArbJsonObject = this.tryParseArbFormat(contents), ): ParsedTranslationBundle { const bundle: ParsedTranslationBundle = { locale: arb['@@locale'], translations: {}, diagnostics: new Diagnostics(), }; for (const messageId of Object.keys(arb)) { if (messageId.startsWith('@')) { // Skip metadata keys continue; } const targetMessage = arb[messageId] as string; bundle.translations[messageId] = ɵparseTranslation(targetMessage); } return bundle; } private tryParseArbFormat(contents: string): ArbJsonObject { const json = JSON.parse(contents) as ArbJsonObject; if (typeof json['@@locale'] !== 'string') { throw new Error('Missing @@locale property.'); } return json; } }
github
angular/angular
packages/localize/tools/src/translate/translation_files/translation_parsers/arb_translation_parser.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {InputDescriptor} from '../utils/input_id'; import {ExtractedInput} from './input_decorator'; import {InputNode} from './input_node'; import {DirectiveInfo} from './directive_info'; import { ClassIncompatibilityReason, FieldIncompatibility, FieldIncompatibilityReason, isFieldIncompatibility, pickFieldIncompatibility, } from '../passes/problematic_patterns/incompatibility'; import {ClassFieldUniqueKey, KnownFields} from '../passes/reference_resolution/known_fields'; import {attemptRetrieveInputFromSymbol} from './nodes_to_input'; import {ProgramInfo, projectFile, ProjectFile} from '../../../../utils/tsurge'; import {MigrationConfig} from '../migration_config'; import {ProblematicFieldRegistry} from '../passes/problematic_patterns/problematic_field_registry'; import {InheritanceTracker} from '../passes/problematic_patterns/check_inheritance'; /** * Public interface describing a single known `@Input()` in the * compilation. * * A known `@Input()` may be defined in sources, or inside some `d.ts` files * loaded into the program. */ export type KnownInputInfo = { file: ProjectFile; metadata: ExtractedInput; descriptor: InputDescriptor; container: DirectiveInfo; extendsFrom: InputDescriptor | null; isIncompatible: () => boolean; }; /** * Registry keeping track of all known `@Input()`s in the compilation. * * A known `@Input()` may be defined in sources, or inside some `d.ts` files * loaded into the program. */ export class KnownInputs implements KnownFields<InputDescriptor>, ProblematicFieldRegistry<InputDescriptor>, InheritanceTracker<InputDescriptor> { /** * Known inputs from the whole program. */ knownInputIds = new Map<ClassFieldUniqueKey, KnownInputInfo>(); /** Known container classes of inputs. */ private _allClasses = new Set<ts.ClassDeclaration>(); /** Maps classes to their directive info. */ private _classToDirectiveInfo = new Map<ts.ClassDeclaration, DirectiveInfo>(); constructor( private readonly programInfo: ProgramInfo, private readonly config: MigrationConfig, ) {} /** Whether the given input exists. */ has(descr: Pick<InputDescriptor, 'key'>): boolean { return this.knownInputIds.has(descr.key); } /** Whether the given class contains `@Input`s. */ isInputContainingClass(clazz: ts.ClassDeclaration): boolean { return this._classToDirectiveInfo.has(clazz); } /** Gets precise `@Input()` information for the given class. */ getDirectiveInfoForClass(clazz: ts.ClassDeclaration): DirectiveInfo | undefined { return this._classToDirectiveInfo.get(clazz); } /** Gets known input information for the given `@Input()`. */ get(descr: Pick<InputDescriptor, 'key'>): KnownInputInfo | undefined { return this.knownInputIds.get(descr.key); } /** Gets all classes containing `@Input`s in the compilation. */ getAllInputContainingClasses(): ts.ClassDeclaration[] { return Array.from(this._allClasses.values()); } /** Registers an `@Input()` in the registry. */ register(data: {descriptor: InputDescriptor; node: InputNode; metadata: ExtractedInput}) { if (!this._classToDirectiveInfo.has(data.node.parent)) { this._classToDirectiveInfo.set(data.node.parent, new DirectiveInfo(data.node.parent)); } const directiveInfo = this._classToDirectiveInfo.get(data.node.parent)!; const inputInfo: KnownInputInfo = { file: projectFile(data.node.getSourceFile(), this.programInfo), metadata: data.metadata, descriptor: data.descriptor, container: directiveInfo, extendsFrom: null, isIncompatible: () => directiveInfo.isInputMemberIncompatible(data.descriptor), }; directiveInfo.inputFields.set(data.descriptor.key, { descriptor: data.descriptor, metadata: data.metadata, }); this.knownInputIds.set(data.descriptor.key, inputInfo); this._allClasses.add(data.node.parent); } /** Whether the given input is incompatible for migration. */ isFieldIncompatible(descriptor: InputDescriptor): boolean { return !!this.get(descriptor)?.isIncompatible(); } /** Marks the given input as incompatible for migration. */ markFieldIncompatible(input: InputDescriptor, incompatibility: FieldIncompatibility) { if (!this.knownInputIds.has(input.key)) { throw new Error(`Input cannot be marked as incompatible because it's not registered.`); } const inputInfo = this.knownInputIds.get(input.key)!; const existingIncompatibility = inputInfo.container.getInputMemberIncompatibility(input); // Ensure an existing more significant incompatibility is not overridden. if (existingIncompatibility !== null && isFieldIncompatibility(existingIncompatibility)) { incompatibility = pickFieldIncompatibility(existingIncompatibility, incompatibility); } this.knownInputIds .get(input.key)! .container.memberIncompatibility.set(input.key, incompatibility); } /** Marks the given class as incompatible for migration. */ markClassIncompatible(clazz: ts.ClassDeclaration, incompatibility: ClassIncompatibilityReason) { if (!this._classToDirectiveInfo.has(clazz)) { throw new Error(`Class cannot be marked as incompatible because it's not known.`); } this._classToDirectiveInfo.get(clazz)!.incompatible = incompatibility; } attemptRetrieveDescriptorFromSymbol(symbol: ts.Symbol): InputDescriptor | null { return attemptRetrieveInputFromSymbol(this.programInfo, symbol, this)?.descriptor ?? null; } shouldTrackClassReference(clazz: ts.ClassDeclaration): boolean { return this.isInputContainingClass(clazz); } captureKnownFieldInheritanceRelationship( derived: InputDescriptor, parent: InputDescriptor, ): void { if (!this.has(derived)) { throw new Error(`Expected input to exist in registry: ${derived.key}`); } this.get(derived)!.extendsFrom = parent; } captureUnknownDerivedField(field: InputDescriptor): void { this.markFieldIncompatible(field, { context: null, reason: FieldIncompatibilityReason.OverriddenByDerivedClass, }); } captureUnknownParentField(field: InputDescriptor): void { this.markFieldIncompatible(field, { context: null, reason: FieldIncompatibilityReason.TypeConflictWithBaseClass, }); } }
github
angular/angular
packages/core/schematics/migrations/signal-migration/src/input_detection/known_inputs.ts
/*! * @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 {CssPropertyValue} from './parser'; export type AnimationConfig = { /** * In milliseconds. How much the time increments or decrements when you go forward or back in time. * In the case of auto play, the timestep virtually acts as FPS (frames per second). * * Default: `100` */ timestep: number; }; export type Styles = {[key: string]: string}; export type ParsedStyles = {[key: string]: CssPropertyValue}; interface AnimationRuleBase { /** * Selector in the form of `LAYER_ID >> OBJECT_SELECTOR`. * The object selector should be a class (prefixed with dot: `.my-class`) and is optional. */ selector: string; } /** Animation definition */ export interface DynamicAnimationRule<T extends Styles | ParsedStyles> extends AnimationRuleBase { at?: never; /** In seconds. Marks the time frame between which the styles are applied (`[START, END]`). */ timeframe: [number, number]; /** Start styles. */ from: T; /** End styles. */ to: T; } export interface StaticAnimationRule<T extends Styles | ParsedStyles> extends AnimationRuleBase { timeframe?: never; /** In seconds. Time at which the styles are applied. */ at: number; /** Styles to be applied. */ styles: T; } export type AnimationRule<T extends Styles | ParsedStyles> = | DynamicAnimationRule<T> | StaticAnimationRule<T>; export type AnimationDefinition = AnimationRule<Styles>[];
github
angular/angular
adev/src/app/features/home/animation/types.ts
/** * @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 { KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Pipe, PipeTransform, } from '@angular/core'; function makeKeyValuePair<K, V>(key: K, value: V): KeyValue<K, V> { return {key: key, value: value}; } /** * A key value pair. * Usually used to represent the key value pairs from a Map or Object. * * @publicApi */ export interface KeyValue<K, V> { key: K; value: V; } /** * @ngModule CommonModule * @description * * Transforms Object or Map into an array of key value pairs. * * The output array will be ordered by keys. * By default the comparator will be by Unicode point value. * You can optionally pass a compareFn if your keys are complex types. * Passing `null` as the compareFn will use natural ordering of the input. * * @usageNotes * ### Examples * * This examples show how an Object or a Map can be iterated by ngFor with the use of this * keyvalue pipe. * * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'} * * @see [Built-in Pipes](guide/templates/pipes#built-in-pipes) * * @publicApi */ @Pipe({ name: 'keyvalue', pure: false, }) export class KeyValuePipe implements PipeTransform { constructor(private readonly differs: KeyValueDiffers) {} private differ!: KeyValueDiffer<any, any>; private keyValues: Array<KeyValue<any, any>> = []; private compareFn: ((a: KeyValue<any, any>, b: KeyValue<any, any>) => number) | null = defaultComparator; /* * NOTE: when the `input` value is a simple Record<K, V> object, the keys are extracted with * Object.keys(). This means that even if the `input` type is Record<number, V> the keys are * compared/returned as `string`s. */ transform<K, V>( input: ReadonlyMap<K, V>, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>>; transform<K extends number, V>( input: Record<K, V>, compareFn?: ((a: KeyValue<string, V>, b: KeyValue<string, V>) => number) | null, ): Array<KeyValue<string, V>>; transform<K extends string, V>( input: Record<K, V> | ReadonlyMap<K, V>, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>>; transform( input: null | undefined, compareFn?: ((a: KeyValue<unknown, unknown>, b: KeyValue<unknown, unknown>) => number) | null, ): null; transform<K, V>( input: ReadonlyMap<K, V> | null | undefined, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>> | null; transform<K extends number, V>( input: Record<K, V> | null | undefined, compareFn?: ((a: KeyValue<string, V>, b: KeyValue<string, V>) => number) | null, ): Array<KeyValue<string, V>> | null; transform<K extends string, V>( input: Record<K, V> | ReadonlyMap<K, V> | null | undefined, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>> | null; transform<T>( input: T, compareFn?: T extends object ? (a: T[keyof T], b: T[keyof T]) => number : never, ): T extends object ? Array<KeyValue<keyof T, T[keyof T]>> : null; transform<K, V>( input: undefined | null | {[key: string]: V; [key: number]: V} | ReadonlyMap<K, V>, compareFn: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null = defaultComparator, ): Array<KeyValue<K, V>> | null { if (!input || (!(input instanceof Map) && typeof input !== 'object')) { return null; } // make a differ for whatever type we've been passed in this.differ ??= this.differs.find(input).create(); const differChanges: KeyValueChanges<K, V> | null = this.differ.diff(input as any); const compareFnChanged = compareFn !== this.compareFn; if (differChanges) { this.keyValues = []; differChanges.forEachItem((r: KeyValueChangeRecord<K, V>) => { this.keyValues.push(makeKeyValuePair(r.key, r.currentValue!)); }); } if (differChanges || compareFnChanged) { if (compareFn) { this.keyValues.sort(compareFn); } this.compareFn = compareFn; } return this.keyValues; } } export function defaultComparator<K, V>( keyValueA: KeyValue<K, V>, keyValueB: KeyValue<K, V>, ): number { const a = keyValueA.key; const b = keyValueB.key; // If both keys are the same, return 0 (no sorting needed). if (a === b) return 0; // If one of the keys is `null` or `undefined`, place it at the end of the sort. if (a == null) return 1; // `a` comes after `b`. if (b == null) return -1; // `b` comes after `a`. // If both keys are strings, compare them lexicographically. if (typeof a == 'string' && typeof b == 'string') { return a < b ? -1 : 1; } // If both keys are numbers, sort them numerically. if (typeof a == 'number' && typeof b == 'number') { return a - b; } // If both keys are booleans, sort `false` before `true`. if (typeof a == 'boolean' && typeof b == 'boolean') { return a < b ? -1 : 1; } // Fallback case: if keys are of different types, compare their string representations. const aString = String(a); const bString = String(b); // Compare the string representations lexicographically. return aString == bString ? 0 : aString < bString ? -1 : 1; }
github
angular/angular
packages/common/src/pipes/keyvalue_pipe.ts
/** * @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 {ExtendedTsCompilerHost, UnifiedModulesHost} from './interfaces'; /** * Names of methods from `ExtendedTsCompilerHost` that need to be provided by the * `NgCompilerAdapter`. */ export type ExtendedCompilerHostMethods = // Used to normalize filenames for the host system. Important for proper case-sensitive file // handling. | 'getCanonicalFileName' // An optional method of `ts.CompilerHost` where an implementer can override module resolution. | 'resolveModuleNames' // Retrieve the current working directory. Unlike in `ts.ModuleResolutionHost`, this is a // required method. | 'getCurrentDirectory' // Additional methods of `ExtendedTsCompilerHost` related to resource files (e.g. HTML // templates). These are optional. | 'getModifiedResourceFiles' | 'readResource' | 'resourceNameToFileName' | 'transformResource'; /** * Adapter for `NgCompiler` that allows it to be used in various circumstances, such as * command-line `ngc`, as a plugin to `ts_library` in Bazel, or from the Language Service. * * `NgCompilerAdapter` is a subset of the `NgCompilerHost` implementation of `ts.CompilerHost` * which is relied upon by `NgCompiler`. A consumer of `NgCompiler` can therefore use the * `NgCompilerHost` or implement `NgCompilerAdapter` itself. */ export interface NgCompilerAdapter // getCurrentDirectory is removed from `ts.ModuleResolutionHost` because it's optional, and // incompatible with the `ts.CompilerHost` version which isn't. The combination of these two // still satisfies `ts.ModuleResolutionHost`. extends Omit<ts.ModuleResolutionHost, 'getCurrentDirectory'>, Pick<ExtendedTsCompilerHost, 'getCurrentDirectory' | ExtendedCompilerHostMethods>, SourceFileTypeIdentifier { /** * A path to a single file which represents the entrypoint of an Angular Package Format library, * if the current program is one. * * This is used to emit a flat module index if requested, and can be left `null` if that is not * required. */ readonly entryPoint: AbsoluteFsPath | null; /** * An array of `ts.Diagnostic`s that occurred during construction of the `ts.Program`. */ readonly constructionDiagnostics: ts.Diagnostic[]; /** * A `Set` of `ts.SourceFile`s which are internal to the program and should not be emitted as JS * files. * * Often these are shim files such as `ngtypecheck` shims used for template type-checking in * command-line ngc. */ readonly ignoreForEmit: Set<ts.SourceFile>; /** * A specialized interface provided in some environments (such as Bazel) which overrides how * import specifiers are generated. * * If not required, this can be `null`. */ readonly unifiedModulesHost: UnifiedModulesHost | null; /** * Resolved list of root directories explicitly set in, or inferred from, the tsconfig. */ readonly rootDirs: ReadonlyArray<AbsoluteFsPath>; } export interface SourceFileTypeIdentifier { /** * Distinguishes between shim files added by Angular to the compilation process (both those * intended for output, like ngfactory files, as well as internal shims like ngtypecheck files) * and original files in the user's program. * * This is mostly used to limit type-checking operations to only user files. It should return * `true` if a file was written by the user, and `false` if a file was added by the compiler. */ isShim(sf: ts.SourceFile): boolean; /** * Distinguishes between resource files added by Angular to the project and original files in the * user's program. * * This is necessary only for the language service because it adds resource files as root files * when they are read. This is done to indicate to TS Server that these resources are part of the * project and ensures that projects are retained properly when navigating around the workspace. */ isResource(sf: ts.SourceFile): boolean; }
github
angular/angular
packages/compiler-cli/src/ngtsc/core/api/src/adapter.ts
/** * @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 */ /** * @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 {AST, PropertyRead, TmplAstNode} from '@angular/compiler'; import {ProjectFile} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor} from './known_fields'; /** Possible types of references to known fields detected. */ export enum ReferenceKind { InTemplate, InHostBinding, TsReference, TsClassTypeReference, } /** Interface describing a template reference to a known field. */ export interface TemplateReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.InTemplate; /** From where the reference is made. */ from: { /** Template file containing the reference. */ templateFile: ProjectFile; /** TypeScript file that references, or contains the template. */ originatingTsFile: ProjectFile; /** HTML AST node that contains the reference. */ node: TmplAstNode; /** Expression AST node that represents the reference. */ read: PropertyRead; /** * Expression AST sequentially visited to reach the given read. * This follows top-down down ordering. The last element is the actual read. */ readAstPath: AST[]; /** Whether the reference is part of an object shorthand expression. */ isObjectShorthandExpression: boolean; /** Whether this reference is part of a likely-narrowing expression. */ isLikelyPartOfNarrowing: boolean; /** Whether the reference is a write. E.g. two way binding, or assignment. */ isWrite: boolean; }; /** Target field addressed by the reference. */ target: D; } /** Interface describing a host binding reference to a known field. */ export interface HostBindingReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.InHostBinding; /** From where the reference is made. */ from: { /** File that contains the host binding reference. */ file: ProjectFile; /** TypeScript property node containing the reference. */ hostPropertyNode: ts.Node; /** Expression AST node that represents the reference. */ read: PropertyRead; /** * Expression AST sequentially visited to reach the given read. * This follows top-down down ordering. The last element is the actual read. */ readAstPath: AST[]; /** Whether the reference is part of an object shorthand expression. */ isObjectShorthandExpression: boolean; /** Whether the reference is a write. E.g. an event assignment. */ isWrite: boolean; }; /** Target field addressed by the reference. */ target: D; } /** Interface describing a TypeScript reference to a known field. */ export interface TsReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.TsReference; /** From where the reference is made. */ from: { /** File that contains the TypeScript reference. */ file: ProjectFile; /** TypeScript AST node representing the reference. */ node: ts.Identifier; /** Whether the reference is a write. */ isWrite: boolean; /** Whether the reference is part of an element binding */ isPartOfElementBinding: boolean; }; /** Target field addressed by the reference. */ target: D; } /** * Interface describing a TypeScript `ts.Type` reference to a * class containing known fields. */ export interface TsClassTypeReference { kind: ReferenceKind.TsClassTypeReference; /** From where the reference is made. */ from: { /** File that contains the TypeScript reference. */ file: ProjectFile; /** TypeScript AST node representing the reference. */ node: ts.TypeReferenceNode; }; /** Whether the reference is using `Partial<T>`. */ isPartialReference: boolean; /** Whether the reference is part of a file using Catalyst. */ isPartOfCatalystFile: boolean; /** Target class that contains at least one known field (e.g. inputs) */ target: ts.ClassDeclaration; } /** Possible structures representing known field references. */ export type Reference<D extends ClassFieldDescriptor> = | TsReference<D> | TemplateReference<D> | HostBindingReference<D> | TsClassTypeReference; /** Whether the given reference is a TypeScript reference. */ export function isTsReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TsReference<D> { return (ref as Partial<TsReference<D>>).kind === ReferenceKind.TsReference; } /** Whether the given reference is a template reference. */ export function isTemplateReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TemplateReference<D> { return (ref as Partial<TemplateReference<D>>).kind === ReferenceKind.InTemplate; } /** Whether the given reference is a host binding reference. */ export function isHostBindingReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is HostBindingReference<D> { return (ref as Partial<HostBindingReference<D>>).kind === ReferenceKind.InHostBinding; } /** * Whether the given reference is a TypeScript `ts.Type` reference * to a class containing known fields. */ export function isTsClassTypeReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TsClassTypeReference { return (ref as Partial<TsClassTypeReference>).kind === ReferenceKind.TsClassTypeReference; }
github
angular/angular
packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/reference_kinds.ts
/** * @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 {ActionResolver} from './action_resolver'; import {Dispatcher} from './dispatcher'; import {EventInfo, EventInfoWrapper} from './event_info'; import {isCaptureEventType} from './event_type'; import {UnrenamedEventContract} from './eventcontract'; import {Restriction} from './restriction'; // Necessary to make the `ngDevMode` global types available. import '../../../src/util/ng_dev_mode'; /** * A replayer is a function that is called when there are queued events, from the `EventContract`. */ export type Replayer = (eventInfoWrappers: Event[]) => void; /** An internal symbol used to indicate whether propagation should be stopped or not. */ export const PROPAGATION_STOPPED_SYMBOL: unique symbol = /* @__PURE__ */ Symbol.for('propagationStopped'); /** Extra event phases beyond what the browser provides. */ export const EventPhase = { REPLAY: 101, }; const PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser dispatch, `preventDefault` would have no ' + 'effect. You can check whether an event is being replayed by accessing the event phase: ' + '`event.eventPhase === EventPhase.REPLAY`.'; const PREVENT_DEFAULT_ERROR_MESSAGE = `\`preventDefault\` called during event replay.`; const COMPOSED_PATH_ERROR_MESSAGE_DETAILS = ' Because event replay occurs after browser ' + 'dispatch, `composedPath()` will be empty. Iterate parent nodes from `event.target` or ' + '`event.currentTarget` if you need to check elements in the event path.'; const COMPOSED_PATH_ERROR_MESSAGE = `\`composedPath\` called during event replay.`; declare global { interface Event { [PROPAGATION_STOPPED_SYMBOL]?: boolean; } } /** * A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`, * `currentTarget`, etc. */ export class EventDispatcher { private readonly actionResolver: ActionResolver; private readonly dispatcher: Dispatcher; constructor( private readonly dispatchDelegate: (event: Event, actionName: string) => void, private readonly clickModSupport = true, ) { this.actionResolver = new ActionResolver({clickModSupport}); this.dispatcher = new Dispatcher( (eventInfoWrapper: EventInfoWrapper) => { this.dispatchToDelegate(eventInfoWrapper); }, { actionResolver: this.actionResolver, }, ); } /** * The entrypoint for the `EventContract` dispatch. */ dispatch(eventInfo: EventInfo): void { this.dispatcher.dispatch(eventInfo); } /** Internal method that does basic disaptching. */ private dispatchToDelegate(eventInfoWrapper: EventInfoWrapper) { if (eventInfoWrapper.getIsReplay()) { prepareEventForReplay(eventInfoWrapper); } prepareEventForBubbling(eventInfoWrapper); while (eventInfoWrapper.getAction()) { prepareEventForDispatch(eventInfoWrapper); // If this is a capture event, ONLY dispatch if the action element is the target. if ( isCaptureEventType(eventInfoWrapper.getEventType()) && eventInfoWrapper.getAction()!.element !== eventInfoWrapper.getTargetElement() ) { return; } this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction()!.name); if (propagationStopped(eventInfoWrapper)) { return; } this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo); } } } function prepareEventForBubbling(eventInfoWrapper: EventInfoWrapper) { const event = eventInfoWrapper.getEvent(); const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event); const stopPropagation = () => { event[PROPAGATION_STOPPED_SYMBOL] = true; originalStopPropagation(); }; patchEventInstance(event, 'stopPropagation', stopPropagation); patchEventInstance(event, 'stopImmediatePropagation', stopPropagation); } function propagationStopped(eventInfoWrapper: EventInfoWrapper) { const event = eventInfoWrapper.getEvent(); return !!event[PROPAGATION_STOPPED_SYMBOL]; } function prepareEventForReplay(eventInfoWrapper: EventInfoWrapper) { const event = eventInfoWrapper.getEvent(); const target = eventInfoWrapper.getTargetElement(); const originalPreventDefault = event.preventDefault.bind(event); patchEventInstance(event, 'target', target); patchEventInstance(event, 'eventPhase', EventPhase.REPLAY); patchEventInstance(event, 'preventDefault', () => { originalPreventDefault(); throw new Error( PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''), ); }); patchEventInstance(event, 'composedPath', () => { throw new Error( COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''), ); }); } function prepareEventForDispatch(eventInfoWrapper: EventInfoWrapper) { const event = eventInfoWrapper.getEvent(); const currentTarget = eventInfoWrapper.getAction()?.element; if (currentTarget) { patchEventInstance(event, 'currentTarget', currentTarget, { // `currentTarget` is going to get reassigned every dispatch. configurable: true, }); } } /** * Patch `Event` instance during non-standard `Event` dispatch. This patches just the `Event` * instance that the browser created, it does not patch global properties or methods. * * This is necessary because dispatching an `Event` outside of browser dispatch results in * incorrect properties and methods that need to be polyfilled or do not work. * * JSAction dispatch adds two extra "phases" to event dispatch: * 1. Event delegation - the event is being dispatched by a delegating event handler on a container * (typically `window.document.documentElement`), to a delegated event handler on some child * element. Certain `Event` properties will be unintuitive, such as `currentTarget`, which would * be the container rather than the child element. Bubbling would also not work. In order to * emulate the browser, these properties and methods on the `Event` are patched. * 2. Event replay - the event is being dispatched by the framework once the handlers have been * loaded (during hydration, or late-loaded). Certain `Event` properties can be unset by the * browser because the `Event` is no longer actively being dispatched, such as `target`. Other * methods have no effect because the `Event` has already been dispatched, such as * `preventDefault`. Bubbling would also not work. These properties and methods are patched, * either to fill in information that the browser may have removed, or to throw errors in methods * that no longer behave as expected. */ function patchEventInstance<T>( event: Event, property: string, value: T, {configurable = false}: {configurable?: boolean} = {}, ) { Object.defineProperty(event, property, {value, configurable}); } /** * Registers deferred functionality for an EventContract and a Jsaction * Dispatcher. */ export function registerDispatcher( eventContract: UnrenamedEventContract, dispatcher: EventDispatcher, ) { eventContract.ecrd((eventInfo: EventInfo) => { dispatcher.dispatch(eventInfo); }, Restriction.I_AM_THE_JSACTION_FRAMEWORK); }
github
angular/angular
packages/core/primitives/event-dispatch/src/event_dispatcher.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Type} from '../../interface/type'; import {NgModuleType} from '../../metadata/ng_module_def'; import { ComponentType, DependencyTypeList, DirectiveType, NgModuleScopeInfoFromDecorator, PipeType, } from '../interfaces/definition'; /** * Represents the set of dependencies of a type in a certain context. */ interface ScopeData { pipes: Set<PipeType<any>>; directives: Set<DirectiveType<any> | ComponentType<any> | Type<any>>; /** * If true it indicates that calculating this scope somehow was not successful. The consumers * should interpret this as empty dependencies. The application of this flag is when calculating * scope recursively, the presence of this flag in a scope dependency implies that the scope is * also poisoned and thus we can return immediately without having to continue the recursion. The * reason for this error is displayed as an error message in the console as per JIT behavior * today. In addition to that, in local compilation the other build/compilations run in parallel * with local compilation may or may not reveal some details about the error as well. */ isPoisoned?: boolean; } /** * Represents scope data for standalone components as calculated during runtime by the deps * tracker. */ interface StandaloneCompScopeData extends ScopeData { // Standalone components include the imported NgModules in their dependencies in order to // determine their injector info. The following field stores the set of such NgModules. ngModules: Set<NgModuleType<any>>; } /** Represents scope data for NgModule as calculated during runtime by the deps tracker. */ export interface NgModuleScope { compilation: ScopeData; exported: ScopeData; } /** * Represents scope data for standalone component as calculated during runtime by the deps tracker. */ export interface StandaloneComponentScope { compilation: StandaloneCompScopeData; } /** Component dependencies info as calculated during runtime by the deps tracker. */ export interface ComponentDependencies { dependencies: DependencyTypeList; } /** * Public API for runtime deps tracker (RDT). * * All downstream tools should only use these methods. */ export interface DepsTrackerApi { /** * Computes the component dependencies, i.e., a set of components/directive/pipes that could be * present in the component's template (This set might contain directives/components/pipes not * necessarily used in the component's template depending on the implementation). * * Standalone components should specify `rawImports` as this information is not available from * their type. The consumer (e.g., {@link getStandaloneDefFunctions}) is expected to pass this * parameter. * * The implementation is expected to use some caching mechanism in order to optimize the resources * needed to do this computation. */ getComponentDependencies( cmp: ComponentType<any>, rawImports?: (Type<any> | (() => Type<any>))[], ): ComponentDependencies; /** * Registers an NgModule into the tracker with the given scope info. * * This method should be called for every NgModule whether it is compiled in local mode or not. * This is needed in order to compute component's dependencies as some dependencies might be in * different compilation units with different compilation mode. */ registerNgModule(type: Type<any>, scopeInfo: NgModuleScopeInfoFromDecorator): void; /** * Clears the scope cache for NgModule or standalone component. This will force re-calculation of * the scope, which could be an expensive operation as it involves aggregating transitive closure. * * The main application of this method is for test beds where we want to clear the cache to * enforce scope update after overriding. */ clearScopeCacheFor(type: Type<any>): void; /** * Returns the scope of NgModule. Mainly to be used by JIT and test bed. * * The scope value here is memoized. To enforce a new calculation bust the cache by using * `clearScopeCacheFor` method. */ getNgModuleScope(type: NgModuleType<any>): NgModuleScope; /** * Returns the scope of standalone component. Mainly to be used by JIT. This method should be * called lazily after the initial parsing so that all the forward refs can be resolved. * * @param rawImports the imports statement as appears on the component decorate which consists of * Type as well as forward refs. * * The scope value here is memoized. To enforce a new calculation bust the cache by using * `clearScopeCacheFor` method. */ getStandaloneComponentScope( type: ComponentType<any>, rawImports: (Type<any> | (() => Type<any>))[], ): StandaloneComponentScope; /** * Checks if the NgModule declaring the component is not loaded into the browser yet. Always * returns false for standalone components. */ isOrphanComponent(cmp: ComponentType<any>): boolean; }
github
angular/angular
packages/core/src/render3/deps_tracker/api.ts
import { afterRenderEffect, Component, computed, ElementRef, signal, viewChild, WritableSignal, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {Grid, GridRow, GridCell, GridCellWidget} from '@angular/aria/grid'; type Rank = 'S' | 'A' | 'B' | 'C'; interface Task { reward: number; target: string; rank: Rank; hunter: string; } @Component({ selector: 'app-root', templateUrl: 'app.html', styleUrl: 'app.css', imports: [Grid, GridRow, GridCell, GridCellWidget, FormsModule], }) export class App { private readonly _headerCheckbox = viewChild<ElementRef<HTMLInputElement>>('headerCheckbox'); readonly allSelected = computed(() => this.data().every((t) => t.selected())); readonly partiallySelected = computed( () => !this.allSelected() && this.data().some((t) => t.selected()), ); readonly data = signal<(Task & {selected: WritableSignal<boolean>})[]>([ { selected: signal(false), reward: 50, target: '10 Goblins', rank: 'C', hunter: 'KB Smasher', }, { selected: signal(false), reward: 999, target: '1 Dragon', rank: 'S', hunter: 'Donkey', }, { selected: signal(false), reward: 150, target: '2 Trolls', rank: 'B', hunter: 'Meme Spammer', }, { selected: signal(false), reward: 500, target: '1 Demon', rank: 'A', hunter: 'Dante', }, { selected: signal(false), reward: 10, target: '5 Slimes', rank: 'C', hunter: '[Help Wanted]', }, ]); sortAscending: boolean = true; tempInput: string = ''; constructor() { afterRenderEffect(() => { this._headerCheckbox()!.nativeElement.indeterminate = this.partiallySelected(); }); } startEdit( event: KeyboardEvent | FocusEvent | undefined, task: Task, inputEl: HTMLInputElement, ): void { this.tempInput = task.hunter; inputEl.focus(); if (!(event instanceof KeyboardEvent)) return; // Start editing with an alphanumeric character. if (event.key.length === 1) { this.tempInput = event.key; } } onClickEdit(widget: GridCellWidget, task: Task, inputEl: HTMLInputElement) { if (widget.isActivated()) return; widget.activate(); setTimeout(() => this.startEdit(undefined, task, inputEl)); } completeEdit(event: KeyboardEvent | FocusEvent | undefined, task: Task): void { if (!(event instanceof KeyboardEvent)) { return; } if (event.key === 'Enter') { task.hunter = this.tempInput; } } updateSelection(event: Event): void { const checked = (event.target as HTMLInputElement).checked; this.data().forEach((t) => t.selected.set(checked)); } sortTaskById(): void { this.sortAscending = !this.sortAscending; if (this.sortAscending) { this.data.update((tasks) => tasks.sort((a, b) => a.reward - b.reward)); } else { this.data.update((tasks) => tasks.sort((a, b) => b.reward - a.reward)); } } }
github
angular/angular
adev/src/content/examples/aria/grid/src/table/retro/app/app.ts
/** * @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 {createSignal, SIGNAL, SignalGetter, SignalNode} from '../../../primitives/signals'; import {Signal, ValueEqualityFn} from './api'; /** Symbol used distinguish `WritableSignal` from other non-writable signals and functions. */ export const ɵWRITABLE_SIGNAL: unique symbol = /* @__PURE__ */ Symbol('WRITABLE_SIGNAL'); /** * A `Signal` with a value that can be mutated via a setter interface. * * @publicApi 17.0 */ export interface WritableSignal<T> extends Signal<T> { [ɵWRITABLE_SIGNAL]: T; /** * Directly set the signal to a new value, and notify any dependents. */ set(value: T): void; /** * Update the value of the signal based on its current value, and * notify any dependents. */ update(updateFn: (value: T) => T): void; /** * Returns a readonly version of this signal. Readonly signals can be accessed to read their value * but can't be changed using set or update methods. The readonly signals do _not_ have * any built-in mechanism that would prevent deep-mutation of their value. */ asReadonly(): Signal<T>; } /** * Utility function used during template type checking to extract the value from a `WritableSignal`. * @codeGenApi */ export function ɵunwrapWritableSignal<T>(value: T | {[ɵWRITABLE_SIGNAL]: T}): T { // Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`, // because the latter incorrectly unwraps non-signal getter functions. return null!; } /** * Options passed to the `signal` creation function. */ export interface CreateSignalOptions<T> { /** * A comparison function which defines equality for signal values. */ equal?: ValueEqualityFn<T>; /** * A debug name for the signal. Used in Angular DevTools to identify the signal. */ debugName?: string; } /** * Create a `Signal` that can be set or updated directly. * @see [Angular Signals](guide/signals) */ export function signal<T>(initialValue: T, options?: CreateSignalOptions<T>): WritableSignal<T> { const [get, set, update] = createSignal(initialValue, options?.equal); const signalFn = get as SignalGetter<T> & WritableSignal<T>; const node = signalFn[SIGNAL]; signalFn.set = set; signalFn.update = update; signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn as any) as () => Signal<T>; if (ngDevMode) { signalFn.toString = () => `[Signal: ${signalFn()}]`; node.debugName = options?.debugName; } return signalFn as WritableSignal<T>; } export function signalAsReadonlyFn<T>(this: SignalGetter<T>): Signal<T> { const node = this[SIGNAL] as SignalNode<T> & {readonlyFn?: Signal<T>}; if (node.readonlyFn === undefined) { const readonlyFn = () => this(); (readonlyFn as any)[SIGNAL] = node; node.readonlyFn = readonlyFn as Signal<T>; } return node.readonlyFn; }
github
angular/angular
packages/core/src/render3/reactivity/signal.ts
/** * @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 { Replacement, TextUpdate, ProgramInfo, projectFile, ProjectFile, } from '../../../../../../utils/tsurge'; import {getBindingElementDeclaration} from '../../../utils/binding_elements'; import {UniqueNamesGenerator} from '../../../utils/unique_names'; import assert from 'assert'; import {createNewBlockToInsertVariable} from './create_block_arrow_function'; /** An identifier part of a binding element. */ export interface IdentifierOfBindingElement extends ts.Identifier { parent: ts.BindingElement; } /** * Migrates a binding element that refers to an Angular input. * * E.g. `const {myInput} = this`. * * For references in binding elements, we extract the element into a variable * where we unwrap the input. This ensures narrowing naturally works in subsequent * places, and we also don't need to detect potential aliases. * * ```ts * const {myInput} = this; * // turns into * const {myInput: myInputValue} = this; * const myInput = myInputValue(); * ``` */ export function migrateBindingElementInputReference( tsReferencesInBindingElements: Set<IdentifierOfBindingElement>, info: ProgramInfo, replacements: Replacement[], printer: ts.Printer, ) { const nameGenerator = new UniqueNamesGenerator(['Input', 'Signal', 'Ref']); for (const reference of tsReferencesInBindingElements) { const bindingElement = reference.parent; const bindingDecl = getBindingElementDeclaration(bindingElement); const sourceFile = bindingElement.getSourceFile(); const file = projectFile(sourceFile, info); const inputFieldName = bindingElement.propertyName ?? bindingElement.name; assert( !ts.isObjectBindingPattern(inputFieldName) && !ts.isArrayBindingPattern(inputFieldName), 'Property of binding element cannot be another pattern.', ); const tmpName: string | undefined = nameGenerator.generate(reference.text, bindingElement); // Only use the temporary name, if really needed. A temporary name is needed if // the input field simply aliased via the binding element, or if the exposed identifier // is a string-literal like. const useTmpNameForInputField = !ts.isObjectBindingPattern(bindingElement.name) || !ts.isIdentifier(inputFieldName); const propertyName = useTmpNameForInputField ? inputFieldName : undefined; const exposedName = useTmpNameForInputField ? ts.factory.createIdentifier(tmpName) : inputFieldName; const newBindingToAccessInputField = ts.factory.updateBindingElement( bindingElement, bindingElement.dotDotDotToken, propertyName, exposedName, bindingElement.initializer, ); const temporaryVariableReplacements = insertTemporaryVariableForBindingElement( bindingDecl, file, `const ${bindingElement.name.getText()} = ${exposedName.text}();`, ); if (temporaryVariableReplacements === null) { console.error(`Could not migrate reference ${reference.text} in ${file.rootRelativePath}`); continue; } replacements.push( new Replacement( file, new TextUpdate({ position: bindingElement.getStart(), end: bindingElement.getEnd(), toInsert: printer.printNode( ts.EmitHint.Unspecified, newBindingToAccessInputField, sourceFile, ), }), ), ...temporaryVariableReplacements, ); } } /** * Inserts the given code snippet after the given variable or * parameter declaration. * * If this is a parameter of an arrow function, a block may be * added automatically. */ function insertTemporaryVariableForBindingElement( expansionDecl: ts.VariableDeclaration | ts.ParameterDeclaration, file: ProjectFile, toInsert: string, ): Replacement[] | null { const sf = expansionDecl.getSourceFile(); const parent = expansionDecl.parent; // The snippet is simply inserted after the variable declaration. // The other case of a variable declaration inside a catch clause is handled // below. if (ts.isVariableDeclaration(expansionDecl) && ts.isVariableDeclarationList(parent)) { const leadingSpaceCount = ts.getLineAndCharacterOfPosition(sf, parent.getStart()).character; const leadingSpace = ' '.repeat(leadingSpaceCount); const statement: ts.Statement = parent.parent; return [ new Replacement( file, new TextUpdate({ position: statement.getEnd(), end: statement.getEnd(), toInsert: `\n${leadingSpace}${toInsert}`, }), ), ]; } // If we are dealing with a object expansion inside a parameter of // a function-like declaration w/ block, add the variable as the first // node inside the block. const bodyBlock = getBodyBlockOfNode(parent); if (bodyBlock !== null) { const firstElementInBlock = bodyBlock.statements[0] as ts.Statement | undefined; const spaceReferenceNode = firstElementInBlock ?? bodyBlock; const spaceOffset = firstElementInBlock !== undefined ? 0 : 2; const leadingSpaceCount = ts.getLineAndCharacterOfPosition(sf, spaceReferenceNode.getStart()).character + spaceOffset; const leadingSpace = ' '.repeat(leadingSpaceCount); return [ new Replacement( file, new TextUpdate({ position: bodyBlock.getStart() + 1, end: bodyBlock.getStart() + 1, toInsert: `\n${leadingSpace}${toInsert}`, }), ), ]; } // Other cases where we see an arrow function without a block. // We need to create one now. if (ts.isArrowFunction(parent) && !ts.isBlock(parent.body)) { return createNewBlockToInsertVariable(parent, file, toInsert); } return null; } /** Gets the body block of a given node, if available. */ function getBodyBlockOfNode(node: ts.Node): ts.Block | null { if ( (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isArrowFunction(node)) && node.body !== undefined && ts.isBlock(node.body) ) { return node.body; } if (ts.isCatchClause(node.parent)) { return node.parent.block; } return null; }
github
angular/angular
packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/object_expansion_refs.ts
/** * @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; }
github
angular/angular
packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.ts
/** * @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 { confirmAsSerializable, ProgramInfo, projectFile, ProjectFile, Replacement, Serializable, TextUpdate, TsurgeFunnelMigration, } from '../../utils/tsurge'; import {NgComponentTemplateVisitor} from '../../utils/ng_component_template'; import {migrateTemplateToSelfClosingTags} from './to-self-closing-tags'; import {AbsoluteFsPath} from '../../../../compiler-cli'; export interface MigrationConfig { /** * Whether to migrate this component template to self-closing tags. */ shouldMigrate?: (containingFile: ProjectFile) => boolean; } export interface SelfClosingTagsMigrationData { file: ProjectFile; replacementCount: number; replacements: Replacement[]; } export interface SelfClosingTagsCompilationUnitData { tagReplacements: Array<SelfClosingTagsMigrationData>; } export class SelfClosingTagsMigration extends TsurgeFunnelMigration< SelfClosingTagsCompilationUnitData, SelfClosingTagsCompilationUnitData > { constructor(private readonly config: MigrationConfig = {}) { super(); } override async analyze( info: ProgramInfo, ): Promise<Serializable<SelfClosingTagsCompilationUnitData>> { const {sourceFiles, program} = info; const typeChecker = program.getTypeChecker(); const tagReplacements: Array<SelfClosingTagsMigrationData> = []; for (const sf of sourceFiles) { ts.forEachChild(sf, (node: ts.Node) => { // Skipping any non component declarations if (!ts.isClassDeclaration(node)) { return; } const file = projectFile(node.getSourceFile(), info); if (this.config.shouldMigrate && this.config.shouldMigrate(file) === false) { return; } const templateVisitor = new NgComponentTemplateVisitor(typeChecker); templateVisitor.visitNode(node); templateVisitor.resolvedTemplates.forEach((template) => { const {migrated, changed, replacementCount} = migrateTemplateToSelfClosingTags( template.content, ); if (!changed) { return; } const fileToMigrate = template.inline ? file : projectFile(template.filePath as AbsoluteFsPath, info); const end = template.start + template.content.length; const replacements = [ prepareTextReplacement(fileToMigrate, migrated, template.start, end), ]; const fileReplacements = tagReplacements.find( (tagReplacement) => tagReplacement.file === file, ); if (fileReplacements) { fileReplacements.replacements.push(...replacements); fileReplacements.replacementCount += replacementCount; } else { tagReplacements.push({file, replacements, replacementCount}); } }); }); } return confirmAsSerializable({tagReplacements}); } override async combine( unitA: SelfClosingTagsCompilationUnitData, unitB: SelfClosingTagsCompilationUnitData, ): Promise<Serializable<SelfClosingTagsCompilationUnitData>> { return confirmAsSerializable({ tagReplacements: [...unitA.tagReplacements, ...unitB.tagReplacements], }); } override async globalMeta( combinedData: SelfClosingTagsCompilationUnitData, ): Promise<Serializable<SelfClosingTagsCompilationUnitData>> { const globalMeta: SelfClosingTagsCompilationUnitData = { tagReplacements: combinedData.tagReplacements, }; return confirmAsSerializable(globalMeta); } override async stats(globalMetadata: SelfClosingTagsCompilationUnitData) { const touchedFilesCount = globalMetadata.tagReplacements.length; const replacementCount = globalMetadata.tagReplacements.reduce( (acc, cur) => acc + cur.replacementCount, 0, ); return confirmAsSerializable({ touchedFilesCount, replacementCount, }); } override async migrate(globalData: SelfClosingTagsCompilationUnitData) { return {replacements: globalData.tagReplacements.flatMap(({replacements}) => replacements)}; } } function prepareTextReplacement( file: ProjectFile, replacement: string, start: number, end: number, ): Replacement { return new Replacement( file, new TextUpdate({ position: start, end: end, toInsert: replacement, }), ); }
github
angular/angular
packages/core/schematics/migrations/self-closing-tags-migration/self-closing-tags-migration.ts
/** * @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 {TreeD3Node, TreeNode} from '../../shared/tree-visualizer/tree-visualizer'; import {Route} from '../../../../../protocol'; import {TreeVisualizerComponent} from '../../shared/tree-visualizer/tree-visualizer.component'; export interface RouterTreeNode extends TreeNode, Route { children: RouterTreeNode[]; } export type RouterTreeVisualizer = TreeVisualizerComponent<RouterTreeNode>; export type RouterTreeD3Node = TreeD3Node<RouterTreeNode>; export function getRouteLabel( route: Route | RouterTreeNode, parent: Route | RouterTreeNode | undefined, showFullPath: boolean, ): string { return (showFullPath ? route.path : route.path.replace(parent?.path || '', '')) || ''; } export function mapRoute( route: Route, parent: Route | undefined, showFullPath: boolean, ): RouterTreeNode { return { ...route, label: getRouteLabel(route, parent, showFullPath), children: [], }; } export function transformRoutesIntoVisTree(root: Route, showFullPath: boolean): RouterTreeNode { let rootNode: RouterTreeNode | undefined; const routesQueue: {route: Route; parent?: RouterTreeNode}[] = [{route: root}]; while (routesQueue.length) { const {route, parent} = routesQueue.shift()!; const routeNode = mapRoute(route, parent, showFullPath); if (!rootNode) { rootNode = routeNode; } if (parent) { parent.children.push(routeNode); } if (route.children) { for (const child of route.children) { routesQueue.push({route: child, parent: routeNode}); } } } return rootNode!; } export function findNodesByLabel(root: RouterTreeNode, searchString: string): Set<RouterTreeNode> { let matches: Set<RouterTreeNode> = new Set(); if (!searchString) { return matches; } const traverse = (node: RouterTreeNode) => { if (node.label.toLowerCase().includes(searchString)) { matches.add(node); } if (node.children) { for (const child of node.children) { traverse(child); } } }; traverse(root); return matches; }
github
angular/angular
devtools/projects/ng-devtools/src/lib/devtools-tabs/router-tree/router-tree-fns.ts
/** * @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 o from '../../../../../../src/output/output_ast'; import {ParseSourceSpan} from '../../../../../../src/parse_util'; import {SecurityContext} from '../../../../../core'; import {BindingKind, OpKind} from '../enums'; import {Op, XrefId} from '../operations'; import {ConsumesVarsTrait, TRAIT_CONSUMES_VARS} from '../traits'; import {NEW_OP} from './shared'; import type {Interpolation, UpdateOp} from './update'; /** * Logical operation representing a binding to a native DOM property. */ export interface DomPropertyOp extends Op<UpdateOp>, ConsumesVarsTrait { kind: OpKind.DomProperty; name: string; expression: o.Expression | Interpolation; bindingKind: BindingKind; i18nContext: XrefId | null; securityContext: SecurityContext | SecurityContext[]; sanitizer: o.Expression | null; sourceSpan: ParseSourceSpan; } export function createDomPropertyOp( name: string, expression: o.Expression | Interpolation, bindingKind: BindingKind, i18nContext: XrefId | null, securityContext: SecurityContext | SecurityContext[], sourceSpan: ParseSourceSpan, ): DomPropertyOp { return { kind: OpKind.DomProperty, name, expression, bindingKind, i18nContext, securityContext, sanitizer: null, sourceSpan, ...TRAIT_CONSUMES_VARS, ...NEW_OP, }; }
github
angular/angular
packages/compiler/src/template/pipeline/ir/src/ops/host.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; export type Entry = string | Directory; export interface Directory { [name: string]: Entry; } export class MockAotContext { private files: Entry[]; constructor( public currentDirectory: string, ...files: Entry[] ) { this.files = files; } fileExists(fileName: string): boolean { return typeof this.getEntry(fileName) === 'string'; } directoryExists(path: string): boolean { return path === this.currentDirectory || typeof this.getEntry(path) === 'object'; } readFile(fileName: string): string { const data = this.getEntry(fileName); if (typeof data === 'string') { return data; } return undefined!; } readResource(fileName: string): Promise<string> { const result = this.readFile(fileName); if (result == null) { return Promise.reject(new Error(`Resource not found: ${fileName}`)); } return Promise.resolve(result); } writeFile(fileName: string, data: string): void { const parts = fileName.split('/'); const name = parts.pop()!; const entry = this.getEntry(parts); if (entry && typeof entry !== 'string') { entry[name] = data; } } assumeFileExists(fileName: string): void { this.writeFile(fileName, ''); } getEntry(fileName: string | string[]): Entry | undefined { let parts = typeof fileName === 'string' ? fileName.split('/') : fileName; if (parts[0]) { parts = this.currentDirectory.split('/').concat(parts); } parts.shift(); parts = normalize(parts); return first(this.files, (files) => getEntryFromFiles(parts, files)); } getDirectories(path: string): string[] { const dir = this.getEntry(path); if (typeof dir !== 'object') { return []; } else { return Object.keys(dir).filter((key) => typeof dir[key] === 'object'); } } override(files: Entry) { return new MockAotContext(this.currentDirectory, files, ...this.files); } } function first<T>(a: T[], cb: (value: T) => T | undefined): T | undefined { for (const value of a) { const result = cb(value); if (result != null) return result; } return; } function getEntryFromFiles(parts: string[], files: Entry) { let current = files; while (parts.length) { const part = parts.shift()!; if (typeof current === 'string') { return undefined; } const next = (<Directory>current)[part]; if (next === undefined) { return undefined; } current = next; } return current; } function normalize(parts: string[]): string[] { const result: string[] = []; while (parts.length) { const part = parts.shift()!; switch (part) { case '.': break; case '..': result.pop(); break; default: result.push(part); } } return result; } export class MockCompilerHost implements ts.CompilerHost { constructor(private context: MockAotContext) {} fileExists(fileName: string): boolean { return this.context.fileExists(fileName); } readFile(fileName: string): string { return this.context.readFile(fileName); } directoryExists(directoryName: string): boolean { return this.context.directoryExists(directoryName); } getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void, ): ts.SourceFile { const sourceText = this.context.readFile(fileName); if (sourceText != null) { return ts.createSourceFile(fileName, sourceText, languageVersion); } else { return undefined!; } } getDefaultLibFileName(options: ts.CompilerOptions): string { return ts.getDefaultLibFileName(options); } writeFile: ts.WriteFileCallback = (fileName, text) => { this.context.writeFile(fileName, text); }; getCurrentDirectory(): string { return this.context.currentDirectory; } getCanonicalFileName(fileName: string): string { return fileName; } useCaseSensitiveFileNames(): boolean { return false; } getNewLine(): string { return '\n'; } getDirectories(path: string): string[] { return this.context.getDirectories(path); } }
github
angular/angular
packages/compiler-cli/test/mocks.ts
/** * @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'; /** * A host backed by a build system which has a unified view of the module namespace. * * Such a build system supports the `fileNameToModuleName` method provided by certain build system * integrations (such as the integration with Bazel). See the docs on `fileNameToModuleName` for * more details. */ export interface UnifiedModulesHost { /** * Converts a file path to a module name that can be used as an `import ...`. * * For example, such a host might determine that `/absolute/path/to/monorepo/lib/importedFile.ts` * should be imported using a module specifier of `monorepo/lib/importedFile`. */ fileNameToModuleName(importedFilePath: string, containingFilePath: string): string; } /** * A host which additionally tracks and produces "resources" (HTML templates, CSS * files, etc). */ export interface ResourceHost { /** * Converts a file path for a resource that is used in a source file or another resource * into a filepath. * * The optional `fallbackResolve` method can be used as a way to attempt a fallback resolution if * the implementation's `resourceNameToFileName` resolution fails. */ resourceNameToFileName( resourceName: string, containingFilePath: string, fallbackResolve?: (url: string, fromFile: string) => string | null, ): string | null; /** * Load a referenced resource either statically or asynchronously. If the host returns a * `Promise<string>` it is assumed the user of the corresponding `Program` will call * `loadNgStructureAsync()`. Returning `Promise<string>` outside `loadNgStructureAsync()` will * cause a diagnostics error or an exception to be thrown. */ readResource(fileName: string): Promise<string> | string; /** * Get the absolute paths to the changed files that triggered the current compilation * or `undefined` if this is not an incremental build. */ getModifiedResourceFiles?(): Set<string> | undefined; /** * Transform an inline or external resource asynchronously. * It is assumed the consumer of the corresponding `Program` will call * `loadNgStructureAsync()`. Using outside `loadNgStructureAsync()` will * cause a diagnostics error or an exception to be thrown. * Only style resources are currently supported. * * @param data The resource data to transform. * @param context Information regarding the resource such as the type and containing file. * @returns A promise of either the transformed resource data or null if no transformation occurs. */ transformResource?( data: string, context: ResourceHostContext, ): Promise<TransformResourceResult | null>; } /** * Contextual information used by members of the ResourceHost interface. */ export interface ResourceHostContext { /** * The type of the component resource. Templates are not yet supported. * * Resources referenced via a component's `styles` or `styleUrls` properties are of * type `style`. */ readonly type: 'style'; /** * The absolute path to the resource file. If the resource is inline, the value will be null. */ readonly resourceFile: string | null; /** * The absolute path to the file that contains the resource or reference to the resource. */ readonly containingFile: string; /** * For style resources, the placement of the style within the containing file with lower numbers * being before higher numbers. * The value is primarily used by the Angular CLI to create a deterministic identifier for each * style in HMR scenarios. * This is undefined for templates. */ readonly order?: number; /** * The name of the class that defines the component using the resource. * This allows identifying the source usage of a resource in cases where multiple components are * contained in a single source file. */ className: string; } /** * The successful transformation result of the `ResourceHost.transformResource` function. * This interface may be expanded in the future to include diagnostic information and source mapping * support. */ export interface TransformResourceResult { /** * The content generated by the transformation. */ content: string; } /** * A `ts.CompilerHost` interface which supports some number of optional methods in addition to the * core interface. */ export interface ExtendedTsCompilerHost extends ts.CompilerHost, Partial<ResourceHost>, Partial<UnifiedModulesHost> {}
github
angular/angular
packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts
/** * @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 {DocEntry} from '../../../src/ngtsc/docs'; import {EntryType, TypeAliasEntry} from '../../../src/ngtsc/docs/src/entities'; import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../../src/ngtsc/testing'; import {NgtscTestEnvironment} from '../env'; const testFiles = loadStandardTestFiles({fakeCommon: true}); runInEachFileSystem(() => { let env!: NgtscTestEnvironment; describe('ngtsc type alias docs extraction', () => { beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig(); }); it('should extract type aliases based on primitives', () => { env.write( 'index.ts', ` export type SuperNumber = number | string; `, ); const docs: DocEntry[] = env.driveDocsExtraction('index.ts'); expect(docs.length).toBe(1); const typeAliasEntry = docs[0] as TypeAliasEntry; expect(typeAliasEntry.name).toBe('SuperNumber'); expect(typeAliasEntry.entryType).toBe(EntryType.TypeAlias); expect(typeAliasEntry.type).toBe('number | string'); }); it('should extract type aliases for objects', () => { env.write( 'index.ts', ` export type UserProfile = { name: string; age: number; }; `, ); const docs: DocEntry[] = env.driveDocsExtraction('index.ts'); expect(docs.length).toBe(1); const typeAliasEntry = docs[0] as TypeAliasEntry; expect(typeAliasEntry.name).toBe('UserProfile'); expect(typeAliasEntry.entryType).toBe(EntryType.TypeAlias); expect(typeAliasEntry.type).toBe(`{ name: string; age: number; }`); }); it('should extract type aliases based with generics', () => { env.write( 'index.ts', ` type Foo<T> = undefined; export type Bar<T extends string> = Foo<T>; `, ); const docs: DocEntry[] = env.driveDocsExtraction('index.ts'); expect(docs.length).toBe(1); const typeAliasEntry = docs[0] as TypeAliasEntry; expect(typeAliasEntry.name).toBe('Bar'); expect(typeAliasEntry.entryType).toBe(EntryType.TypeAlias); expect(typeAliasEntry.type).toBe('Foo<T>'); expect(typeAliasEntry.generics).toEqual([ {name: 'T', constraint: 'string', default: undefined}, ]); }); }); });
github
angular/angular
packages/compiler-cli/test/ngtsc/doc_extraction/type_alias_doc_extraction_spec.ts
/** * @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 {PerfCheckpoint, PerfEvent, PerfPhase, PerfRecorder} from './api'; import {HrTime, mark, timeSinceInMicros} from './clock'; /** * Serializable performance data for the compilation, using string names. */ export interface PerfResults { events: Record<string, number>; phases: Record<string, number>; memory: Record<string, number>; } /** * A `PerfRecorder` that actively tracks performance statistics. */ export class ActivePerfRecorder implements PerfRecorder { private counters: number[]; private phaseTime: number[]; private bytes: number[]; private currentPhase = PerfPhase.Unaccounted; private currentPhaseEntered: HrTime; /** * Creates an `ActivePerfRecorder` with its zero point set to the current time. */ static zeroedToNow(): ActivePerfRecorder { return new ActivePerfRecorder(mark()); } private constructor(private zeroTime: HrTime) { this.currentPhaseEntered = this.zeroTime; this.counters = Array(PerfEvent.LAST).fill(0); this.phaseTime = Array(PerfPhase.LAST).fill(0); this.bytes = Array(PerfCheckpoint.LAST).fill(0); // Take an initial memory snapshot before any other compilation work begins. this.memory(PerfCheckpoint.Initial); } reset(): void { this.counters = Array(PerfEvent.LAST).fill(0); this.phaseTime = Array(PerfPhase.LAST).fill(0); this.bytes = Array(PerfCheckpoint.LAST).fill(0); this.zeroTime = mark(); this.currentPhase = PerfPhase.Unaccounted; this.currentPhaseEntered = this.zeroTime; } memory(after: PerfCheckpoint): void { this.bytes[after] = process.memoryUsage().heapUsed; } phase(phase: PerfPhase): PerfPhase { const previous = this.currentPhase; this.phaseTime[this.currentPhase] += timeSinceInMicros(this.currentPhaseEntered); this.currentPhase = phase; this.currentPhaseEntered = mark(); return previous; } inPhase<T>(phase: PerfPhase, fn: () => T): T { const previousPhase = this.phase(phase); try { return fn(); } finally { this.phase(previousPhase); } } eventCount(counter: PerfEvent, incrementBy: number = 1): void { this.counters[counter] += incrementBy; } /** * Return the current performance metrics as a serializable object. */ finalize(): PerfResults { // Track the last segment of time spent in `this.currentPhase` in the time array. this.phase(PerfPhase.Unaccounted); const results: PerfResults = { events: {}, phases: {}, memory: {}, }; for (let i = 0; i < this.phaseTime.length; i++) { if (this.phaseTime[i] > 0) { results.phases[PerfPhase[i]] = this.phaseTime[i]; } } for (let i = 0; i < this.phaseTime.length; i++) { if (this.counters[i] > 0) { results.events[PerfEvent[i]] = this.counters[i]; } } for (let i = 0; i < this.bytes.length; i++) { if (this.bytes[i] > 0) { results.memory[PerfCheckpoint[i]] = this.bytes[i]; } } return results; } } /** * A `PerfRecorder` that delegates to a target `PerfRecorder` which can be updated later. * * `DelegatingPerfRecorder` is useful when a compiler class that needs a `PerfRecorder` can outlive * the current compilation. This is true for most compiler classes as resource-only changes reuse * the same `NgCompiler` for a new compilation. */ export class DelegatingPerfRecorder implements PerfRecorder { constructor(public target: PerfRecorder) {} eventCount(counter: PerfEvent, incrementBy?: number): void { this.target.eventCount(counter, incrementBy); } phase(phase: PerfPhase): PerfPhase { return this.target.phase(phase); } inPhase<T>(phase: PerfPhase, fn: () => T): T { // Note: this doesn't delegate to `this.target.inPhase` but instead is implemented manually here // to avoid adding an additional frame of noise to the stack when debugging. const previousPhase = this.target.phase(phase); try { return fn(); } finally { this.target.phase(previousPhase); } } memory(after: PerfCheckpoint): void { this.target.memory(after); } reset(): void { this.target.reset(); } }
github
angular/angular
packages/compiler-cli/src/ngtsc/perf/src/recorder.ts
/** * @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'; export interface FileUpdate { /** * The source file text. */ newText: string; /** * Represents the source file from the original program that is being updated. If the file update * targets a shim file then this is null, as shim files do not have an associated original file. */ originalFile: ts.SourceFile | null; } export const NgOriginalFile: unique symbol = Symbol('NgOriginalFile'); /** * If an updated file has an associated original source file, then the original source file * is attached to the updated file using the `NgOriginalFile` symbol. */ export interface MaybeSourceFileWithOriginalFile extends ts.SourceFile { [NgOriginalFile]?: ts.SourceFile; } export interface ProgramDriver { /** * Whether this strategy supports modifying user files (inline modifications) in addition to * modifying type-checking shims. */ readonly supportsInlineOperations: boolean; /** * Retrieve the latest version of the program, containing all the updates made thus far. */ getProgram(): ts.Program; /** * Incorporate a set of changes to either augment or completely replace the type-checking code * included in the type-checking program. */ updateFiles(contents: Map<AbsoluteFsPath, FileUpdate>, updateMode: UpdateMode): void; /** * Retrieve a string version for a given `ts.SourceFile`, which much change when the contents of * the file have changed. * * If this method is present, the compiler will use these versions in addition to object identity * for `ts.SourceFile`s to determine what's changed between two incremental programs. This is * valuable for some clients (such as the Language Service) that treat `ts.SourceFile`s as mutable * objects. */ getSourceFileVersion?(sf: ts.SourceFile): string; } export enum UpdateMode { /** * A complete update creates a completely new overlay of type-checking code on top of the user's * original program, which doesn't include type-checking code from previous calls to * `updateFiles`. */ Complete, /** * An incremental update changes the contents of some files in the type-checking program without * reverting any prior changes. */ Incremental, }
github
angular/angular
packages/compiler-cli/src/ngtsc/program_driver/src/api.ts
/** * @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 {Component, ErrorHandler, Injectable, NgModule} from '@angular/core'; @Component({ selector: 'benchmark-area', template: '<ng-content></ng-content>', styles: [ ` :host { padding: 1; margin: 1; background-color: white; width: 1000px; display: block; } `, ], host: { 'class': 'cfc-ng2-region', }, standalone: false, }) export class BenchmarkArea {} declare interface ExtendedWindow extends Window { benchmarkErrors?: string[]; } const extendedWindow = window as ExtendedWindow; @Injectable({providedIn: 'root'}) export class BenchmarkErrorHandler implements ErrorHandler { handleError(error: Error) { if (!extendedWindow.benchmarkErrors) { extendedWindow.benchmarkErrors = []; } extendedWindow.benchmarkErrors.push(error.message); console.error(error); } } @NgModule({ declarations: [BenchmarkArea], exports: [BenchmarkArea], providers: [{provide: ErrorHandler, useClass: BenchmarkErrorHandler}], }) export class BenchmarkModule {}
github
angular/angular
modules/benchmarks/src/expanding_rows/benchmark_module.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import {asyncData} from '../../../testing'; import {map} from 'rxjs/operators'; // re-export for tester convenience export {Hero} from '../hero'; export {HeroService} from '../hero.service'; export {getTestHeroes} from './test-heroes'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; import {getTestHeroes} from './test-heroes'; @Injectable() /** * FakeHeroService pretends to make real http requests. * implements only as much of HeroService as is actually consumed by the app */ export class TestHeroService extends HeroService { constructor() { // This is a fake testing service that won't be making HTTP // requests so we can pass in `null` as the HTTP client. super(null!); } heroes = getTestHeroes(); lastResult!: Observable<any>; // result from last method call override addHero(hero: Hero): Observable<Hero> { throw new Error('Method not implemented.'); } override deleteHero(hero: number | Hero): Observable<Hero> { throw new Error('Method not implemented.'); } override getHeroes(): Observable<Hero[]> { return (this.lastResult = asyncData(this.heroes)); } override getHero(id: number | string): Observable<Hero> { if (typeof id === 'string') { id = parseInt(id, 10); } const hero = this.heroes.find((h) => h.id === id); this.lastResult = asyncData(hero); return this.lastResult; } override updateHero(hero: Hero): Observable<Hero> { return (this.lastResult = this.getHero(hero.id).pipe( map((h) => { if (h) { return Object.assign(h, hero); } throw new Error(`Hero ${hero.id} not found`); }), )); } }
github
angular/angular
adev/src/content/examples/testing/src/app/model/testing/test-hero.service.ts
/** * @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 {ClassDeclaration} from '../../reflection'; import {SymbolWithValueDeclaration} from '../../util/src/typescript'; /** * A PotentialImport for some Angular trait has a TypeScript module specifier, which can be * relative, as well as an identifier name. */ export interface PotentialImport { kind: PotentialImportKind; // If no moduleSpecifier is present, the given symbol name is already in scope. moduleSpecifier?: string; symbolName: string; isForwardReference: boolean; } /** * Which kind of Angular Trait the import targets. */ export enum PotentialImportKind { NgModule, Standalone, } export interface TsCompletionEntryInfo { /** * Sometimes, the location of the tsCompletionEntry symbol does not match the location of the Angular symbol. * * For example, the BarComponent is declared in `bar.ts` and exported from there. The `public_api.ts` also * reexports the BarComponent from `bar.ts`, so the `tsCompletionEntrySymbolFileName` will be `public_api.ts`. */ tsCompletionEntrySymbolFileName: string; /** * Sometime the component can be exported with a different name than the class name. * For example, `export {BarComponent as NewBarComponent} from './bar.component';` * * Sometimes, the component is exported by the `NgModule`. */ tsCompletionEntrySymbolName: string; /** * This data is from the tsLs completion entry, and * will be used in the `ls.getCompletionEntryDetails`. */ tsCompletionEntryData?: ts.CompletionEntryData; } /** * Metadata on a directive which is available in a template. */ export interface PotentialDirective { ref: Reference<ClassDeclaration>; /** * The `ts.Symbol` for the directive class. */ tsSymbol: SymbolWithValueDeclaration; /** * The module which declares the directive. */ ngModule: ClassDeclaration | null; /** * The selector for the directive or component. */ selector: string | null; /** * `true` if this directive is a component. */ isComponent: boolean; /** * `true` if this directive is a structural directive. */ isStructural: boolean; /** * Whether or not this directive is in scope. */ isInScope: boolean; /** * The directive can be exported by multiple modules, * collecting all the entry information here. * * Filter the appropriate entry information when using it to compute the module specifier. */ tsCompletionEntryInfos: TsCompletionEntryInfo[] | null; } /** * Metadata for a pipe which is available in a template. */ export interface PotentialPipe { ref: Reference<ClassDeclaration>; /** * The `ts.Symbol` for the pipe class. */ tsSymbol: ts.Symbol; /** * Name of the pipe. */ name: string | null; /** * Whether or not this pipe is in scope. */ isInScope: boolean; /** * The pipe can be exported by multiple modules, * collecting all the entry information here. * * Filter the appropriate entry information when using it to compute the module specifier. */ tsCompletionEntryInfos: TsCompletionEntryInfo[] | null; } /** * Possible modes in which to look up a potential import. */ export enum PotentialImportMode { /** Whether an import is standalone is inferred based on its metadata. */ Normal, /** * An import is assumed to be standalone and is imported directly. This is useful for migrations * where a declaration wasn't standalone when the program was created, but will become standalone * as a part of the migration. */ ForceDirect, } export interface DirectiveModuleExportDetails { moduleSpecifier: string; exportName: string; } export interface PotentialDirectiveModuleSpecifierResolver { resolve( toImport: Reference<ClassDeclaration>, importOn: ts.Node | null, ): DirectiveModuleExportDetails | null; }
github
angular/angular
packages/compiler-cli/src/ngtsc/typecheck/api/scope.ts
/** * @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'; /** * A type reference resolver function is responsible for translating a type reference from the * origin source file into a type reference that is valid in the desired source file. If the type * cannot be translated to the desired source file, then null can be returned. */ export type TypeReferenceTranslator = (type: ts.TypeReferenceNode) => ts.TypeReferenceNode | null; /** * A marker to indicate that a type reference is ineligible for emitting. This needs to be truthy * as it's returned from `ts.forEachChild`, which only returns truthy values. */ type INELIGIBLE = { __brand: 'ineligible'; }; const INELIGIBLE: INELIGIBLE = {} as INELIGIBLE; /** * Determines whether the provided type can be emitted, which means that it can be safely emitted * into a different location. * * If this function returns true, a `TypeEmitter` should be able to succeed. Vice versa, if this * function returns false, then using the `TypeEmitter` should not be attempted as it is known to * fail. */ export function canEmitType( type: ts.TypeNode, canEmit: (type: ts.TypeReferenceNode) => boolean, ): boolean { return canEmitTypeWorker(type); function canEmitTypeWorker(type: ts.TypeNode): boolean { return visitNode(type) !== INELIGIBLE; } // To determine whether a type can be emitted, we have to recursively look through all type nodes. // If an unsupported type node is found at any position within the type, then the `INELIGIBLE` // constant is returned to stop the recursive walk as the type as a whole cannot be emitted in // that case. Otherwise, the result of visiting all child nodes determines the result. If no // ineligible type reference node is found then the walk returns `undefined`, indicating that // no type node was visited that could not be emitted. function visitNode(node: ts.Node): INELIGIBLE | undefined { // `import('module')` type nodes are not supported, as it may require rewriting the module // specifier which is currently not done. if (ts.isImportTypeNode(node)) { return INELIGIBLE; } // Emitting a type reference node in a different context requires that an import for the type // can be created. If a type reference node cannot be emitted, `INELIGIBLE` is returned to stop // the walk. if (ts.isTypeReferenceNode(node) && !canEmitTypeReference(node)) { return INELIGIBLE; } else { return ts.forEachChild(node, visitNode); } } function canEmitTypeReference(type: ts.TypeReferenceNode): boolean { if (!canEmit(type)) { return false; } // The type can be emitted if either it does not have any type arguments, or all of them can be // emitted. return type.typeArguments === undefined || type.typeArguments.every(canEmitTypeWorker); } } /** * Given a `ts.TypeNode`, this class derives an equivalent `ts.TypeNode` that has been emitted into * a different context. * * For example, consider the following code: * * ```ts * import {NgIterable} from '@angular/core'; * * class NgForOf<T, U extends NgIterable<T>> {} * ``` * * Here, the generic type parameters `T` and `U` can be emitted into a different context, as the * type reference to `NgIterable` originates from an absolute module import so that it can be * emitted anywhere, using that same module import. The process of emitting translates the * `NgIterable` type reference to a type reference that is valid in the context in which it is * emitted, for example: * * ```ts * import * as i0 from '@angular/core'; * import * as i1 from '@angular/common'; * * const _ctor1: <T, U extends i0.NgIterable<T>>(o: Pick<i1.NgForOf<T, U>, 'ngForOf'>): * i1.NgForOf<T, U>; * ``` * * Notice how the type reference for `NgIterable` has been translated into a qualified name, * referring to the namespace import that was created. */ export class TypeEmitter { constructor(private translator: TypeReferenceTranslator) {} emitType(type: ts.TypeNode): ts.TypeNode { const typeReferenceTransformer: ts.TransformerFactory<ts.TypeNode> = (context) => { const visitNode = (node: ts.Node): ts.Node => { if (ts.isImportTypeNode(node)) { throw new Error('Unable to emit import type'); } if (ts.isTypeReferenceNode(node)) { return this.emitTypeReference(node); } else if (ts.isLiteralExpression(node)) { // TypeScript would typically take the emit text for a literal expression from the source // file itself. As the type node is being emitted into a different file, however, // TypeScript would extract the literal text from the wrong source file. To mitigate this // issue the literal is cloned and explicitly marked as synthesized by setting its text // range to a negative range, forcing TypeScript to determine the node's literal text from // the synthesized node's text instead of the incorrect source file. let clone: ts.LiteralExpression; if (ts.isStringLiteral(node)) { clone = ts.factory.createStringLiteral(node.text); } else if (ts.isNumericLiteral(node)) { clone = ts.factory.createNumericLiteral(node.text); } else if (ts.isBigIntLiteral(node)) { clone = ts.factory.createBigIntLiteral(node.text); } else if (ts.isNoSubstitutionTemplateLiteral(node)) { clone = ts.factory.createNoSubstitutionTemplateLiteral(node.text, node.rawText); } else if (ts.isRegularExpressionLiteral(node)) { clone = ts.factory.createRegularExpressionLiteral(node.text); } else { throw new Error(`Unsupported literal kind ${ts.SyntaxKind[node.kind]}`); } ts.setTextRange(clone, {pos: -1, end: -1}); return clone; } else { return ts.visitEachChild(node, visitNode, context); } }; return (node) => ts.visitNode(node, visitNode, ts.isTypeNode); }; return ts.transform(type, [typeReferenceTransformer]).transformed[0]; } private emitTypeReference(type: ts.TypeReferenceNode): ts.TypeNode { // Determine the reference that the type corresponds with. const translatedType = this.translator(type); if (translatedType === null) { throw new Error('Unable to emit an unresolved reference'); } // Emit the type arguments, if any. let typeArguments: ts.NodeArray<ts.TypeNode> | undefined = undefined; if (type.typeArguments !== undefined) { typeArguments = ts.factory.createNodeArray( type.typeArguments.map((typeArg) => this.emitType(typeArg)), ); } return ts.factory.updateTypeReferenceNode(type, translatedType.typeName, typeArguments); } }
github
angular/angular
packages/compiler-cli/src/ngtsc/translator/src/type_emitter.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstContent, TmplAstDeferredBlock, TmplAstDeferredBlockError, TmplAstDeferredBlockLoading, TmplAstDeferredBlockPlaceholder, TmplAstDeferredTrigger, TmplAstElement, TmplAstIfBlockBranch, TmplAstForLoopBlock, TmplAstForLoopBlockEmpty, TmplAstIcu, TmplAstIfBlock, TmplAstNode, TmplAstRecursiveVisitor, TmplAstReference, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstText, TmplAstTextAttribute, TmplAstVariable, TmplAstUnknownBlock, TmplAstLetDeclaration, TmplAstComponent, TmplAstDirective, } from '@angular/compiler'; /** * A base class that can be used to implement a Render3 Template AST visitor. * Schematics are also currently required to be CommonJS to support execution within the Angular * CLI. As a result, the ESM `@angular/compiler` package must be loaded via a native dynamic import. * Using a dynamic import makes classes extending from classes present in `@angular/compiler` * complicated due to the class not being present at module evaluation time. The classes using a * base class found within `@angular/compiler` must be wrapped in a factory to allow the class value * to be accessible at runtime after the dynamic import has completed. This class implements the * interface of the `TmplAstRecursiveVisitor` class (but does not extend) as the * `TmplAstRecursiveVisitor` as an interface provides the required set of visit methods. The base * interface `Visitor<T>` is not exported. */ export class TemplateAstVisitor implements TmplAstRecursiveVisitor { /** * Creates a new Render3 Template AST visitor using an instance of the `@angular/compiler` * package. Passing in the compiler is required due to the need to dynamically import the * ESM `@angular/compiler` into a CommonJS schematic. * * @param compilerModule The compiler instance that should be used within the visitor. */ constructor(protected readonly compilerModule: typeof import('@angular/compiler')) {} visitElement(element: TmplAstElement): void {} visitTemplate(template: TmplAstTemplate): void {} visitContent(content: TmplAstContent): void {} visitVariable(variable: TmplAstVariable): void {} visitReference(reference: TmplAstReference): void {} visitTextAttribute(attribute: TmplAstTextAttribute): void {} visitBoundAttribute(attribute: TmplAstBoundAttribute): void {} visitBoundEvent(attribute: TmplAstBoundEvent): void {} visitText(text: TmplAstText): void {} visitBoundText(text: TmplAstBoundText): void {} visitIcu(icu: TmplAstIcu): void {} visitDeferredBlock(deferred: TmplAstDeferredBlock): void {} visitDeferredBlockPlaceholder(block: TmplAstDeferredBlockPlaceholder): void {} visitDeferredBlockError(block: TmplAstDeferredBlockError): void {} visitDeferredBlockLoading(block: TmplAstDeferredBlockLoading): void {} visitDeferredTrigger(trigger: TmplAstDeferredTrigger): void {} visitUnknownBlock(block: TmplAstUnknownBlock): void {} visitSwitchBlock(block: TmplAstSwitchBlock): void {} visitSwitchBlockCase(block: TmplAstSwitchBlockCase): void {} visitForLoopBlock(block: TmplAstForLoopBlock): void {} visitForLoopBlockEmpty(block: TmplAstForLoopBlockEmpty): void {} visitIfBlock(block: TmplAstIfBlock): void {} visitIfBlockBranch(block: TmplAstIfBlockBranch): void {} visitLetDeclaration(decl: TmplAstLetDeclaration): void {} visitComponent(component: TmplAstComponent): void {} visitDirective(directive: TmplAstDirective): void {} /** * Visits all the provided nodes in order using this Visitor's visit methods. * This is a simplified variant of the `visitAll` function found inside of (but not * exported from) the `@angular/compiler` that does not support returning a value * since the migrations do not directly transform the nodes. * * @param nodes An iterable of nodes to visit using this visitor. */ visitAll(nodes: Iterable<TmplAstNode>): void { for (const node of nodes) { node.visit(this); } } }
github
angular/angular
packages/core/schematics/utils/template_ast_visitor.ts
// #docplaster // #docregion builder, builder-skeleton import {BuilderContext, BuilderOutput, createBuilder} from '@angular-devkit/architect'; import {JsonObject} from '@angular-devkit/core'; // #enddocregion builder-skeleton import {promises as fs} from 'fs'; // #docregion builder-skeleton interface Options extends JsonObject { source: string; destination: string; } export default createBuilder(copyFileBuilder); async function copyFileBuilder(options: Options, context: BuilderContext): Promise<BuilderOutput> { // #enddocregion builder, builder-skeleton // #docregion progress-reporting context.reportStatus(`Copying ${options.source} to ${options.destination}.`); // #docregion builder, handling-output try { // #docregion report-status await fs.copyFile(options.source, options.destination); // #enddocregion report-status } catch (err) { // #enddocregion builder context.logger.error('Failed to copy file.'); // #docregion builder return { success: false, error: (err as Error).message, }; } // #enddocregion builder, handling-output context.reportStatus('Done.'); // #docregion builder return {success: true}; // #enddocregion progress-reporting // #docregion builder-skeleton } // #enddocregion builder, builder-skeleton
github
angular/angular
adev/src/content/examples/cli-builder/src/my-builder.ts
/** * @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 { afterNextRender, Component, ElementRef, effect, input, output, signal, viewChild, ChangeDetectionStrategy, linkedSignal, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {ContainerType} from '../../../../../../../../../../protocol'; type EditorType = string | number | boolean; type EditorResult = EditorType | Array<EditorType>; enum PropertyEditorState { Read, Write, } const parseValue = (value: EditorResult): EditorResult => { try { return JSON.parse(value as any) as EditorResult; } catch { return value.toString(); } }; @Component({ templateUrl: './property-editor.component.html', selector: 'ng-property-editor', styleUrls: ['./property-editor.component.scss'], imports: [FormsModule], changeDetection: ChangeDetectionStrategy.OnPush, host: { '(click)': 'onClick()', }, }) export class PropertyEditorComponent { readonly key = input.required<string>(); readonly initialValue = input.required<EditorResult>(); readonly previewValue = input.required<string>(); readonly containerType = input<ContainerType>(); readonly updateValue = output<EditorResult>(); readonly inputEl = viewChild<ElementRef<HTMLInputElement>>('inputEl'); readState = PropertyEditorState.Read; writeState = PropertyEditorState.Write; readonly valueToSubmit = linkedSignal<EditorResult | undefined>(this.initialValue); readonly currentPropertyState = signal(this.readState); constructor() { effect(() => { const editor = this.inputEl()?.nativeElement; if (editor && this.currentPropertyState() === this.writeState) { editor.focus(); } }); } accept(): void { const parsed = parseValue(this.valueToSubmit()!); this.updateValue.emit(parsed); this.currentPropertyState.set(this.readState); } reject(): void { this.valueToSubmit.set(this.initialValue()); this.currentPropertyState.set(this.readState); } onClick(): void { if (this.currentPropertyState() === this.readState) { this.currentPropertyState.set(this.writeState); } } onFocus() { // A slight timeout is required for text selection. setTimeout(() => { this.inputEl()?.nativeElement.select(); }); } onBlur(): void { if (this.currentPropertyState() === this.writeState) { this.accept(); } } }
github
angular/angular
devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-body/property-view-tree/property-editor/property-editor.component.ts
/** * @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 {InputNode} from '../input_detection/input_node'; import {ProgramInfo, projectFile} from '../../../../utils/tsurge'; import {MigrationHost} from '../migration_host'; import { ClassFieldDescriptor, ClassFieldUniqueKey, } from '../passes/reference_resolution/known_fields'; /** * Interface that describes an input recognized in the * migration and project. */ export interface InputDescriptor extends ClassFieldDescriptor { node: InputNode; } /** * Gets the descriptor for the given input node. * * An input descriptor describes a recognized input in the * whole project (regardless of batching) and allows easy * access to the associated TypeScript declaration node, while * also providing a unique key for the input that can be used * for serializable communication between compilation units * (e.g. when running via batching; in e.g. go/tsunami). */ export function getInputDescriptor(host: MigrationHost, node: InputNode): InputDescriptor; export function getInputDescriptor(info: ProgramInfo, node: InputNode): InputDescriptor; export function getInputDescriptor( hostOrInfo: ProgramInfo | MigrationHost, node: InputNode, ): InputDescriptor { let className: string; if (ts.isAccessor(node)) { className = node.parent.name?.text || '<anonymous>'; } else { className = node.parent.name?.text ?? '<anonymous>'; } const info = hostOrInfo instanceof MigrationHost ? hostOrInfo.programInfo : hostOrInfo; const file = projectFile(node.getSourceFile(), info); // Inputs may be detected in `.d.ts` files. Ensure that if the file IDs // match regardless of extension. E.g. `/google3/blaze-out/bin/my_file.ts` should // have the same ID as `/google3/my_file.ts`. const id = file.id.replace(/\.d\.ts$/, '.ts'); return { key: `${id}@@${className}@@${node.name.text}` as unknown as ClassFieldUniqueKey, node, }; } /** Whether the given value is an input descriptor. */ export function isInputDescriptor(v: unknown): v is InputDescriptor { return ( (v as Partial<InputDescriptor>).key !== undefined && (v as Partial<InputDescriptor>).node !== undefined ); }
github
angular/angular
packages/core/schematics/migrations/signal-migration/src/utils/input_id.ts
/*! * @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, setFileSystem} from '@angular/compiler-cli'; import {SchematicsException, Tree} from '@angular-devkit/schematics'; import {DevkitMigrationFilesystem} from './devkit_filesystem'; import {groupReplacementsByFile} from '../group_replacements'; import {synchronouslyCombineUnitData} from '../combine_units'; import {TsurgeFunnelMigration, TsurgeMigration} from '../../migration'; import {Replacement, TextUpdate} from '../../replacement'; import {ProjectRootRelativePath} from '../../project_paths'; import {ProgramInfo} from '../../program_info'; import {getProjectTsConfigPaths} from '../../../../utils/project_tsconfig_paths'; import ts from 'typescript'; export enum MigrationStage { /** The migration is analyzing an entrypoint */ Analysis, /** The migration is about to migrate an entrypoint */ Migrate, } /** Information necessary to run a Tsurge migration in the devkit. */ export interface TsurgeDevkitMigration<Stats> { /** Instantiates the migration. */ getMigration: (fs: FileSystem) => TsurgeMigration<unknown, unknown, Stats>; /** File tree of the schematic. */ tree: Tree; /** Called before a program is created. Useful to notify the user before processing starts. */ beforeProgramCreation?: (tsconfigPath: string, stage: MigrationStage) => void; /** * Called after a program is created. Useful when the * structure needs to be modified (e.g. filtering files). */ afterProgramCreation?: (info: ProgramInfo, fileSystem: FileSystem, stage: MigrationStage) => void; /** Called before a unit is analyzed. Useful for logging. */ beforeUnitAnalysis?: (tsconfigPath: string) => void; /** Called after all units are analyzed. Useful for logging. */ afterAllAnalyzed?: () => void; /** Called if analysis has failed. Useful for logging. */ afterAnalysisFailure?: () => void; /** Called when the migration is done running and stats are available. Useful for logging. */ whenDone?: (stats: Stats) => void; } /** Runs a Tsurge within an Angular Devkit context. */ export async function runMigrationInDevkit<Stats>( config: TsurgeDevkitMigration<Stats>, ): Promise<void> { const {buildPaths, testPaths} = await getProjectTsConfigPaths(config.tree); if (!buildPaths.length && !testPaths.length) { throw new SchematicsException('Could not find any tsconfig file. Cannot run the migration.'); } const tsconfigPaths = [...buildPaths, ...testPaths]; const fs = new DevkitMigrationFilesystem(config.tree); setFileSystem(fs); const migration = config.getMigration(fs); const unitResults: unknown[] = []; const isFunnelMigration = migration instanceof TsurgeFunnelMigration; const compilationUnitAssignments = new Map<string, string>(); for (const tsconfigPath of tsconfigPaths) { config.beforeProgramCreation?.(tsconfigPath, MigrationStage.Analysis); const info = migration.createProgram(tsconfigPath, fs); modifyProgramInfoToEnsureNonOverlappingFiles(tsconfigPath, info, compilationUnitAssignments); config.afterProgramCreation?.(info, fs, MigrationStage.Analysis); config.beforeUnitAnalysis?.(tsconfigPath); unitResults.push(await migration.analyze(info)); } config.afterAllAnalyzed?.(); const combined = await synchronouslyCombineUnitData(migration, unitResults); if (combined === null) { config.afterAnalysisFailure?.(); return; } const globalMeta = await migration.globalMeta(combined); let replacements: Replacement[]; if (isFunnelMigration) { replacements = (await migration.migrate(globalMeta)).replacements; } else { replacements = []; for (const tsconfigPath of tsconfigPaths) { config.beforeProgramCreation?.(tsconfigPath, MigrationStage.Migrate); const info = migration.createProgram(tsconfigPath, fs); modifyProgramInfoToEnsureNonOverlappingFiles(tsconfigPath, info, compilationUnitAssignments); config.afterProgramCreation?.(info, fs, MigrationStage.Migrate); const result = await migration.migrate(globalMeta, info); replacements.push(...result.replacements); } } const replacementsPerFile: Map<ProjectRootRelativePath, TextUpdate[]> = new Map(); const changesPerFile = groupReplacementsByFile(replacements); for (const [file, changes] of changesPerFile) { if (!replacementsPerFile.has(file)) { replacementsPerFile.set(file, changes); } } for (const [file, changes] of replacementsPerFile) { const recorder = config.tree.beginUpdate(file); for (const c of changes) { recorder .remove(c.data.position, c.data.end - c.data.position) .insertRight(c.data.position, c.data.toInsert); } config.tree.commitUpdate(recorder); } config.whenDone?.(await migration.stats(globalMeta)); } /** * Special logic for devkit migrations. In the Angular CLI, or in 3P precisely, * projects can have tsconfigs with overlapping source files. i.e. two tsconfigs * like e.g. build or test include the same `ts.SourceFile` (`.ts`). Migrations * should never have 2+ compilation units with overlapping source files as this * can result in duplicated replacements or analysis— hence we only ever assign a * source file to a compilation unit *once*. * * Note that this is fine as we expect Tsurge migrations to work together as * isolated compilation units— so it shouldn't matter if worst case a `.ts` * file ends up in the e.g. test program. */ function modifyProgramInfoToEnsureNonOverlappingFiles( tsconfigPath: string, info: ProgramInfo, compilationUnitAssignments: Map<string, string>, ) { const sourceFiles: ts.SourceFile[] = []; for (const sf of info.sourceFiles) { const assignment = compilationUnitAssignments.get(sf.fileName); // File is already assigned to a different compilation unit. if (assignment !== undefined && assignment !== tsconfigPath) { continue; } compilationUnitAssignments.set(sf.fileName, tsconfigPath); sourceFiles.push(sf); } info.sourceFiles = sourceFiles; }
github
angular/angular
packages/core/schematics/utils/tsurge/helpers/angular_devkit/run_in_devkit.ts
/** * @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 {trustedHTMLFromString} from '../util/security/trusted_types'; /** * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML * that needs sanitizing. * Depending upon browser support we use one of two strategies for doing this. * Default: DOMParser strategy * Fallback: InertDocument strategy */ export function getInertBodyHelper(defaultDoc: Document): InertBodyHelper { const inertDocumentHelper = new InertDocumentHelper(defaultDoc); return isDOMParserAvailable() ? new DOMParserHelper(inertDocumentHelper) : inertDocumentHelper; } export interface InertBodyHelper { /** * Get an inert DOM element containing DOM created from the dirty HTML string provided. */ getInertBodyElement: (html: string) => HTMLElement | null; } /** * Uses DOMParser to create and fill an inert body element. * This is the default strategy used in browsers that support it. */ class DOMParserHelper implements InertBodyHelper { constructor(private inertDocumentHelper: InertBodyHelper) {} getInertBodyElement(html: string): HTMLElement | null { // We add these extra elements to ensure that the rest of the content is parsed as expected // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the // `<head>` tag. Note that the `<body>` tag is closed implicitly to prevent unclosed tags // in `html` from consuming the otherwise explicit `</body>` tag. html = '<body><remove></remove>' + html; try { const body = new window.DOMParser().parseFromString( trustedHTMLFromString(html) as string, 'text/html', ).body as HTMLBodyElement; if (body === null) { // In some browsers (e.g. Mozilla/5.0 iPad AppleWebKit Mobile) the `body` property only // becomes available in the following tick of the JS engine. In that case we fall back to // the `inertDocumentHelper` instead. return this.inertDocumentHelper.getInertBodyElement(html); } body.firstChild?.remove(); return body; } catch { return null; } } } /** * Use an HTML5 `template` element to create and fill an inert DOM element. * This is the fallback strategy if the browser does not support DOMParser. */ class InertDocumentHelper implements InertBodyHelper { private inertDocument: Document; constructor(private defaultDoc: Document) { this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert'); } getInertBodyElement(html: string): HTMLElement | null { const templateEl = this.inertDocument.createElement('template'); templateEl.innerHTML = trustedHTMLFromString(html) as string; return templateEl; } } /** * We need to determine whether the DOMParser exists in the global context and * supports parsing HTML; HTML parsing support is not as wide as other formats, see * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility. * * @suppress {uselessCode} */ export function isDOMParserAvailable() { try { return !!new window.DOMParser().parseFromString( trustedHTMLFromString('') as string, 'text/html', ); } catch { return false; } }
github
angular/angular
packages/core/src/sanitization/inert_body.ts
import { afterRenderEffect, Component, computed, ElementRef, signal, viewChild, WritableSignal, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {Grid, GridRow, GridCell, GridCellWidget} from '@angular/aria/grid'; type Priority = 'High' | 'Medium' | 'Low'; interface Task { taskId: number; summary: string; priority: Priority; assignee: string; } @Component({ selector: 'app-root', templateUrl: 'app.html', styleUrl: 'app.css', imports: [Grid, GridRow, GridCell, GridCellWidget, FormsModule], }) export class App { private readonly _headerCheckbox = viewChild<ElementRef<HTMLInputElement>>('headerCheckbox'); readonly allSelected = computed(() => this.data().every((t) => t.selected())); readonly partiallySelected = computed( () => !this.allSelected() && this.data().some((t) => t.selected()), ); readonly data = signal<(Task & {selected: WritableSignal<boolean>})[]>([ { selected: signal(false), taskId: 101, summary: 'Create Grid Aria Pattern', priority: 'High', assignee: 'Cyber Cat', }, { selected: signal(false), taskId: 102, summary: 'Build a Pill List example', priority: 'Medium', assignee: 'Caffeinated Owl', }, { selected: signal(false), taskId: 103, summary: 'Build a Calendar example', priority: 'Medium', assignee: 'Copybara', }, { selected: signal(false), taskId: 104, summary: 'Build a Data Table example', priority: 'Low', assignee: 'Rubber Duck', }, { selected: signal(false), taskId: 105, summary: 'Explore Grid possibilities', priority: 'High', assignee: '[Your Name Here]', }, ]); sortAscending: boolean = true; tempInput: string = ''; constructor() { afterRenderEffect(() => { this._headerCheckbox()!.nativeElement.indeterminate = this.partiallySelected(); }); } startEdit( event: KeyboardEvent | FocusEvent | undefined, task: Task, inputEl: HTMLInputElement, ): void { this.tempInput = task.assignee; inputEl.focus(); if (!(event instanceof KeyboardEvent)) return; // Start editing with an alphanumeric character. if (event.key.length === 1) { this.tempInput = event.key; } } onClickEdit(widget: GridCellWidget, task: Task, inputEl: HTMLInputElement) { if (widget.isActivated()) return; widget.activate(); setTimeout(() => this.startEdit(undefined, task, inputEl)); } completeEdit(event: KeyboardEvent | FocusEvent | undefined, task: Task): void { if (!(event instanceof KeyboardEvent)) { return; } if (event.key === 'Enter') { task.assignee = this.tempInput; } } updateSelection(event: Event): void { const checked = (event.target as HTMLInputElement).checked; this.data().forEach((t) => t.selected.set(checked)); } sortTaskById(): void { this.sortAscending = !this.sortAscending; if (this.sortAscending) { this.data.update((tasks) => tasks.sort((a, b) => a.taskId - b.taskId)); } else { this.data.update((tasks) => tasks.sort((a, b) => b.taskId - a.taskId)); } } }
github
angular/angular
adev/src/content/examples/aria/grid/src/table/basic/app/app.ts
/** * @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 {isArray} from '../../util/type_guards'; import {LogicFn, OneOrMany, PathKind, ValidationResult, type FieldContext} from '../types'; import {customError, ValidationError} from '../validation_errors'; /** Represents a value that has a length or size, such as an array or string, or set. */ export type ValueWithLengthOrSize = {length: number} | {size: number}; /** Common options available on the standard validators. */ export type BaseValidatorConfig<TValue, TPathKind extends PathKind = PathKind.Root> = | { /** A user-facing error message to include with the error. */ message?: string | LogicFn<TValue, string, TPathKind>; error?: never; } | { /** * Custom validation error(s) to report instead of the default, * or a function that receives the `FieldContext` and returns custom validation error(s). */ error?: OneOrMany<ValidationError> | LogicFn<TValue, OneOrMany<ValidationError>, TPathKind>; message?: never; }; /** Gets the length or size of the given value. */ export function getLengthOrSize(value: ValueWithLengthOrSize) { const v = value as {length: number; size: number}; return typeof v.length === 'number' ? v.length : v.size; } /** * Gets the value for an option that may be either a static value or a logic function that produces * the option value. * * @param opt The option from BaseValidatorConfig. * @param ctx The current FieldContext. * @returns The value for the option. */ export function getOption<TOption, TValue, TPathKind extends PathKind = PathKind.Root>( opt: Exclude<TOption, Function> | LogicFn<TValue, TOption, TPathKind> | undefined, ctx: FieldContext<TValue, TPathKind>, ): TOption | undefined { return opt instanceof Function ? opt(ctx) : opt; } /** * Checks if the given value is considered empty. Empty values are: null, undefined, '', false, NaN. */ export function isEmpty(value: unknown): boolean { if (typeof value === 'number') { return isNaN(value); } return value === '' || value === false || value == null; } /** * Whether the value is a plain object, as opposed to being an instance of Validation error. * @param error An error that could be a plain object, or an instance of a class implementing ValidationError. */ function isPlainError(error: ValidationError) { return ( typeof error === 'object' && (Object.getPrototypeOf(error) === Object.prototype || Object.getPrototypeOf(error) === null) ); } /** * If the value provided is a plain object, it wraps it into a custom error. * @param error An error that could be a plain object, or an instance of a class implementing ValidationError. */ function ensureCustomValidationError(error: ValidationError.WithField): ValidationError.WithField { if (isPlainError(error)) { return customError(error); } return error; } /** * Makes sure every provided error is wrapped as a custom error. * @param result Validation result with a field. */ export function ensureCustomValidationResult( result: ValidationResult<ValidationError.WithField>, ): ValidationResult<ValidationError.WithField> { if (result === null || result === undefined) { return result; } if (isArray(result)) { return result.map(ensureCustomValidationError); } return ensureCustomValidationError(result); }
github
angular/angular
packages/forms/signals/src/api/validators/util.ts
/** * @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 ir from '../../ir'; import {CompilationJobKind, type CompilationJob} from '../compilation'; function kindTest(kind: ir.OpKind): (op: ir.UpdateOp) => boolean { return (op: ir.UpdateOp) => op.kind === kind; } function kindWithInterpolationTest( kind: ir.OpKind.Attribute | ir.OpKind.Property | ir.OpKind.DomProperty, interpolation: boolean, ): (op: ir.UpdateOp) => boolean { return (op: ir.UpdateOp) => { return op.kind === kind && interpolation === op.expression instanceof ir.Interpolation; }; } function basicListenerKindTest(op: ir.CreateOp): boolean { return ( (op.kind === ir.OpKind.Listener && !(op.hostListener && op.isLegacyAnimationListener)) || op.kind === ir.OpKind.TwoWayListener || op.kind === ir.OpKind.Animation || op.kind === ir.OpKind.AnimationListener ); } function nonInterpolationPropertyKindTest(op: ir.UpdateOp): boolean { return ( (op.kind === ir.OpKind.Property || op.kind === ir.OpKind.TwoWayProperty) && !(op.expression instanceof ir.Interpolation) ); } interface Rule<T extends ir.CreateOp | ir.UpdateOp> { test: (op: T) => boolean; transform?: (ops: Array<T>) => Array<T>; } /** * Defines the groups based on `OpKind` that ops will be divided into, for the various create * op kinds. Ops will be collected into groups, then optionally transformed, before recombining * the groups in the order defined here. */ const CREATE_ORDERING: Array<Rule<ir.CreateOp>> = [ {test: (op) => op.kind === ir.OpKind.Listener && op.hostListener && op.isLegacyAnimationListener}, {test: basicListenerKindTest}, ]; /** * Defines the groups based on `OpKind` that ops will be divided into, for the various update * op kinds. */ const UPDATE_ORDERING: Array<Rule<ir.UpdateOp>> = [ {test: kindTest(ir.OpKind.StyleMap), transform: keepLast}, {test: kindTest(ir.OpKind.ClassMap), transform: keepLast}, {test: kindTest(ir.OpKind.StyleProp)}, {test: kindTest(ir.OpKind.ClassProp)}, {test: kindWithInterpolationTest(ir.OpKind.Attribute, true)}, {test: kindWithInterpolationTest(ir.OpKind.Property, true)}, {test: nonInterpolationPropertyKindTest}, {test: kindWithInterpolationTest(ir.OpKind.Attribute, false)}, ]; /** * Host bindings have their own update ordering. */ const UPDATE_HOST_ORDERING: Array<Rule<ir.UpdateOp>> = [ {test: kindWithInterpolationTest(ir.OpKind.DomProperty, true)}, {test: kindWithInterpolationTest(ir.OpKind.DomProperty, false)}, {test: kindTest(ir.OpKind.Attribute)}, {test: kindTest(ir.OpKind.StyleMap), transform: keepLast}, {test: kindTest(ir.OpKind.ClassMap), transform: keepLast}, {test: kindTest(ir.OpKind.StyleProp)}, {test: kindTest(ir.OpKind.ClassProp)}, ]; /** * The set of all op kinds we handle in the reordering phase. */ const handledOpKinds = new Set([ ir.OpKind.Listener, ir.OpKind.TwoWayListener, ir.OpKind.AnimationListener, ir.OpKind.StyleMap, ir.OpKind.ClassMap, ir.OpKind.StyleProp, ir.OpKind.ClassProp, ir.OpKind.Property, ir.OpKind.TwoWayProperty, ir.OpKind.DomProperty, ir.OpKind.Attribute, ir.OpKind.Animation, ]); /** * Many type of operations have ordering constraints that must be respected. For example, a * `ClassMap` instruction must be ordered after a `StyleMap` instruction, in order to have * predictable semantics that match TemplateDefinitionBuilder and don't break applications. */ export function orderOps(job: CompilationJob) { for (const unit of job.units) { // First, we pull out ops that need to be ordered. Then, when we encounter an op that shouldn't // be reordered, put the ones we've pulled so far back in the correct order. Finally, if we // still have ops pulled at the end, put them back in the correct order. // Create mode: orderWithin(unit.create, CREATE_ORDERING as Array<Rule<ir.CreateOp | ir.UpdateOp>>); // Update mode: const ordering = unit.job.kind === CompilationJobKind.Host ? UPDATE_HOST_ORDERING : UPDATE_ORDERING; orderWithin(unit.update, ordering as Array<Rule<ir.CreateOp | ir.UpdateOp>>); } } /** * Order all the ops within the specified group. */ function orderWithin( opList: ir.OpList<ir.CreateOp | ir.UpdateOp>, ordering: Array<Rule<ir.CreateOp | ir.UpdateOp>>, ) { let opsToOrder: Array<ir.CreateOp | ir.UpdateOp> = []; // Only reorder ops that target the same xref; do not mix ops that target different xrefs. let firstTargetInGroup: ir.XrefId | null = null; for (const op of opList) { const currentTarget = ir.hasDependsOnSlotContextTrait(op) ? op.target : null; if ( !handledOpKinds.has(op.kind) || (currentTarget !== firstTargetInGroup && firstTargetInGroup !== null && currentTarget !== null) ) { ir.OpList.insertBefore(reorder(opsToOrder, ordering), op); opsToOrder = []; firstTargetInGroup = null; } if (handledOpKinds.has(op.kind)) { opsToOrder.push(op); ir.OpList.remove(op); firstTargetInGroup = currentTarget ?? firstTargetInGroup; } } opList.push(reorder(opsToOrder, ordering)); } /** * Reorders the given list of ops according to the ordering defined by `ORDERING`. */ function reorder<T extends ir.CreateOp | ir.UpdateOp>( ops: Array<T>, ordering: Array<Rule<T>>, ): Array<T> { // Break the ops list into groups based on OpKind. const groups = Array.from(ordering, () => new Array<T>()); for (const op of ops) { const groupIndex = ordering.findIndex((o) => o.test(op)); groups[groupIndex].push(op); } // Reassemble the groups into a single list, in the correct order. return groups.flatMap((group, i) => { const transform = ordering[i].transform; return transform ? transform(group) : group; }); } /** * Keeps only the last op in a list of ops. */ function keepLast<T>(ops: Array<T>) { return ops.slice(ops.length - 1); }
github
angular/angular
packages/compiler/src/template/pipeline/src/phases/ordering.ts
/** * @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 {computed, Signal, signal, WritableSignal} from '@angular/core'; import {FormFieldManager} from '../../src/field/manager'; import {FieldNode, ParentFieldNode} from '../../src/field/node'; import { ChildFieldNodeOptions, FieldNodeOptions, FieldNodeStructure, RootFieldNodeOptions, } from '../../src/field/structure'; import {toSignal} from '@angular/core/rxjs-interop'; import {AbstractControl} from '@angular/forms'; import {map, takeUntil} from 'rxjs/operators'; import {extractControlPropToSignal} from './compat_field_node'; /** * Child Field Node options also exposing control property. */ export interface CompatChildFieldNodeOptions extends ChildFieldNodeOptions { control: Signal<AbstractControl>; } /** * Root Field Node options also exposing control property. */ export interface CompatRootFieldNodeOptions extends RootFieldNodeOptions { control: Signal<AbstractControl>; } /** * Field Node options also exposing control property. */ export type CompatFieldNodeOptions = CompatRootFieldNodeOptions | CompatChildFieldNodeOptions; /** * A helper function allowing to get parent if it exists. */ function getParentFromOptions(options: FieldNodeOptions) { if (options.kind === 'root') { return undefined; } return options.parent; } /** * A helper function allowing to get fieldManager regardless of the option type. */ function getFieldManagerFromOptions(options: FieldNodeOptions) { if (options.kind === 'root') { return options.fieldManager; } return options.parent.structure.root.structure.fieldManager; } /** * A helper function that takes CompatFieldNodeOptions, and produce a writable signal synced to the * value of contained AbstractControl. * * This uses toSignal, which requires an injector. * * @param options */ function getControlValueSignal<T>(options: CompatFieldNodeOptions) { const value = extractControlPropToSignal<T>(options, (control, destroy$) => { return toSignal( control.valueChanges.pipe( map(() => control.getRawValue()), takeUntil(destroy$), ), { initialValue: control.getRawValue(), }, ); }) as WritableSignal<T>; value.set = (value: T) => { options.control().setValue(value); }; value.update = (fn: (current: T) => T) => { value.set(fn(value())); }; return value; } /** * Compat version of FieldNodeStructure, * - It has no children * - It wraps FormControl and proxies its value. */ export class CompatStructure extends FieldNodeStructure { override value: WritableSignal<unknown>; override keyInParent: Signal<string> = (() => { throw new Error('Compat nodes do not use keyInParent.'); }) as unknown as Signal<string>; override root: FieldNode; override pathKeys: Signal<readonly string[]>; override readonly children = signal([]); override readonly childrenMap = signal(undefined); override readonly parent: ParentFieldNode | undefined; override readonly fieldManager: FormFieldManager; constructor(node: FieldNode, options: CompatFieldNodeOptions) { super(options.logic); this.value = getControlValueSignal(options); this.parent = getParentFromOptions(options); this.root = this.parent?.structure.root ?? node; this.fieldManager = getFieldManagerFromOptions(options); this.pathKeys = computed(() => this.parent ? [...this.parent.structure.pathKeys(), this.keyInParent()] : [], ); } override getChild(): FieldNode | undefined { return undefined; } }
github
angular/angular
packages/forms/signals/compat/src/compat_structure.ts
/** * @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 {computed, resource, ɵisPromise, Signal} from '@angular/core'; import type {StandardSchemaV1} from '@standard-schema/spec'; import {addDefaultField} from '../../field/validation'; import {validateAsync} from '../async'; import {metadata, validateTree} from '../logic'; import type {SchemaPath, SchemaPathTree, FieldTree} from '../types'; import {standardSchemaError, StandardSchemaValidationError} from '../validation_errors'; /** * Utility type that removes a string index key when its value is `unknown`, * i.e. `{[key: string]: unknown}`. It allows specific string keys to pass through, even if their * value is `unknown`, e.g. `{key: unknown}`. * * @experimental 21.0.0 */ export type RemoveStringIndexUnknownKey<K, V> = string extends K ? unknown extends V ? never : K : K; /** * Utility type that recursively ignores unknown string index properties on the given object. * We use this on the `TSchema` type in `validateStandardSchema` in order to accommodate Zod's * `looseObject` which includes `{[key: string]: unknown}` as part of the type. * * @experimental 21.0.0 */ export type IgnoreUnknownProperties<T> = T extends Record<PropertyKey, unknown> ? { [K in keyof T as RemoveStringIndexUnknownKey<K, T[K]>]: IgnoreUnknownProperties<T[K]>; } : T; /** * Validates a field using a `StandardSchemaV1` compatible validator (e.g. a Zod validator). * * See https://github.com/standard-schema/standard-schema for more about standard schema. * * @param path The `FieldPath` to the field to validate. * @param schema The standard schema compatible validator to use for validation. * @template TSchema The type validated by the schema. This may be either the full `TValue` type, * or a partial of it. * @template TValue The type of value stored in the field being validated. * * @category validation * @experimental 21.0.0 */ export function validateStandardSchema<TSchema, TModel extends IgnoreUnknownProperties<TSchema>>( path: SchemaPath<TModel> & SchemaPathTree<TModel>, schema: StandardSchemaV1<TSchema>, ) { // We create both a sync and async validator because the standard schema validator can return // either a sync result or a Promise, and we need to handle both cases. The sync validator // handles the sync result, and the async validator handles the Promise. // We memoize the result of the validation function here, so that it is only run once for both // validators, it can then be passed through both sync & async validation. type Result = StandardSchemaV1.Result<TSchema> | Promise<StandardSchemaV1.Result<TSchema>>; const VALIDATOR_MEMO = metadata<TModel, Signal<Result>>(path, ({value}) => { return computed(() => schema['~standard'].validate(value())); }); validateTree<TModel>(path, ({state, fieldTreeOf}) => { // Skip sync validation if the result is a Promise. const result = state.metadata(VALIDATOR_MEMO)!(); if (ɵisPromise(result)) { return []; } return ( result.issues?.map((issue) => standardIssueToFormTreeError(fieldTreeOf<TModel>(path), issue), ) ?? [] ); }); validateAsync< TModel, Promise<StandardSchemaV1.Result<TSchema>> | undefined, readonly StandardSchemaV1.Issue[] >(path, { params: ({state}) => { // Skip async validation if the result is *not* a Promise. const result = state.metadata(VALIDATOR_MEMO)!(); return ɵisPromise(result) ? result : undefined; }, factory: (params) => { return resource({ params, loader: async ({params}) => (await params)?.issues ?? [], }); }, onSuccess: (issues, {fieldTreeOf}) => { return issues.map((issue) => standardIssueToFormTreeError(fieldTreeOf<TModel>(path), issue)); }, onError: () => {}, }); } /** * Converts a `StandardSchemaV1.Issue` to a `FormTreeError`. * * @param field The root field to which the issue's path is relative. * @param issue The `StandardSchemaV1.Issue` to convert. * @returns A `ValidationError` representing the issue. */ function standardIssueToFormTreeError( field: FieldTree<unknown>, issue: StandardSchemaV1.Issue, ): StandardSchemaValidationError { let target = field as FieldTree<Record<PropertyKey, unknown>>; for (const pathPart of issue.path ?? []) { const pathKey = typeof pathPart === 'object' ? pathPart.key : pathPart; target = target[pathKey] as FieldTree<Record<PropertyKey, unknown>>; } return addDefaultField(standardSchemaError(issue, {message: issue.message}), target); }
github
angular/angular
packages/forms/signals/src/api/validators/standard_schema.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken} from '../di/injection_token'; /** Actions that are supported by the tracing framework. */ export enum TracingAction { CHANGE_DETECTION, AFTER_NEXT_RENDER, } /** A single tracing snapshot. */ export interface TracingSnapshot { run<T>(action: TracingAction, fn: () => T): T; /** Disposes of the tracing snapshot. Must be run exactly once per TracingSnapshot. */ dispose(): void; } /** * Injection token for a `TracingService`, optionally provided. */ export const TracingService = new InjectionToken<TracingService<TracingSnapshot>>( typeof ngDevMode !== undefined && ngDevMode ? 'TracingService' : '', ); /** * Tracing mechanism which can associate causes (snapshots) with runs of * subsequent operations. * * Not defined by Angular directly, but defined in contexts where tracing is * desired. */ export interface TracingService<T extends TracingSnapshot> { /** * Take a snapshot of the current context which will be stored by Angular and * used when additional work is performed that was scheduled in this context. * * @param linkedSnapshot Optional snapshot to use link to the current context. * The caller is no longer responsible for calling dispose on the linkedSnapshot. * * @return The tracing snapshot. The caller is responsible for diposing of the * snapshot. */ snapshot(linkedSnapshot: T | null): T; /** * Propagate the current tracing context to the provided function. * @param fn A function. * @return A function that will propagate the current tracing context. */ propagate?<T extends Function>(fn: T): T; /** * Wrap an event listener bound by the framework for tracing. * @param element Element on which the event is bound. * @param eventName Name of the event. * @param handler Event handler. * @return A new event handler to be bound instead of the original one. */ wrapEventListener?<T extends Function>(element: HTMLElement, eventName: string, handler: T): T; }
github
angular/angular
packages/core/src/application/tracing.ts
/** * @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 { LegacyAnimationTriggerNames, DeclarationListEmitMode, DeferBlockDepsEmitMode, R3ClassDebugInfo, R3ClassMetadata, R3ComponentMetadata, R3DeferPerBlockDependency, R3DeferPerComponentDependency, R3TemplateDependencyMetadata, SchemaMetadata, TmplAstDeferredBlock, } from '@angular/compiler'; import ts from 'typescript'; import {Reference} from '../../../imports'; import { ClassPropertyMapping, DirectiveResources, DirectiveTypeCheckMeta, HostDirectiveMeta, InputMapping, } from '../../../metadata'; import {ClassDeclaration, Import} from '../../../reflection'; import {SubsetOfKeys} from '../../../util/src/typescript'; import {ParsedTemplateWithSource, StyleUrlMeta} from './resources'; import {HostBindingNodes} from '../../directive'; /** * These fields of `R3ComponentMetadata` are updated in the `resolve` phase. * * The `keyof R3ComponentMetadata &` condition ensures that only fields of `R3ComponentMetadata` can * be included here. */ export type ComponentMetadataResolvedFields = SubsetOfKeys< R3ComponentMetadata<R3TemplateDependencyMetadata>, 'declarations' | 'declarationListEmitMode' | 'defer' | 'hasDirectiveDependencies' >; export interface ComponentAnalysisData { /** * `meta` includes those fields of `R3ComponentMetadata` which are calculated at `analyze` time * (not during resolve). */ meta: Omit<R3ComponentMetadata<R3TemplateDependencyMetadata>, ComponentMetadataResolvedFields>; baseClass: Reference<ClassDeclaration> | 'dynamic' | null; typeCheckMeta: DirectiveTypeCheckMeta; template: ParsedTemplateWithSource; classMetadata: R3ClassMetadata | null; classDebugInfo: R3ClassDebugInfo | null; inputs: ClassPropertyMapping<InputMapping>; inputFieldNamesFromMetadataArray: Set<string>; outputs: ClassPropertyMapping; /** * Providers extracted from the `providers` field of the component annotation which will require * an Angular factory definition at runtime. */ providersRequiringFactory: Set<Reference<ClassDeclaration>> | null; /** * Providers extracted from the `viewProviders` field of the component annotation which will * require an Angular factory definition at runtime. */ viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>> | null; resources: DirectiveResources; /** * `styleUrls` extracted from the decorator, if present. */ styleUrls: StyleUrlMeta[] | null; /** * Inline stylesheets extracted from the decorator, if present. */ inlineStyles: string[] | null; isPoisoned: boolean; legacyAnimationTriggerNames: LegacyAnimationTriggerNames | null; rawImports: ts.Expression | null; resolvedImports: Reference<ClassDeclaration>[] | null; rawDeferredImports: ts.Expression | null; resolvedDeferredImports: Reference<ClassDeclaration>[] | null; /** * Map of symbol name -> import path for types from `@Component.deferredImports` field. */ explicitlyDeferredTypes: R3DeferPerComponentDependency[] | null; schemas: SchemaMetadata[] | null; decorator: ts.Decorator | null; /** Additional directives applied to the component host. */ hostDirectives: HostDirectiveMeta[] | null; /** Raw expression that defined the host directives array. Used for diagnostics. */ rawHostDirectives: ts.Expression | null; /** Raw nodes representing the host bindings of the directive. */ hostBindingNodes: HostBindingNodes; /** Whether selectorless is enabled for the specific component. */ selectorlessEnabled: boolean; /** * Names of the symbols within the source file that are referenced directly inside the template. * Used to reduce the amount of lookups when determining which dependencies to expose. */ localReferencedSymbols: Set<string> | null; } export interface ComponentResolutionData { declarations: R3TemplateDependencyMetadata[]; declarationListEmitMode: DeclarationListEmitMode; /** * Map of all types that can be defer loaded (ts.ClassDeclaration) -> * corresponding import information (reflection `Import`) within * the current source file. The `Import` preserves the exported name * as seen by the importing module so aliasing is handled correctly. */ deferrableDeclToImportDecl: Map<ClassDeclaration, Import>; /** * Map of `@defer` blocks -> their corresponding dependencies. * Required to compile the defer resolver function in `PerBlock` mode. */ deferPerBlockDependencies: Map<TmplAstDeferredBlock, DeferredComponentDependency[]>; /** * Defines how dynamic imports for deferred dependencies should be grouped: * - either in a function on per-component basis (in case of local compilation) * - or in a function on per-block basis (in full compilation mode) */ deferBlockDepsEmitMode: DeferBlockDepsEmitMode; /** * List of deferrable dependencies in the entire component. Used to compile the * defer resolver function in `PerComponent` mode. */ deferPerComponentDependencies: R3DeferPerComponentDependency[]; /** Whether the component is standalone and has any directly-imported directive dependencies. */ hasDirectiveDependencies: boolean; } /** * Describes a dependency used within a `@defer` block. */ export type DeferredComponentDependency = R3DeferPerBlockDependency & { /** Reference to the declaration that defines the dependency. */ declaration: Reference<ClassDeclaration>; };
github
angular/angular
packages/compiler-cli/src/ngtsc/annotations/component/src/metadata.ts
/** * @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 { AST, CombinedRecursiveAstVisitor, ParseSourceSpan, TmplAstNode, TmplAstTemplate, } from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../diagnostics'; import {NgTemplateDiagnostic, TemplateTypeChecker} from '../../api'; /** * A Template Check receives information about the template it's checking and returns * information about the diagnostics to be generated. */ export interface TemplateCheck<Code extends ErrorCode> { /** Unique template check code, used for configuration and searching the error. */ code: Code; /** Runs check and returns information about the diagnostics to be generated. */ run( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, template: TmplAstNode[], ): NgTemplateDiagnostic<Code>[]; } /** * The TemplateContext provided to a Template Check to get diagnostic information. */ export interface TemplateContext<Code extends ErrorCode> { /** Interface that provides information about template nodes. */ templateTypeChecker: TemplateTypeChecker; /** * TypeScript interface that provides type information about symbols that appear * in the template (it is not to query types outside the Angular component). */ typeChecker: ts.TypeChecker; /** * Creates a template diagnostic with the given information for the template being processed and * using the diagnostic category configured for the extended template diagnostic. */ makeTemplateDiagnostic( sourceSpan: ParseSourceSpan, message: string, relatedInformation?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): NgTemplateDiagnostic<Code>; } /** * A factory which creates a template check for a particular code and name. This binds the two * together and associates them with a specific `TemplateCheck`. */ export interface TemplateCheckFactory< Code extends ErrorCode, Name extends ExtendedTemplateDiagnosticName, > { code: Code; name: Name; create(options: NgCompilerOptions): TemplateCheck<Code> | null; } /** * This abstract class provides a base implementation for the run method. */ export abstract class TemplateCheckWithVisitor<Code extends ErrorCode> implements TemplateCheck<Code> { abstract code: Code; /** * Base implementation for run function, visits all nodes in template and calls * `visitNode()` for each one. */ run( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, template: TmplAstNode[], ): NgTemplateDiagnostic<Code>[] { const visitor = new TemplateVisitor<Code>(ctx, component, this); return visitor.getDiagnostics(template); } /** * Visit a TmplAstNode or AST node of the template. Authors should override this * method to implement the check and return diagnostics. */ abstract visitNode( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<Code>[]; } /** * Visits all nodes in a template (TmplAstNode and AST) and calls `visitNode` for each one. */ class TemplateVisitor<Code extends ErrorCode> extends CombinedRecursiveAstVisitor { diagnostics: NgTemplateDiagnostic<Code>[] = []; constructor( private readonly ctx: TemplateContext<Code>, private readonly component: ts.ClassDeclaration, private readonly check: TemplateCheckWithVisitor<Code>, ) { super(); } override visit(node: AST | TmplAstNode) { this.diagnostics.push(...this.check.visitNode(this.ctx, this.component, node)); super.visit(node); } override visitTemplate(template: TmplAstTemplate) { const isInlineTemplate = template.tagName === 'ng-template'; this.visitAllTemplateNodes(template.attributes); if (isInlineTemplate) { // Only visit input/outputs if this isn't an inline template node generated for a structural // directive (like `<div *ngIf></div>`). These nodes would be visited when the underlying // element of an inline template node is processed. this.visitAllTemplateNodes(template.inputs); this.visitAllTemplateNodes(template.outputs); } this.visitAllTemplateNodes(template.directives); // `templateAttrs` aren't transferred over to the inner element so we always have to visit them. this.visitAllTemplateNodes(template.templateAttrs); this.visitAllTemplateNodes(template.variables); this.visitAllTemplateNodes(template.references); this.visitAllTemplateNodes(template.children); } getDiagnostics(template: TmplAstNode[]): NgTemplateDiagnostic<Code>[] { this.diagnostics = []; this.visitAllTemplateNodes(template); return this.diagnostics; } }
github
angular/angular
packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.ts
/** * @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 {Events, MessageBus, Parameters} from '../../../protocol'; type AnyEventCallback<Ev> = <E extends keyof Ev>(topic: E, args: Parameters<Ev[E]>) => void; type ListenerFn = (e: MessageEvent) => void; export class SamePageMessageBus extends MessageBus<Events> { private _listeners: ListenerFn[] = []; constructor( private _source: string, private _destination: string, ) { super(); } onAny(cb: AnyEventCallback<Events>): () => void { const listener: ListenerFn = (e) => { if (e.source !== window || !e.data || !e.data.topic || e.data.source !== this._destination) { return; } cb(e.data.topic, e.data.args); }; window.addEventListener('message', listener); this._listeners.push(listener); return () => { this._listeners.splice(this._listeners.indexOf(listener), 1); window.removeEventListener('message', listener); }; } override on<E extends keyof Events>(topic: E, cb: Events[E]): () => void { const listener: ListenerFn = (e) => { if (e.source !== window || !e.data || e.data.source !== this._destination || !e.data.topic) { return; } if (e.data.topic === topic) { (cb as any).apply(null, e.data.args); } }; window.addEventListener('message', listener); this._listeners.push(listener); return () => { this._listeners.splice(this._listeners.indexOf(listener), 1); window.removeEventListener('message', listener); }; } override once<E extends keyof Events>(topic: E, cb: Events[E]): void { const listener: ListenerFn = (e) => { if (e.source !== window || !e.data || e.data.source !== this._destination || !e.data.topic) { return; } if (e.data.topic === topic) { (cb as any).apply(null, e.data.args); } window.removeEventListener('message', listener); }; window.addEventListener('message', listener); } override emit<E extends keyof Events>(topic: E, args?: Parameters<Events[E]>): boolean { window.postMessage( { source: this._source, topic, args, __ignore_ng_zone__: true, __NG_DEVTOOLS_EVENT__: true, }, '*', ); return true; } override destroy(): void { this._listeners.forEach((l) => window.removeEventListener('message', l)); this._listeners = []; } }
github
angular/angular
devtools/projects/shell-browser/src/app/same-page-message-bus.ts
/** * @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;
github
angular/angular
packages/compiler-cli/src/ngtsc/incremental/src/state.ts
/** * @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 {SchemaMetadata} from '@angular/compiler'; import {Reexport, Reference} from '../../imports'; import {DirectiveMeta, NgModuleMeta, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import ts from 'typescript'; /** * Data for one of a given NgModule's scopes (either compilation scope or export scopes). */ export interface ScopeData { dependencies: Array<DirectiveMeta | PipeMeta>; /** * Whether some module or component in this scope contains errors and is thus semantically * unreliable. */ isPoisoned: boolean; } /** * An export scope of an NgModule, containing the directives/pipes it contributes to other NgModules * which import it. */ export interface ExportScope { /** * The scope exported by an NgModule, and available for import. */ exported: ScopeData; } /** * A resolved scope for a given component that cannot be set locally in the component definition, * and must be set via remote scoping call in the component's NgModule file. */ export interface RemoteScope { /** * Those directives used by the component that requires this scope to be set remotely. */ directives: Reference[]; /** * Those pipes used by the component that requires this scope to be set remotely. */ pipes: Reference[]; } export enum ComponentScopeKind { NgModule, Standalone, Selectorless, } export interface LocalModuleScope extends ExportScope { kind: ComponentScopeKind.NgModule; ngModule: ClassDeclaration; compilation: ScopeData; reexports: Reexport[] | null; schemas: SchemaMetadata[]; } export interface StandaloneScope { kind: ComponentScopeKind.Standalone; dependencies: Array<DirectiveMeta | PipeMeta | NgModuleMeta>; deferredDependencies: Array<DirectiveMeta | PipeMeta>; component: ClassDeclaration; schemas: SchemaMetadata[]; isPoisoned: boolean; } export interface SelectorlessScope { kind: ComponentScopeKind.Selectorless; dependencies: Map<string, DirectiveMeta | PipeMeta>; dependencyIdentifiers: ts.Identifier[]; component: ClassDeclaration; schemas: SchemaMetadata[]; isPoisoned: boolean; } export type ComponentScope = LocalModuleScope | StandaloneScope | SelectorlessScope; /** * Read information about the compilation scope of components. */ export interface ComponentScopeReader { getScopeForComponent(clazz: ClassDeclaration): ComponentScope | null; /** * Get the `RemoteScope` required for this component, if any. * * If the component requires remote scoping, then retrieve the directives/pipes registered for * that component. If remote scoping is not required (the common case), returns `null`. */ getRemoteScope(clazz: ClassDeclaration): RemoteScope | null; }
github
angular/angular
packages/compiler-cli/src/ngtsc/scope/src/api.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Type} from '../interface/type'; import {assertLessThan} from '../util/assert'; import {ɵɵdefineInjectable} from './interface/defs'; /** * Creates a token that can be used in a DI Provider. * * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a * runtime representation) such as when injecting an interface, callable type, array or * parameterized type. * * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by * the `Injector`. This provides an additional level of type safety. * * <div class="docs-alert docs-alert-helpful"> * * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the * provider and the injection call. Creating a new instance of `InjectionToken` in different places, * even with the same description, will be treated as different tokens by Angular's DI system, * leading to a `NullInjectorError`. * * </div> * * {@example injection-token/src/main.ts region='InjectionToken'} * * When creating an `InjectionToken`, you can optionally specify a factory function which returns * (possibly by creating) a default value of the parameterized type `T`. This sets up the * `InjectionToken` using this factory as a provider as if it was defined explicitly in the * application's root injector. If the factory function, which takes zero arguments, needs to inject * dependencies, it can do so using the [`inject`](api/core/inject) function. * As you can see in the Tree-shakable InjectionToken example below. * * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note: * this option is now deprecated). As mentioned above, `'root'` is the default value for * `providedIn`. * * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated. * * @usageNotes * ### Basic Examples * * ### Plain InjectionToken * * {@example core/di/ts/injector_spec.ts region='InjectionToken'} * * ### Tree-shakable InjectionToken * * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'} * * * @see [What is an InjectionToken?](guide/di/defining-dependency-providers#what-is-an-injectiontoken) * * @publicApi */ export class InjectionToken<T> { /** @internal */ readonly ngMetadataName = 'InjectionToken'; readonly ɵprov: unknown; /** * @param _desc Description for the token, * used only for debugging purposes, * it should but does not need to be unique * @param options Options for the token's usage, as described above */ constructor( protected _desc: string, options?: { providedIn?: Type<any> | 'root' | 'platform' | 'any' | null; factory: () => T; }, ) { this.ɵprov = undefined; if (typeof options == 'number') { (typeof ngDevMode === 'undefined' || ngDevMode) && assertLessThan(options, 0, 'Only negative numbers are supported here'); // This is a special hack to assign __NG_ELEMENT_ID__ to this instance. // See `InjectorMarkers` (this as any).__NG_ELEMENT_ID__ = options; } else if (options !== undefined) { this.ɵprov = ɵɵdefineInjectable({ token: this, providedIn: options.providedIn || 'root', factory: options.factory, }); } } /** * @internal */ get multi(): InjectionToken<Array<T>> { return this as InjectionToken<Array<T>>; } toString(): string { return `InjectionToken ${this._desc}`; } } export interface InjectableDefToken<T> extends InjectionToken<T> { ɵprov: unknown; }
github
angular/angular
packages/core/src/di/injection_token.ts
End of preview.