_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts_9377_13096
it(`does not list hidden schematics when 'includeHidden' is false`, () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const collection = engine.createCollection('hidden-schematics'); expect(collection.listSchematicNames(false /** includeHidden */)).toEqual([ 'schematic-1', 'schematic-2', ]); }); it(`does list hidden schematics when 'includeHidden' is true`, () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const collection = engine.createCollection('hidden-schematics'); expect(collection.listSchematicNames(true /** includeHidden */)).toEqual([ 'hidden-schematic', 'schematic-1', 'schematic-2', ]); }); it('does not list private schematics', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const collection = engine.createCollection('private-schematics'); expect(collection.listSchematicNames()).toEqual(['schematic-1', 'schematic-2']); }); it('cannot instanciate a private schematic', () => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const collection = engine.createCollection('private-schematics'); expect(() => engine.createSchematic('schematic-1', collection)).not.toThrow(); expect(() => engine.createSchematic('private-schematic', collection)).toThrow(); expect(() => collection.createSchematic('private-schematic')).toThrow(); }); it('allows extra properties on schema', (done) => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const host = new virtualFs.test.TestHost(); const collection = engine.createCollection('extra-properties'); const schematic = collection.createSchematic('schematic1'); lastValueFrom(schematic.call({}, observableOf(new HostTree(host)))) .then((tree) => { return lastValueFrom(new HostSink(host).commit(tree)); }) .then(() => { expect(host.files as string[]).toEqual(['/extra-schematic']); expect(host.sync.read(normalize('/extra-schematic')).toString()).toEqual( 'extra-collection', ); }) .then(done, done.fail); }); it('discovers a file-based task', () => { const engineHost = new FileSystemEngineHost(root); expect(engineHost.hasTaskExecutor('file-tasks/file-task.js')).toBeTruthy(); }); it('creates a file-based task', (done) => { const engineHost = new FileSystemEngineHost(root); engineHost.createTaskExecutor('file-tasks/file-task.js').subscribe((executor) => { expect(executor).toBeTruthy(); lastValueFrom(from(executor(undefined, undefined as any))).then( () => done.fail, () => done(), ); }, done.fail); }); it('allows executing a schematic with a file-based task', (done) => { const engineHost = new FileSystemEngineHost(root); const engine = new SchematicEngine(engineHost); const host = new virtualFs.test.TestHost(); const collection = engine.createCollection('file-tasks'); const schematic = collection.createSchematic('schematic-1'); lastValueFrom(schematic.call({}, observableOf(new HostTree(host)))) .then((tree) => { return lastValueFrom(new HostSink(host).commit(tree)); }) .then(() => engine.executePostTasks().toPromise()) .then(() => done.fail()) .catch((reason) => { if (reason.message === 'task exception') { done(); } else { done.fail(); } }); }); });
{ "end_byte": 13096, "start_byte": 9377, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host_spec.ts" }
angular-cli/packages/angular_devkit/schematics/tools/fallback-engine-host.ts_0_4264
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { Observable, mergeMap, of as observableOf, throwError } from 'rxjs'; import { Url } from 'url'; import { CollectionDescription, EngineHost, RuleFactory, SchematicDescription, Source, TaskExecutor, TypedSchematicContext, UnknownCollectionException, UnregisteredTaskException, } from '../src'; export type FallbackCollectionDescription = { host: EngineHost<{}, {}>; description: CollectionDescription<{}>; }; export type FallbackSchematicDescription = { description: SchematicDescription<{}, {}>; }; export type FallbackContext = TypedSchematicContext< FallbackCollectionDescription, FallbackSchematicDescription >; /** * An EngineHost that support multiple hosts in a fallback configuration. If a host does not * have a collection/schematics, use the following host before giving up. */ export class FallbackEngineHost implements EngineHost<{}, {}> { private _hosts: EngineHost<{}, {}>[] = []; addHost<CollectionT extends object, SchematicT extends object>( host: EngineHost<CollectionT, SchematicT>, ) { this._hosts.push(host); } createCollectionDescription( name: string, requester?: CollectionDescription<{}>, ): CollectionDescription<FallbackCollectionDescription> { for (const host of this._hosts) { try { const description = host.createCollectionDescription(name, requester); return { name, host, description }; } catch (_) {} } throw new UnknownCollectionException(name); } createSchematicDescription( name: string, collection: CollectionDescription<FallbackCollectionDescription>, ): SchematicDescription<FallbackCollectionDescription, FallbackSchematicDescription> | null { const description = collection.host.createSchematicDescription(name, collection.description); if (!description) { return null; } return { name, collection, description }; } getSchematicRuleFactory<OptionT extends object>( schematic: SchematicDescription<FallbackCollectionDescription, FallbackSchematicDescription>, collection: CollectionDescription<FallbackCollectionDescription>, ): RuleFactory<OptionT> { return collection.host.getSchematicRuleFactory(schematic.description, collection.description); } createSourceFromUrl(url: Url, context: FallbackContext): Source | null { return context.schematic.collection.description.host.createSourceFromUrl(url, context); } transformOptions<OptionT extends object, ResultT extends object>( schematic: SchematicDescription<FallbackCollectionDescription, FallbackSchematicDescription>, options: OptionT, context?: FallbackContext, ): Observable<ResultT> { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (observableOf(options) as any).pipe( ...this._hosts.map((host) => mergeMap((opt: {}) => host.transformOptions(schematic, opt, context)), ), ) as {} as Observable<ResultT>; } transformContext(context: FallbackContext): FallbackContext { let result = context; this._hosts.forEach((host) => { result = (host.transformContext(result) || result) as FallbackContext; }); return result; } listSchematicNames( collection: CollectionDescription<FallbackCollectionDescription>, includeHidden?: boolean, ): string[] { const allNames = new Set<string>(); this._hosts.forEach((host) => { try { host .listSchematicNames(collection.description, includeHidden) .forEach((name) => allNames.add(name)); } catch (_) {} }); return [...allNames]; } createTaskExecutor(name: string): Observable<TaskExecutor> { for (const host of this._hosts) { if (host.hasTaskExecutor(name)) { return host.createTaskExecutor(name); } } return throwError(new UnregisteredTaskException(name)); } hasTaskExecutor(name: string): boolean { for (const host of this._hosts) { if (host.hasTaskExecutor(name)) { return true; } } return false; } }
{ "end_byte": 4264, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/fallback-engine-host.ts" }
angular-cli/packages/angular_devkit/schematics/tools/node-module-engine-host.ts_0_4563
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException } from '@angular-devkit/core'; import { dirname, join, resolve } from 'path'; import { RuleFactory } from '../src'; import { FileSystemCollectionDesc, FileSystemSchematicDesc } from './description'; import { ExportStringRef } from './export-ref'; import { CollectionCannotBeResolvedException, CollectionMissingSchematicsMapException, FileSystemEngineHostBase, SchematicMissingFieldsException, } from './file-system-engine-host-base'; import { readJsonFile } from './file-system-utility'; export class NodePackageDoesNotSupportSchematics extends BaseException { constructor(name: string) { super(`Package ${JSON.stringify(name)} was found but does not support schematics.`); } } /** * A simple EngineHost that uses NodeModules to resolve collections. */ export class NodeModulesEngineHost extends FileSystemEngineHostBase { constructor(private readonly paths?: string[]) { super(); } private resolve(name: string, requester?: string, references = new Set<string>()): string { // Keep track of the package requesting the schematic, in order to avoid infinite recursion if (requester) { if (references.has(requester)) { references.add(requester); throw new Error( 'Circular schematic reference detected: ' + JSON.stringify(Array.from(references)), ); } else { references.add(requester); } } const relativeBase = requester ? dirname(requester) : process.cwd(); let collectionPath: string | undefined = undefined; if (name.startsWith('.')) { name = resolve(relativeBase, name); } const resolveOptions = { paths: requester ? [dirname(requester), ...(this.paths || [])] : this.paths, }; // Try to resolve as a package try { const packageJsonPath = require.resolve(join(name, 'package.json'), resolveOptions); const { schematics } = require(packageJsonPath); if (!schematics || typeof schematics !== 'string') { throw new NodePackageDoesNotSupportSchematics(name); } // If this is a relative path to the collection, then create the collection // path in relation to the package path if (schematics.startsWith('.')) { const packageDirectory = dirname(packageJsonPath); collectionPath = resolve(packageDirectory, schematics); } // Otherwise treat this as a package, and recurse to find the collection path else { collectionPath = this.resolve(schematics, packageJsonPath, references); } } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { throw e; } } // If not a package, try to resolve as a file if (!collectionPath) { try { collectionPath = require.resolve(name, resolveOptions); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { throw e; } } } // If not a package or a file, error if (!collectionPath) { throw new CollectionCannotBeResolvedException(name); } return collectionPath; } protected _resolveCollectionPath(name: string, requester?: string): string { const collectionPath = this.resolve(name, requester); readJsonFile(collectionPath); return collectionPath; } protected _resolveReferenceString( refString: string, parentPath: string, collectionDescription?: FileSystemCollectionDesc, ) { const ref = new ExportStringRef<RuleFactory<{}>>(refString, parentPath); if (!ref.ref) { return null; } return { ref: ref.ref, path: ref.module }; } protected _transformCollectionDescription( name: string, desc: Partial<FileSystemCollectionDesc>, ): FileSystemCollectionDesc { if (!desc.schematics || typeof desc.schematics != 'object') { throw new CollectionMissingSchematicsMapException(name); } return { ...desc, name, } as FileSystemCollectionDesc; } protected _transformSchematicDescription( name: string, _collection: FileSystemCollectionDesc, desc: Partial<FileSystemSchematicDesc>, ): FileSystemSchematicDesc { if (!desc.factoryFn || !desc.path || !desc.description) { throw new SchematicMissingFieldsException(name); } return desc as FileSystemSchematicDesc; } }
{ "end_byte": 4563, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/node-module-engine-host.ts" }
angular-cli/packages/angular_devkit/schematics/tools/schema-option-transform.ts_0_1697
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { deepCopy, schema } from '@angular-devkit/core'; import { Observable, from, of as observableOf } from 'rxjs'; import { first, map, mergeMap } from 'rxjs/operators'; import { FileSystemSchematicContext, FileSystemSchematicDescription } from './description'; export class InvalidInputOptions<T = {}> extends schema.SchemaValidationException { constructor(options: T, errors: schema.SchemaValidatorError[]) { super( errors, `Schematic input does not validate against the Schema: ${JSON.stringify(options)}\nErrors:\n`, ); } } // This can only be used in NodeJS. export function validateOptionsWithSchema(registry: schema.SchemaRegistry) { return <T extends {} | null>( schematic: FileSystemSchematicDescription, options: T, context?: FileSystemSchematicContext, ): Observable<T> => { // Prevent a schematic from changing the options object by making a copy of it. options = deepCopy(options); const withPrompts = context ? context.interactive : true; if (schematic.schema && schematic.schemaJson) { // Make a deep copy of options. return from(registry.compile(schematic.schemaJson)).pipe( mergeMap((validator) => validator(options, { withPrompts })), first(), map((result) => { if (!result.success) { throw new InvalidInputOptions(options, result.errors || []); } return options; }), ); } return observableOf(options); }; }
{ "end_byte": 1697, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/schema-option-transform.ts" }
angular-cli/packages/angular_devkit/schematics/tools/node-modules-test-engine-host.ts_0_1476
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { TaskConfiguration, TaskConfigurationGenerator, TaskId } from '../src/engine'; import { FileSystemSchematicContext } from './description'; import { NodeModulesEngineHost } from './node-module-engine-host'; /** * An EngineHost that uses a registry to super seed locations of collection.json files, but * revert back to using node modules resolution. This is done for testing. */ export class NodeModulesTestEngineHost extends NodeModulesEngineHost { #collections = new Map<string, string>(); #tasks: TaskConfiguration[] = []; get tasks() { return this.#tasks; } clearTasks() { this.#tasks = []; } registerCollection(name: string, path: string) { this.#collections.set(name, path); } override transformContext(context: FileSystemSchematicContext): FileSystemSchematicContext { const oldAddTask = context.addTask.bind(context); context.addTask = (task: TaskConfigurationGenerator, dependencies?: TaskId[]) => { this.#tasks.push(task.toConfiguration()); return oldAddTask(task, dependencies); }; return context; } protected override _resolveCollectionPath(name: string, requester?: string): string { return this.#collections.get(name) ?? super._resolveCollectionPath(name, requester); } }
{ "end_byte": 1476, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/node-modules-test-engine-host.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host.ts_0_3514
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { existsSync } from 'fs'; import { join } from 'path'; import { Observable, catchError, from, throwError } from 'rxjs'; import { RuleFactory, TaskExecutor, UnregisteredTaskException } from '../src'; import { FileSystemCollectionDesc, FileSystemSchematicDesc } from './description'; import { ExportStringRef } from './export-ref'; import { CollectionCannotBeResolvedException, CollectionMissingSchematicsMapException, FileSystemEngineHostBase, SchematicMissingFieldsException, } from './file-system-engine-host-base'; /** * A simple EngineHost that uses a root with one directory per collection inside of it. The * collection declaration follows the same rules as the regular FileSystemEngineHostBase. */ export class FileSystemEngineHost extends FileSystemEngineHostBase { constructor(protected _root: string) { super(); } protected _resolveCollectionPath(name: string): string { try { // Allow `${_root}/${name}.json` as a collection. const maybePath = require.resolve(join(this._root, name + '.json')); if (existsSync(maybePath)) { return maybePath; } } catch (error) {} try { // Allow `${_root}/${name}/collection.json. const maybePath = require.resolve(join(this._root, name, 'collection.json')); if (existsSync(maybePath)) { return maybePath; } } catch (error) {} throw new CollectionCannotBeResolvedException(name); } protected _resolveReferenceString(refString: string, parentPath: string) { // Use the same kind of export strings as NodeModule. const ref = new ExportStringRef<RuleFactory<{}>>(refString, parentPath); if (!ref.ref) { return null; } return { ref: ref.ref, path: ref.module }; } protected _transformCollectionDescription( name: string, desc: Partial<FileSystemCollectionDesc>, ): FileSystemCollectionDesc { if (!desc.schematics || typeof desc.schematics != 'object') { throw new CollectionMissingSchematicsMapException(name); } return { ...desc, name, } as FileSystemCollectionDesc; } protected _transformSchematicDescription( name: string, _collection: FileSystemCollectionDesc, desc: Partial<FileSystemSchematicDesc>, ): FileSystemSchematicDesc { if (!desc.factoryFn || !desc.path || !desc.description) { throw new SchematicMissingFieldsException(name); } return desc as FileSystemSchematicDesc; } override hasTaskExecutor(name: string): boolean { if (super.hasTaskExecutor(name)) { return true; } try { const maybePath = require.resolve(join(this._root, name)); if (existsSync(maybePath)) { return true; } } catch {} return false; } override createTaskExecutor(name: string): Observable<TaskExecutor> { if (!super.hasTaskExecutor(name)) { try { const path = require.resolve(join(this._root, name)); // Default handling code is for old tasks that incorrectly export `default` with non-ESM module return from(import(path).then((mod) => (mod.default?.default || mod.default)())).pipe( catchError(() => throwError(() => new UnregisteredTaskException(name))), ); } catch {} } return super.createTaskExecutor(name); } }
{ "end_byte": 3514, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host.ts" }
angular-cli/packages/angular_devkit/schematics/tools/BUILD.bazel_0_1781
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "tools", srcs = glob( include = ["**/*.ts"], exclude = [ "**/*_spec.ts", "test/**/*.ts", ], ), data = ["package.json"], module_name = "@angular-devkit/schematics/tools", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/tasks/node", "@npm//@types/node", "@npm//jsonc-parser", "@npm//rxjs", ], ) # @external_begin ts_library( name = "tools_test_lib", testonly = True, srcs = glob( include = [ "**/*_spec.ts", "test/**/*.ts", ], ), deps = [ ":tools", "//packages/angular_devkit/core", "//packages/angular_devkit/core/node", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/testing", "//tests/angular_devkit/schematics/tools/file-system-engine-host:file_system_engine_host_test_lib", "@npm//rxjs", ], ) jasmine_node_test( name = "tools_test", srcs = [":tools_test_lib"], deps = [ "@npm//jasmine", "@npm//source-map", ], ) # @external_end
{ "end_byte": 1781, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics/tools/index.ts_0_681
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './description'; export * from './export-ref'; export * from './file-system-engine-host-base'; export * from './workflow/node-workflow'; export { FileSystemEngineHost } from './file-system-engine-host'; export { NodeModulesEngineHost, NodePackageDoesNotSupportSchematics, } from './node-module-engine-host'; export { NodeModulesTestEngineHost } from './node-modules-test-engine-host'; export { validateOptionsWithSchema } from './schema-option-transform';
{ "end_byte": 681, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/index.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-utility.ts_0_1075
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonValue } from '@angular-devkit/core'; import { FileDoesNotExistException } from '@angular-devkit/schematics'; import { readFileSync } from 'fs'; import { ParseError, parse, printParseErrorCode } from 'jsonc-parser'; export function readJsonFile(path: string): JsonValue { let data; try { data = readFileSync(path, 'utf-8'); } catch (e) { if (e && typeof e === 'object' && 'code' in e && e.code === 'ENOENT') { throw new FileDoesNotExistException(path); } throw e; } const errors: ParseError[] = []; const content = parse(data, errors, { allowTrailingComma: true }) as JsonValue; if (errors.length) { const { error, offset } = errors[0]; throw new Error( `Failed to parse "${path}" as JSON AST Object. ${printParseErrorCode( error, )} at location: ${offset}.`, ); } return content; }
{ "end_byte": 1075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-utility.ts" }
angular-cli/packages/angular_devkit/schematics/tools/node-module-engine-host_spec.ts_0_2267
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { SchematicEngine } from '@angular-devkit/schematics'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { NodeModulesEngineHost } from './node-module-engine-host'; const TMP_DIR = process.env['TEST_TMPDIR'] || os.tmpdir(); describe('NodeModulesEngineHost', () => { let tmpDir!: string; let previousDir!: string; beforeEach(() => { tmpDir = fs.mkdtempSync( path.join(TMP_DIR, 'angular-devkit-schematics-tools-node-module-engine-host'), ); previousDir = process.cwd(); process.chdir(tmpDir); }); afterEach(() => process.chdir(previousDir)); /** Creates a fake NPM module that can be used to test the node module engine host. */ function createFakeNpmModule() { fs.mkdirSync(path.join(tmpDir, 'node_modules')); fs.mkdirSync(path.join(tmpDir, 'node_modules/@angular/')); fs.mkdirSync(path.join(tmpDir, 'node_modules/@angular/core')); fs.mkdirSync(path.join(tmpDir, 'node_modules/@angular/core/schematics')); fs.writeFileSync( path.join(tmpDir, 'node_modules/@angular/core/package.json'), JSON.stringify({ name: '@angular/core' }), ); fs.writeFileSync( path.join(tmpDir, 'node_modules/@angular/core/schematics/migrations.json'), JSON.stringify({ schematics: {} }), ); } it('should properly create collections with explicit collection path', () => { createFakeNpmModule(); const engineHost = new NodeModulesEngineHost(); const engine = new SchematicEngine(engineHost); // Under Bazel 'require.resolve' is patched to use Bazel resolutions from the MANIFEST FILES. // Adding a temporary file won't be enough to make Bazel aware of this file. // We provide the full path here just to verify that the underlying logic works let prefix = ''; if (process.env['BAZEL_TARGET']) { prefix = path.join(process.cwd(), 'node_modules'); } expect(() => { engine.createCollection(path.join(prefix, '@angular/core', './schematics/migrations.json')); }).not.toThrow(); }); });
{ "end_byte": 2267, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/node-module-engine-host_spec.ts" }
angular-cli/packages/angular_devkit/schematics/tools/description.ts_0_2225
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonObject } from '@angular-devkit/core'; import { Collection, CollectionDescription, Engine, EngineHost, RuleFactory, Schematic, SchematicDescription, TypedSchematicContext, } from '../src'; export interface FileSystemCollectionDescription { readonly name: string; readonly path: string; readonly version?: string; readonly schematics: { [name: string]: FileSystemSchematicDesc }; readonly encapsulation?: boolean; } export interface FileSystemSchematicJsonDescription { readonly aliases?: string[]; readonly factory: string; readonly name: string; readonly collection: FileSystemCollectionDescription; readonly description: string; readonly schema?: string; readonly extends?: string; } export interface FileSystemSchematicDescription extends FileSystemSchematicJsonDescription { // Processed by the EngineHost. readonly path: string; readonly schemaJson?: JsonObject; // Using `any` here is okay because the type isn't resolved when we read this value, // but rather when the Engine asks for it. readonly factoryFn: RuleFactory<{}>; } /** * Used to simplify typings. */ export declare type FileSystemEngine = Engine< FileSystemCollectionDescription, FileSystemSchematicDescription >; export declare type FileSystemEngineHost = EngineHost< FileSystemCollectionDescription, FileSystemSchematicDescription >; export declare type FileSystemCollection = Collection< FileSystemCollectionDescription, FileSystemSchematicDescription >; export declare type FileSystemSchematic = Schematic< FileSystemCollectionDescription, FileSystemSchematicDescription >; export declare type FileSystemCollectionDesc = CollectionDescription<FileSystemCollectionDescription>; export declare type FileSystemSchematicDesc = SchematicDescription< FileSystemCollectionDescription, FileSystemSchematicDescription >; export declare type FileSystemSchematicContext = TypedSchematicContext< FileSystemCollectionDescription, FileSystemSchematicDescription >;
{ "end_byte": 2225, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/description.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host-base.ts_0_3227
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException, JsonObject, normalize, virtualFs } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { existsSync, statSync } from 'fs'; import { dirname, isAbsolute, join, resolve } from 'path'; import { Observable, isObservable, lastValueFrom, from as observableFrom, throwError } from 'rxjs'; import { Url } from 'url'; import { HostCreateTree, RuleFactory, Source, TaskExecutor, TaskExecutorFactory, UnregisteredTaskException, } from '../src'; import { FileSystemCollectionDesc, FileSystemEngineHost, FileSystemSchematicContext, FileSystemSchematicDesc, FileSystemSchematicDescription, } from './description'; import { readJsonFile } from './file-system-utility'; export declare type OptionTransform<T extends object | null, R extends object> = ( schematic: FileSystemSchematicDescription, options: T, context?: FileSystemSchematicContext, ) => Observable<R> | PromiseLike<R> | R; export declare type ContextTransform = ( context: FileSystemSchematicContext, ) => FileSystemSchematicContext; export class CollectionCannotBeResolvedException extends BaseException { constructor(name: string) { super(`Collection ${JSON.stringify(name)} cannot be resolved.`); } } export class InvalidCollectionJsonException extends BaseException { constructor(_name: string, path: string, jsonException?: Error) { let msg = `Collection JSON at path ${JSON.stringify(path)} is invalid.`; if (jsonException) { msg = `${msg} ${jsonException.message}`; } super(msg); } } export class SchematicMissingFactoryException extends BaseException { constructor(name: string) { super(`Schematic ${JSON.stringify(name)} is missing a factory.`); } } export class FactoryCannotBeResolvedException extends BaseException { constructor(name: string) { super(`Schematic ${JSON.stringify(name)} cannot resolve the factory.`); } } export class CollectionMissingSchematicsMapException extends BaseException { constructor(name: string) { super(`Collection "${name}" does not have a schematics map.`); } } export class CollectionMissingFieldsException extends BaseException { constructor(name: string) { super(`Collection "${name}" is missing fields.`); } } export class SchematicMissingFieldsException extends BaseException { constructor(name: string) { super(`Schematic "${name}" is missing fields.`); } } export class SchematicMissingDescriptionException extends BaseException { constructor(name: string) { super(`Schematics "${name}" does not have a description.`); } } export class SchematicNameCollisionException extends BaseException { constructor(name: string) { super( `Schematics/alias ${JSON.stringify(name)} collides with another alias or schematic` + ' name.', ); } } /** * A EngineHost base class that uses the file system to resolve collections. This is the base of * all other EngineHost provided by the tooling part of the Schematics library. */
{ "end_byte": 3227, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host-base.ts" }
angular-cli/packages/angular_devkit/schematics/tools/file-system-engine-host-base.ts_3228_11560
export abstract class FileSystemEngineHostBase implements FileSystemEngineHost { protected abstract _resolveCollectionPath(name: string, requester?: string): string; protected abstract _resolveReferenceString( name: string, parentPath: string, collectionDescription: FileSystemCollectionDesc, ): { ref: RuleFactory<{}>; path: string } | null; protected abstract _transformCollectionDescription( name: string, desc: Partial<FileSystemCollectionDesc>, ): FileSystemCollectionDesc; protected abstract _transformSchematicDescription( name: string, collection: FileSystemCollectionDesc, desc: Partial<FileSystemSchematicDesc>, ): FileSystemSchematicDesc; // eslint-disable-next-line @typescript-eslint/no-explicit-any private _transforms: OptionTransform<any, any>[] = []; private _contextTransforms: ContextTransform[] = []; private _taskFactories = new Map<string, () => Observable<TaskExecutor>>(); listSchematicNames(collection: FileSystemCollectionDesc, includeHidden?: boolean) { const schematics: string[] = []; for (const key of Object.keys(collection.schematics)) { const schematic = collection.schematics[key]; if ((schematic.hidden && !includeHidden) || schematic.private) { continue; } // If extends is present without a factory it is an alias, do not return it // unless it is from another collection. if (!schematic.extends || schematic.factory) { schematics.push(key); } else if (schematic.extends && schematic.extends.indexOf(':') !== -1) { schematics.push(key); } } return schematics; } registerOptionsTransform<T extends object | null, R extends object>(t: OptionTransform<T, R>) { this._transforms.push(t); } registerContextTransform(t: ContextTransform) { this._contextTransforms.push(t); } /** * * @param name * @return {{path: string}} */ createCollectionDescription( name: string, requester?: FileSystemCollectionDesc, ): FileSystemCollectionDesc { const path = this._resolveCollectionPath(name, requester?.path); const jsonValue = readJsonFile(path); if (!jsonValue || typeof jsonValue != 'object' || Array.isArray(jsonValue)) { throw new InvalidCollectionJsonException(name, path); } // normalize extends property to an array if (typeof jsonValue['extends'] === 'string') { jsonValue['extends'] = [jsonValue['extends']]; } const description = this._transformCollectionDescription(name, { ...jsonValue, path, }); if (!description || !description.name) { throw new InvalidCollectionJsonException(name, path); } // Validate aliases. const allNames = Object.keys(description.schematics); for (const schematicName of Object.keys(description.schematics)) { const aliases = description.schematics[schematicName].aliases || []; for (const alias of aliases) { if (allNames.indexOf(alias) != -1) { throw new SchematicNameCollisionException(alias); } } allNames.push(...aliases); } return description; } createSchematicDescription( name: string, collection: FileSystemCollectionDesc, ): FileSystemSchematicDesc | null { // Resolve aliases first. for (const schematicName of Object.keys(collection.schematics)) { const schematicDescription = collection.schematics[schematicName]; if (schematicDescription.aliases && schematicDescription.aliases.indexOf(name) != -1) { name = schematicName; break; } } if (!(name in collection.schematics)) { return null; } const collectionPath = dirname(collection.path); const partialDesc: Partial<FileSystemSchematicDesc> | null = collection.schematics[name]; if (!partialDesc) { return null; } if (partialDesc.extends) { const index = partialDesc.extends.indexOf(':'); const collectionName = index !== -1 ? partialDesc.extends.slice(0, index) : null; const schematicName = index === -1 ? partialDesc.extends : partialDesc.extends.slice(index + 1); if (collectionName !== null) { const extendCollection = this.createCollectionDescription(collectionName); return this.createSchematicDescription(schematicName, extendCollection); } else { return this.createSchematicDescription(schematicName, collection); } } // Use any on this ref as we don't have the OptionT here, but we don't need it (we only need // the path). if (!partialDesc.factory) { throw new SchematicMissingFactoryException(name); } const resolvedRef = this._resolveReferenceString( partialDesc.factory, collectionPath, collection, ); if (!resolvedRef) { throw new FactoryCannotBeResolvedException(name); } let schema = partialDesc.schema; let schemaJson: JsonObject | undefined = undefined; if (schema) { if (!isAbsolute(schema)) { schema = join(collectionPath, schema); } schemaJson = readJsonFile(schema) as JsonObject; } // The schematic path is used to resolve URLs. // We should be able to just do `dirname(resolvedRef.path)` but for compatibility with // Bazel under Windows this directory needs to be resolved from the collection instead. // This is needed because on Bazel under Windows the data files (such as the collection or // url files) are not in the same place as the compiled JS. const maybePath = join(collectionPath, partialDesc.factory); const path = existsSync(maybePath) && statSync(maybePath).isDirectory() ? maybePath : dirname(maybePath); return this._transformSchematicDescription(name, collection, { ...partialDesc, schema, schemaJson, name, path, factoryFn: resolvedRef.ref, collection, }); } createSourceFromUrl(url: Url): Source | null { switch (url.protocol) { case null: case 'file:': return (context) => { // Check if context has necessary FileSystemSchematicContext path property const fileDescription = context.schematic.description as { path?: string }; if (fileDescription.path === undefined) { throw new Error( 'Unsupported schematic context. Expected a FileSystemSchematicContext.', ); } // Resolve all file:///a/b/c/d from the schematic's own path, and not the current // path. const root = normalize(resolve(fileDescription.path, url.path || '')); return new HostCreateTree(new virtualFs.ScopedHost(new NodeJsSyncHost(), root)); }; } return null; } transformOptions<OptionT extends object, ResultT extends object>( schematic: FileSystemSchematicDesc, options: OptionT, context?: FileSystemSchematicContext, ): Observable<ResultT> { const transform = async () => { let transformedOptions = options; for (const transformer of this._transforms) { const transformerResult = transformer(schematic, transformedOptions, context); transformedOptions = await (isObservable(transformerResult) ? lastValueFrom(transformerResult) : transformerResult); } return transformedOptions; }; return observableFrom(transform()) as unknown as Observable<ResultT>; } transformContext(context: FileSystemSchematicContext): FileSystemSchematicContext { return this._contextTransforms.reduce((acc, curr) => curr(acc), context); } getSchematicRuleFactory<OptionT extends object>( schematic: FileSystemSchematicDesc, _collection: FileSystemCollectionDesc, ): RuleFactory<OptionT> { return schematic.factoryFn; } registerTaskExecutor<T>(factory: TaskExecutorFactory<T>, options?: T): void { this._taskFactories.set(factory.name, () => observableFrom(factory.create(options))); } createTaskExecutor(name: string): Observable<TaskExecutor> { const factory = this._taskFactories.get(name); if (factory) { return factory(); } return throwError(new UnregisteredTaskException(name)); } hasTaskExecutor(name: string): boolean { return this._taskFactories.has(name); } }
{ "end_byte": 11560, "start_byte": 3228, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/file-system-engine-host-base.ts" }
angular-cli/packages/angular_devkit/schematics/tools/export-ref.ts_0_909
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { dirname, resolve } from 'path'; export class ExportStringRef<T> { private _ref?: T; private _module: string; private _path: string; constructor(ref: string, parentPath: string = process.cwd(), inner = true) { const [path, name] = ref.split('#', 2); this._module = path[0] == '.' ? resolve(parentPath, path) : path; this._module = require.resolve(this._module); this._path = dirname(this._module); if (inner) { this._ref = require(this._module)[name || 'default']; } else { this._ref = require(this._module); } } get ref() { return this._ref; } get module() { return this._module; } get path() { return this._path; } }
{ "end_byte": 909, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/export-ref.ts" }
angular-cli/packages/angular_devkit/schematics/tools/workflow/node-workflow_spec.ts_0_931
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable import/no-extraneous-dependencies */ import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { NodeWorkflow } from '@angular-devkit/schematics/tools'; import * as path from 'path'; describe('NodeWorkflow', () => { // TODO: this test seems to either not work on windows or on linux. xit('works', (done) => { const workflow = new NodeWorkflow(new NodeJsSyncHost(), { dryRun: true }); const collection = path.join(__dirname, '../../../../schematics/angular/package.json'); workflow .execute({ collection, schematic: 'ng-new', options: { name: 'workflow-test', version: '6.0.0-rc.4' }, }) .toPromise() .then(done, done.fail); }); });
{ "end_byte": 931, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/workflow/node-workflow_spec.ts" }
angular-cli/packages/angular_devkit/schematics/tools/workflow/node-workflow.ts_0_3050
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Path, getSystemPath, normalize, schema, virtualFs } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { workflow } from '@angular-devkit/schematics'; import { BuiltinTaskExecutor } from '../../tasks/node'; import { FileSystemEngine } from '../description'; import { OptionTransform } from '../file-system-engine-host-base'; import { NodeModulesEngineHost } from '../node-module-engine-host'; import { validateOptionsWithSchema } from '../schema-option-transform'; export interface NodeWorkflowOptions { force?: boolean; dryRun?: boolean; packageManager?: string; packageManagerForce?: boolean; packageRegistry?: string; registry?: schema.CoreSchemaRegistry; resolvePaths?: string[]; schemaValidation?: boolean; optionTransforms?: OptionTransform<Record<string, unknown> | null, object>[]; engineHostCreator?: (options: NodeWorkflowOptions) => NodeModulesEngineHost; } /** * A workflow specifically for Node tools. */ export class NodeWorkflow extends workflow.BaseWorkflow { constructor(root: string, options: NodeWorkflowOptions); constructor(host: virtualFs.Host, options: NodeWorkflowOptions & { root?: Path }); constructor(hostOrRoot: virtualFs.Host | string, options: NodeWorkflowOptions & { root?: Path }) { let host; let root; if (typeof hostOrRoot === 'string') { root = normalize(hostOrRoot); host = new virtualFs.ScopedHost(new NodeJsSyncHost(), root); } else { host = hostOrRoot; root = options.root; } const engineHost = options.engineHostCreator?.(options) || new NodeModulesEngineHost(options.resolvePaths); super({ host, engineHost, force: options.force, dryRun: options.dryRun, registry: options.registry, }); engineHost.registerTaskExecutor(BuiltinTaskExecutor.NodePackage, { allowPackageManagerOverride: true, packageManager: options.packageManager, force: options.packageManagerForce, rootDirectory: root && getSystemPath(root), registry: options.packageRegistry, }); engineHost.registerTaskExecutor(BuiltinTaskExecutor.RepositoryInitializer, { rootDirectory: root && getSystemPath(root), }); engineHost.registerTaskExecutor(BuiltinTaskExecutor.RunSchematic); if (options.optionTransforms) { for (const transform of options.optionTransforms) { engineHost.registerOptionsTransform(transform); } } if (options.schemaValidation) { engineHost.registerOptionsTransform(validateOptionsWithSchema(this.registry)); } this._context = []; } override get engine(): FileSystemEngine { return this._engine as FileSystemEngine; } override get engineHost(): NodeModulesEngineHost { return this._engineHost as NodeModulesEngineHost; } }
{ "end_byte": 3050, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/tools/workflow/node-workflow.ts" }
angular-cli/packages/angular_devkit/schematics/testing/schematic-test-runner.ts_0_3670
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { logging, schema } from '@angular-devkit/core'; import { Observable, lastValueFrom, of as observableOf } from 'rxjs'; import { Collection, DelegateTree, HostTree, Rule, Schematic, SchematicContext, SchematicEngine, TaskConfiguration, Tree, formats, } from '../src'; import { callRule } from '../src/rules/call'; import { BuiltinTaskExecutor } from '../tasks/node'; import { NodeModulesTestEngineHost, validateOptionsWithSchema } from '../tools'; export class UnitTestTree extends DelegateTree { get files() { const result: string[] = []; this.visit((path) => result.push(path)); return result; } readContent(path: string): string { const buffer = this.read(path); if (buffer === null) { return ''; } return buffer.toString(); } } export class SchematicTestRunner { private _engineHost = new NodeModulesTestEngineHost(); private _engine: SchematicEngine<{}, {}> = new SchematicEngine(this._engineHost); private _collection: Collection<{}, {}>; private _logger: logging.Logger; constructor( private _collectionName: string, collectionPath: string, ) { this._engineHost.registerCollection(_collectionName, collectionPath); this._logger = new logging.Logger('test'); const registry = new schema.CoreSchemaRegistry(formats.standardFormats); registry.addPostTransform(schema.transforms.addUndefinedDefaults); this._engineHost.registerOptionsTransform(validateOptionsWithSchema(registry)); this._engineHost.registerTaskExecutor(BuiltinTaskExecutor.NodePackage); this._engineHost.registerTaskExecutor(BuiltinTaskExecutor.RepositoryInitializer); this._engineHost.registerTaskExecutor(BuiltinTaskExecutor.RunSchematic); this._collection = this._engine.createCollection(this._collectionName); } get engine() { return this._engine; } get logger(): logging.Logger { return this._logger; } get tasks(): TaskConfiguration[] { return [...this._engineHost.tasks]; } registerCollection(collectionName: string, collectionPath: string) { this._engineHost.registerCollection(collectionName, collectionPath); } async runSchematic<SchematicSchemaT extends object>( schematicName: string, opts?: SchematicSchemaT, tree?: Tree, ): Promise<UnitTestTree> { const schematic = this._collection.createSchematic(schematicName, true); const host = observableOf(tree || new HostTree()); this._engineHost.clearTasks(); const newTree = await lastValueFrom(schematic.call(opts || {}, host, { logger: this._logger })); return new UnitTestTree(newTree); } async runExternalSchematic<SchematicSchemaT extends object>( collectionName: string, schematicName: string, opts?: SchematicSchemaT, tree?: Tree, ): Promise<UnitTestTree> { const externalCollection = this._engine.createCollection(collectionName); const schematic = externalCollection.createSchematic(schematicName, true); const host = observableOf(tree || new HostTree()); this._engineHost.clearTasks(); const newTree = await lastValueFrom(schematic.call(opts || {}, host, { logger: this._logger })); return new UnitTestTree(newTree); } callRule(rule: Rule, tree: Tree, parentContext?: Partial<SchematicContext>): Observable<Tree> { const context = this._engine.createContext({} as Schematic<{}, {}>, parentContext); return callRule(rule, observableOf(tree), context); } }
{ "end_byte": 3670, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/testing/schematic-test-runner.ts" }
angular-cli/packages/angular_devkit/schematics/testing/BUILD.bazel_0_837
load("//tools:defaults.bzl", "ts_library") # Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( include = ["**/*.ts"], ), data = ["package.json"], module_name = "@angular-devkit/schematics/testing", module_root = "index.d.ts", deps = [ "//packages/angular_devkit/core", "//packages/angular_devkit/schematics", "//packages/angular_devkit/schematics/tasks", "//packages/angular_devkit/schematics/tasks/node", "//packages/angular_devkit/schematics/tools", "@npm//@types/node", "@npm//rxjs", ], )
{ "end_byte": 837, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/testing/BUILD.bazel" }
angular-cli/packages/angular_devkit/schematics/testing/index.ts_0_245
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './schematic-test-runner';
{ "end_byte": 245, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/testing/index.ts" }
angular-cli/packages/angular_devkit/schematics/src/index.ts_0_2095
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { strings } from '@angular-devkit/core'; import * as formats from './formats/index'; import { FilePredicate, MergeStrategy, Tree as TreeInterface } from './tree/interface'; import { branch, empty, merge, partition } from './tree/static'; import * as workflow from './workflow/index'; export { SchematicsException } from './exception/exception'; export * from './tree/action'; export * from './engine/index'; export * from './exception/exception'; export * from './tree/interface'; export * from './rules/base'; export * from './rules/call'; export * from './rules/move'; export * from './rules/random'; export * from './rules/schematic'; export * from './rules/template'; export * from './rules/url'; export * from './tree/delegate'; export * from './tree/empty'; export * from './tree/host-tree'; export type { UpdateRecorder } from './tree/interface'; export * from './engine/schematic'; export * from './sink/dryrun'; export * from './sink/host'; export * from './sink/sink'; export { formats, strings, workflow }; export interface TreeConstructor { empty(): TreeInterface; branch(tree: TreeInterface): TreeInterface; merge(tree: TreeInterface, other: TreeInterface, strategy?: MergeStrategy): TreeInterface; partition(tree: TreeInterface, predicate: FilePredicate<boolean>): [TreeInterface, TreeInterface]; optimize(tree: TreeInterface): TreeInterface; } export type Tree = TreeInterface; export const Tree: TreeConstructor = { empty() { return empty(); }, branch(tree: TreeInterface) { return branch(tree); }, merge( tree: TreeInterface, other: TreeInterface, strategy: MergeStrategy = MergeStrategy.Default, ) { return merge(tree, other, strategy); }, partition(tree: TreeInterface, predicate: FilePredicate<boolean>) { return partition(tree, predicate); }, optimize(tree: TreeInterface) { return tree; }, };
{ "end_byte": 2095, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/index.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/host-tree_spec.ts_0_4894
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize, virtualFs } from '@angular-devkit/core'; import { FilterHostTree, HostTree } from './host-tree'; import { MergeStrategy } from './interface'; describe('HostTree', () => { describe('readText', () => { it('returns text when reading a file that exists', () => { const tree = new HostTree(); tree.create('/textfile1', 'abc'); tree.create('/textfile2', '123'); expect(tree.readText('/textfile1')).toEqual('abc'); expect(tree.readText('/textfile2')).toEqual('123'); }); it('throws an error when a file does not exist', () => { const tree = new HostTree(); const path = '/textfile1'; expect(() => tree.readText(path)).toThrowError(`Path "${path}" does not exist.`); }); it('throws an error when invalid UTF-8 characters are present', () => { const tree = new HostTree(); const path = '/textfile1'; tree.create(path, Buffer.from([0xff, 0xff, 0xff, 0xff])); expect(() => tree.readText(path)).toThrowError(`Failed to decode "${path}" as UTF-8 text.`); }); }); describe('readJson', () => { it('returns a JSON value when reading a file that exists', () => { const tree = new HostTree(); tree.create('/textfile1', '{ "a": true, "b": "xyz" }'); tree.create('/textfile2', '123'); tree.create('/textfile3', 'null'); expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' }); expect(tree.readJson('/textfile2')).toEqual(123); expect(tree.readJson('/textfile3')).toBeNull(); }); it('returns a JSON value when reading a file with comments', () => { const tree = new HostTree(); tree.create( '/textfile1', '{ "a": true, /* inner object\nmultiline comment\n */ "b": "xyz" }', ); tree.create('/textfile2', '123 // number value'); tree.create('/textfile3', 'null // null value'); expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' }); expect(tree.readJson('/textfile2')).toEqual(123); expect(tree.readJson('/textfile3')).toBeNull(); }); it('returns a JSON value when reading a file with trailing commas', () => { const tree = new HostTree(); tree.create('/textfile1', '{ "a": true, "b": "xyz", }'); tree.create('/textfile2', '[5, 4, 3, 2, 1, ]'); expect(tree.readJson('/textfile1')).toEqual({ a: true, b: 'xyz' }); expect(tree.readJson('/textfile2')).toEqual([5, 4, 3, 2, 1]); }); it('throws an error when a file does not exist', () => { const tree = new HostTree(); const path = '/textfile1'; expect(() => tree.readJson(path)).toThrowError(`Path "${path}" does not exist.`); }); it('throws an error if the JSON is malformed', () => { const tree = new HostTree(); const path = '/textfile1'; tree.create(path, '{ "a": true;;;;; "b": "xyz" }'); expect(() => tree.readJson(path)).toThrowError( `Failed to parse "${path}" as JSON. InvalidSymbol at offset: 7.`, ); }); it('throws an error when invalid UTF-8 characters are present', () => { const tree = new HostTree(); const path = '/textfile1'; tree.create(path, Buffer.from([0xff, 0xff, 0xff, 0xff])); expect(() => tree.readJson(path)).toThrowError(`Failed to decode "${path}" as UTF-8 text.`); }); }); describe('merge', () => { it('should create files from each tree', () => { const tree = new HostTree(); tree.create('/file1', 'a'); const tree2 = new HostTree(); tree2.create('/file2', 'a'); tree.merge(tree2); expect(tree.actions[0].kind).toEqual('c'); expect(tree.actions[1].kind).toEqual('c'); }); it('should overwrite if the file exists in one tree', () => { const tree = new HostTree(); tree.create('/file1', 'a'); const tree2 = new HostTree(); tree2.create('/file1', 'b'); tree.merge(tree2, MergeStrategy.Overwrite); expect(tree.actions[0].kind).toEqual('c'); }); it('should throw if the file exists in one tree with the correct MergeStrategy', () => { const tree = new HostTree(); tree.create('/file1', 'a'); const tree2 = new HostTree(); tree2.create('/file1', 'b'); expect(() => tree.merge(tree2)).toThrow(); }); it('should not have a second action if the file content is the same', () => { const tree = new HostTree(); tree.create('/file1', 'a'); const tree2 = new HostTree(); tree2.create('/file1', 'a'); tree.merge(tree2, MergeStrategy.Overwrite); expect(tree.actions[0].kind).toEqual('c'); expect(tree.actions.length).toEqual(1); }); }); });
{ "end_byte": 4894, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/host-tree_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/host-tree_spec.ts_4896_8146
describe('FilterHostTree', () => { it('works', () => { const tree = new HostTree(); tree.create('/file1', ''); tree.create('/file2', ''); tree.create('/file3', ''); const filtered = new FilterHostTree(tree, (p) => p != '/file2'); const filteredFiles: string[] = []; filtered.visit((path) => filteredFiles.push(path)); filteredFiles.sort(); expect(filteredFiles).toEqual(['/file1', '/file3'].map(normalize)); expect(filtered.actions.length).toEqual(2); }); it('works with two filters', () => { const tree = new HostTree(); tree.create('/file1', ''); tree.create('/file2', ''); tree.create('/file3', ''); const filtered = new FilterHostTree(tree, (p) => p != '/file2'); const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3'); const filteredFiles: string[] = []; filtered2.visit((path) => filteredFiles.push(path)); filteredFiles.sort(); expect(filteredFiles).toEqual(['/file1'].map(normalize)); expect(filtered2.actions.map((a) => a.kind)).toEqual(['c']); }); it('works with underlying files', () => { const fs = new virtualFs.test.TestHost({ '/file1': '', }); const tree = new HostTree(fs); tree.create('/file2', ''); tree.create('/file3', ''); const filtered = new FilterHostTree(tree, (p) => p != '/file2'); const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3'); const filteredFiles: string[] = []; filtered2.visit((path) => filteredFiles.push(path)); filteredFiles.sort(); expect(filteredFiles).toEqual(['/file1'].map(normalize)); expect(filtered2.actions.map((a) => a.kind)).toEqual([]); }); it('works with created paths and files', () => { const tree = new HostTree(); tree.create('/dir1/file1', ''); tree.create('/dir2/file2', ''); tree.create('/file3', ''); const filtered = new FilterHostTree(tree, (p) => p != '/dir2/file2'); const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3'); const filteredFiles: string[] = []; filtered2.visit((path) => filteredFiles.push(path)); filteredFiles.sort(); expect(filteredFiles).toEqual(['/dir1/file1'].map(normalize)); expect(filtered2.actions.map((a) => a.kind)).toEqual(['c']); }); it('works with underlying paths and files', () => { const fs = new virtualFs.test.TestHost({ '/dir1/file1': '', '/dir2/file2': '', }); const tree = new HostTree(fs); tree.create('/file3', ''); const filtered = new FilterHostTree(tree, (p) => p != '/dir2/file2'); const filtered2 = new FilterHostTree(filtered, (p) => p != '/file3'); const filteredFiles: string[] = []; filtered2.visit((path) => filteredFiles.push(path)); filteredFiles.sort(); expect(filteredFiles).toEqual(['/dir1/file1'].map(normalize)); expect(filtered2.actions.map((a) => a.kind)).toEqual([]); }); it('subdirs only contains directories', () => { const fs = new virtualFs.test.TestHost({ '/dir1/file1': '', '/dir1/dir2/file2': '', '/dir1/dir3/file3': '', }); const tree = new HostTree(fs); const subDirs = tree.getDir('/dir1').subdirs; expect(subDirs as string[]).toEqual(['dir2', 'dir3']); }); });
{ "end_byte": 8146, "start_byte": 4896, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/host-tree_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/static.ts_0_998
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { SchematicsException } from '../exception/exception'; import { FilterHostTree, HostTree } from './host-tree'; import { FilePredicate, MergeStrategy, Tree } from './interface'; export function empty() { return new HostTree(); } export function branch(tree: Tree) { return tree.branch(); } export function merge(tree: Tree, other: Tree, strategy: MergeStrategy = MergeStrategy.Default) { tree.merge(other, strategy); return tree; } export function partition(tree: Tree, predicate: FilePredicate<boolean>): [Tree, Tree] { if (tree instanceof HostTree) { return [ new FilterHostTree(tree, predicate), new FilterHostTree(tree, (path, entry) => !predicate(path, entry)), ]; } else { throw new SchematicsException('Tree type is not supported.'); } }
{ "end_byte": 998, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/static.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/entry.ts_0_835
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Path } from '@angular-devkit/core'; import { FileEntry } from './interface'; export class SimpleFileEntry implements FileEntry { constructor( private _path: Path, private _content: Buffer, ) {} get path() { return this._path; } get content() { return this._content; } } export class LazyFileEntry implements FileEntry { private _content: Buffer | null = null; constructor( private _path: Path, private _load: (path?: Path) => Buffer, ) {} get path() { return this._path; } get content() { return this._content || (this._content = this._load(this._path)); } }
{ "end_byte": 835, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/entry.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/recorder_spec.ts_0_3011
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize } from '@angular-devkit/core'; import { SimpleFileEntry } from './entry'; import { UpdateRecorderBase } from './recorder'; describe('UpdateRecorderBase', () => { it('works for simple files', () => { const buffer = Buffer.from('Hello World'); const entry = new SimpleFileEntry(normalize('/some/path'), buffer); const recorder = UpdateRecorderBase.createFromFileEntry(entry); recorder.insertLeft(5, ' beautiful'); const result = recorder.apply(buffer); expect(result.toString()).toBe('Hello beautiful World'); }); it('works for simple files (2)', () => { const buffer = Buffer.from('Hello World'); const entry = new SimpleFileEntry(normalize('/some/path'), buffer); const recorder = UpdateRecorderBase.createFromFileEntry(entry); recorder.insertRight(5, ' beautiful'); const result = recorder.apply(buffer); expect(result.toString()).toBe('Hello beautiful World'); }); it('works with multiple adjacent inserts', () => { const buffer = Buffer.from('Hello beautiful World'); const entry = new SimpleFileEntry(normalize('/some/path'), buffer); const recorder = UpdateRecorderBase.createFromFileEntry(entry); recorder.remove(6, 9); recorder.insertRight(6, 'amazing'); recorder.insertRight(15, ' and fantastic'); const result = recorder.apply(buffer); expect(result.toString()).toBe('Hello amazing and fantastic World'); }); it('can create the proper recorder', () => { const e = new SimpleFileEntry(normalize('/some/path'), Buffer.from('hello')); expect(UpdateRecorderBase.createFromFileEntry(e) instanceof UpdateRecorderBase).toBe(true); }); it('can create the proper recorder (bom)', () => { const eBom = new SimpleFileEntry(normalize('/some/path'), Buffer.from('\uFEFFhello')); expect(UpdateRecorderBase.createFromFileEntry(eBom) instanceof UpdateRecorderBase).toBe(true); }); it('supports empty files', () => { const e = new SimpleFileEntry(normalize('/some/path'), Buffer.from('')); expect(UpdateRecorderBase.createFromFileEntry(e) instanceof UpdateRecorderBase).toBe(true); }); it('supports empty files (bom)', () => { const eBom = new SimpleFileEntry(normalize('/some/path'), Buffer.from('\uFEFF')); expect(UpdateRecorderBase.createFromFileEntry(eBom) instanceof UpdateRecorderBase).toBe(true); }); }); describe('UpdateRecorderBom', () => { it('works for simple files', () => { const buffer = Buffer.from('\uFEFFHello World'); const entry = new SimpleFileEntry(normalize('/some/path'), buffer); const recorder = UpdateRecorderBase.createFromFileEntry(entry); recorder.insertLeft(5, ' beautiful'); const result = recorder.apply(buffer); expect(result.toString()).toBe('\uFEFFHello beautiful World'); }); });
{ "end_byte": 3011, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/recorder_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/action.ts_0_4841
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException, Path } from '@angular-devkit/core'; export class UnknownActionException extends BaseException { constructor(action: Action) { super(`Unknown action: "${action.kind}".`); } } export type Action = CreateFileAction | OverwriteFileAction | RenameFileAction | DeleteFileAction; export interface ActionBase { readonly id: number; readonly parent: number; readonly path: Path; } let _id = 1; export class ActionList implements Iterable<Action> { private _actions: Action[] = []; protected _action(action: Partial<Action>) { this._actions.push({ ...(action as Action), id: _id++, parent: this._actions[this._actions.length - 1]?.id ?? 0, }); } create(path: Path, content: Buffer) { this._action({ kind: 'c', path, content }); } overwrite(path: Path, content: Buffer) { this._action({ kind: 'o', path, content }); } rename(path: Path, to: Path) { this._action({ kind: 'r', path, to }); } delete(path: Path) { this._action({ kind: 'd', path }); } optimize() { const toCreate = new Map<Path, Buffer>(); const toRename = new Map<Path, Path>(); const toOverwrite = new Map<Path, Buffer>(); const toDelete = new Set<Path>(); for (const action of this._actions) { switch (action.kind) { case 'c': toCreate.set(action.path, action.content); break; case 'o': if (toCreate.has(action.path)) { toCreate.set(action.path, action.content); } else { toOverwrite.set(action.path, action.content); } break; case 'd': toDelete.add(action.path); break; case 'r': { const maybeCreate = toCreate.get(action.path); const maybeOverwrite = toOverwrite.get(action.path); if (maybeCreate) { toCreate.delete(action.path); toCreate.set(action.to, maybeCreate); } if (maybeOverwrite) { toOverwrite.delete(action.path); toOverwrite.set(action.to, maybeOverwrite); } let maybeRename: Path | undefined = undefined; for (const [from, to] of toRename.entries()) { if (to == action.path) { maybeRename = from; break; } } if (maybeRename) { toRename.set(maybeRename, action.to); } if (!maybeCreate && !maybeOverwrite && !maybeRename) { toRename.set(action.path, action.to); } break; } } } this._actions = []; toDelete.forEach((x) => { this.delete(x); }); toRename.forEach((to, from) => { this.rename(from, to); }); toCreate.forEach((content, path) => { this.create(path, content); }); toOverwrite.forEach((content, path) => { this.overwrite(path, content); }); } push(action: Action) { this._actions.push(action); } get(i: number) { return this._actions[i]; } has(action: Action) { for (let i = 0; i < this._actions.length; i++) { const a = this._actions[i]; if (a.id == action.id) { return true; } if (a.id > action.id) { return false; } } return false; } find(predicate: (value: Action) => boolean): Action | null { return this._actions.find(predicate) || null; } forEach(fn: (value: Action, index: number, array: Action[]) => void, thisArg?: {}) { this._actions.forEach(fn, thisArg); } get length() { return this._actions.length; } [Symbol.iterator](): IterableIterator<Action> { return this._actions[Symbol.iterator](); } } export function isContentAction(action: Action): action is CreateFileAction | OverwriteFileAction { return action.kind == 'c' || action.kind == 'o'; } // Create a file. If the file already exists then this is an error. export interface CreateFileAction extends ActionBase { readonly kind: 'c'; readonly content: Buffer; } // Overwrite a file. If the file does not already exist, this is an error. export interface OverwriteFileAction extends ActionBase { readonly kind: 'o'; readonly content: Buffer; } // Move a file from one path to another. If the source files does not exist, this is an error. // If the target path already exists, this is an error. export interface RenameFileAction extends ActionBase { readonly kind: 'r'; readonly to: Path; } // Delete a file. If the file does not exist, this is an error. export interface DeleteFileAction extends ActionBase { readonly kind: 'd'; }
{ "end_byte": 4841, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/action.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/host-tree.ts_0_2433
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonValue, Path, PathFragment, PathIsDirectoryException, PathIsFileException, dirname, join, normalize, virtualFs, } from '@angular-devkit/core'; import { ParseError, parse as jsoncParse, printParseErrorCode } from 'jsonc-parser'; import { ContentHasMutatedException, FileAlreadyExistException, FileDoesNotExistException, InvalidUpdateRecordException, MergeConflictException, SchematicsException, } from '../exception/exception'; import { Action, CreateFileAction, DeleteFileAction, OverwriteFileAction, RenameFileAction, } from './action'; import { DelegateTree } from './delegate'; import { LazyFileEntry } from './entry'; import { DirEntry, FileEntry, FilePredicate, FileVisitor, FileVisitorCancelToken, MergeStrategy, Tree, TreeSymbol, UpdateRecorder, } from './interface'; import { UpdateRecorderBase } from './recorder'; import { ScopedTree } from './scoped'; let _uniqueId = 0; export class HostDirEntry implements DirEntry { constructor( readonly parent: DirEntry | null, readonly path: Path, protected _host: virtualFs.SyncDelegateHost, protected _tree: Tree, ) {} get subdirs(): PathFragment[] { return this._host .list(this.path) .filter((fragment) => this._host.isDirectory(join(this.path, fragment))); } get subfiles(): PathFragment[] { return this._host .list(this.path) .filter((fragment) => this._host.isFile(join(this.path, fragment))); } dir(name: PathFragment): DirEntry { return this._tree.getDir(join(this.path, name)); } file(name: PathFragment): FileEntry | null { return this._tree.get(join(this.path, name)); } visit(visitor: FileVisitor): void { try { this.getSubfilesRecursively().forEach((file) => visitor(file.path, file)); } catch (e) { if (e !== FileVisitorCancelToken) { throw e; } } } private getSubfilesRecursively() { function _recurse(entry: DirEntry): FileEntry[] { return entry.subdirs.reduce( (files, subdir) => [...files, ..._recurse(entry.dir(subdir))], entry.subfiles.map((subfile) => entry.file(subfile) as FileEntry), ); } return _recurse(this); } }
{ "end_byte": 2433, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/host-tree.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/host-tree.ts_2435_10960
export class HostTree implements Tree { private readonly _id = --_uniqueId; private _record: virtualFs.CordHost; private _recordSync: virtualFs.SyncDelegateHost; private _ancestry = new Set<number>(); private _dirCache = new Map<Path, HostDirEntry>(); [TreeSymbol]() { return this; } static isHostTree(tree: Tree): tree is HostTree { if (tree instanceof HostTree) { return true; } if (typeof tree === 'object' && typeof (tree as HostTree)._ancestry === 'object') { return true; } return false; } constructor(protected _backend: virtualFs.ReadonlyHost<{}> = new virtualFs.Empty()) { this._record = new virtualFs.CordHost(new virtualFs.SafeReadonlyHost(_backend)); this._recordSync = new virtualFs.SyncDelegateHost(this._record); } protected _normalizePath(path: string): Path { return normalize('/' + path); } protected _willCreate(path: Path) { return this._record.willCreate(path); } protected _willOverwrite(path: Path) { return this._record.willOverwrite(path); } protected _willDelete(path: Path) { return this._record.willDelete(path); } protected _willRename(path: Path) { return this._record.willRename(path); } branch(): Tree { const branchedTree = new HostTree(this._backend); branchedTree._record = this._record.clone(); branchedTree._recordSync = new virtualFs.SyncDelegateHost(branchedTree._record); branchedTree._ancestry = new Set(this._ancestry).add(this._id); return branchedTree; } private isAncestorOf(tree: Tree): boolean { if (tree instanceof HostTree) { return tree._ancestry.has(this._id); } if (tree instanceof DelegateTree) { return this.isAncestorOf((tree as unknown as { _other: Tree })._other); } if (tree instanceof ScopedTree) { return this.isAncestorOf((tree as unknown as { _base: Tree })._base); } return false; } merge(other: Tree, strategy: MergeStrategy = MergeStrategy.Default): void { if (other === this) { // Merging with yourself? Tsk tsk. Nothing to do at least. return; } if (this.isAncestorOf(other)) { // Workaround for merging a branch back into one of its ancestors // More complete branch point tracking is required to avoid strategy |= MergeStrategy.Overwrite; } const creationConflictAllowed = (strategy & MergeStrategy.AllowCreationConflict) == MergeStrategy.AllowCreationConflict; const overwriteConflictAllowed = (strategy & MergeStrategy.AllowOverwriteConflict) == MergeStrategy.AllowOverwriteConflict; const deleteConflictAllowed = (strategy & MergeStrategy.AllowDeleteConflict) == MergeStrategy.AllowDeleteConflict; other.actions.forEach((action) => { switch (action.kind) { case 'c': { const { path, content } = action; if (this._willCreate(path) || this._willOverwrite(path) || this.exists(path)) { const existingContent = this.read(path); if (existingContent && content.equals(existingContent)) { // Identical outcome; no action required return; } if (!creationConflictAllowed) { throw new MergeConflictException(path); } this._record.overwrite(path, content as {} as virtualFs.FileBuffer).subscribe(); } else { this._record.create(path, content as {} as virtualFs.FileBuffer).subscribe(); } return; } case 'o': { const { path, content } = action; if (this._willDelete(path) && !overwriteConflictAllowed) { throw new MergeConflictException(path); } // Ignore if content is the same (considered the same change). if (this._willOverwrite(path)) { const existingContent = this.read(path); if (existingContent && content.equals(existingContent)) { // Identical outcome; no action required return; } if (!overwriteConflictAllowed) { throw new MergeConflictException(path); } } // We use write here as merge validation has already been done, and we want to let // the CordHost do its job. this._record.write(path, content as {} as virtualFs.FileBuffer).subscribe(); return; } case 'r': { const { path, to } = action; if (this._willDelete(path)) { throw new MergeConflictException(path); } if (this._willRename(path)) { if (this._record.willRenameTo(path, to)) { // Identical outcome; no action required return; } // No override possible for renaming. throw new MergeConflictException(path); } this.rename(path, to); return; } case 'd': { const { path } = action; if (this._willDelete(path)) { // TODO: This should technically check the content (e.g., hash on delete) // Identical outcome; no action required return; } if (!this.exists(path) && !deleteConflictAllowed) { throw new MergeConflictException(path); } this._recordSync.delete(path); return; } } }); } get root(): DirEntry { return this.getDir('/'); } // Readonly. read(path: string): Buffer | null { const entry = this.get(path); return entry ? entry.content : null; } readText(path: string): string { const data = this.read(path); if (data === null) { throw new FileDoesNotExistException(path); } const decoder = new TextDecoder('utf-8', { fatal: true }); try { // With the `fatal` option enabled, invalid data will throw a TypeError return decoder.decode(data); } catch (e) { // The second part should not be needed. But Jest does not support instanceof correctly. // See: https://github.com/jestjs/jest/issues/2549 if ( e instanceof TypeError || (e as NodeJS.ErrnoException).code === 'ERR_ENCODING_INVALID_ENCODED_DATA' ) { throw new Error(`Failed to decode "${path}" as UTF-8 text.`); } throw e; } } readJson(path: string): JsonValue { const content = this.readText(path); const errors: ParseError[] = []; const result = jsoncParse(content, errors, { allowTrailingComma: true }); // If there is a parse error throw with the error information if (errors[0]) { const { error, offset } = errors[0]; throw new Error( `Failed to parse "${path}" as JSON. ${printParseErrorCode(error)} at offset: ${offset}.`, ); } return result; } exists(path: string): boolean { return this._recordSync.isFile(this._normalizePath(path)); } get(path: string): FileEntry | null { const p = this._normalizePath(path); if (this._recordSync.isDirectory(p)) { throw new PathIsDirectoryException(p); } if (!this._recordSync.exists(p)) { return null; } return new LazyFileEntry(p, () => Buffer.from(this._recordSync.read(p))); } getDir(path: string): DirEntry { const p = this._normalizePath(path); if (this._recordSync.isFile(p)) { throw new PathIsFileException(p); } let maybeCache = this._dirCache.get(p); if (!maybeCache) { let parent: Path | null = dirname(p); if (p === parent) { parent = null; } maybeCache = new HostDirEntry(parent && this.getDir(parent), p, this._recordSync, this); this._dirCache.set(p, maybeCache); } return maybeCache; } visit(visitor: FileVisitor): void { this.root.visit((path, entry) => { visitor(path, entry); }); } // Change content of host files. overwrite(path: string, content: Buffer | string): void { const p = this._normalizePath(path); if (!this._recordSync.exists(p)) { throw new FileDoesNotExistException(p); } const c = typeof content == 'string' ? Buffer.from(content) : content; this._record.overwrite(p, c as {} as virtualFs.FileBuffer).subscribe(); } beginUpdate(path: string): UpdateRecorder { const entry = this.get(path); if (!entry) { throw new FileDoesNotExistException(path); } return UpdateRecorderBase.createFromFileEntry(entry); }
{ "end_byte": 10960, "start_byte": 2435, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/host-tree.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/host-tree.ts_10963_15563
commitUpdate(record: UpdateRecorder): void { if (record instanceof UpdateRecorderBase) { const path = record.path; const entry = this.get(path); if (!entry) { throw new ContentHasMutatedException(path); } else { const newContent = record.apply(entry.content); if (!newContent.equals(entry.content)) { this.overwrite(path, newContent); } } } else { throw new InvalidUpdateRecordException(); } } // Structural methods. create(path: string, content: Buffer | string): void { const p = this._normalizePath(path); if (this._recordSync.exists(p)) { throw new FileAlreadyExistException(p); } const c = typeof content == 'string' ? Buffer.from(content) : content; this._record.create(p, c as {} as virtualFs.FileBuffer).subscribe(); } delete(path: string): void { this._recordSync.delete(this._normalizePath(path)); } rename(from: string, to: string): void { this._recordSync.rename(this._normalizePath(from), this._normalizePath(to)); } apply(action: Action, strategy?: MergeStrategy): void { throw new SchematicsException('Apply not implemented on host trees.'); } private *generateActions(): Iterable<Action> { for (const record of this._record.records()) { switch (record.kind) { case 'create': yield { id: this._id, parent: 0, kind: 'c', path: record.path, content: Buffer.from(record.content), } as CreateFileAction; break; case 'overwrite': yield { id: this._id, parent: 0, kind: 'o', path: record.path, content: Buffer.from(record.content), } as OverwriteFileAction; break; case 'rename': yield { id: this._id, parent: 0, kind: 'r', path: record.from, to: record.to, } as RenameFileAction; break; case 'delete': yield { id: this._id, parent: 0, kind: 'd', path: record.path, } as DeleteFileAction; break; } } } get actions(): Action[] { // Create a list of all records until we hit our original backend. This is to support branches // that diverge from each others. return Array.from(this.generateActions()); } } export class HostCreateTree extends HostTree { constructor(host: virtualFs.ReadonlyHost) { super(); const tempHost = new HostTree(host); tempHost.visit((path) => { const content = tempHost.read(path); if (content) { this.create(path, content); } }); } } export class FilterHostTree extends HostTree { constructor(tree: HostTree, filter: FilePredicate<boolean> = () => true) { const newBackend = new virtualFs.SimpleMemoryHost(); // cast to allow access const originalBackend = (tree as FilterHostTree)._backend; // Walk the original backend and add files that match the filter to the new backend const pendingPaths: Path[] = ['/' as Path]; while (pendingPaths.length > 0) { const currentPath = pendingPaths.pop(); if (currentPath === undefined) { break; } let isDirectory = false; originalBackend.isDirectory(currentPath).subscribe((val) => (isDirectory = val)); if (isDirectory) { originalBackend .list(currentPath) .subscribe((val) => pendingPaths.push(...val.map((p) => join(currentPath, p)))); continue; } let isFile = false; originalBackend.isFile(currentPath).subscribe((val) => (isFile = val)); if (!isFile || !filter(currentPath)) { continue; } let content = null; originalBackend.read(currentPath).subscribe((val) => (content = val)); if (content !== null) { newBackend.write(currentPath, content).subscribe(); } } super(newBackend); // Add actions that match the filter to new tree for (const action of tree.actions) { if (!filter(action.path)) { continue; } switch (action.kind) { case 'c': this.create(action.path, action.content); break; case 'd': this.delete(action.path); break; case 'o': this.overwrite(action.path, action.content); break; case 'r': this.rename(action.path, action.to); break; } } } }
{ "end_byte": 15563, "start_byte": 10963, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/host-tree.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/delegate.ts_0_2128
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { JsonValue } from '@angular-devkit/core'; import { Action } from './action'; import { DirEntry, FileEntry, FileVisitor, MergeStrategy, Tree, TreeSymbol, UpdateRecorder, } from './interface'; export class DelegateTree implements Tree { constructor(protected _other: Tree) {} branch(): Tree { return this._other.branch(); } merge(other: Tree, strategy?: MergeStrategy): void { this._other.merge(other, strategy); } get root(): DirEntry { return this._other.root; } // Readonly. read(path: string): Buffer | null { return this._other.read(path); } readText(path: string): string { return this._other.readText(path); } readJson(path: string): JsonValue { return this._other.readJson(path); } exists(path: string): boolean { return this._other.exists(path); } get(path: string): FileEntry | null { return this._other.get(path); } getDir(path: string): DirEntry { return this._other.getDir(path); } visit(visitor: FileVisitor): void { return this._other.visit(visitor); } // Change content of host files. overwrite(path: string, content: Buffer | string): void { return this._other.overwrite(path, content); } beginUpdate(path: string): UpdateRecorder { return this._other.beginUpdate(path); } commitUpdate(record: UpdateRecorder): void { return this._other.commitUpdate(record); } // Structural methods. create(path: string, content: Buffer | string): void { return this._other.create(path, content); } delete(path: string): void { return this._other.delete(path); } rename(from: string, to: string): void { return this._other.rename(from, to); } apply(action: Action, strategy?: MergeStrategy): void { return this._other.apply(action, strategy); } get actions(): Action[] { return this._other.actions; } [TreeSymbol]() { return this; } }
{ "end_byte": 2128, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/delegate.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/scoped.ts_0_5619
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonValue, NormalizedRoot, Path, PathFragment, join, normalize, relative, } from '@angular-devkit/core'; import { Action } from './action'; import { DelegateTree } from './delegate'; import { DirEntry, FileEntry, FileVisitor, MergeStrategy, Tree, TreeSymbol, UpdateRecorder, } from './interface'; class ScopedFileEntry implements FileEntry { constructor( private _base: FileEntry, private scope: Path, ) {} get path(): Path { return join(NormalizedRoot, relative(this.scope, this._base.path)); } get content(): Buffer { return this._base.content; } } class ScopedDirEntry implements DirEntry { constructor( private _base: DirEntry, readonly scope: Path, ) {} get parent(): DirEntry | null { if (!this._base.parent || this._base.path == this.scope) { return null; } return new ScopedDirEntry(this._base.parent, this.scope); } get path(): Path { return join(NormalizedRoot, relative(this.scope, this._base.path)); } get subdirs(): PathFragment[] { return this._base.subdirs; } get subfiles(): PathFragment[] { return this._base.subfiles; } dir(name: PathFragment): DirEntry { const entry = this._base.dir(name); return entry && new ScopedDirEntry(entry, this.scope); } file(name: PathFragment): FileEntry | null { const entry = this._base.file(name); return entry && new ScopedFileEntry(entry, this.scope); } visit(visitor: FileVisitor): void { return this._base.visit((path, entry) => { visitor( join(NormalizedRoot, relative(this.scope, path)), entry && new ScopedFileEntry(entry, this.scope), ); }); } } export class ScopedTree implements Tree { readonly _root: ScopedDirEntry; constructor( private _base: Tree, scope: string, ) { const normalizedScope = normalize('/' + scope); this._root = new ScopedDirEntry(this._base.getDir(normalizedScope), normalizedScope); } get root(): DirEntry { return this._root; } branch(): Tree { return new ScopedTree(this._base.branch(), this._root.scope); } merge(other: Tree, strategy?: MergeStrategy): void { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; const delegate = new (class extends DelegateTree { override get actions(): Action[] { return other.actions.map((action) => self._fullPathAction(action)); } })(other); this._base.merge(delegate, strategy); } // Readonly. read(path: string): Buffer | null { return this._base.read(this._fullPath(path)); } readText(path: string): string { return this._base.readText(this._fullPath(path)); } readJson(path: string): JsonValue { return this._base.readJson(this._fullPath(path)); } exists(path: string): boolean { return this._base.exists(this._fullPath(path)); } get(path: string): FileEntry | null { const entry = this._base.get(this._fullPath(path)); return entry && new ScopedFileEntry(entry, this._root.scope); } getDir(path: string): DirEntry { const entry = this._base.getDir(this._fullPath(path)); return entry && new ScopedDirEntry(entry, this._root.scope); } visit(visitor: FileVisitor): void { return this._root.visit(visitor); } // Change content of host files. overwrite(path: string, content: Buffer | string): void { return this._base.overwrite(this._fullPath(path), content); } beginUpdate(path: string): UpdateRecorder { return this._base.beginUpdate(this._fullPath(path)); } commitUpdate(record: UpdateRecorder): void { return this._base.commitUpdate(record); } // Structural methods. create(path: string, content: Buffer | string): void { return this._base.create(this._fullPath(path), content); } delete(path: string): void { return this._base.delete(this._fullPath(path)); } rename(from: string, to: string): void { return this._base.rename(this._fullPath(from), this._fullPath(to)); } apply(action: Action, strategy?: MergeStrategy): void { return this._base.apply(this._fullPathAction(action), strategy); } get actions(): Action[] { const scopedActions: Action[] = []; for (const action of this._base.actions) { if (!action.path.startsWith(this._root.scope + '/')) { continue; } if (action.kind !== 'r') { scopedActions.push({ ...action, path: join(NormalizedRoot, relative(this._root.scope, action.path)), }); } else if (action.to.startsWith(this._root.scope + '/')) { scopedActions.push({ ...action, path: join(NormalizedRoot, relative(this._root.scope, action.path)), to: join(NormalizedRoot, relative(this._root.scope, action.to)), }); } } return scopedActions; } [TreeSymbol]() { return this; } private _fullPath(path: string): Path { return join(this._root.scope, normalize('/' + path)); } private _fullPathAction(action: Action) { let fullPathAction: Action; if (action.kind === 'r') { fullPathAction = { ...action, path: this._fullPath(action.path), to: this._fullPath(action.to), }; } else { fullPathAction = { ...action, path: this._fullPath(action.path), }; } return fullPathAction; } }
{ "end_byte": 5619, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/scoped.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/empty.ts_0_324
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { HostTree } from './host-tree'; export class EmptyTree extends HostTree { constructor() { super(); } }
{ "end_byte": 324, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/empty.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/interface.ts_0_4479
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonValue, Path, PathFragment } from '@angular-devkit/core'; import { Action } from './action'; export enum MergeStrategy { AllowOverwriteConflict = 1 << 1, AllowCreationConflict = 1 << 2, AllowDeleteConflict = 1 << 3, // Uses the default strategy. Default = 0, // Error out if 2 files have the same path. It is useful to have a different value than // Default in this case as the tooling Default might differ. Error = 1 << 0, // Only content conflicts are overwritten. ContentOnly = AllowOverwriteConflict, // Overwrite everything with the latest change. Overwrite = AllowOverwriteConflict + AllowCreationConflict + AllowDeleteConflict, } // eslint-disable-next-line @typescript-eslint/no-inferrable-types export const FileVisitorCancelToken: symbol = Symbol(); export type FileVisitor = FilePredicate<void>; export interface FileEntry { readonly path: Path; readonly content: Buffer; } export interface DirEntry { readonly parent: DirEntry | null; readonly path: Path; readonly subdirs: PathFragment[]; readonly subfiles: PathFragment[]; dir(name: PathFragment): DirEntry; file(name: PathFragment): FileEntry | null; visit(visitor: FileVisitor): void; } export interface FilePredicate<T> { (path: Path, entry?: Readonly<FileEntry> | null): T; } declare const window: { Symbol: { schematicTree: symbol }; window: {} }; declare const self: { Symbol: { schematicTree: symbol }; self: {} }; declare const global: { Symbol: { schematicTree: symbol }; global: {} }; export const TreeSymbol: symbol = (function () { const globalSymbol = (typeof window == 'object' && window.window === window && window.Symbol) || (typeof self == 'object' && self.self === self && self.Symbol) || (typeof global == 'object' && global.global === global && global.Symbol); if (!globalSymbol) { return Symbol('schematic-tree'); } if (!globalSymbol.schematicTree) { globalSymbol.schematicTree = Symbol('schematic-tree'); } return globalSymbol.schematicTree; })(); export interface Tree { branch(): Tree; merge(other: Tree, strategy?: MergeStrategy): void; readonly root: DirEntry; // Readonly. read(path: string): Buffer | null; /** * Reads a file from the Tree as a UTF-8 encoded text file. * * @param path The path of the file to read. * @returns A string containing the contents of the file. * @throws {@link FileDoesNotExistException} if the file is not found. * @throws An error if the file contains invalid UTF-8 characters. */ readText(path: string): string; /** * Reads and parses a file from the Tree as a UTF-8 encoded JSON file. * Supports parsing JSON (RFC 8259) with the following extensions: * * Single-line and multi-line JavaScript comments * * Trailing commas within objects and arrays * * @param path The path of the file to read. * @returns A JsonValue containing the parsed contents of the file. * @throws {@link FileDoesNotExistException} if the file is not found. * @throws An error if the file contains invalid UTF-8 characters. * @throws An error if the file contains malformed JSON. */ readJson(path: string): JsonValue; exists(path: string): boolean; get(path: string): FileEntry | null; getDir(path: string): DirEntry; visit(visitor: FileVisitor): void; // Change content of host files. overwrite(path: string, content: Buffer | string): void; beginUpdate(path: string): UpdateRecorder; commitUpdate(record: UpdateRecorder): void; // Structural methods. create(path: string, content: Buffer | string): void; delete(path: string): void; rename(from: string, to: string): void; apply(action: Action, strategy?: MergeStrategy): void; readonly actions: Action[]; } export interface TreeConstructor { isTree(maybeTree: object): maybeTree is Tree; } export const Tree: TreeConstructor = Object.freeze({ isTree(maybeTree: object): maybeTree is Tree { return TreeSymbol in maybeTree; }, }); export interface UpdateRecorder { // These just record changes. insertLeft(index: number, content: Buffer | string): UpdateRecorder; insertRight(index: number, content: Buffer | string): UpdateRecorder; remove(index: number, length: number): UpdateRecorder; }
{ "end_byte": 4479, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/interface.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/recorder.ts_0_3096
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException } from '@angular-devkit/core'; import MagicString from 'magic-string'; import { ContentHasMutatedException } from '../exception/exception'; import { FileEntry, UpdateRecorder } from './interface'; export class IndexOutOfBoundException extends BaseException { constructor(index: number, min: number, max = Infinity) { super(`Index ${index} outside of range [${min}, ${max}].`); } } export class UpdateRecorderBase implements UpdateRecorder { protected _path: string; protected content: MagicString; constructor( private readonly data: Uint8Array, path: string, encoding = 'utf-8', private readonly bom = false, ) { let text; try { text = new TextDecoder(encoding, { fatal: true, ignoreBOM: false }).decode(data); } catch (e) { if (e instanceof TypeError) { throw new Error(`Failed to decode "${path}" as ${encoding} text.`); } throw e; } this._path = path; this.content = new MagicString(text); } static createFromFileEntry(entry: FileEntry): UpdateRecorderBase { const c0 = entry.content.byteLength > 0 && entry.content.readUInt8(0); const c1 = entry.content.byteLength > 1 && entry.content.readUInt8(1); const c2 = entry.content.byteLength > 2 && entry.content.readUInt8(2); // Check if we're BOM. if (c0 == 0xef && c1 == 0xbb && c2 == 0xbf) { return new UpdateRecorderBase(entry.content, entry.path, 'utf-8', true); } else if (c0 === 0xff && c1 == 0xfe) { return new UpdateRecorderBase(entry.content, entry.path, 'utf-16le', true); } else if (c0 === 0xfe && c1 == 0xff) { return new UpdateRecorderBase(entry.content, entry.path, 'utf-16be', true); } return new UpdateRecorderBase(entry.content, entry.path); } get path() { return this._path; } protected _assertIndex(index: number) { if (index < 0 || index > this.content.original.length) { throw new IndexOutOfBoundException(index, 0, this.content.original.length); } } // These just record changes. insertLeft(index: number, content: Buffer | string): UpdateRecorder { this._assertIndex(index); this.content.appendLeft(index, content.toString()); return this; } insertRight(index: number, content: Buffer | string): UpdateRecorder { this._assertIndex(index); this.content.appendRight(index, content.toString()); return this; } remove(index: number, length: number): UpdateRecorder { this._assertIndex(index); this.content.remove(index, index + length); return this; } apply(content: Buffer): Buffer { if (!content.equals(this.data)) { throw new ContentHasMutatedException(this.path); } // Schematics only support writing UTF-8 text const result = Buffer.from((this.bom ? '\uFEFF' : '') + this.content.toString(), 'utf-8'); return result; } }
{ "end_byte": 3096, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/recorder.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/common_spec.ts_0_1790
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize } from '@angular-devkit/core'; import { Tree } from './interface'; export interface VisitTestVisitSpec { root: string; expected?: string[]; exception?: (spec: { path: string }) => Error; focus?: boolean; } export interface VisitTestSet { name: string; files: string[]; visits: VisitTestVisitSpec[]; focus?: boolean; } export interface VisitTestSpec { createTree: (paths: string[]) => Tree; sets: VisitTestSet[]; } export function testTreeVisit({ createTree, sets }: VisitTestSpec) { sets.forEach(({ name, files: paths, visits, focus: focusSet }) => { visits.forEach(({ root, expected, exception, focus }) => { if (expected == null) { expected = paths; } const that = focusSet || focus ? fit : it; that(`can visit: ${name} from ${root}`, () => { const tree = createTree(paths); const normalizedRoot = normalize(root); if (exception != null) { // eslint-disable-next-line @typescript-eslint/no-empty-function expect(() => tree.getDir(normalizedRoot).visit(() => {})).toThrow( exception({ path: normalizedRoot }), ); return; } const allPaths: string[] = []; tree.getDir(normalizedRoot).visit((path, entry) => { expect(entry).not.toBeNull(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(entry!.content.toString()).toEqual(path); allPaths.push(path); }); expect(allPaths).toEqual(expected); }); }); }); }
{ "end_byte": 1790, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/common_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/null.ts_0_2833
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException, JsonValue, Path, PathFragment, dirname, join, normalize, } from '@angular-devkit/core'; import { FileDoesNotExistException } from '../exception/exception'; import { Action } from './action'; import { DirEntry, MergeStrategy, Tree, TreeSymbol, UpdateRecorder } from './interface'; import { UpdateRecorderBase } from './recorder'; export class CannotCreateFileException extends BaseException { constructor(path: string) { super(`Cannot create file "${path}".`); } } export class NullTreeDirEntry implements DirEntry { get parent(): DirEntry | null { return this.path == '/' ? null : new NullTreeDirEntry(dirname(this.path)); } constructor(public readonly path: Path) {} readonly subdirs: PathFragment[] = []; readonly subfiles: PathFragment[] = []; dir(name: PathFragment): DirEntry { return new NullTreeDirEntry(join(this.path, name)); } file(_name: PathFragment) { return null; } visit() {} } export class NullTree implements Tree { [TreeSymbol]() { return this; } branch(): Tree { return new NullTree(); } merge(_other: Tree, _strategy?: MergeStrategy): void {} readonly root: DirEntry = new NullTreeDirEntry(normalize('/')); // Simple readonly file system operations. exists(_path: string) { return false; } read(_path: string) { return null; } readText(path: string): string { throw new FileDoesNotExistException(path); } readJson(path: string): JsonValue { throw new FileDoesNotExistException(path); } get(_path: string) { return null; } getDir(path: string) { return new NullTreeDirEntry(normalize('/' + path)); } visit() {} // Change content of host files. beginUpdate(path: string): never { throw new FileDoesNotExistException(path); } commitUpdate(record: UpdateRecorder): never { throw new FileDoesNotExistException( record instanceof UpdateRecorderBase ? record.path : '<unknown>', ); } // Change structure of the host. copy(path: string, _to: string): never { throw new FileDoesNotExistException(path); } delete(path: string): never { throw new FileDoesNotExistException(path); } create(path: string, _content: Buffer | string): never { throw new CannotCreateFileException(path); } rename(path: string, _to: string): never { throw new FileDoesNotExistException(path); } overwrite(path: string, _content: Buffer | string): never { throw new FileDoesNotExistException(path); } apply(_action: Action, _strategy?: MergeStrategy): void {} get actions(): Action[] { return []; } }
{ "end_byte": 2833, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/null.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/action_spec.ts_0_3788
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize } from '@angular-devkit/core'; import { Action, ActionList } from './action'; describe('Action', () => { describe('optimize', () => { it('works with create', () => { const actions = new ActionList(); actions.create(normalize('/a/b'), Buffer.from('1')); actions.create(normalize('/a/c'), Buffer.from('2')); actions.create(normalize('/a/c'), Buffer.from('3')); expect(actions.length).toBe(3); actions.optimize(); expect(actions.length).toBe(2); }); it('works with overwrite', () => { const actions = new ActionList(); actions.create(normalize('/a/b'), Buffer.from('1')); actions.create(normalize('/a/c'), Buffer.from('2')); actions.overwrite(normalize('/a/c'), Buffer.from('3')); actions.overwrite(normalize('/a/b'), Buffer.from('4')); expect(actions.length).toBe(4); actions.optimize(); expect(actions.length).toBe(2); }); it('works with cloning a list', () => { const actions = new ActionList(); actions.create(normalize('/a/b'), Buffer.from('1')); actions.create(normalize('/a/c'), Buffer.from('2')); actions.overwrite(normalize('/a/c'), Buffer.from('3')); actions.overwrite(normalize('/a/b'), Buffer.from('4')); actions.create(normalize('/a/d'), Buffer.from('5')); const actions2 = new ActionList(); actions.forEach((x) => actions2.push(x)); expect(actions.length).toBe(5); expect(actions2.length).toBe(5); actions.optimize(); expect(actions.length).toBe(3); expect(actions2.length).toBe(5); actions2.optimize(); expect(actions2.length).toBe(3); }); it('handles edge cases (1)', () => { const actions = new ActionList(); actions.create(normalize('/test'), Buffer.from('1')); actions.overwrite(normalize('/test'), Buffer.from('3')); actions.overwrite(normalize('/hello'), Buffer.from('2')); actions.overwrite(normalize('/test'), Buffer.from('4')); const actions2 = new ActionList(); actions.forEach((x) => actions2.push(x)); expect(actions.length).toBe(4); expect(actions2.length).toBe(4); actions.optimize(); expect(actions.length).toBe(2); expect(actions2.length).toBe(4); actions2.optimize(); expect(actions2.length).toBe(2); }); it('handles edge cases (2)', () => { const actions = new ActionList(); actions.create(normalize('/test'), Buffer.from('1')); actions.rename(normalize('/test'), normalize('/test1')); actions.overwrite(normalize('/test1'), Buffer.from('2')); actions.rename(normalize('/test1'), normalize('/test2')); actions.optimize(); expect(actions.length).toBe(1); expect(actions.get(0)).toEqual( jasmine.objectContaining<Action>({ kind: 'c', path: normalize('/test2') }), ); }); it('handles edge cases (3)', () => { const actions = new ActionList(); actions.rename(normalize('/test'), normalize('/test1')); actions.overwrite(normalize('/test1'), Buffer.from('2')); actions.rename(normalize('/test1'), normalize('/test2')); actions.optimize(); expect(actions.length).toBe(2); expect(actions.get(0)).toEqual( jasmine.objectContaining<Action>({ kind: 'r', path: normalize('/test'), to: normalize('/test2'), }), ); expect(actions.get(1)).toEqual( jasmine.objectContaining<Action>({ kind: 'o', path: normalize('/test2') }), ); }); }); });
{ "end_byte": 3788, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/action_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/tree/scoped_spec.ts_0_5114
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { UnitTestTree } from '../../testing'; import { HostTree } from './host-tree'; import { ScopedTree } from './scoped'; describe('ScopedTree', () => { let base: HostTree; let scoped: ScopedTree; beforeEach(() => { base = new HostTree(); base.create('/file-0-1', '0-1'); base.create('/file-0-2', '0-2'); base.create('/file-0-3', '0-3'); base.create('/level-1/file-1-1', '1-1'); base.create('/level-1/file-1-2', '1-2'); base.create('/level-1/file-1-3', '1-3'); base.create('/level-1/level-2/file-2-1', '2-1'); base.create('/level-1/level-2/file-2-2', '2-2'); base.create('/level-1/level-2/file-2-3', '2-3'); scoped = new ScopedTree(base, 'level-1'); }); it('supports exists', () => { expect(scoped.exists('/file-1-1')).toBeTruthy(); expect(scoped.exists('file-1-1')).toBeTruthy(); expect(scoped.exists('/level-2/file-2-1')).toBeTruthy(); expect(scoped.exists('level-2/file-2-1')).toBeTruthy(); expect(scoped.exists('/file-1-4')).toBeFalsy(); expect(scoped.exists('file-1-4')).toBeFalsy(); expect(scoped.exists('/file-0-1')).toBeFalsy(); expect(scoped.exists('file-0-1')).toBeFalsy(); expect(scoped.exists('/level-1/file-1-1')).toBeFalsy(); expect(scoped.exists('level-1/file-1-1')).toBeFalsy(); }); it('supports read', () => { expect(scoped.read('/file-1-2')).not.toBeNull(); expect(scoped.read('file-1-2')).not.toBeNull(); const test = new UnitTestTree(scoped); expect(test.readContent('/file-1-2')).toBe('1-2'); expect(test.readContent('file-1-2')).toBe('1-2'); expect(scoped.read('/file-0-2')).toBeNull(); expect(scoped.read('file-0-2')).toBeNull(); }); it('supports create', () => { expect(() => scoped.create('/file-1-4', '1-4')).not.toThrow(); const test = new UnitTestTree(scoped); expect(test.readContent('/file-1-4')).toBe('1-4'); expect(test.readContent('file-1-4')).toBe('1-4'); expect(base.exists('/level-1/file-1-4')).toBeTruthy(); }); it('supports delete', () => { expect(() => scoped.delete('/file-0-3')).toThrow(); expect(() => scoped.delete('/file-1-3')).not.toThrow(); expect(scoped.exists('/file-1-3')).toBeFalsy(); expect(base.exists('/level-1/file-1-3')).toBeFalsy(); }); it('supports overwrite', () => { expect(() => scoped.overwrite('/file-1-1', '1-1*')).not.toThrow(); expect(() => scoped.overwrite('/file-1-4', '1-4*')).toThrow(); const test = new UnitTestTree(scoped); expect(test.readContent('/file-1-1')).toBe('1-1*'); expect(test.readContent('file-1-1')).toBe('1-1*'); }); it('supports rename', () => { expect(() => scoped.rename('/file-1-1', '/file-1-1-new')).not.toThrow(); expect(() => scoped.rename('/file-1-4', '/file-1-4-new')).toThrow(); const test = new UnitTestTree(scoped); expect(test.readContent('/file-1-1-new')).toBe('1-1'); expect(test.readContent('file-1-1-new')).toBe('1-1'); }); it('supports get', () => { expect(scoped.get('/file-1-1')).not.toBeNull(); const file = scoped.get('file-1-1'); expect(file && (file.path as string)).toBe('/file-1-1'); expect(scoped.get('/file-0-1')).toBeNull(); expect(scoped.get('file-0-1')).toBeNull(); }); it('supports getDir', () => { expect(scoped.getDir('/level-2')).not.toBeNull(); const dir = scoped.getDir('level-2'); expect(dir.path as string).toBe('/level-2'); expect(dir.parent).not.toBeNull(); const files: string[] = []; dir.visit((path) => files.push(path)); files.sort(); expect(files).toEqual(['/level-2/file-2-1', '/level-2/file-2-2', '/level-2/file-2-3']); }); it('supports visit', () => { const files: string[] = []; scoped.visit((path) => files.push(path)); files.sort(); expect(files).toEqual([ '/file-1-1', '/file-1-2', '/file-1-3', '/level-2/file-2-1', '/level-2/file-2-2', '/level-2/file-2-3', ]); }); it('supports merge into a scoped tree', () => { const other = new HostTree(); other.create('other-file', 'other'); scoped.merge(other); expect(base.exists('/level-1/other-file')).toBeTruthy(); expect(base.exists('/other-file')).toBeFalsy(); }); it('supports merge from a scoped tree', () => { const other = new HostTree(); other.merge(scoped); expect(other.exists('/file-1-1')).toBeTruthy(); expect(other.exists('file-1-1')).toBeTruthy(); expect(other.exists('/file-1-2')).toBeTruthy(); expect(other.exists('/file-0-1')).toBeFalsy(); expect(other.exists('file-0-1')).toBeFalsy(); expect(other.exists('/level-1/file-1-1')).toBeFalsy(); expect(other.exists('level-1/file-1-1')).toBeFalsy(); }); it('supports root', () => { expect(scoped.root).not.toBeNull(); expect(scoped.root.path as string).toBe('/'); expect(scoped.root.parent).toBeNull(); }); });
{ "end_byte": 5114, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/tree/scoped_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/path.ts_0_703
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize, schema } from '@angular-devkit/core'; export const pathFormat: schema.SchemaFormat = { name: 'path', formatter: { async: false, validate: (path: string) => { // Check path is normalized already. return path === normalize(path); // TODO: check if path is valid (is that just checking if it's normalized?) // TODO: check path is from root of schematics even if passed absolute // TODO: error out if path is outside of host }, }, };
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/path.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/html-selector.ts_0_1350
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { schema } from '@angular-devkit/core'; // As per https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name // * Without mandatory `-` as the application prefix will generally cover its inclusion // * And an allowance for upper alpha characters // NOTE: This should eventually be broken out into two formats: full and partial (allows for prefix) const unicodeRanges = [ [0xc0, 0xd6], [0xd8, 0xf6], [0xf8, 0x37d], [0x37f, 0x1fff], [0x200c, 0x200d], [0x203f, 0x2040], [0x2070, 0x218f], [0x2c00, 0x2fef], [0x3001, 0xd7ff], [0xf900, 0xfdcf], [0xfdf0, 0xfffd], [0x10000, 0xeffff], ]; function isValidElementName(name: string) { let regex = '^[a-zA-Z]['; regex += '-.0-9_a-zA-Z\\u{B7}'; for (const range of unicodeRanges) { regex += `\\u{${range[0].toString(16)}}-\\u{${range[1].toString(16)}}`; } regex += ']*$'; return new RegExp(regex, 'u').test(name); } export const htmlSelectorFormat: schema.SchemaFormat = { name: 'html-selector', formatter: { async: false, validate: (name: unknown) => typeof name === 'string' && isValidElementName(name), }, };
{ "end_byte": 1350, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/html-selector.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/format-validator.ts_0_645
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { JsonObject, JsonValue, schema } from '@angular-devkit/core'; export async function formatValidator( data: JsonValue, dataSchema: JsonObject, formats: schema.SchemaFormat[], ): Promise<schema.SchemaValidatorResult> { const registry = new schema.CoreSchemaRegistry(); for (const format of formats) { registry.addFormat(format); } const validator = await registry.compile(dataSchema); return validator(data); }
{ "end_byte": 645, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/format-validator.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts_0_2093
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { formatValidator } from './format-validator'; import { htmlSelectorFormat } from './html-selector'; describe('Schematics HTML selector format', () => { it('accepts correct selectors', async () => { const data = { selector: 'my-selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); expect(result.success).toBeTrue(); }); it('rejects selectors starting with invalid characters', async () => { const data = { selector: 'my-selector$' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); expect(result.success).toBeFalse(); }); it('rejects selectors starting with number', async () => { const data = { selector: '1selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); expect(result.success).toBeFalse(); }); it('accepts selectors with non-letter after dash', async () => { const data = { selector: 'my-1selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); expect(result.success).toBeTrue(); }); it('accepts selectors with unicode', async () => { const data = { selector: 'app-root😀' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); expect(result.success).toBeTrue(); }); });
{ "end_byte": 2093, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/index.ts_0_523
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { schema } from '@angular-devkit/core'; import { htmlSelectorFormat } from './html-selector'; import { pathFormat } from './path'; export { htmlSelectorFormat } from './html-selector'; export { pathFormat } from './path'; export const standardFormats: schema.SchemaFormat[] = [htmlSelectorFormat, pathFormat];
{ "end_byte": 523, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/index.ts" }
angular-cli/packages/angular_devkit/schematics/src/formats/path_spec.ts_0_957
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { formatValidator } from './format-validator'; import { pathFormat } from './path'; describe('Schematics Path format', () => { it('accepts correct Paths', async () => { const data = { path: 'a/b/c' }; const dataSchema = { properties: { path: { type: 'string', format: 'path' } }, }; const result = await formatValidator(data, dataSchema, [pathFormat]); expect(result.success).toBeTrue(); }); it('rejects Paths that are not normalized', async () => { const data = { path: 'a/b/c/../' }; const dataSchema = { properties: { path: { type: 'string', format: 'path' } }, }; const result = await formatValidator(data, dataSchema, [pathFormat]); expect(result.success).toBeFalse(); }); });
{ "end_byte": 957, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/formats/path_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/sink/dryrun.ts_0_3449
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize, virtualFs } from '@angular-devkit/core'; import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { Observable, Subject, of } from 'rxjs'; import { HostSink } from './host'; export interface DryRunErrorEvent { kind: 'error'; description: 'alreadyExist' | 'doesNotExist'; path: string; } export interface DryRunDeleteEvent { kind: 'delete'; path: string; } export interface DryRunCreateEvent { kind: 'create'; path: string; content: Buffer; } export interface DryRunUpdateEvent { kind: 'update'; path: string; content: Buffer; } export interface DryRunRenameEvent { kind: 'rename'; path: string; to: string; } export type DryRunEvent = | DryRunErrorEvent | DryRunDeleteEvent | DryRunCreateEvent | DryRunUpdateEvent | DryRunRenameEvent; export class DryRunSink extends HostSink { protected _subject = new Subject<DryRunEvent>(); protected _fileDoesNotExistExceptionSet = new Set<string>(); protected _fileAlreadyExistExceptionSet = new Set<string>(); readonly reporter: Observable<DryRunEvent> = this._subject.asObservable(); /** * @param {host} dir The host to use to output. This should be scoped. * @param {boolean} force Whether to force overwriting files that already exist. */ constructor(host: virtualFs.Host, force?: boolean); constructor(host: virtualFs.Host | string, force = false) { super( typeof host == 'string' ? new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(host)) : host, force, ); } protected override _fileAlreadyExistException(path: string): void { this._fileAlreadyExistExceptionSet.add(path); } protected override _fileDoesNotExistException(path: string): void { this._fileDoesNotExistExceptionSet.add(path); } override _done() { this._fileAlreadyExistExceptionSet.forEach((path) => { this._subject.next({ kind: 'error', description: 'alreadyExist', path, }); }); this._fileDoesNotExistExceptionSet.forEach((path) => { this._subject.next({ kind: 'error', description: 'doesNotExist', path, }); }); this._filesToDelete.forEach((path) => { // Check if this is a renaming. for (const [from] of this._filesToRename) { if (from == path) { // The event is sent later on. return; } } this._subject.next({ kind: 'delete', path }); }); this._filesToRename.forEach(([path, to]) => { this._subject.next({ kind: 'rename', path, to }); }); this._filesToCreate.forEach((content, path) => { // Check if this is a renaming. for (const [, to] of this._filesToRename) { if (to == path) { // The event is sent later on. return; } } if ( this._fileAlreadyExistExceptionSet.has(path) || this._fileDoesNotExistExceptionSet.has(path) ) { return; } this._subject.next({ kind: 'create', path, content }); }); this._filesToUpdate.forEach((content, path) => { this._subject.next({ kind: 'update', path, content }); }); this._subject.complete(); return of<void>(undefined); } }
{ "end_byte": 3449, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/sink/dryrun.ts" }
angular-cli/packages/angular_devkit/schematics/src/sink/host_spec.ts_0_4835
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { normalize, virtualFs } from '@angular-devkit/core'; import { HostSink } from '@angular-devkit/schematics'; import { HostCreateTree, HostTree } from '../tree/host-tree'; describe('FileSystemSink', () => { it('works', (done) => { const host = new virtualFs.test.TestHost({ '/hello': 'world', '/sub/directory/file2': '', '/sub/file1': '', }); const tree = new HostCreateTree(host); tree.create('/test', 'testing 1 2'); const recorder = tree.beginUpdate('/test'); recorder.insertLeft(8, 'testing '); tree.commitUpdate(recorder); const files = ['/hello', '/sub/directory/file2', '/sub/file1', '/test']; const treeFiles: string[] = []; tree.visit((path) => treeFiles.push(path)); treeFiles.sort(); expect(treeFiles).toEqual(files); const outputHost = new virtualFs.test.TestHost(); const sink = new HostSink(outputHost); sink .commit(tree) .toPromise() .then(() => { const tmpFiles = outputHost.files.sort(); expect(tmpFiles as string[]).toEqual(files); expect(outputHost.sync.read(normalize('/test')).toString()).toBe('testing testing 1 2'); }) .then(done, done.fail); }); describe('complex tests', () => { beforeEach((done) => { // Commit a version of the tree. const host = new virtualFs.test.TestHost({ '/file0': '/file0', '/sub/directory/file2': '/sub/directory/file2', '/sub/file1': '/sub/file1', }); const tree = new HostCreateTree(host); const outputHost = new virtualFs.test.TestHost(); const sink = new HostSink(outputHost); sink.commit(tree).toPromise().then(done, done.fail); }); it('can rename files', (done) => { const host = new virtualFs.test.TestHost({ '/file0': '/file0', }); const tree = new HostTree(host); tree.rename('/file0', '/file1'); const sink = new HostSink(host); sink .commit(tree) .toPromise() .then(() => { expect(host.sync.exists(normalize('/file0'))).toBe(false); expect(host.sync.exists(normalize('/file1'))).toBe(true); }) .then(done, done.fail); }); it('can rename nested files', (done) => { const host = new virtualFs.test.TestHost({ '/sub/directory/file2': '', }); const tree = new HostTree(host); tree.rename('/sub/directory/file2', '/another-directory/file2'); const sink = new HostSink(host); sink .commit(tree) .toPromise() .then(() => { expect(host.sync.exists(normalize('/sub/directory/file2'))).toBe(false); expect(host.sync.exists(normalize('/another-directory/file2'))).toBe(true); }) .then(done, done.fail); }); it('can delete and create the same file', (done) => { const host = new virtualFs.test.TestHost({ '/file0': 'world', }); const tree = new HostTree(host); tree.delete('/file0'); tree.create('/file0', 'hello'); const sink = new HostSink(host); sink .commit(tree) .toPromise() .then(() => { expect(host.sync.read(normalize('/file0')).toString()).toBe('hello'); }) .then(done, done.fail); }); it('can rename then create the same file', (done) => { const host = new virtualFs.test.TestHost({ '/file0': 'world', }); const tree = new HostTree(host); tree.rename('/file0', '/file1'); expect(tree.exists('/file0')).toBeFalsy(); expect(tree.exists('/file1')).toBeTruthy(); tree.create('/file0', 'hello'); expect(tree.exists('/file0')).toBeTruthy(); const sink = new HostSink(host); sink .commit(tree) .toPromise() .then(() => { expect(host.sync.read(normalize('/file0')).toString()).toBe('hello'); expect(virtualFs.fileBufferToString(host.sync.read(normalize('/file1')))).toBe('world'); }) .then(done, done.fail); }); it('can rename then modify the same file', async () => { const host = new virtualFs.test.TestHost({ '/file0': 'world', }); const tree = new HostTree(host); tree.rename('/file0', '/file1'); expect(tree.exists('/file0')).toBeFalsy(); expect(tree.exists('/file1')).toBeTruthy(); tree.overwrite('/file1', 'hello'); const sink = new HostSink(host); await sink.commit(tree).toPromise(); expect(virtualFs.fileBufferToString(host.sync.read(normalize('/file1')))).toBe('hello'); }); }); });
{ "end_byte": 4835, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/sink/host_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/sink/dryrun_spec.ts_0_2441
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Path, normalize, virtualFs } from '@angular-devkit/core'; import { lastValueFrom, toArray } from 'rxjs'; import { HostCreateTree, HostTree } from '../tree/host-tree'; import { DryRunSink } from './dryrun'; const host = new virtualFs.test.TestHost({ '/hello': '', '/sub/file1': '', '/sub/directory/file2': '', }); describe('DryRunSink', () => { it('works when creating everything', async () => { const tree = new HostCreateTree(host); tree.create('/test', 'testing 1 2'); const recorder = tree.beginUpdate('/test'); recorder.insertLeft(8, 'testing '); tree.commitUpdate(recorder); tree.overwrite('/hello', 'world'); const files = ['/hello', '/sub/directory/file2', '/sub/file1', '/test']; const treeFiles: Path[] = []; tree.visit((path) => treeFiles.push(path)); treeFiles.sort(); expect(treeFiles).toEqual(files.map(normalize)); const sink = new DryRunSink(new virtualFs.SimpleMemoryHost()); const [infos] = await Promise.all([ lastValueFrom(sink.reporter.pipe(toArray())), lastValueFrom(sink.commit(tree)), ]); expect(infos.length).toBe(4); for (const info of infos) { expect(info.kind).toBe('create'); } }); it('works with root', async () => { const tree = new HostTree(host); tree.create('/test', 'testing 1 2'); const recorder = tree.beginUpdate('/test'); recorder.insertLeft(8, 'testing '); tree.commitUpdate(recorder); tree.overwrite('/hello', 'world'); const files = ['/hello', '/sub/directory/file2', '/sub/file1', '/test']; const treeFiles: Path[] = []; tree.visit((path) => treeFiles.push(path)); treeFiles.sort(); expect(treeFiles).toEqual(files.map(normalize)); // Need to create this file on the filesystem, otherwise the commit phase will fail. const outputHost = new virtualFs.SimpleMemoryHost(); outputHost.write(normalize('/hello'), virtualFs.stringToFileBuffer('')).subscribe(); const sink = new DryRunSink(outputHost); const [infos] = await Promise.all([ lastValueFrom(sink.reporter.pipe(toArray())), lastValueFrom(sink.commit(tree)), ]); expect(infos.map((x) => x.kind)).toEqual(['create', 'update']); }); });
{ "end_byte": 2441, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/sink/dryrun_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/sink/host.ts_0_2884
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Path, virtualFs } from '@angular-devkit/core'; import { EMPTY, Observable, concatMap, concat as concatObservables, from as observableFrom, of as observableOf, reduce, } from 'rxjs'; import { CreateFileAction } from '../tree/action'; import { SimpleSinkBase } from './sink'; export class HostSink extends SimpleSinkBase { protected _filesToDelete = new Set<Path>(); protected _filesToRename = new Set<[Path, Path]>(); protected _filesToCreate = new Map<Path, Buffer>(); protected _filesToUpdate = new Map<Path, Buffer>(); constructor( protected _host: virtualFs.Host, protected _force = false, ) { super(); } protected override _validateCreateAction(action: CreateFileAction): Observable<void> { return this._force ? EMPTY : super._validateCreateAction(action); } protected _validateFileExists(p: Path): Observable<boolean> { if (this._filesToCreate.has(p) || this._filesToUpdate.has(p)) { return observableOf(true); } if (this._filesToDelete.has(p)) { return observableOf(false); } for (const [from, to] of this._filesToRename.values()) { switch (p) { case from: return observableOf(false); case to: return observableOf(true); } } return this._host.exists(p); } protected _overwriteFile(path: Path, content: Buffer): Observable<void> { this._filesToUpdate.set(path, content); return EMPTY; } protected _createFile(path: Path, content: Buffer): Observable<void> { this._filesToCreate.set(path, content); return EMPTY; } protected _renameFile(from: Path, to: Path): Observable<void> { this._filesToRename.add([from, to]); return EMPTY; } protected _deleteFile(path: Path): Observable<void> { if (this._filesToCreate.has(path)) { this._filesToCreate.delete(path); this._filesToUpdate.delete(path); } else { this._filesToDelete.add(path); } return EMPTY; } _done() { // Really commit everything to the actual filesystem. return concatObservables( observableFrom([...this._filesToDelete.values()]).pipe( concatMap((path) => this._host.delete(path)), ), observableFrom([...this._filesToRename.entries()]).pipe( concatMap(([_, [path, to]]) => this._host.rename(path, to)), ), observableFrom([...this._filesToCreate.entries()]).pipe( concatMap(([path, buffer]) => this._host.write(path, buffer)), ), observableFrom([...this._filesToUpdate.entries()]).pipe( concatMap(([path, buffer]) => this._host.write(path, buffer)), ), ).pipe(reduce(() => {})); } }
{ "end_byte": 2884, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/sink/host.ts" }
angular-cli/packages/angular_devkit/schematics/src/sink/sink.ts_0_5394
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { Observable, concat, concatMap, defaultIfEmpty, defer as deferObservable, ignoreElements, isObservable, map, mergeMap, from as observableFrom, of as observableOf, } from 'rxjs'; import { FileAlreadyExistException, FileDoesNotExistException } from '../exception/exception'; import { Action, CreateFileAction, DeleteFileAction, OverwriteFileAction, RenameFileAction, UnknownActionException, } from '../tree/action'; import { Tree } from '../tree/interface'; export interface Sink { commit(tree: Tree): Observable<void>; } const Noop = function () {}; export abstract class SimpleSinkBase implements Sink { preCommitAction: (action: Action) => void | Action | PromiseLike<Action> | Observable<Action> = Noop; postCommitAction: (action: Action) => void | Observable<void> = Noop; preCommit: () => void | Observable<void> = Noop; postCommit: () => void | Observable<void> = Noop; protected abstract _validateFileExists(p: string): Observable<boolean>; protected abstract _overwriteFile(path: string, content: Buffer): Observable<void>; protected abstract _createFile(path: string, content: Buffer): Observable<void>; protected abstract _renameFile(path: string, to: string): Observable<void>; protected abstract _deleteFile(path: string): Observable<void>; protected abstract _done(): Observable<void>; protected _fileAlreadyExistException(path: string): void { throw new FileAlreadyExistException(path); } protected _fileDoesNotExistException(path: string): void { throw new FileDoesNotExistException(path); } protected _validateOverwriteAction(action: OverwriteFileAction): Observable<void> { return this._validateFileExists(action.path).pipe( map((b) => { if (!b) { this._fileDoesNotExistException(action.path); } }), ); } protected _validateCreateAction(action: CreateFileAction): Observable<void> { return this._validateFileExists(action.path).pipe( map((b) => { if (b) { this._fileAlreadyExistException(action.path); } }), ); } protected _validateRenameAction(action: RenameFileAction): Observable<void> { return this._validateFileExists(action.path).pipe( map((b) => { if (!b) { this._fileDoesNotExistException(action.path); } }), mergeMap(() => this._validateFileExists(action.to)), map((b) => { if (b) { this._fileAlreadyExistException(action.to); } }), ); } protected _validateDeleteAction(action: DeleteFileAction): Observable<void> { return this._validateFileExists(action.path).pipe( map((b) => { if (!b) { this._fileDoesNotExistException(action.path); } }), ); } validateSingleAction(action: Action): Observable<void> { switch (action.kind) { case 'o': return this._validateOverwriteAction(action); case 'c': return this._validateCreateAction(action); case 'r': return this._validateRenameAction(action); case 'd': return this._validateDeleteAction(action); default: throw new UnknownActionException(action); } } commitSingleAction(action: Action): Observable<void> { return concat( this.validateSingleAction(action), new Observable<void>((observer) => { let committed: Observable<void> | null = null; switch (action.kind) { case 'o': committed = this._overwriteFile(action.path, action.content); break; case 'c': committed = this._createFile(action.path, action.content); break; case 'r': committed = this._renameFile(action.path, action.to); break; case 'd': committed = this._deleteFile(action.path); break; } if (committed) { committed.subscribe(observer); } else { observer.complete(); } }), ).pipe(ignoreElements()); } commit(tree: Tree): Observable<void> { const actions = observableFrom(tree.actions); return concat( this.preCommit() || observableOf(null), deferObservable(() => actions).pipe( concatMap((action) => { const maybeAction = this.preCommitAction(action); if (isObservable(maybeAction) || isPromiseLike(maybeAction)) { return maybeAction; } return observableOf(maybeAction || action); }), concatMap((action) => { return concat( this.commitSingleAction(action).pipe(ignoreElements()), observableOf(action), ); }), concatMap((action) => this.postCommitAction(action) || observableOf(null)), ), deferObservable(() => this._done()), deferObservable(() => this.postCommit() || observableOf(null)), ).pipe(ignoreElements(), defaultIfEmpty(undefined)); } } function isPromiseLike<T, U = unknown>(value: U | PromiseLike<T>): value is PromiseLike<T> { return !!value && typeof (value as PromiseLike<T>).then === 'function'; }
{ "end_byte": 5394, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/sink/sink.ts" }
angular-cli/packages/angular_devkit/schematics/src/workflow/base.ts_0_6310
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { logging, schema, virtualFs } from '@angular-devkit/core'; import { EMPTY, Observable, Subject, concat, concatMap, defaultIfEmpty, from, ignoreElements, last, of, tap, throwError, } from 'rxjs'; import { Engine, EngineHost, SchematicEngine } from '../engine'; import { UnsuccessfulWorkflowExecution } from '../exception/exception'; import { standardFormats } from '../formats'; import { DryRunEvent, DryRunSink } from '../sink/dryrun'; import { HostSink } from '../sink/host'; import { Sink } from '../sink/sink'; import { HostTree } from '../tree/host-tree'; import { Tree } from '../tree/interface'; import { LifeCycleEvent, RequiredWorkflowExecutionContext, Workflow, WorkflowExecutionContext, } from './interface'; export interface BaseWorkflowOptions { host: virtualFs.Host; engineHost: EngineHost<{}, {}>; registry?: schema.CoreSchemaRegistry; force?: boolean; dryRun?: boolean; } /** * Base class for workflows. Even without abstract methods, this class should not be used without * surrounding some initialization for the registry and host. This class only adds life cycle and * dryrun/force support. You need to provide any registry and task executors that you need to * support. * See {@see NodeWorkflow} implementation for how to make a specialized subclass of this. * TODO: add default set of CoreSchemaRegistry transforms. Once the job refactor is done, use that * as the support for tasks. * * @public */ export abstract class BaseWorkflow implements Workflow { protected _engine: Engine<{}, {}>; protected _engineHost: EngineHost<{}, {}>; protected _registry: schema.CoreSchemaRegistry; protected _host: virtualFs.Host; protected _reporter: Subject<DryRunEvent> = new Subject(); protected _lifeCycle: Subject<LifeCycleEvent> = new Subject(); protected _context: WorkflowExecutionContext[]; protected _force: boolean; protected _dryRun: boolean; constructor(options: BaseWorkflowOptions) { this._host = options.host; this._engineHost = options.engineHost; if (options.registry) { this._registry = options.registry; } else { this._registry = new schema.CoreSchemaRegistry(standardFormats); this._registry.addPostTransform(schema.transforms.addUndefinedDefaults); } this._engine = new SchematicEngine(this._engineHost, this); this._context = []; this._force = options.force || false; this._dryRun = options.dryRun || false; } get context(): Readonly<WorkflowExecutionContext> { const maybeContext = this._context[this._context.length - 1]; if (!maybeContext) { throw new Error('Cannot get context when workflow is not executing...'); } return maybeContext; } get engine(): Engine<{}, {}> { return this._engine; } get engineHost(): EngineHost<{}, {}> { return this._engineHost; } get registry(): schema.SchemaRegistry { return this._registry; } get reporter(): Observable<DryRunEvent> { return this._reporter.asObservable(); } get lifeCycle(): Observable<LifeCycleEvent> { return this._lifeCycle.asObservable(); } protected _createSinks(): Sink[] { let error = false; const dryRunSink = new DryRunSink(this._host, this._force); const dryRunSubscriber = dryRunSink.reporter.subscribe((event) => { this._reporter.next(event); error = error || event.kind == 'error'; }); // We need two sinks if we want to output what will happen, and actually do the work. return [ dryRunSink, // Add a custom sink that clean ourselves and throws an error if an error happened. { commit() { dryRunSubscriber.unsubscribe(); if (error) { return throwError(new UnsuccessfulWorkflowExecution()); } return of(); }, }, // Only add a HostSink if this is not a dryRun. ...(!this._dryRun ? [new HostSink(this._host, this._force)] : []), ]; } execute( options: Partial<WorkflowExecutionContext> & RequiredWorkflowExecutionContext, ): Observable<void> { const parentContext = this._context[this._context.length - 1]; if (!parentContext) { this._lifeCycle.next({ kind: 'start' }); } /** Create the collection and the schematic. */ const collection = this._engine.createCollection(options.collection); // Only allow private schematics if called from the same collection. const allowPrivate = options.allowPrivate || (parentContext && parentContext.collection === options.collection); const schematic = collection.createSchematic(options.schematic, allowPrivate); const sinks = this._createSinks(); this._lifeCycle.next({ kind: 'workflow-start' }); const context = { ...options, debug: options.debug || false, logger: options.logger || (parentContext && parentContext.logger) || new logging.NullLogger(), parentContext, }; this._context.push(context); return schematic .call(options.options, of(new HostTree(this._host)), { logger: context.logger }) .pipe( concatMap((tree: Tree) => { // Process all sinks. return concat( from(sinks).pipe( concatMap((sink) => sink.commit(tree)), ignoreElements(), ), of(tree), ); }), concatMap(() => { if (this._dryRun) { return EMPTY; } this._lifeCycle.next({ kind: 'post-tasks-start' }); return this._engine .executePostTasks() .pipe( tap({ complete: () => this._lifeCycle.next({ kind: 'post-tasks-end' }) }), defaultIfEmpty(undefined), last(), ); }), tap({ complete: () => { this._lifeCycle.next({ kind: 'workflow-end' }); this._context.pop(); if (this._context.length == 0) { this._lifeCycle.next({ kind: 'end' }); } }, }), ); } }
{ "end_byte": 6310, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/workflow/base.ts" }
angular-cli/packages/angular_devkit/schematics/src/workflow/interface.ts_0_1135
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { logging } from '@angular-devkit/core'; import { Observable } from 'rxjs'; export interface RequiredWorkflowExecutionContext { collection: string; schematic: string; options: object; } export interface WorkflowExecutionContext extends RequiredWorkflowExecutionContext { debug: boolean; logger: logging.Logger; parentContext?: Readonly<WorkflowExecutionContext>; allowPrivate?: boolean; } export interface LifeCycleEvent { kind: | 'start' | 'end' // Start and end of the full workflow execution. | 'workflow-start' | 'workflow-end' // Start and end of a workflow execution. Can be more. | 'post-tasks-start' | 'post-tasks-end'; // Start and end of the post tasks execution. } export interface Workflow { readonly context: Readonly<WorkflowExecutionContext>; execute( options: Partial<WorkflowExecutionContext> & RequiredWorkflowExecutionContext, ): Observable<void>; }
{ "end_byte": 1135, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/workflow/interface.ts" }
angular-cli/packages/angular_devkit/schematics/src/workflow/index.ts_0_257
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './base'; export * from './interface';
{ "end_byte": 257, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/workflow/index.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/schematic.ts_0_2321
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { last, map, of as observableOf } from 'rxjs'; import { ExecutionOptions, Rule, SchematicContext } from '../engine/interface'; import { MergeStrategy, Tree } from '../tree/interface'; import { branch } from '../tree/static'; /** * Run a schematic from a separate collection. * * @param collectionName The name of the collection that contains the schematic to run. * @param schematicName The name of the schematic to run. * @param options The options to pass as input to the RuleFactory. */ export function externalSchematic<OptionT extends object>( collectionName: string, schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>, ): Rule { return (input: Tree, context: SchematicContext) => { const collection = context.engine.createCollection( collectionName, context.schematic.collection, ); const schematic = collection.createSchematic(schematicName); return schematic.call(options, observableOf(branch(input)), context, executionOptions).pipe( last(), map((x) => { input.merge(x, MergeStrategy.AllowOverwriteConflict); return input; }), ); }; } /** * Run a schematic from the same collection. * * @param schematicName The name of the schematic to run. * @param options The options to pass as input to the RuleFactory. */ export function schematic<OptionT extends object>( schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>, ): Rule { return (input: Tree, context: SchematicContext) => { const collection = context.schematic.collection; const schematic = collection.createSchematic(schematicName, true); return schematic.call(options, observableOf(branch(input)), context, executionOptions).pipe( last(), map((x) => { // We allow overwrite conflict here because they're the only merge conflict we particularly // don't want to deal with; the input tree might have an OVERWRITE which the sub input.merge(x, MergeStrategy.AllowOverwriteConflict); return input; }), ); }; }
{ "end_byte": 2321, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/schematic.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/base.ts_0_4910
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { Observable, concat, map, mapTo, toArray } from 'rxjs'; import { FileOperator, Rule, Source } from '../engine/interface'; import { SchematicsException } from '../exception/exception'; import { FilterHostTree, HostTree } from '../tree/host-tree'; import { FileEntry, FilePredicate, MergeStrategy, Tree } from '../tree/interface'; import { ScopedTree } from '../tree/scoped'; import { partition, empty as staticEmpty } from '../tree/static'; import { callRule, callSource } from './call'; /** * A Source that returns an tree as its single value. */ export function source(tree: Tree): Source { return () => tree; } /** * A source that returns an empty tree. */ export function empty(): Source { return () => staticEmpty(); } /** * Chain multiple rules into a single rule. */ export function chain(rules: Iterable<Rule> | AsyncIterable<Rule>): Rule { return async (initialTree, context) => { let intermediateTree: Observable<Tree> | undefined; if (Symbol.asyncIterator in rules) { for await (const rule of rules) { intermediateTree = callRule(rule, intermediateTree ?? initialTree, context); } } else { for (const rule of rules) { intermediateTree = callRule(rule, intermediateTree ?? initialTree, context); } } return () => intermediateTree; }; } /** * Apply multiple rules to a source, and returns the source transformed. */ export function apply(source: Source, rules: Rule[]): Source { return (context) => callRule(chain(rules), callSource(source, context), context); } /** * Merge an input tree with the source passed in. */ export function mergeWith(source: Source, strategy: MergeStrategy = MergeStrategy.Default): Rule { return (tree, context) => { return callSource(source, context).pipe( map((sourceTree) => tree.merge(sourceTree, strategy || context.strategy)), mapTo(tree), ); }; } export function noop(): Rule { return () => {}; } export function filter(predicate: FilePredicate<boolean>): Rule { return (tree: Tree) => { if (HostTree.isHostTree(tree)) { return new FilterHostTree(tree, predicate); } else { throw new SchematicsException('Tree type is not supported.'); } }; } export function asSource(rule: Rule): Source { return (context) => callRule(rule, staticEmpty(), context); } export function branchAndMerge(rule: Rule, strategy = MergeStrategy.Default): Rule { return (tree, context) => { return callRule(rule, tree.branch(), context).pipe( map((branch) => tree.merge(branch, strategy || context.strategy)), mapTo(tree), ); }; } export function when(predicate: FilePredicate<boolean>, operator: FileOperator): FileOperator { return (entry: FileEntry) => { if (predicate(entry.path, entry)) { return operator(entry); } else { return entry; } }; } export function partitionApplyMerge( predicate: FilePredicate<boolean>, ruleYes: Rule, ruleNo?: Rule, ): Rule { return (tree, context) => { const [yes, no] = partition(tree, predicate); return concat(callRule(ruleYes, yes, context), callRule(ruleNo || noop(), no, context)).pipe( toArray(), map(([yesTree, noTree]) => { yesTree.merge(noTree, context.strategy); return yesTree; }), ); }; } export function forEach(operator: FileOperator): Rule { return (tree: Tree) => { tree.visit((path, entry) => { if (!entry) { return; } const newEntry = operator(entry); if (newEntry === entry) { return; } if (newEntry === null) { tree.delete(path); return; } if (newEntry.path != path) { tree.rename(path, newEntry.path); } if (!newEntry.content.equals(entry.content)) { tree.overwrite(newEntry.path, newEntry.content); } }); }; } export function composeFileOperators(operators: FileOperator[]): FileOperator { return (entry: FileEntry) => { let current: FileEntry | null = entry; for (const op of operators) { current = op(current); if (current === null) { // Deleted, just return. return null; } } return current; }; } export function applyToSubtree(path: string, rules: Rule[]): Rule { return (tree, context) => { const scoped = new ScopedTree(tree, path); return callRule(chain(rules), scoped, context).pipe( map((result) => { if (result === scoped) { return tree; } else { throw new SchematicsException( 'Original tree must be returned from all rules when using "applyToSubtree".', ); } }), ); }; }
{ "end_byte": 4910, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/base.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/call.ts_0_2784
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException } from '@angular-devkit/core'; import { Observable, defaultIfEmpty, defer, isObservable, lastValueFrom, mergeMap } from 'rxjs'; import { Rule, SchematicContext, Source } from '../engine/interface'; import { Tree, TreeSymbol } from '../tree/interface'; function _getTypeOfResult(value?: {}): string { if (value === undefined) { return 'undefined'; } else if (value === null) { return 'null'; } else if (typeof value == 'function') { return `Function()`; } else if (typeof value != 'object') { return `${typeof value}(${JSON.stringify(value)})`; } else { if (Object.getPrototypeOf(value) == Object) { return `Object(${JSON.stringify(value)})`; } else if (value.constructor) { return `Instance of class ${value.constructor.name}`; } else { return 'Unknown Object'; } } } /** * When a rule or source returns an invalid value. */ export class InvalidRuleResultException extends BaseException { constructor(value?: {}) { super(`Invalid rule result: ${_getTypeOfResult(value)}.`); } } export class InvalidSourceResultException extends BaseException { constructor(value?: {}) { super(`Invalid source result: ${_getTypeOfResult(value)}.`); } } export function callSource(source: Source, context: SchematicContext): Observable<Tree> { return defer(async () => { let result: Tree | Observable<Tree> | undefined = source(context); if (isObservable(result)) { result = await lastValueFrom(result.pipe(defaultIfEmpty(undefined))); } if (result && TreeSymbol in result) { return result; } throw new InvalidSourceResultException(result); }); } export function callRule( rule: Rule, input: Tree | Observable<Tree>, context: SchematicContext, ): Observable<Tree> { if (isObservable(input)) { return input.pipe(mergeMap((inputTree) => callRuleAsync(rule, inputTree, context))); } else { return defer(() => callRuleAsync(rule, input, context)); } } async function callRuleAsync(rule: Rule, tree: Tree, context: SchematicContext): Promise<Tree> { let result = await rule(tree, context); while (typeof result === 'function') { // This is considered a Rule, chain the rule and return its output. result = await result(tree, context); } if (typeof result === 'undefined') { return tree; } if (isObservable(result)) { result = await lastValueFrom(result.pipe(defaultIfEmpty(tree))); } if (result && TreeSymbol in result) { return result; } throw new InvalidRuleResultException(result); }
{ "end_byte": 2784, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/call.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/move.ts_0_908
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { join, normalize } from '@angular-devkit/core'; import { Rule } from '../engine/interface'; import { noop } from './base'; export function move(from: string, to?: string): Rule { if (to === undefined) { to = from; from = '/'; } const fromPath = normalize('/' + from); const toPath = normalize('/' + to); if (fromPath === toPath) { return noop; } return (tree) => { if (tree.exists(fromPath)) { // fromPath is a file tree.rename(fromPath, toPath); } else { // fromPath is a directory tree.getDir(fromPath).visit((path) => { tree.rename(path, join(toPath, path.slice(fromPath.length))); }); } return tree; }; }
{ "end_byte": 908, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/move.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/template.ts_0_5951
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException, normalize, template as templateImpl } from '@angular-devkit/core'; import { EOL } from 'node:os'; import { FileOperator, Rule } from '../engine/interface'; import { FileEntry } from '../tree/interface'; import { chain, composeFileOperators, forEach, when } from './base'; export const TEMPLATE_FILENAME_RE = /\.template$/; export class OptionIsNotDefinedException extends BaseException { constructor(name: string) { super(`Option "${name}" is not defined.`); } } export class UnknownPipeException extends BaseException { constructor(name: string) { super(`Pipe "${name}" is not defined.`); } } export class InvalidPipeException extends BaseException { constructor(name: string) { super(`Pipe "${name}" is invalid.`); } } export type PathTemplateValue = boolean | string | number | undefined; export type PathTemplatePipeFunction = (x: string) => PathTemplateValue; export type PathTemplateData = { [key: string]: PathTemplateValue | PathTemplateData | PathTemplatePipeFunction; }; export interface PathTemplateOptions { // Interpolation start and end strings. interpolationStart: string; // Interpolation start and end strings. interpolationEnd: string; // Separator for pipes. Do not specify to remove pipe support. pipeSeparator?: string; } const decoder = new TextDecoder('utf-8', { fatal: true }); export function applyContentTemplate<T>(options: T): FileOperator { return (entry: FileEntry) => { const { path, content } = entry; try { const decodedContent = decoder.decode(content).replace(/\r?\n/g, EOL); return { path, content: Buffer.from(templateImpl(decodedContent, {})(options)), }; } catch (e) { // The second part should not be needed. But Jest does not support instanceof correctly. // See: https://github.com/jestjs/jest/issues/2549 if ( e instanceof TypeError || (e as NodeJS.ErrnoException).code === 'ERR_ENCODING_INVALID_ENCODED_DATA' ) { return entry; } throw e; } }; } export function contentTemplate<T>(options: T): Rule { return forEach(applyContentTemplate(options)); } export function applyPathTemplate<T extends PathTemplateData>( data: T, options: PathTemplateOptions = { interpolationStart: '__', interpolationEnd: '__', pipeSeparator: '@', }, ): FileOperator { const is = options.interpolationStart; const ie = options.interpolationEnd; const isL = is.length; const ieL = ie.length; return (entry: FileEntry) => { let path = entry.path as string; const content = entry.content; const original = path; let start = path.indexOf(is); // + 1 to have at least a length 1 name. `____` is not valid. let end = path.indexOf(ie, start + isL + 1); while (start != -1 && end != -1) { const match = path.substring(start + isL, end); let replacement = data[match]; if (!options.pipeSeparator) { if (typeof replacement == 'function') { replacement = replacement.call(data, original); } if (replacement === undefined) { throw new OptionIsNotDefinedException(match); } } else { const [name, ...pipes] = match.split(options.pipeSeparator); replacement = data[name]; if (typeof replacement == 'function') { replacement = replacement.call(data, original); } if (replacement === undefined) { throw new OptionIsNotDefinedException(name); } replacement = pipes.reduce((acc: string, pipe: string) => { if (!pipe) { return acc; } if (!(pipe in data)) { throw new UnknownPipeException(pipe); } const pipeFn = data[pipe]; if (typeof pipeFn != 'function') { throw new InvalidPipeException(pipe); } // Coerce to string. return '' + pipeFn(acc); }, '' + replacement); } path = path.substring(0, start) + replacement + path.substring(end + ieL); start = path.indexOf(options.interpolationStart); // See above. end = path.indexOf(options.interpolationEnd, start + isL + 1); } return { path: normalize(path), content }; }; } export function pathTemplate<T extends PathTemplateData>(options: T): Rule { return forEach(applyPathTemplate(options)); } /** * Remove every `.template` suffix from file names. */ export function renameTemplateFiles(): Rule { return forEach((entry) => { if (entry.path.match(TEMPLATE_FILENAME_RE)) { return { content: entry.content, path: normalize(entry.path.replace(TEMPLATE_FILENAME_RE, '')), }; } else { return entry; } }); } export function template<T extends object>(options: T): Rule { return chain([ contentTemplate(options), // Force cast to PathTemplateData. We need the type for the actual pathTemplate() call, // but in this case we cannot do anything as contentTemplate are more permissive. // Since values are coerced to strings in PathTemplates it will be fine in the end. pathTemplate(options as {} as PathTemplateData), ]); } export function applyTemplates<T extends object>(options: T): Rule { return forEach( when( (path) => path.endsWith('.template'), composeFileOperators([ applyContentTemplate(options), // See above for this weird cast. applyPathTemplate(options as {} as PathTemplateData), (entry) => { return { content: entry.content, path: entry.path.replace(TEMPLATE_FILENAME_RE, ''), } as FileEntry; }, ]), ), ); }
{ "end_byte": 5951, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/template.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/call_spec.ts_0_3892
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { MergeStrategy } from '@angular-devkit/schematics'; import { of as observableOf } from 'rxjs'; import { Rule, SchematicContext, Source } from '../engine/interface'; import { Tree } from '../tree/interface'; import { empty } from '../tree/static'; import { InvalidRuleResultException, InvalidSourceResultException, callRule, callSource, } from './call'; const context: SchematicContext = { engine: null, debug: false, strategy: MergeStrategy.Default, } as {} as SchematicContext; describe('callSource', () => { it('errors if undefined source', (done) => { const source0: any = () => undefined; callSource(source0, context) .toPromise() .then( () => done.fail(), (err) => { expect(err).toEqual(new InvalidSourceResultException()); }, ) .then(done, done.fail); }); it('errors if invalid source object', (done) => { const source0: Source = () => ({}) as Tree; callSource(source0, context) .toPromise() .then( () => done.fail(), (err) => { expect(err).toEqual(new InvalidSourceResultException({})); }, ) .then(done, done.fail); }); it('errors if Observable of invalid source object', (done) => { const source0: Source = () => observableOf({} as Tree); callSource(source0, context) .toPromise() .then( () => done.fail(), (err) => { expect(err).toEqual(new InvalidSourceResultException({})); }, ) .then(done, done.fail); }); it('works with a Tree', (done) => { const tree0 = empty(); const source0: Source = () => tree0; callSource(source0, context) .toPromise() .then((tree) => { expect(tree).toBe(tree0); }) .then(done, done.fail); }); it('works with an Observable', (done) => { const tree0 = empty(); const source0: Source = () => observableOf(tree0); callSource(source0, context) .toPromise() .then((tree) => { expect(tree).toBe(tree0); }) .then(done, done.fail); }); }); describe('callRule', () => { it('should throw InvalidRuleResultException when rule result is non-Tree object', async () => { const rule0: Rule = () => ({}) as Tree; await expectAsync(callRule(rule0, empty(), context).toPromise()).toBeRejectedWithError( InvalidRuleResultException, ); }); it('should throw InvalidRuleResultException when rule result is null', async () => { const rule0: Rule = () => null as unknown as Tree; await expectAsync(callRule(rule0, empty(), context).toPromise()).toBeRejectedWithError( InvalidRuleResultException, ); }); it('works with undefined result', (done) => { const tree0 = empty(); const rule0: Rule = () => undefined; callRule(rule0, observableOf(tree0), context) .toPromise() .then((tree) => { expect(tree).toBe(tree0); }) .then(done, done.fail); }); it('works with a Tree', (done) => { const tree0 = empty(); const rule0: Rule = () => tree0; callRule(rule0, observableOf(tree0), context) .toPromise() .then((tree) => { expect(tree).toBe(tree0); }) .then(done, done.fail); }); it('works with an Observable', (done) => { const tree0 = empty(); const rule0: Rule = () => observableOf(tree0); callRule(rule0, observableOf(tree0), context) .toPromise() .then((tree) => { expect(tree).toBe(tree0); }) .then(done, done.fail); }); });
{ "end_byte": 3892, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/call_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/url.ts_0_481
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { parse } from 'url'; import { SchematicContext, Source } from '../engine/interface'; export function url(urlString: string): Source { const url = parse(urlString); return (context: SchematicContext) => context.engine.createSourceFromUrl(url, context)(context); }
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/url.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/random.ts_0_1345
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { Source } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; function generateStringOfLength(l: number) { return new Array(l) .fill(0) .map((_x) => { return 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)]; }) .join(''); } function random(from: number, to: number) { return Math.floor(Math.random() * (to - from)) + from; } export interface RandomOptions { root?: string; multi?: boolean | number; multiFiles?: boolean | number; } export default function (options: RandomOptions): Source { return () => { const root = 'root' in options ? options.root : '/'; const map = new HostTree(); const nbFiles = 'multiFiles' in options ? typeof options.multiFiles == 'number' ? options.multiFiles : random(2, 12) : 1; for (let i = 0; i < nbFiles; i++) { const path = 'a/b/c/d/e/f'.slice(Math.random() * 10); const fileName = generateStringOfLength(20); const content = generateStringOfLength(100); map.create(root + '/' + path + '/' + fileName, content); } return map; }; }
{ "end_byte": 1345, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/random.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/move_spec.ts_0_3406
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { lastValueFrom, of as observableOf } from 'rxjs'; import { SchematicContext } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; import { callRule } from './call'; import { move } from './move'; const context: SchematicContext = null!; describe('move', () => { it('works on moving the whole structure', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(move('sub'), observableOf(tree), context)) .then((result) => { expect(result.exists('sub/a/b/file1')).toBe(true); expect(result.exists('sub/a/b/file2')).toBe(true); expect(result.exists('sub/a/c/file3')).toBe(true); }) .then(done, done.fail); }); it('works on moving a subdirectory structure', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(move('a/b', 'sub'), observableOf(tree), context)) .then((result) => { expect(result.exists('sub/file1')).toBe(true); expect(result.exists('sub/file2')).toBe(true); expect(result.exists('a/c/file3')).toBe(true); }) .then(done, done.fail); }); it('works on moving a directory into a subdirectory of itself', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(move('a/b', 'a/b/c'), observableOf(tree), context)) .then((result) => { expect(result.exists('a/b/c/file1')).toBe(true); expect(result.exists('a/b/c/file2')).toBe(true); expect(result.exists('a/c/file3')).toBe(true); }) .then(done, done.fail); }); it('works on moving a directory into a parent of itself', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(move('a/b', 'a'), observableOf(tree), context)) .then((result) => { expect(result.exists('file1')).toBe(false); expect(result.exists('file2')).toBe(false); expect(result.exists('a/file1')).toBe(true); expect(result.exists('a/file2')).toBe(true); expect(result.exists('a/c/file3')).toBe(true); }) .then(done, done.fail); }); it('becomes a noop with identical from and to', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(move(''), observableOf(tree), context)) .then((result) => { expect(result.exists('a/b/file1')).toBe(true); expect(result.exists('a/b/file2')).toBe(true); expect(result.exists('a/c/file3')).toBe(true); }) .then(done, done.fail); }); });
{ "end_byte": 3406, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/move_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/template_spec.ts_0_5882
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable import/no-extraneous-dependencies */ import { normalize } from '@angular-devkit/core'; import { UnitTestTree } from '@angular-devkit/schematics/testing'; import { of as observableOf } from 'rxjs'; import { SchematicContext } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; import { FileEntry, MergeStrategy } from '../tree/interface'; import { callRule } from './call'; import { InvalidPipeException, OptionIsNotDefinedException, UnknownPipeException, applyContentTemplate, applyPathTemplate, applyTemplates, } from './template'; function _entry(path?: string, content?: string): FileEntry { if (!path) { path = 'a/b/c'; } if (!content) { content = 'hello world'; } return { path: normalize(path), content: Buffer.from(content), }; } describe('applyPathTemplate', () => { function _applyPathTemplate(path: string, options: {}): string | null { const newEntry = applyPathTemplate(options)(_entry(path)); if (newEntry) { return newEntry.path; } else { return null; } } it('works', () => { expect(_applyPathTemplate('/a/b/c/d', {})).toBe('/a/b/c/d'); expect(_applyPathTemplate('/a/b/__c__/d', { c: 1 })).toBe('/a/b/1/d'); expect(_applyPathTemplate('/a/b/__c__/d', { c: 'hello/world' })).toBe('/a/b/hello/world/d'); expect(_applyPathTemplate('/a__c__b', { c: 'hello/world' })).toBe('/ahello/worldb'); expect(_applyPathTemplate('/a__c__b__d__c', { c: '1', d: '2' })).toBe('/a1b2c'); }); it('works with single _', () => { expect(_applyPathTemplate('/a_b_c/d__e_f__g', { e_f: 1 })).toBe('/a_b_c/d1g'); }); it('works with complex _________...', () => { expect( _applyPathTemplate('/_____' + 'a' + '___a__' + '_/' + '__a___/__b___', { _a: 0, a: 1, b: 2, _: '.', }), ).toBe('/.a0_/1_/2_'); expect(_applyPathTemplate('_____' + '_____' + '_____' + '___', { _: '.' })).toBe('...___'); }); it('works with functions', () => { let arg = ''; expect( _applyPathTemplate('/a__c__b', { c: (x: string) => { arg = x; return 'hello'; }, }), ).toBe('/ahellob'); expect(arg).toBe('/a__c__b'); }); it('works with pipes', () => { let called = ''; let called2 = ''; expect( _applyPathTemplate('/a__c@d__b', { c: 1, d: (x: string) => ((called = x), 2), }), ).toBe('/a2b'); expect(called).toBe('1'); expect( _applyPathTemplate('/a__c@d@e__b', { c: 10, d: (x: string) => ((called = x), 20), e: (x: string) => ((called2 = x), 30), }), ).toBe('/a30b'); expect(called).toBe('10'); expect(called2).toBe('20'); }); it('errors out on undefined values', () => { expect(() => _applyPathTemplate('/a__b__c', {})).toThrow(new OptionIsNotDefinedException('b')); }); it('errors out on undefined or invalid pipes', () => { expect(() => _applyPathTemplate('/a__b@d__c', { b: 1 })).toThrow(new UnknownPipeException('d')); expect(() => _applyPathTemplate('/a__b@d__c', { b: 1, d: 1 })).toThrow( new InvalidPipeException('d'), ); }); }); describe('contentTemplate', () => { function _applyContentTemplate(content: string, options: {}) { const newEntry = applyContentTemplate(options)(_entry('', content)); if (newEntry) { return newEntry.content.toString('utf-8'); } else { return null; } } it('works with echo token <%= ... %>', () => { expect(_applyContentTemplate('a<%= value %>b', { value: 123 })).toBe('a123b'); }); it('works with if', () => { expect( _applyContentTemplate('a<% if (a) { %>b<% } %>c', { value: 123, a: true, }), ).toBe('abc'); expect( _applyContentTemplate('a<% if (a) { %>b<% } %>c', { value: 123, a: false, }), ).toBe('ac'); }); it('works with for', () => { expect( _applyContentTemplate('a<% for (let i = 0; i < value; i++) { %>1<% } %>b', { value: 5, }), ).toBe('a11111b'); }); it('escapes HTML', () => { expect( _applyContentTemplate('a<%- html %>b', { html: '<script>', }), ).toBe('a&lt;script&gt;b'); }); it('escapes strings properly', () => { expect(_applyContentTemplate('a<%= value %>b', { value: `'abc'` })).toBe("a'abc'b"); expect(_applyContentTemplate('a<%= \'a\' + "b" %>b', {})).toBe('aabb'); expect(_applyContentTemplate('a<%= "\\n" + "b" %>b', {})).toBe('a\nbb'); }); }); describe('applyTemplateFiles', () => { it('works with template files exclusively', (done) => { const tree = new UnitTestTree(new HostTree()); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/b/file3.template', 'hello <%= 1 %> world'); tree.create('a/b/file__a__.template', 'hello <%= 1 %> world'); tree.create('a/b/file__norename__', 'hello <%= 1 %> world'); tree.create('a/c/file4', 'hello world'); const context: SchematicContext = { strategy: MergeStrategy.Default, } as SchematicContext; // Rename all files that contain 'b' to 'hello'. callRule(applyTemplates({ a: 'foo' }), observableOf(tree), context) .toPromise() .then(() => { expect([...tree.files].sort()).toEqual([ '/a/b/file1', '/a/b/file2', '/a/b/file3', '/a/b/file__norename__', '/a/b/filefoo', '/a/c/file4', ]); expect(tree.readContent('/a/b/file3')).toBe('hello 1 world'); }) .then(done, done.fail); }); });
{ "end_byte": 5882, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/template_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/rules/base_spec.ts_0_7312
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { Path, virtualFs } from '@angular-devkit/core'; import { HostTree, MergeStrategy, partitionApplyMerge } from '@angular-devkit/schematics'; import { lastValueFrom, of as observableOf } from 'rxjs'; import { Rule, SchematicContext, Source } from '../engine/interface'; import { Tree } from '../tree/interface'; import { empty } from '../tree/static'; import { apply, applyToSubtree, chain } from './base'; import { callRule, callSource } from './call'; import { move } from './move'; const context: SchematicContext = { engine: null, debug: false, strategy: MergeStrategy.Default, } as {} as SchematicContext; describe('chain', () => { it('works with simple rules', (done) => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); lastValueFrom(callRule(chain([rule0, rule1, rule2]), observableOf(tree0), context)) .then((result) => { expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }) .then(done, done.fail); }); it('works with a sync generator of rules', async () => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); function* generateRules() { yield rule0; yield rule1; yield rule2; } const result = await lastValueFrom(callRule(chain(generateRules()), tree0, context)); expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }); it('works with an async generator of rules', async () => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); async function* generateRules() { yield rule0; yield rule1; yield rule2; } const result = await lastValueFrom(callRule(chain(generateRules()), tree0, context)); expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }); it('works with observable rules', (done) => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), observableOf(tree1)); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), observableOf(tree2)); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); lastValueFrom(callRule(chain([rule0, rule1, rule2]), observableOf(tree0), context)) .then((result) => { expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }) .then(done, done.fail); }); }); describe('apply', () => { it('works with simple rules', (done) => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const source: Source = () => tree0; const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); lastValueFrom(callSource(apply(source, [rule0, rule1, rule2]), context)) .then((result) => { expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }) .then(done, done.fail); }); it('works with observable rules', (done) => { const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); const source: Source = () => tree0; const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), observableOf(tree1)); const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), observableOf(tree2)); const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); lastValueFrom(callSource(apply(source, [rule0, rule1, rule2]), context)) .then((result) => { expect(result).not.toBe(tree0); expect(rulesCalled[0]).toBe(tree0); expect(rulesCalled[1]).toBe(tree1); expect(rulesCalled[2]).toBe(tree2); expect(result).toBe(tree3); }) .then(done, done.fail); }); }); describe('partitionApplyMerge', () => { it('works with simple rules', (done) => { const host = new virtualFs.test.TestHost({ '/test1': '', '/test2': '', }); const tree = new HostTree(host); const predicate = (path: Path) => path.indexOf('1') != -1; const ruleYes: Rule = (tree: Tree) => { expect(tree.exists('/test1')).toBe(true); expect(tree.exists('/test2')).toBe(false); return empty(); }; const ruleNo: Rule = (tree: Tree) => { expect(tree.exists('/test1')).toBe(false); expect(tree.exists('/test2')).toBe(true); return empty(); }; lastValueFrom( callRule(partitionApplyMerge(predicate, ruleYes, ruleNo), observableOf(tree), context), ) .then((result) => { expect(result.exists('/test1')).toBe(false); expect(result.exists('/test2')).toBe(false); }) .then(done, done.fail); }); }); describe('applyToSubtree', () => { it('works', (done) => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); lastValueFrom(callRule(applyToSubtree('a/b', [move('x')]), observableOf(tree), context)) .then((result) => { expect(result.exists('a/b/x/file1')).toBe(true); expect(result.exists('a/b/x/file2')).toBe(true); expect(result.exists('a/c/file3')).toBe(true); }) .then(done, done.fail); }); });
{ "end_byte": 7312, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/rules/base_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/schematic.ts_0_2592
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException } from '@angular-devkit/core'; import { Observable, concatMap, first, map } from 'rxjs'; import { callRule } from '../rules/call'; import { Tree } from '../tree/interface'; import { ScopedTree } from '../tree/scoped'; import { Collection, Engine, ExecutionOptions, RuleFactory, Schematic, SchematicDescription, TypedSchematicContext, } from './interface'; export class InvalidSchematicsNameException extends BaseException { constructor(name: string) { super(`Schematics has invalid name: "${name}".`); } } export class SchematicImpl<CollectionT extends object, SchematicT extends object> implements Schematic<CollectionT, SchematicT> { constructor( private _description: SchematicDescription<CollectionT, SchematicT>, private _factory: RuleFactory<{}>, private _collection: Collection<CollectionT, SchematicT>, private _engine: Engine<CollectionT, SchematicT>, ) { if (!_description.name.match(/^[-@/_.a-zA-Z0-9]+$/)) { throw new InvalidSchematicsNameException(_description.name); } } get description() { return this._description; } get collection() { return this._collection; } call<OptionT extends object>( options: OptionT, host: Observable<Tree>, parentContext?: Partial<TypedSchematicContext<CollectionT, SchematicT>>, executionOptions?: Partial<ExecutionOptions>, ): Observable<Tree> { const context = this._engine.createContext(this, parentContext, executionOptions); return host.pipe( first(), concatMap((tree) => this._engine .transformOptions(this, options, context) .pipe(map((o) => [tree, o] as [Tree, OptionT])), ), concatMap(([tree, transformedOptions]) => { let input: Tree; let scoped = false; if (executionOptions && executionOptions.scope) { scoped = true; input = new ScopedTree(tree, executionOptions.scope); } else { input = tree; } return callRule(this._factory(transformedOptions), input, context).pipe( map((output) => { if (output === input) { return tree; } else if (scoped) { tree.merge(output); return tree; } else { return output; } }), ); }), ); } }
{ "end_byte": 2592, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/schematic.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/schematic_spec.ts_0_4532
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { logging } from '@angular-devkit/core'; import { lastValueFrom, of as observableOf } from 'rxjs'; import { chain } from '../rules/base'; import { MergeStrategy, Tree } from '../tree/interface'; import { branch, empty } from '../tree/static'; import { CollectionDescription, Engine, Rule, Schematic, SchematicDescription } from './interface'; import { SchematicImpl } from './schematic'; type CollectionT = { description: string; }; type SchematicT = { collection: CollectionT; description: string; path: string; factory: <T>(options: T) => Rule; }; const context = { debug: false, logger: new logging.NullLogger(), strategy: MergeStrategy.Default, }; const engine: Engine<CollectionT, SchematicT> = { createContext: (schematic: Schematic<{}, {}>) => ({ engine, schematic, ...context }), transformOptions: (_: {}, options: {}) => observableOf(options), defaultMergeStrategy: MergeStrategy.Default, } as {} as Engine<CollectionT, SchematicT>; const collection = { name: 'collection', description: 'description', } as CollectionDescription<CollectionT>; function files(tree: Tree) { const files: string[] = []; tree.visit((x) => files.push(x)); return files; } describe('Schematic', () => { it('works with a rule', (done) => { let inner: Tree | null = null; const desc: SchematicDescription<CollectionT, SchematicT> = { collection, name: 'test', description: '', path: '/a/b/c', factory: () => (tree: Tree) => { inner = branch(tree); tree.create('a/b/c', 'some content'); return tree; }, }; const schematic = new SchematicImpl(desc, desc.factory, null!, engine); lastValueFrom(schematic.call({}, observableOf(empty()))) .then((x) => { expect(files(inner!)).toEqual([]); expect(files(x)).toEqual(['/a/b/c']); }) .then(done, done.fail); }); it('works with a rule that returns an observable', (done) => { let inner: Tree | null = null; const desc: SchematicDescription<CollectionT, SchematicT> = { collection, name: 'test', description: '', path: 'a/b/c', factory: () => (fem: Tree) => { inner = fem; return observableOf(empty()); }, }; const schematic = new SchematicImpl(desc, desc.factory, null!, engine); lastValueFrom(schematic.call({}, observableOf(empty()))) .then((x) => { expect(files(inner!)).toEqual([]); expect(files(x)).toEqual([]); expect(inner).not.toBe(x); }) .then(done, done.fail); }); it('works with nested chained function rules', (done) => { let chainCount = 0; let oneCount = 0; let twoCount = 0; let threeCount = 0; const one = () => { return chain([ () => { oneCount++; }, ]); }; const two = () => { return chain([ () => { twoCount++; }, ]); }; const three = () => { threeCount++; }; const desc: SchematicDescription<CollectionT, SchematicT> = { collection, name: 'test', description: '', path: '/a/b/c', factory: () => { return chain([ () => { chainCount++; }, one, two, three, ]); }, }; const schematic = new SchematicImpl(desc, desc.factory, null!, engine); lastValueFrom(schematic.call({}, observableOf(empty()))) .then((_x) => { expect(chainCount).toBe(1); expect(oneCount).toBe(1); expect(twoCount).toBe(1); expect(threeCount).toBe(1); }) .then(done, done.fail); }); it('can be called with a scope', (done) => { const desc: SchematicDescription<CollectionT, SchematicT> = { collection, name: 'test', description: '', path: '/a/b/c', factory: () => (tree: Tree) => { tree.create('a/b/c', 'some content'); }, }; const schematic = new SchematicImpl(desc, desc.factory, null!, engine); lastValueFrom(schematic.call({}, observableOf(empty()), {}, { scope: 'base' })) .then((x) => { expect(files(x)).toEqual(['/base/a/b/c']); }) .then(done, done.fail); }); });
{ "end_byte": 4532, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/schematic_spec.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/engine.ts_0_4670
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException, PriorityQueue, logging } from '@angular-devkit/core'; import { Observable, concatMap, from as observableFrom } from 'rxjs'; import { Url } from 'url'; import { MergeStrategy } from '../tree/interface'; import { NullTree } from '../tree/null'; import { empty } from '../tree/static'; import { Workflow } from '../workflow/interface'; import { Collection, CollectionDescription, Engine, EngineHost, ExecutionOptions, Schematic, SchematicContext, SchematicDescription, Source, TaskConfiguration, TaskConfigurationGenerator, TaskExecutor, TaskId, TaskInfo, TypedSchematicContext, } from './interface'; import { SchematicImpl } from './schematic'; export class UnknownUrlSourceProtocol extends BaseException { constructor(url: string) { super(`Unknown Protocol on url "${url}".`); } } export class UnknownCollectionException extends BaseException { constructor(name: string) { super(`Unknown collection "${name}".`); } } export class CircularCollectionException extends BaseException { constructor(name: string) { super(`Circular collection reference "${name}".`); } } export class UnknownSchematicException extends BaseException { constructor(name: string, collection: CollectionDescription<{}>) { super(`Schematic "${name}" not found in collection "${collection.name}".`); } } export class PrivateSchematicException extends BaseException { constructor(name: string, collection: CollectionDescription<{}>) { super(`Schematic "${name}" not found in collection "${collection.name}".`); } } export class SchematicEngineConflictingException extends BaseException { constructor() { super(`A schematic was called from a different engine as its parent.`); } } export class UnregisteredTaskException extends BaseException { constructor(name: string, schematic?: SchematicDescription<{}, {}>) { const addendum = schematic ? ` in schematic "${schematic.name}"` : ''; super(`Unregistered task "${name}"${addendum}.`); } } export class UnknownTaskDependencyException extends BaseException { constructor(id: TaskId) { super(`Unknown task dependency [ID: ${id.id}].`); } } export class CollectionImpl<CollectionT extends object, SchematicT extends object> implements Collection<CollectionT, SchematicT> { constructor( private _description: CollectionDescription<CollectionT>, private _engine: SchematicEngine<CollectionT, SchematicT>, public readonly baseDescriptions?: Array<CollectionDescription<CollectionT>>, ) {} get description() { return this._description; } get name() { return this.description.name || '<unknown>'; } createSchematic(name: string, allowPrivate = false): Schematic<CollectionT, SchematicT> { return this._engine.createSchematic(name, this, allowPrivate); } listSchematicNames(includeHidden?: boolean): string[] { return this._engine.listSchematicNames(this, includeHidden); } } export class TaskScheduler { private _queue = new PriorityQueue<TaskInfo>((x, y) => x.priority - y.priority); private _taskIds = new Map<TaskId, TaskInfo>(); private static _taskIdCounter = 1; constructor(private _context: SchematicContext) {} private _calculatePriority(dependencies: Set<TaskInfo>): number { if (dependencies.size === 0) { return 0; } const prio = [...dependencies].reduce((prio, task) => prio + task.priority, 1); return prio; } private _mapDependencies(dependencies?: Array<TaskId>): Set<TaskInfo> { if (!dependencies) { return new Set(); } const tasks = dependencies.map((dep) => { const task = this._taskIds.get(dep); if (!task) { throw new UnknownTaskDependencyException(dep); } return task; }); return new Set(tasks); } schedule<T extends object>(taskConfiguration: TaskConfiguration<T>): TaskId { const dependencies = this._mapDependencies(taskConfiguration.dependencies); const priority = this._calculatePriority(dependencies); const task = { id: TaskScheduler._taskIdCounter++, priority, configuration: taskConfiguration, context: this._context, }; this._queue.push(task); const id = { id: task.id }; this._taskIds.set(id, task); return id; } finalize(): ReadonlyArray<TaskInfo> { const tasks = this._queue.toArray(); this._queue.clear(); this._taskIds.clear(); return tasks; } }
{ "end_byte": 4670, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/engine.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/engine.ts_4672_12106
export class SchematicEngine<CollectionT extends object, SchematicT extends object> implements Engine<CollectionT, SchematicT> { private _collectionCache = new Map<string, CollectionImpl<CollectionT, SchematicT>>(); private _schematicCache = new WeakMap< Collection<CollectionT, SchematicT>, Map<string, SchematicImpl<CollectionT, SchematicT>> >(); private _taskSchedulers = new Array<TaskScheduler>(); constructor( private _host: EngineHost<CollectionT, SchematicT>, protected _workflow?: Workflow, ) {} get workflow() { return this._workflow || null; } get defaultMergeStrategy() { return this._host.defaultMergeStrategy || MergeStrategy.Default; } createCollection( name: string, requester?: Collection<CollectionT, SchematicT>, ): Collection<CollectionT, SchematicT> { let collection = this._collectionCache.get(name); if (collection) { return collection; } const [description, bases] = this._createCollectionDescription(name, requester?.description); collection = new CollectionImpl<CollectionT, SchematicT>(description, this, bases); this._collectionCache.set(name, collection); this._schematicCache.set(collection, new Map()); return collection; } private _createCollectionDescription( name: string, requester?: CollectionDescription<CollectionT>, parentNames?: Set<string>, ): [CollectionDescription<CollectionT>, Array<CollectionDescription<CollectionT>>] { const description = this._host.createCollectionDescription(name, requester); if (!description) { throw new UnknownCollectionException(name); } if (parentNames && parentNames.has(description.name)) { throw new CircularCollectionException(name); } const bases = new Array<CollectionDescription<CollectionT>>(); if (description.extends) { parentNames = (parentNames || new Set<string>()).add(description.name); for (const baseName of description.extends) { const [base, baseBases] = this._createCollectionDescription( baseName, description, new Set(parentNames), ); bases.unshift(base, ...baseBases); } } return [description, bases]; } createContext( schematic: Schematic<CollectionT, SchematicT>, parent?: Partial<TypedSchematicContext<CollectionT, SchematicT>>, executionOptions?: Partial<ExecutionOptions>, ): TypedSchematicContext<CollectionT, SchematicT> { // Check for inconsistencies. if (parent && parent.engine && parent.engine !== this) { throw new SchematicEngineConflictingException(); } let interactive = true; if (executionOptions && executionOptions.interactive != undefined) { interactive = executionOptions.interactive; } else if (parent && parent.interactive != undefined) { interactive = parent.interactive; } let context: TypedSchematicContext<CollectionT, SchematicT> = { debug: (parent && parent.debug) || false, engine: this, logger: (parent && parent.logger && parent.logger.createChild(schematic.description.name)) || new logging.NullLogger(), schematic, strategy: parent && parent.strategy !== undefined ? parent.strategy : this.defaultMergeStrategy, interactive, addTask, }; const maybeNewContext = this._host.transformContext(context); if (maybeNewContext) { context = maybeNewContext; } const taskScheduler = new TaskScheduler(context); const host = this._host; this._taskSchedulers.push(taskScheduler); function addTask<T extends object>( task: TaskConfigurationGenerator<T>, dependencies?: Array<TaskId>, ): TaskId { const config = task.toConfiguration(); if (!host.hasTaskExecutor(config.name)) { throw new UnregisteredTaskException(config.name, schematic.description); } config.dependencies = config.dependencies || []; if (dependencies) { config.dependencies.unshift(...dependencies); } return taskScheduler.schedule(config); } return context; } createSchematic( name: string, collection: Collection<CollectionT, SchematicT>, allowPrivate = false, ): Schematic<CollectionT, SchematicT> { const schematicMap = this._schematicCache.get(collection); let schematic = schematicMap?.get(name); if (schematic) { return schematic; } let collectionDescription = collection.description; let description = this._host.createSchematicDescription(name, collection.description); if (!description) { if (collection.baseDescriptions) { for (const base of collection.baseDescriptions) { description = this._host.createSchematicDescription(name, base); if (description) { collectionDescription = base; break; } } } if (!description) { // Report the error for the top level schematic collection throw new UnknownSchematicException(name, collection.description); } } if (description.private && !allowPrivate) { throw new PrivateSchematicException(name, collection.description); } const factory = this._host.getSchematicRuleFactory(description, collectionDescription); schematic = new SchematicImpl<CollectionT, SchematicT>(description, factory, collection, this); schematicMap?.set(name, schematic); return schematic; } listSchematicNames( collection: Collection<CollectionT, SchematicT>, includeHidden?: boolean, ): string[] { const names = this._host.listSchematicNames(collection.description, includeHidden); if (collection.baseDescriptions) { for (const base of collection.baseDescriptions) { names.push(...this._host.listSchematicNames(base, includeHidden)); } } // remove duplicates return [...new Set(names)].sort(); } transformOptions<OptionT extends object, ResultT extends object>( schematic: Schematic<CollectionT, SchematicT>, options: OptionT, context?: TypedSchematicContext<CollectionT, SchematicT>, ): Observable<ResultT> { return this._host.transformOptions<OptionT, ResultT>(schematic.description, options, context); } createSourceFromUrl(url: Url, context: TypedSchematicContext<CollectionT, SchematicT>): Source { switch (url.protocol) { case 'null:': return () => new NullTree(); case 'empty:': return () => empty(); } const hostSource = this._host.createSourceFromUrl(url, context); if (!hostSource) { throw new UnknownUrlSourceProtocol(url.toString()); } return hostSource; } executePostTasks(): Observable<void> { const executors = new Map<string, TaskExecutor>(); const taskObservable = observableFrom(this._taskSchedulers).pipe( concatMap((scheduler) => scheduler.finalize()), concatMap((task) => { const { name, options } = task.configuration; const executor = executors.get(name); if (executor) { return executor(options, task.context); } return this._host.createTaskExecutor(name).pipe( concatMap((executor) => { executors.set(name, executor); return executor(options, task.context); }), ); }), ); return taskObservable; } }
{ "end_byte": 12106, "start_byte": 4672, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/engine.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/interface.ts_0_9126
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { logging } from '@angular-devkit/core'; import { Observable } from 'rxjs'; import { Url } from 'url'; import { FileEntry, MergeStrategy, Tree } from '../tree/interface'; import { Workflow } from '../workflow/interface'; export interface TaskConfiguration<T = {}> { name: string; dependencies?: Array<TaskId>; options?: T; } export interface TaskConfigurationGenerator<T = {}> { toConfiguration(): TaskConfiguration<T>; } export type TaskExecutor<T = {}> = ( options: T | undefined, context: SchematicContext, ) => Promise<void> | Observable<void>; export interface TaskExecutorFactory<T> { readonly name: string; create(options?: T): Promise<TaskExecutor> | Observable<TaskExecutor>; } export interface TaskId { readonly id: number; } export interface TaskInfo { readonly id: number; readonly priority: number; readonly configuration: TaskConfiguration; readonly context: SchematicContext; } export interface ExecutionOptions { scope: string; interactive: boolean; } /** * The description (metadata) of a collection. This type contains every information the engine * needs to run. The CollectionMetadataT type parameter contains additional metadata that you * want to store while remaining type-safe. */ export type CollectionDescription<CollectionMetadataT extends object> = CollectionMetadataT & { readonly name: string; readonly extends?: string[]; }; /** * The description (metadata) of a schematic. This type contains every information the engine * needs to run. The SchematicMetadataT and CollectionMetadataT type parameters contain additional * metadata that you want to store while remaining type-safe. */ export type SchematicDescription< CollectionMetadataT extends object, SchematicMetadataT extends object, > = SchematicMetadataT & { readonly collection: CollectionDescription<CollectionMetadataT>; readonly name: string; readonly private?: boolean; readonly hidden?: boolean; }; /** * The Host for the Engine. Specifically, the piece of the tooling responsible for resolving * collections and schematics descriptions. The SchematicMetadataT and CollectionMetadataT type * parameters contain additional metadata that you want to store while remaining type-safe. */ export interface EngineHost<CollectionMetadataT extends object, SchematicMetadataT extends object> { createCollectionDescription( name: string, requester?: CollectionDescription<CollectionMetadataT>, ): CollectionDescription<CollectionMetadataT>; listSchematicNames( collection: CollectionDescription<CollectionMetadataT>, includeHidden?: boolean, ): string[]; createSchematicDescription( name: string, collection: CollectionDescription<CollectionMetadataT>, ): SchematicDescription<CollectionMetadataT, SchematicMetadataT> | null; getSchematicRuleFactory<OptionT extends object>( schematic: SchematicDescription<CollectionMetadataT, SchematicMetadataT>, collection: CollectionDescription<CollectionMetadataT>, ): RuleFactory<OptionT>; createSourceFromUrl( url: Url, context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>, ): Source | null; transformOptions<OptionT extends object, ResultT extends object>( schematic: SchematicDescription<CollectionMetadataT, SchematicMetadataT>, options: OptionT, context?: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>, ): Observable<ResultT>; transformContext( context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>, ): TypedSchematicContext<CollectionMetadataT, SchematicMetadataT> | void; createTaskExecutor(name: string): Observable<TaskExecutor>; hasTaskExecutor(name: string): boolean; readonly defaultMergeStrategy?: MergeStrategy; } /** * The root Engine for creating and running schematics and collections. Everything related to * a schematic execution starts from this interface. * * CollectionMetadataT is, by default, a generic Collection metadata type. This is used throughout * the engine typings so that you can use a type that's merged into descriptions, while being * type-safe. * * SchematicMetadataT is a type that contains additional typing for the Schematic Description. */ export interface Engine<CollectionMetadataT extends object, SchematicMetadataT extends object> { createCollection( name: string, requester?: Collection<CollectionMetadataT, SchematicMetadataT>, ): Collection<CollectionMetadataT, SchematicMetadataT>; createContext( schematic: Schematic<CollectionMetadataT, SchematicMetadataT>, parent?: Partial<TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>>, executionOptions?: Partial<ExecutionOptions>, ): TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>; createSchematic( name: string, collection: Collection<CollectionMetadataT, SchematicMetadataT>, ): Schematic<CollectionMetadataT, SchematicMetadataT>; createSourceFromUrl( url: Url, context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>, ): Source; transformOptions<OptionT extends object, ResultT extends object>( schematic: Schematic<CollectionMetadataT, SchematicMetadataT>, options: OptionT, context?: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>, ): Observable<ResultT>; executePostTasks(): Observable<void>; readonly defaultMergeStrategy: MergeStrategy; readonly workflow: Workflow | null; } /** * A Collection as created by the Engine. This should be used by the tool to create schematics, * or by rules to create other schematics as well. */ export interface Collection<CollectionMetadataT extends object, SchematicMetadataT extends object> { readonly description: CollectionDescription<CollectionMetadataT>; readonly baseDescriptions?: Array<CollectionDescription<CollectionMetadataT>>; createSchematic( name: string, allowPrivate?: boolean, ): Schematic<CollectionMetadataT, SchematicMetadataT>; listSchematicNames(includeHidden?: boolean): string[]; } /** * A Schematic as created by the Engine. This should be used by the tool to execute the main * schematics, or by rules to execute other schematics as well. */ export interface Schematic<CollectionMetadataT extends object, SchematicMetadataT extends object> { readonly description: SchematicDescription<CollectionMetadataT, SchematicMetadataT>; readonly collection: Collection<CollectionMetadataT, SchematicMetadataT>; call<OptionT extends object>( options: OptionT, host: Observable<Tree>, parentContext?: Partial<TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>>, executionOptions?: Partial<ExecutionOptions>, ): Observable<Tree>; } /** * A SchematicContext. Contains information necessary for Schematics to execute some rules, for * example when using another schematics, as we need the engine and collection. */ export interface TypedSchematicContext< CollectionMetadataT extends object, SchematicMetadataT extends object, > { readonly debug: boolean; readonly engine: Engine<CollectionMetadataT, SchematicMetadataT>; readonly logger: logging.LoggerApi; readonly schematic: Schematic<CollectionMetadataT, SchematicMetadataT>; readonly strategy: MergeStrategy; readonly interactive: boolean; addTask<T extends object>( task: TaskConfigurationGenerator<T>, dependencies?: Array<TaskId>, ): TaskId; } /** * This is used by the Schematics implementations in order to avoid needing to have typing from * the tooling. Schematics are not specific to a tool. */ export type SchematicContext = TypedSchematicContext<{}, {}>; /** * A rule factory, which is normally the way schematics are implemented. Returned by the tooling * after loading a schematic description. */ export type RuleFactory<T extends object> = (options: T) => Rule; /** * A FileOperator applies changes synchronously to a FileEntry. An async operator returns * asynchronously. We separate them so that the type system can catch early errors. */ export type FileOperator = (entry: FileEntry) => FileEntry | null; export type AsyncFileOperator = (tree: FileEntry) => Observable<FileEntry | null>; /** * A source is a function that generates a Tree from a specific context. A rule transforms a tree * into another tree from a specific context. In both cases, an Observable can be returned if * the source or the rule are asynchronous. Only the last Tree generated in the observable will * be used though. * * We obfuscate the context of Source and Rule because the schematic implementation should not * know which types is the schematic or collection metadata, as they are both tooling specific. */ export type Source = (context: SchematicContext) => Tree | Observable<Tree>; export type Rule = ( tree: Tree, context: SchematicContext, ) => Tree | Observable<Tree> | Rule | Promise<void | Rule> | void;
{ "end_byte": 9126, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/interface.ts" }
angular-cli/packages/angular_devkit/schematics/src/engine/index.ts_0_288
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './engine'; export * from './interface'; export * from './schematic';
{ "end_byte": 288, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/engine/index.ts" }
angular-cli/packages/angular_devkit/schematics/src/exception/exception.ts_0_1411
/** * @license * Copyright Google LLC All Rights Reserved. * * Use 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 { BaseException } from '@angular-devkit/core'; // Used by schematics to throw exceptions. export class SchematicsException extends BaseException {} // Exceptions export class FileDoesNotExistException extends BaseException { constructor(path: string) { super(`Path "${path}" does not exist.`); } } export class FileAlreadyExistException extends BaseException { constructor(path: string) { super(`Path "${path}" already exist.`); } } export class ContentHasMutatedException extends BaseException { constructor(path: string) { super(`Content at path "${path}" has changed between the start and the end of an update.`); } } export class InvalidUpdateRecordException extends BaseException { constructor() { super(`Invalid record instance.`); } } export class MergeConflictException extends BaseException { constructor(path: string) { super(`A merge conflicted on path "${path}".`); } } export class UnsuccessfulWorkflowExecution extends BaseException { constructor() { super('Workflow did not execute successfully.'); } } export class UnimplementedException extends BaseException { constructor() { super('This function is unimplemented.'); } }
{ "end_byte": 1411, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/src/exception/exception.ts" }
angular-cli/goldens/BUILD.bazel_0_149
package(default_visibility = ["//visibility:public"]) filegroup( name = "public-api", srcs = glob([ "public-api/**/*.md", ]), )
{ "end_byte": 149, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/BUILD.bazel" }
angular-cli/goldens/public-api/manage.js_0_2058
const {exec} = require('shelljs'); const {Parser: parser} = require('yargs/helpers'); // Remove all command line flags from the arguments. const argv = parser(process.argv.slice(2)); // The command the user would like to run, either 'accept' or 'test' const USER_COMMAND = argv._[0]; // The shell command to query for all Public API guard tests. const BAZEL_PUBLIC_API_TARGET_QUERY_CMD = `yarn bazel query --output label 'kind(nodejs_test, ...) intersect attr("tags", "api_guard", ...)'` // Bazel targets for testing Public API goldens process.stdout.write('Gathering all Public API targets'); const ALL_PUBLIC_API_TESTS = exec(BAZEL_PUBLIC_API_TARGET_QUERY_CMD, {silent: true}) .trim() .split('\n') .map(test => test.trim()); process.stdout.clearLine(); process.stdout.cursorTo(0); // Bazel targets for generating Public API goldens const ALL_PUBLIC_API_ACCEPTS = ALL_PUBLIC_API_TESTS.map(test => `${test}.accept`); /** * Run the provided bazel commands on each provided target individually. */ function runBazelCommandOnTargets(command, targets, present) { for (const target of targets) { process.stdout.write(`${present}: ${target}`); const commandResult = exec(`yarn bazel ${command} ${target}`, {silent: true}); process.stdout.clearLine(); process.stdout.cursorTo(0); if (commandResult.code) { console.error(`Failed ${command}: ${target}`); console.group(); console.error(commandResult.stdout || commandResult.stderr); console.groupEnd(); } else { console.log(`Successful ${command}: ${target}`); } } } switch (USER_COMMAND) { case 'accept': runBazelCommandOnTargets('run', ALL_PUBLIC_API_ACCEPTS, 'Running'); break; case 'test': runBazelCommandOnTargets('test', ALL_PUBLIC_API_TESTS, 'Testing'); break; default: console.warn('Invalid command provided.'); console.warn(); console.warn(`Run this script with either "accept" and "test"`); break; }
{ "end_byte": 2058, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/manage.js" }
angular-cli/goldens/public-api/angular/ssr/index.api.md_0_1047
## API Report File for "@angular/ssr" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { EnvironmentProviders } from '@angular/core'; // @public export class AngularAppEngine { getPrerenderHeaders(request: Request): ReadonlyMap<string, string>; render(request: Request, requestContext?: unknown): Promise<Response | null>; static ɵhooks: Hooks; } // @public export function createRequestHandler(handler: RequestHandlerFunction): RequestHandlerFunction; // @public export enum PrerenderFallback { Client = 1, None = 2, Server = 0 } // @public export function provideServerRoutesConfig(routes: ServerRoute[]): EnvironmentProviders; // @public export enum RenderMode { AppShell = 0, Client = 2, Prerender = 3, Server = 1 } // @public export type ServerRoute = ServerRouteAppShell | ServerRouteClient | ServerRoutePrerender | ServerRoutePrerenderWithParams | ServerRouteServer; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 1047, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular/ssr/index.api.md" }
angular-cli/goldens/public-api/angular/ssr/index_transitive.api.md_0_1075
## API Report File for "@angular/devkit-repo" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts // @public export interface ServerRouteAppShell extends Omit<ServerRouteCommon, 'headers' | 'status'> { renderMode: RenderMode.AppShell; } // @public export interface ServerRouteClient extends ServerRouteCommon { renderMode: RenderMode.Client; } // @public export interface ServerRouteCommon { headers?: Record<string, string>; path: string; status?: number; } // @public export interface ServerRoutePrerender extends Omit<ServerRouteCommon, 'status'> { fallback?: never; renderMode: RenderMode.Prerender; } // @public export interface ServerRoutePrerenderWithParams extends Omit<ServerRoutePrerender, 'fallback'> { fallback?: PrerenderFallback; getPrerenderParams: () => Promise<Record<string, string>[]>; } // @public export interface ServerRouteServer extends ServerRouteCommon { renderMode: RenderMode.Server; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 1075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular/ssr/index_transitive.api.md" }
angular-cli/goldens/public-api/angular/ssr/node/index.api.md_0_1781
## API Report File for "@angular/ssr_node" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { ApplicationRef } from '@angular/core'; import type { IncomingMessage } from 'node:http'; import type { ServerResponse } from 'node:http'; import { StaticProvider } from '@angular/core'; import { Type } from '@angular/core'; // @public export class AngularNodeAppEngine { getPrerenderHeaders(request: IncomingMessage): ReadonlyMap<string, string>; render(request: IncomingMessage, requestContext?: unknown): Promise<Response | null>; } // @public export class CommonEngine { constructor(options?: CommonEngineOptions | undefined); render(opts: CommonEngineRenderOptions): Promise<string>; } // @public (undocumented) export interface CommonEngineOptions { bootstrap?: Type<{}> | (() => Promise<ApplicationRef>); enablePerformanceProfiler?: boolean; providers?: StaticProvider[]; } // @public (undocumented) export interface CommonEngineRenderOptions { bootstrap?: Type<{}> | (() => Promise<ApplicationRef>); // (undocumented) document?: string; // (undocumented) documentFilePath?: string; inlineCriticalCss?: boolean; providers?: StaticProvider[]; publicPath?: string; // (undocumented) url?: string; } // @public export function createNodeRequestHandler<T extends RequestHandlerFunction>(handler: T): T; // @public export function createWebRequestFromNodeRequest(nodeRequest: IncomingMessage): Request; // @public export function isMainModule(url: string): boolean; // @public export function writeResponseToNodeResponse(source: Response, destination: ServerResponse): Promise<void>; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 1781, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular/ssr/node/index.api.md" }
angular-cli/goldens/public-api/angular/ssr/tokens/index.api.md_0_457
## API Report File for "@angular/ssr_tokens" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { InjectionToken } from '@angular/core'; // @public export const REQUEST: InjectionToken<Request>; // @public export const REQUEST_CONTEXT: InjectionToken<unknown>; // @public export const RESPONSE_INIT: InjectionToken<ResponseInit>; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 457, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular/ssr/tokens/index.api.md" }
angular-cli/goldens/public-api/angular/build/index.api.md_0_4591
## API Report File for "@angular/build" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { BuilderContext } from '@angular-devkit/architect'; import { BuilderOutput } from '@angular-devkit/architect'; import type http from 'node:http'; import { OutputFile } from 'esbuild'; import type { Plugin as Plugin_2 } from 'esbuild'; // @public export interface ApplicationBuilderOptions { allowedCommonJsDependencies?: string[]; aot?: boolean; appShell?: boolean; assets?: AssetPattern[]; baseHref?: string; browser: string; budgets?: Budget[]; clearScreen?: boolean; crossOrigin?: CrossOrigin; define?: { [key: string]: string; }; deleteOutputPath?: boolean; deployUrl?: string; externalDependencies?: string[]; extractLicenses?: boolean; fileReplacements?: FileReplacement[]; i18nDuplicateTranslation?: I18NTranslation; i18nMissingTranslation?: I18NTranslation; index: IndexUnion; inlineStyleLanguage?: InlineStyleLanguage; loader?: { [key: string]: any; }; localize?: Localize; namedChunks?: boolean; optimization?: OptimizationUnion; outputHashing?: OutputHashing; outputMode?: OutputMode; outputPath: OutputPathUnion; poll?: number; polyfills?: string[]; prerender?: PrerenderUnion; preserveSymlinks?: boolean; progress?: boolean; scripts?: ScriptElement[]; security?: Security; server?: string; serviceWorker?: ServiceWorker_2; sourceMap?: SourceMapUnion; ssr?: SsrUnion; statsJson?: boolean; stylePreprocessorOptions?: StylePreprocessorOptions; styles?: StyleElement[]; subresourceIntegrity?: boolean; tsConfig: string; verbose?: boolean; watch?: boolean; webWorkerTsConfig?: string; } // @public (undocumented) export interface ApplicationBuilderOutput extends BuilderOutput { // (undocumented) assetFiles?: { source: string; destination: string; }[]; // (undocumented) outputFiles?: BuildOutputFile[]; } // @public export function buildApplication(options: ApplicationBuilderOptions, context: BuilderContext, plugins?: Plugin_2[]): AsyncIterable<ApplicationBuilderOutput>; // @public export function buildApplication(options: ApplicationBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions): AsyncIterable<ApplicationBuilderOutput>; // @public (undocumented) export interface BuildOutputAsset { // (undocumented) destination: string; // (undocumented) source: string; } // @public (undocumented) export interface BuildOutputFile extends OutputFile { // (undocumented) clone: () => BuildOutputFile; // (undocumented) readonly size: number; // (undocumented) type: BuildOutputFileType; } // @public (undocumented) export enum BuildOutputFileType { // (undocumented) Browser = 0, // (undocumented) Media = 1, // (undocumented) Root = 4, // (undocumented) ServerApplication = 2, // (undocumented) ServerRoot = 3 } // @public export interface DevServerBuilderOptions { buildTarget: string; headers?: { [key: string]: string; }; hmr?: boolean; host?: string; inspect?: Inspect; liveReload?: boolean; open?: boolean; poll?: number; port?: number; prebundle?: PrebundleUnion; proxyConfig?: string; servePath?: string; ssl?: boolean; sslCert?: string; sslKey?: string; verbose?: boolean; watch?: boolean; } // @public export interface DevServerBuilderOutput extends BuilderOutput { // (undocumented) address?: string; // (undocumented) baseUrl: string; // (undocumented) port?: number; } // @public export function executeDevServerBuilder(options: DevServerBuilderOptions, context: BuilderContext, extensions?: { buildPlugins?: Plugin_2[]; middleware?: ((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void) => void)[]; indexHtmlTransformer?: IndexHtmlTransform; }): AsyncIterable<DevServerBuilderOutput>; // @public export function executeExtractI18nBuilder(options: ExtractI18nBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions): Promise<BuilderOutput>; // @public export interface ExtractI18nBuilderOptions { buildTarget?: string; format?: Format; outFile?: string; outputPath?: string; progress?: boolean; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 4591, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular/build/index.api.md" }
angular-cli/goldens/public-api/ngtools/webpack/index.api.md_0_1564
## API Report File for "@ngtools/webpack" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import type { Compiler } from 'webpack'; import type { CompilerOptions } from '@angular/compiler-cli'; import type { LoaderContext } from 'webpack'; // @public (undocumented) function angularWebpackLoader(this: LoaderContext<unknown>, content: string, map: string): void; export default angularWebpackLoader; // @public (undocumented) export const AngularWebpackLoaderPath: string; // @public (undocumented) export class AngularWebpackPlugin { constructor(options?: Partial<AngularWebpackPluginOptions>); // (undocumented) apply(compiler: Compiler): void; // (undocumented) get options(): AngularWebpackPluginOptions; } // @public (undocumented) export interface AngularWebpackPluginOptions { // (undocumented) compilerOptions?: CompilerOptions; // (undocumented) directTemplateLoading: boolean; // (undocumented) emitClassMetadata: boolean; // (undocumented) emitNgModuleScope: boolean; // (undocumented) emitSetClassDebugInfo?: boolean; // (undocumented) fileReplacements: Record<string, string>; // (undocumented) inlineStyleFileExtension?: string; // (undocumented) jitMode: boolean; // (undocumented) substitutions: Record<string, string>; // (undocumented) tsconfig: string; } // @public (undocumented) export const imageDomains: Set<string>; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 1564, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/ngtools/webpack/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_0_152
## API Report File for "@angular-devkit/core" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts
{ "end_byte": 152, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_153_8462
import { ErrorObject } from 'ajv'; import { Format } from 'ajv'; import { Observable } from 'rxjs'; import { ObservableInput } from 'rxjs'; import { Operator } from 'rxjs'; import { PartialObserver } from 'rxjs'; import { Position } from 'source-map'; import { Subject } from 'rxjs'; import { Subscription } from 'rxjs'; import { ValidateFunction } from 'ajv'; // @public (undocumented) function addUndefinedDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue; // @public class AliasHost<StatsT extends object = {}> extends ResolverHost<StatsT> { // (undocumented) get aliases(): Map<Path, Path>; // (undocumented) protected _aliases: Map<Path, Path>; // (undocumented) protected _resolve(path: Path): Path; } // @public (undocumented) export function asPosixPath(path: Path): PosixPath; // @public (undocumented) export function asWindowsPath(path: Path): WindowsPath; // @public export class BaseException extends Error { constructor(message?: string); } // @public export function basename(path: Path): PathFragment; // @public (undocumented) function buildJsonPointer(fragments: string[]): JsonPointer; // @public function camelize(str: string): string; // @public function capitalize(str: string): string; // @public (undocumented) export class CircularDependencyFoundException extends BaseException { constructor(); } // @public function classify(str: string): string; // @public class CordHost extends SimpleMemoryHost { constructor(_back: ReadonlyHost); // (undocumented) protected _back: ReadonlyHost; // (undocumented) get backend(): ReadonlyHost; // (undocumented) get capabilities(): HostCapabilities; clone(): CordHost; commit(host: Host, force?: boolean): Observable<void>; create(path: Path, content: FileBuffer): Observable<void>; // (undocumented) delete(path: Path): Observable<void>; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) protected _filesToCreate: Set<Path>; // (undocumented) protected _filesToDelete: Set<Path>; // (undocumented) protected _filesToOverwrite: Set<Path>; // (undocumented) protected _filesToRename: Map<Path, Path>; // (undocumented) protected _filesToRenameRevert: Map<Path, Path>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) overwrite(path: Path, content: FileBuffer): Observable<void>; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) records(): CordHostRecord[]; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) stat(path: Path): Observable<Stats | null> | null; // (undocumented) watch(path: Path, options?: HostWatchOptions): null; // (undocumented) willCreate(path: Path): boolean; // (undocumented) willDelete(path: Path): boolean; // (undocumented) willOverwrite(path: Path): boolean; // (undocumented) willRename(path: Path): boolean; // (undocumented) willRenameTo(path: Path, to: Path): boolean; // (undocumented) write(path: Path, content: FileBuffer): Observable<void>; } // @public (undocumented) interface CordHostCreate { // (undocumented) content: FileBuffer; // (undocumented) kind: 'create'; // (undocumented) path: Path; } // @public (undocumented) interface CordHostDelete { // (undocumented) kind: 'delete'; // (undocumented) path: Path; } // @public (undocumented) interface CordHostOverwrite { // (undocumented) content: FileBuffer; // (undocumented) kind: 'overwrite'; // (undocumented) path: Path; } // @public (undocumented) type CordHostRecord = CordHostCreate | CordHostOverwrite | CordHostRename | CordHostDelete; // @public (undocumented) interface CordHostRename { // (undocumented) from: Path; // (undocumented) kind: 'rename'; // (undocumented) to: Path; } // @public (undocumented) class CoreSchemaRegistry implements SchemaRegistry { constructor(formats?: SchemaFormat[]); // (undocumented) addFormat(format: SchemaFormat): void; addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; // (undocumented) addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void; compile(schema: JsonSchema): Promise<SchemaValidator>; // (undocumented) registerUriHandler(handler: UriHandler): void; // (undocumented) protected _resolver(ref: string, validate?: ValidateFunction): { context?: ValidateFunction; schema?: JsonObject; }; // (undocumented) usePromptProvider(provider: PromptProvider): void; // (undocumented) useXDeprecatedProvider(onUsage: (message: string) => void): void; ɵflatten(schema: JsonObject): Promise<JsonObject>; } // @public (undocumented) function createSyncHost<StatsT extends object = {}>(handler: SyncHostHandler<StatsT>): Host<StatsT>; // @public (undocumented) function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost; // @public function dasherize(str: string): string; // @public function decamelize(str: string): string; // @public export function deepCopy<T>(value: T): T; // @public (undocumented) type DefinitionCollectionListener<V extends object> = (name: string, newValue: V | undefined, collection: DefinitionCollection<V>) => void; // @public (undocumented) export class DependencyNotFoundException extends BaseException { constructor(); } // @public export function dirname(path: Path): Path; // @public (undocumented) class Empty implements ReadonlyHost { // (undocumented) readonly capabilities: HostCapabilities; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) stat(path: Path): Observable<Stats<{}> | null>; } // @public (undocumented) export function extname(path: Path): string; // @public (undocumented) export class FileAlreadyExistException extends BaseException { constructor(path: string); } // @public (undocumented) type FileBuffer = ArrayBuffer; // @public (undocumented) type FileBufferLike = ArrayBufferLike; // @public (undocumented) function fileBufferToString(fileBuffer: FileBuffer): string; // @public (undocumented) export class FileDoesNotExistException extends BaseException { constructor(path: string); } // @public (undocumented) export function fragment(path: string): PathFragment; // @public (undocumented) export function getSystemPath(path: Path): string; // @public (undocumented) function getTypesOfSchema(schema: JsonSchema): Set<string>; // @public (undocumented) interface Host<StatsT extends object = {}> extends ReadonlyHost<StatsT> { // (undocumented) delete(path: Path): Observable<void>; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null; // (undocumented) write(path: Path, content: FileBufferLike): Observable<void>; } // @public (undocumented) interface HostCapabilities { // (undocumented) synchronous: boolean; } // @public (undocumented) interface HostWatchEvent { // (undocumented) readonly path: Path; // (undocumented) readonly time: Date; // (undocumented) readonly type: HostWatchEventType; } // @public (undocumented) enum HostWatchEventType { // (undocumented) Changed = 0, // (undocumented) Created = 1, // (undocumented) Deleted = 2, // (undocumented) Renamed = 3 } // @public (undocumented) interface HostWatchOptions { // (undocumented) readonly persistent?: boolean; // (undocumented) readonly recursive?:
{ "end_byte": 8462, "start_byte": 153, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_8462_16836
boolean; } // @public (undocumented) function indentBy(indentations: number): TemplateTag; // @public (undocumented) class IndentLogger extends Logger { constructor(name: string, parent?: Logger | null, indentation?: string); } // @public (undocumented) export class InvalidPathException extends BaseException { constructor(path: string); } // @public export function isAbsolute(p: Path): boolean; // @public (undocumented) export function isJsonArray(value: JsonValue): value is JsonArray; // @public (undocumented) export function isJsonObject(value: JsonValue): value is JsonObject; // @public (undocumented) function isJsonSchema(value: unknown): value is JsonSchema; // @public export function isPromise(obj: any): obj is Promise<any>; // @public export function join(p1: Path, ...others: string[]): Path; // @public (undocumented) function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer; declare namespace json { export { schema, isJsonObject, isJsonArray, JsonArray, JsonObject, JsonValue } } export { json } // @public export interface JsonArray extends Array<JsonValue> { } // @public (undocumented) export interface JsonObject { // (undocumented) [prop: string]: JsonValue; } // @public (undocumented) type JsonPointer = string & { __PRIVATE_DEVKIT_JSON_POINTER: void; }; // @public type JsonSchema = JsonObject | boolean; // @public (undocumented) interface JsonSchemaVisitor { // (undocumented) (current: JsonObject | JsonArray, pointer: JsonPointer, parentSchema?: JsonObject | JsonArray, index?: string): void; } // @public (undocumented) export type JsonValue = boolean | string | number | JsonArray | JsonObject | null; // @public (undocumented) interface JsonVisitor { // (undocumented) (value: JsonValue, pointer: JsonPointer, schema?: JsonObject, root?: JsonObject | JsonArray): Observable<JsonValue> | JsonValue; } // @public (undocumented) class LevelCapLogger extends LevelTransformLogger { constructor(name: string, parent: (Logger | null) | undefined, levelCap: LogLevel); // (undocumented) readonly levelCap: LogLevel; // (undocumented) static levelMap: { [cap: string]: { [level: string]: string; }; }; // (undocumented) readonly name: string; // (undocumented) readonly parent: Logger | null; } // @public (undocumented) class LevelTransformLogger extends Logger { constructor(name: string, parent: (Logger | null) | undefined, levelTransform: (level: LogLevel) => LogLevel); // (undocumented) createChild(name: string): Logger; // (undocumented) readonly levelTransform: (level: LogLevel) => LogLevel; // (undocumented) log(level: LogLevel, message: string, metadata?: JsonObject): void; // (undocumented) readonly name: string; // (undocumented) readonly parent: Logger | null; } // @public function levenshtein(a: string, b: string): number; // @public (undocumented) interface LogEntry extends LoggerMetadata { // (undocumented) level: LogLevel; // (undocumented) message: string; // (undocumented) timestamp: number; } // @public (undocumented) class Logger extends Observable<LogEntry> implements LoggerApi { constructor(name: string, parent?: Logger | null); // (undocumented) asApi(): LoggerApi; // (undocumented) complete(): void; // (undocumented) createChild(name: string): Logger; // (undocumented) debug(message: string, metadata?: JsonObject): void; // (undocumented) error(message: string, metadata?: JsonObject): void; // (undocumented) fatal(message: string, metadata?: JsonObject): void; // (undocumented) forEach(next: (value: LogEntry) => void, promiseCtor?: PromiseConstructorLike): Promise<void>; // (undocumented) info(message: string, metadata?: JsonObject): void; // (undocumented) lift<R>(operator: Operator<LogEntry, R>): Observable<R>; // (undocumented) log(level: LogLevel, message: string, metadata?: JsonObject): void; // (undocumented) protected _metadata: LoggerMetadata; // (undocumented) readonly name: string; // (undocumented) next(entry: LogEntry): void; // (undocumented) protected get _observable(): Observable<LogEntry>; protected set _observable(v: Observable<LogEntry>); // (undocumented) readonly parent: Logger | null; // (undocumented) protected readonly _subject: Subject<LogEntry>; // (undocumented) subscribe(): Subscription; // (undocumented) subscribe(observer: PartialObserver<LogEntry>): Subscription; // (undocumented) subscribe(next?: (value: LogEntry) => void, error?: (error: Error) => void, complete?: () => void): Subscription; // (undocumented) toString(): string; // (undocumented) warn(message: string, metadata?: JsonObject): void; } // @public (undocumented) interface LoggerApi { // (undocumented) createChild(name: string): Logger; // (undocumented) debug(message: string, metadata?: JsonObject): void; // (undocumented) error(message: string, metadata?: JsonObject): void; // (undocumented) fatal(message: string, metadata?: JsonObject): void; // (undocumented) info(message: string, metadata?: JsonObject): void; // (undocumented) log(level: LogLevel, message: string, metadata?: JsonObject): void; // (undocumented) warn(message: string, metadata?: JsonObject): void; } // @public (undocumented) interface LoggerMetadata extends JsonObject { // (undocumented) name: string; // (undocumented) path: string[]; } declare namespace logging { export { IndentLogger, LevelTransformLogger, LevelCapLogger, LoggerMetadata, LogEntry, LoggerApi, LogLevel, Logger, NullLogger, TransformLogger } } export { logging } // @public (undocumented) type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; // @public function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema; // @public export function noCacheNormalize(path: string): Path; // @public export function normalize(path: string): Path; // @public export const NormalizedRoot: Path; // @public export const NormalizedSep: Path; // @public (undocumented) class NullLogger extends Logger { constructor(parent?: Logger | null); // (undocumented) asApi(): LoggerApi; } // @public (undocumented) function oneLine(strings: TemplateStringsArray, ...values: any[]): string; // @public (undocumented) function parseJsonPointer(pointer: JsonPointer): string[]; // @public (undocumented) export class PartiallyOrderedSet<T> implements Set<T> { // (undocumented) [Symbol.iterator](): Generator<T, undefined, unknown>; // (undocumented) get [Symbol.toStringTag](): 'Set'; // (undocumented) add(item: T, deps?: Set<T> | T[]): this; // (undocumented) protected _checkCircularDependencies(item: T, deps: Set<T>): void; // (undocumented) clear(): void; // (undocumented) delete(item: T): boolean; entries(): SetIterator<[T, T]>; // (undocumented) forEach(callbackfn: (value: T, value2: T, set: PartiallyOrderedSet<T>) => void, thisArg?: any): void; // (undocumented) has(item: T): boolean; keys(): SetIterator<T>; // (undocumented) get size(): number; values(): SetIterator<T>; } // @public export type Path = string & { __PRIVATE_DEVKIT_PATH: void; }; // @public (undocumented) export const path: TemplateTag<Path>; // @public (undocumented) export class PathCannotBeFragmentException extends BaseException { constructor(path: string); } // @public export type PathFragment = Path & { __PRIVATE_DEVKIT_PATH_FRAGMENT: void; }; // @public (undocumented) export class PathIsDirectoryException extends BaseException { constructor(path: string); } // @public (undocumented) export class PathIsFileException extends BaseException { constructor(path: string); } // @public (undocumented) export class PathMustBeAbsoluteException extends BaseException { constructor(path: string); } // @public (undocumented) class PatternMatchingHost<StatsT extends object = {}> extends ResolverHost<S
{ "end_byte": 16836, "start_byte": 8462, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_16842_25419
{ // (undocumented) addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void; // (undocumented) protected _patterns: Map<RegExp, ReplacementFunction>; // (undocumented) protected _resolve(path: Path): Path; } // @public (undocumented) export type PosixPath = string & { __PRIVATE_DEVKIT_POSIX_PATH: void; }; // @public export class PriorityQueue<T> { constructor(_comparator: (x: T, y: T) => number); // (undocumented) clear(): void; // (undocumented) peek(): T | undefined; // (undocumented) pop(): T | undefined; // (undocumented) push(item: T): void; // (undocumented) get size(): number; // (undocumented) toArray(): Array<T>; } // @public (undocumented) interface ProjectDefinition { // (undocumented) readonly extensions: Record<string, JsonValue | undefined>; // (undocumented) prefix?: string; // (undocumented) root: string; // (undocumented) sourceRoot?: string; // (undocumented) readonly targets: TargetDefinitionCollection; } // @public (undocumented) class ProjectDefinitionCollection extends DefinitionCollection<ProjectDefinition> { constructor(initial?: Record<string, ProjectDefinition>, listener?: DefinitionCollectionListener<ProjectDefinition>); // (undocumented) add(definition: { name: string; root: string; sourceRoot?: string; prefix?: string; targets?: Record<string, TargetDefinition | undefined>; [key: string]: unknown; }): ProjectDefinition; // (undocumented) set(name: string, value: ProjectDefinition): this; } // @public (undocumented) interface PromptDefinition { // (undocumented) default?: string | string[] | number | boolean | null; // (undocumented) id: string; // (undocumented) items?: Array<string | { value: JsonValue; label: string; }>; // (undocumented) message: string; // (undocumented) multiselect?: boolean; // (undocumented) propertyTypes: Set<string>; // (undocumented) raw?: string | JsonObject; // (undocumented) type: string; // (undocumented) validator?: (value: JsonValue) => boolean | string | Promise<boolean | string>; } // @public (undocumented) type PromptProvider = (definitions: Array<PromptDefinition>) => ObservableInput<{ [id: string]: JsonValue; }>; // @public (undocumented) interface ReadonlyHost<StatsT extends object = {}> { // (undocumented) readonly capabilities: HostCapabilities; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) stat(path: Path): Observable<Stats<StatsT> | null> | null; } // @public function readWorkspace(path: string, host: WorkspaceHost, format?: WorkspaceFormat): Promise<{ workspace: WorkspaceDefinition; }>; // @public (undocumented) interface ReferenceResolver<ContextT> { // (undocumented) (ref: string, context?: ContextT): { context?: ContextT; schema?: JsonObject; }; } // @public export function relative(from: Path, to: Path): Path; // @public (undocumented) type ReplacementFunction = (path: Path) => Path; // @public export function resetNormalizeCache(): void; // @public export function resolve(p1: Path, p2: Path): Path; // @public abstract class ResolverHost<T extends object> implements Host<T> { constructor(_delegate: Host<T>); // (undocumented) get capabilities(): HostCapabilities; // (undocumented) protected _delegate: Host<T>; // (undocumented) delete(path: Path): Observable<void>; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) protected abstract _resolve(path: Path): Path; // (undocumented) stat(path: Path): Observable<Stats<T> | null> | null; // (undocumented) watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null; // (undocumented) write(path: Path, content: FileBuffer): Observable<void>; } // @public class SafeReadonlyHost<StatsT extends object = {}> implements ReadonlyHost<StatsT> { constructor(_delegate: ReadonlyHost<StatsT>); // (undocumented) get capabilities(): HostCapabilities; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) stat(path: Path): Observable<Stats<StatsT> | null> | null; } declare namespace schema { export { transforms, JsonPointer, SchemaValidatorResult, SchemaValidatorError, SchemaValidatorOptions, SchemaValidator, SchemaFormatter, SchemaFormat, SmartDefaultProvider, SchemaKeywordValidator, PromptDefinition, PromptProvider, SchemaRegistry, JsonSchemaVisitor, JsonVisitor, buildJsonPointer, joinJsonPointer, parseJsonPointer, UriHandler, SchemaValidationException, CoreSchemaRegistry, isJsonSchema, mergeSchemas, JsonSchema, visitJson, visitJsonSchema, ReferenceResolver, getTypesOfSchema } } export { schema } // @public (undocumented) interface SchemaFormat { // (undocumented) formatter: SchemaFormatter; // (undocumented) name: string; } // @public (undocumented) type SchemaFormatter = Format; // @public (undocumented) interface SchemaKeywordValidator { // (undocumented) (data: JsonValue, schema: JsonValue, parent: JsonObject | JsonArray | undefined, parentProperty: string | number | undefined, pointer: JsonPointer, rootData: JsonValue): boolean | Observable<boolean>; } // @public (undocumented) interface SchemaRegistry { // (undocumented) addFormat(format: SchemaFormat): void; addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; // (undocumented) addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void; // (undocumented) compile(schema: Object): Promise<SchemaValidator>; // (undocumented) usePromptProvider(provider: PromptProvider): void; // (undocumented) useXDeprecatedProvider(onUsage: (message: string) => void): void; // (undocumented) ɵflatten(schema: JsonObject | string): Promise<JsonObject>; } // @public (undocumented) class SchemaValidationException extends BaseException { constructor(errors?: SchemaValidatorError[], baseMessage?: string); // (undocumented) static createMessages(errors?: SchemaValidatorError[]): string[]; // (undocumented) readonly errors: SchemaValidatorError[]; } // @public (undocumented) interface SchemaValidator { // (undocumented) (data: JsonValue, options?: SchemaValidatorOptions): Promise<SchemaValidatorResult>; } // @public (undocumented) type SchemaValidatorError = Partial<ErrorObject>; // @public (undocumented) interface SchemaValidatorOptions { // (undocumented) applyPostTransforms?: boolean; // (undocumented) applyPreTransforms?: boolean; // (undocumented) withPrompts?: boolean; } // @public (undocumented) interface SchemaValidatorResult { // (undocumented) data: JsonValue; // (undocumented) errors?: SchemaValidatorError[]; // (undocumented) success: boolean; } // @public (undocumented) class ScopedHost<T extends object> extends ResolverHost<T> { constructor(delegate: Host<T>, _root?: Path); // (undocumented) protected _resolve(path: Path): Path; // (undocumented) protected _root: Path; } // @public (un
{ "end_byte": 25419, "start_byte": 16842, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_25431_33699
class SimpleMemoryHost implements Host<{}> { constructor(); // (undocumented) protected _cache: Map<Path, Stats<SimpleMemoryHostStats>>; // (undocumented) get capabilities(): HostCapabilities; // (undocumented) delete(path: Path): Observable<void>; // (undocumented) protected _delete(path: Path): void; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) protected _exists(path: Path): boolean; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) protected _isDirectory(path: Path): boolean; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) protected _isFile(path: Path): boolean; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) protected _list(path: Path): PathFragment[]; // (undocumented) protected _newDirStats(): { inspect(): string; isFile(): boolean; isDirectory(): boolean; size: number; atime: Date; ctime: Date; mtime: Date; birthtime: Date; content: null; }; // (undocumented) protected _newFileStats(content: FileBuffer, oldStats?: Stats<SimpleMemoryHostStats>): { inspect(): string; isFile(): boolean; isDirectory(): boolean; size: number; atime: Date; ctime: Date; mtime: Date; birthtime: Date; content: ArrayBuffer; }; // (undocumented) read(path: Path): Observable<FileBuffer>; // (undocumented) protected _read(path: Path): FileBuffer; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) protected _rename(from: Path, to: Path): void; // (undocumented) reset(): void; // (undocumented) stat(path: Path): Observable<Stats<{}> | null> | null; // (undocumented) protected _stat(path: Path): Stats<SimpleMemoryHostStats> | null; // (undocumented) protected _toAbsolute(path: Path): Path; // (undocumented) protected _updateWatchers(path: Path, type: HostWatchEventType): void; // (undocumented) watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null; // (undocumented) protected _watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent>; // (undocumented) write(path: Path, content: FileBuffer): Observable<void>; protected _write(path: Path, content: FileBuffer): void; } // @public (undocumented) interface SimpleMemoryHostStats { // (undocumented) readonly content: FileBuffer | null; } // @public (undocumented) interface SmartDefaultProvider<T> { // (undocumented) (schema: JsonObject): T | Observable<T>; } // @public export function split(path: Path): PathFragment[]; // @public (undocumented) type Stats<T extends object = {}> = T & { isFile(): boolean; isDirectory(): boolean; readonly size: number; readonly atime: Date; readonly mtime: Date; readonly ctime: Date; readonly birthtime: Date; }; declare namespace strings { export { decamelize, dasherize, camelize, classify, underscore, capitalize, levenshtein } } export { strings } // @public (undocumented) function stringToFileBuffer(str: string): FileBuffer; // @public (undocumented) function stripIndent(strings: TemplateStringsArray, ...values: any[]): string; // @public (undocumented) function stripIndents(strings: TemplateStringsArray, ...values: any[]): string; // @public class SyncDelegateHost<T extends object = {}> { constructor(_delegate: Host<T>); // (undocumented) get capabilities(): HostCapabilities; // (undocumented) get delegate(): Host<T>; // (undocumented) protected _delegate: Host<T>; // (undocumented) delete(path: Path): void; // (undocumented) protected _doSyncCall<ResultT>(observable: Observable<ResultT>): ResultT; // (undocumented) exists(path: Path): boolean; // (undocumented) isDirectory(path: Path): boolean; // (undocumented) isFile(path: Path): boolean; // (undocumented) list(path: Path): PathFragment[]; // (undocumented) read(path: Path): FileBuffer; // (undocumented) rename(from: Path, to: Path): void; // (undocumented) stat(path: Path): Stats<T> | null; // (undocumented) watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null; // (undocumented) write(path: Path, content: FileBufferLike): void; } // @public (undocumented) interface SyncHostHandler<StatsT extends object = {}> { // (undocumented) delete(path: Path): void; // (undocumented) exists(path: Path): boolean; // (undocumented) isDirectory(path: Path): boolean; // (undocumented) isFile(path: Path): boolean; // (undocumented) list(path: Path): PathFragment[]; // (undocumented) read(path: Path): FileBuffer; // (undocumented) rename(from: Path, to: Path): void; // (undocumented) stat(path: Path): Stats<StatsT> | null; // (undocumented) write(path: Path, content: FileBufferLike): void; } // @public (undocumented) class SynchronousDelegateExpectedException extends BaseException { constructor(); } declare namespace tags { export { oneLine, indentBy, stripIndent, stripIndents, trimNewlines, TemplateTag } } export { tags } // @public (undocumented) interface TargetDefinition { // (undocumented) builder: string; // (undocumented) configurations?: Record<string, Record<string, JsonValue | undefined> | undefined>; // (undocumented) defaultConfiguration?: string; // (undocumented) options?: Record<string, JsonValue | undefined>; } // @public (undocumented) class TargetDefinitionCollection extends DefinitionCollection<TargetDefinition> { constructor(initial?: Record<string, TargetDefinition>, listener?: DefinitionCollectionListener<TargetDefinition>); // (undocumented) add(definition: { name: string; } & TargetDefinition): TargetDefinition; // (undocumented) set(name: string, value: TargetDefinition): this; } // @public export function template<T>(content: string, options?: TemplateOptions): (input: T) => string; // @public export interface TemplateAst { // (undocumented) children: TemplateAstNode[]; // (undocumented) content: string; // (undocumented) fileName: string; } // @public export interface TemplateAstBase { // (undocumented) end: Position; // (undocumented) start: Position; } // @public export interface TemplateAstComment extends TemplateAstBase { // (undocumented) kind: 'comment'; // (undocumented) text: string; } // @public export interface TemplateAstContent extends TemplateAstBase { // (undocumented) content: string; // (undocumented) kind: 'content'; } // @public export interface TemplateAstEscape extends TemplateAstBase { // (undocumented) expression: string; // (undocumented) kind: 'escape'; } // @public export interface TemplateAstEvaluate extends TemplateAstBase { // (undocumented) expression: string; // (undocumented) kind: 'evaluate'; } // @public export interface TemplateAstInterpolate extends TemplateAstBase { // (undocumented) expression: string; // (undocumented) kind: 'interpolate'; } // @public (undocumented) export type TemplateAstNode = TemplateAstContent | TemplateAstEvaluate | TemplateAstComment | TemplateAstEscape | TemplateAstInterpolate; // @public (undocumented) export interface TemplateOptions { // (undocumented) fileName?: string; // (undocumented) module?: boolean | { exports: {}; }; // (undocumented) sourceMap?: boolean; // (undocumented) sourceRoot?: string; // (undocumented) sourceURL?: string; } // @public export function templateParser(sourceText: string, fileName: string): TemplateAst; // @public interface TemplateTag<R = string> { // (undocumented) (template: TemplateStringsArray, .
{ "end_byte": 33699, "start_byte": 25431, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/index.api.md_33700_38838
.substitutions: any[]): R; } declare namespace test { export { TestLogRecord, TestHost } } // @public (undocumented) class TestHost extends SimpleMemoryHost { // (undocumented) $exists(path: string): boolean; // (undocumented) $isDirectory(path: string): boolean; // (undocumented) $isFile(path: string): boolean; // (undocumented) $list(path: string): PathFragment[]; // (undocumented) $read(path: string): string; // (undocumented) $write(path: string, content: string): void; constructor(map?: { [path: string]: string; }); // (undocumented) clearRecords(): void; // (undocumented) clone(): TestHost; // (undocumented) protected _delete(path: Path): void; // (undocumented) protected _exists(path: Path): boolean; // (undocumented) get files(): Path[]; // (undocumented) protected _isDirectory(path: Path): boolean; // (undocumented) protected _isFile(path: Path): boolean; // (undocumented) protected _list(path: Path): PathFragment[]; // (undocumented) protected _read(path: Path): ArrayBuffer; // (undocumented) get records(): TestLogRecord[]; // (undocumented) protected _records: TestLogRecord[]; // (undocumented) protected _rename(from: Path, to: Path): void; // (undocumented) protected _stat(path: Path): Stats<SimpleMemoryHostStats> | null; // (undocumented) get sync(): SyncDelegateHost<{}>; // (undocumented) protected _sync: SyncDelegateHost<{}> | null; // (undocumented) protected _watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent>; // (undocumented) protected _write(path: Path, content: FileBuffer): void; } // @public (undocumented) type TestLogRecord = { kind: 'write' | 'read' | 'delete' | 'list' | 'exists' | 'isDirectory' | 'isFile' | 'stat' | 'watch'; path: Path; } | { kind: 'rename'; from: Path; to: Path; }; // @public (undocumented) class TransformLogger extends Logger { constructor(name: string, transform: (stream: Observable<LogEntry>) => Observable<LogEntry>, parent?: Logger | null); } declare namespace transforms { export { addUndefinedDefaults } } // @public (undocumented) function trimNewlines(strings: TemplateStringsArray, ...values: any[]): string; // @public function underscore(str: string): string; // @public (undocumented) export class UnknownException extends BaseException { constructor(message: string); } // @public (undocumented) type UriHandler = (uri: string) => Observable<JsonObject> | Promise<JsonObject> | null | undefined; declare namespace virtualFs { export { test, AliasHost, stringToFileBuffer, fileBufferToString, createSyncHost, SyncHostHandler, Empty, FileBuffer, FileBufferLike, HostWatchOptions, HostWatchEventType, Stats, HostWatchEvent, HostCapabilities, ReadonlyHost, Host, SimpleMemoryHostStats, SimpleMemoryHost, ReplacementFunction, PatternMatchingHost, CordHostCreate, CordHostOverwrite, CordHostRename, CordHostDelete, CordHostRecord, CordHost, SafeReadonlyHost, ScopedHost, SynchronousDelegateExpectedException, SyncDelegateHost, ResolverHost } } export { virtualFs } // @public function visitJson<ContextT>(json: JsonValue, visitor: JsonVisitor, schema?: JsonSchema, refResolver?: ReferenceResolver<ContextT>, context?: ContextT): Observable<JsonValue>; // @public (undocumented) function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor): void; // @public (undocumented) export type WindowsPath = string & { __PRIVATE_DEVKIT_WINDOWS_PATH: void; }; // @public (undocumented) interface WorkspaceDefinition { // (undocumented) readonly extensions: Record<string, JsonValue | undefined>; // (undocumented) readonly projects: ProjectDefinitionCollection; } // @public enum WorkspaceFormat { // (undocumented) JSON = 0 } // @public (undocumented) interface WorkspaceHost { // (undocumented) isDirectory(path: string): Promise<boolean>; // (undocumented) isFile(path: string): Promise<boolean>; // (undocumented) readFile(path: string): Promise<string>; // (undocumented) writeFile(path: string, data: string): Promise<void>; } declare namespace workspaces { export { WorkspaceHost, createWorkspaceHost, WorkspaceFormat, readWorkspace, writeWorkspace, WorkspaceDefinition, ProjectDefinition, TargetDefinition, DefinitionCollectionListener, ProjectDefinitionCollection, TargetDefinitionCollection } } export { workspaces } // @public function writeWorkspace(workspace: WorkspaceDefinition, host: WorkspaceHost, path?: string, format?: WorkspaceFormat): Promise<void>; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 38838, "start_byte": 33700, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/node/index.api.md_0_2673
## API Report File for "@angular-devkit/core_node" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { Observable } from 'rxjs'; import { Operator } from 'rxjs'; import { PartialObserver } from 'rxjs'; import { Stats as Stats_2 } from 'node:fs'; import { Subject } from 'rxjs'; import { Subscription } from 'rxjs'; // @public export function createConsoleLogger(verbose?: boolean, stdout?: ProcessOutput, stderr?: ProcessOutput, colors?: Partial<Record<logging.LogLevel, (s: string) => string>>): logging.Logger; // @public export class NodeJsAsyncHost implements virtualFs.Host<Stats_2> { // (undocumented) get capabilities(): virtualFs.HostCapabilities; // (undocumented) delete(path: Path): Observable<void>; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<virtualFs.FileBuffer>; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) stat(path: Path): Observable<virtualFs.Stats<Stats_2>>; // (undocumented) watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable<virtualFs.HostWatchEvent> | null; // (undocumented) write(path: Path, content: virtualFs.FileBuffer): Observable<void>; } // @public export class NodeJsSyncHost implements virtualFs.Host<Stats_2> { // (undocumented) get capabilities(): virtualFs.HostCapabilities; // (undocumented) delete(path: Path): Observable<void>; // (undocumented) exists(path: Path): Observable<boolean>; // (undocumented) isDirectory(path: Path): Observable<boolean>; // (undocumented) isFile(path: Path): Observable<boolean>; // (undocumented) list(path: Path): Observable<PathFragment[]>; // (undocumented) read(path: Path): Observable<virtualFs.FileBuffer>; // (undocumented) rename(from: Path, to: Path): Observable<void>; // (undocumented) stat(path: Path): Observable<virtualFs.Stats<Stats_2>>; // (undocumented) watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable<virtualFs.HostWatchEvent> | null; // (undocumented) write(path: Path, content: virtualFs.FileBuffer): Observable<void>; } // @public (undocumented) export interface ProcessOutput { // (undocumented) write(buffer: string | Buffer): boolean; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 2673, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/node/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/core/node/testing/index.api.md_0_698
## API Report File for "@angular-devkit/core_node_testing" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import * as fs from 'fs'; import { Observable } from 'rxjs'; // @public export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost<fs.Stats> { constructor(); // (undocumented) get files(): Path[]; // (undocumented) get root(): Path; // (undocumented) protected _root: Path; // (undocumented) get sync(): virtualFs.SyncDelegateHost<fs.Stats>; // (undocumented) protected _sync?: virtualFs.SyncDelegateHost<fs.Stats>; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 698, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/core/node/testing/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/build_angular/index.api.md_0_161
## API Report File for "@angular-devkit/build-angular" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts
{ "end_byte": 161, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/build_angular/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/build_angular/index.api.md_162_8907
import { ApplicationBuilderOptions } from '@angular/build'; import { buildApplication } from '@angular/build'; import { BuilderContext } from '@angular-devkit/architect'; import { BuilderOutput } from '@angular-devkit/architect'; import type { ConfigOptions } from 'karma'; import { Configuration } from 'webpack'; import { DevServerBuilderOutput } from '@angular/build'; import type http from 'node:http'; import { IndexHtmlTransform } from '@angular/build/private'; import { json } from '@angular-devkit/core'; import { Observable } from 'rxjs'; import type { Plugin as Plugin_2 } from 'esbuild'; import webpack from 'webpack'; import { WebpackLoggingCallback } from '@angular-devkit/build-webpack'; export { ApplicationBuilderOptions } // @public (undocumented) export type AssetPattern = AssetPatternObject | string; // @public (undocumented) export interface AssetPatternObject { followSymlinks?: boolean; glob: string; ignore?: string[]; input: string; output?: string; } // @public export interface BrowserBuilderOptions { allowedCommonJsDependencies?: string[]; aot?: boolean; assets?: AssetPattern[]; baseHref?: string; budgets?: Budget[]; buildOptimizer?: boolean; commonChunk?: boolean; crossOrigin?: CrossOrigin; deleteOutputPath?: boolean; deployUrl?: string; extractLicenses?: boolean; fileReplacements?: FileReplacement[]; i18nDuplicateTranslation?: I18NTranslation; i18nMissingTranslation?: I18NTranslation; index: IndexUnion; inlineStyleLanguage?: InlineStyleLanguage; localize?: Localize; main: string; namedChunks?: boolean; ngswConfigPath?: string; optimization?: OptimizationUnion; outputHashing?: OutputHashing; outputPath: string; poll?: number; polyfills?: Polyfills; preserveSymlinks?: boolean; progress?: boolean; resourcesOutputPath?: string; scripts?: ScriptElement[]; serviceWorker?: boolean; sourceMap?: SourceMapUnion; statsJson?: boolean; stylePreprocessorOptions?: StylePreprocessorOptions; styles?: StyleElement[]; subresourceIntegrity?: boolean; tsConfig: string; vendorChunk?: boolean; verbose?: boolean; watch?: boolean; webWorkerTsConfig?: string; } // @public export type BrowserBuilderOutput = BuilderOutput & { stats: BuildEventStats; baseOutputPath: string; outputs: { locale?: string; path: string; baseHref?: string; }[]; }; // @public (undocumented) export interface Budget { baseline?: string; error?: string; maximumError?: string; maximumWarning?: string; minimumError?: string; minimumWarning?: string; name?: string; type: Type; warning?: string; } export { buildApplication } // @public export enum CrossOrigin { // (undocumented) Anonymous = "anonymous", // (undocumented) None = "none", // (undocumented) UseCredentials = "use-credentials" } // @public export interface DevServerBuilderOptions { allowedHosts?: string[]; buildTarget: string; disableHostCheck?: boolean; forceEsbuild?: boolean; headers?: { [key: string]: string; }; hmr?: boolean; host?: string; inspect?: Inspect; liveReload?: boolean; open?: boolean; poll?: number; port?: number; prebundle?: PrebundleUnion; proxyConfig?: string; publicHost?: string; servePath?: string; ssl?: boolean; sslCert?: string; sslKey?: string; verbose?: boolean; watch?: boolean; } export { DevServerBuilderOutput } // @public export function executeBrowserBuilder(options: BrowserBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; logging?: WebpackLoggingCallback; indexHtml?: IndexHtmlTransform; }): Observable<BrowserBuilderOutput>; // @public export function executeDevServerBuilder(options: DevServerBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<Configuration>; logging?: WebpackLoggingCallback; indexHtml?: IndexHtmlTransform; }, extensions?: { buildPlugins?: Plugin_2[]; middleware?: ((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void) => void)[]; builderSelector?: (info: BuilderSelectorInfo, logger: BuilderContext['logger']) => string; }): Observable<DevServerBuilderOutput>; // @public export function executeExtractI18nBuilder(options: ExtractI18nBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; }): Promise<BuilderOutput>; // @public export function executeKarmaBuilder(options: KarmaBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<Configuration>; karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions; }): Observable<BuilderOutput>; // @public export function executeNgPackagrBuilder(options: NgPackagrBuilderOptions, context: BuilderContext): Observable<BuilderOutput>; // @public export function executeProtractorBuilder(options: ProtractorBuilderOptions, context: BuilderContext): Promise<BuilderOutput>; // @public export function executeServerBuilder(options: ServerBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; }): Observable<ServerBuilderOutput>; // @public (undocumented) export function executeSSRDevServerBuilder(options: SSRDevServerBuilderOptions, context: BuilderContext): Observable<SSRDevServerBuilderOutput>; // @public export type ExecutionTransformer<T> = (input: T) => T | Promise<T>; // @public export interface ExtractI18nBuilderOptions { buildTarget?: string; format?: Format; outFile?: string; outputPath?: string; progress?: boolean; } // @public (undocumented) export interface FileReplacement { // (undocumented) replace?: string; // (undocumented) replaceWith?: string; // (undocumented) src?: string; // (undocumented) with?: string; } // @public export interface KarmaBuilderOptions { assets?: AssetPattern_2[]; browsers?: Browsers; builderMode?: BuilderMode; codeCoverage?: boolean; codeCoverageExclude?: string[]; exclude?: string[]; fileReplacements?: FileReplacement_2[]; include?: string[]; inlineStyleLanguage?: InlineStyleLanguage_2; karmaConfig?: string; main?: string; poll?: number; polyfills?: Polyfills_2; preserveSymlinks?: boolean; progress?: boolean; reporters?: string[]; scripts?: ScriptElement_2[]; sourceMap?: SourceMapUnion_2; stylePreprocessorOptions?: StylePreprocessorOptions_2; styles?: StyleElement_2[]; tsConfig: string; watch?: boolean; webWorkerTsConfig?: string; } // @public (undocumented) export type KarmaConfigOptions = ConfigOptions & { buildWebpack?: unknown; configFile?: string; }; // @public export interface NgPackagrBuilderOptions { poll?: number; project: string; tsConfig?: string; watch?: boolean; } // @public (undocumented) export interface OptimizationObject { fonts?: FontsUnion; scripts?: boolean; styles?: StylesUnion; } // @public export type OptimizationUnion = boolean | OptimizationObject; // @public export enum OutputHashing { // (undocumented) All = "all", // (undocumented) Bundles = "bundles", // (undocumented) Media = "media", // (undocumented) None = "none" } // @public export interface ProtractorBuilderOptions { baseUrl?: string; devServerTarget?: string; grep?: string; host?: string; invertGrep?: boolean; port?: number; protractorConfig: string; specs?: string[]; suite?: string; webdriverUpdate?: boolean; } // @public (undocumented) export interface ServerBuilderOptions { assets?: AssetPattern_3[]; buildOptimizer?: boolean; deleteOutputPath?: boolean; deployUrl?: string; externalDependencies?: string[]; extractLicenses?: boolean; fileReplacements?: FileReplacement_3[]; i18nDuplicateTranslation?: I18NTranslation_2; i18nMissingTranslation?: I18NTranslation_2; inlineStyleLanguage?: InlineStyleLanguage_3; localize?: Localize_2; main: string; namedChunks?: boolean; optimization?: OptimizationUnion_2; outputHashing?: OutputHashing_2; outputPath: string; poll?: number; preserveSymlinks?: boolean; progress?: boolean; resourcesOutputPath?: string; sourceMap?: SourceMapUnion_3; statsJson?: boolean; stylePreprocessorOptions?: StylePreprocessorOptions_
{ "end_byte": 8907, "start_byte": 162, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/build_angular/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/build_angular/index.api.md_8908_10157
; tsConfig: string; vendorChunk?: boolean; verbose?: boolean; watch?: boolean; } // @public export type ServerBuilderOutput = BuilderOutput & { baseOutputPath: string; outputPath: string; outputs: { locale?: string; path: string; }[]; }; // @public (undocumented) export interface SourceMapObject { hidden?: boolean; scripts?: boolean; styles?: boolean; vendor?: boolean; } // @public export type SourceMapUnion = boolean | SourceMapObject; // @public (undocumented) export type SSRDevServerBuilderOptions = Schema & json.JsonObject; // @public (undocumented) export type SSRDevServerBuilderOutput = BuilderOutput & { baseUrl?: string; port?: string; }; // @public export interface StylePreprocessorOptions { includePaths?: string[]; } // @public export enum Type { // (undocumented) All = "all", // (undocumented) AllScript = "allScript", // (undocumented) Any = "any", // (undocumented) AnyComponentStyle = "anyComponentStyle", // (undocumented) AnyScript = "anyScript", // (undocumented) Bundle = "bundle", // (undocumented) Initial = "initial" } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 10157, "start_byte": 8908, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/build_angular/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/architect/index.api.md_0_157
## API Report File for "@angular-devkit/architect" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts
{ "end_byte": 157, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/architect/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/architect/index.api.md_158_8658
import { BaseException } from '@angular-devkit/core'; import { json } from '@angular-devkit/core'; import { JsonObject } from '@angular-devkit/core'; import { JsonValue } from '@angular-devkit/core'; import { logging } from '@angular-devkit/core'; import { Observable } from 'rxjs'; import { ObservableInput } from 'rxjs'; import { Observer } from 'rxjs'; import { schema } from '@angular-devkit/core'; // @public (undocumented) export class Architect { constructor(_host: ArchitectHost, registry?: json.schema.SchemaRegistry, additionalJobRegistry?: Registry); // (undocumented) has(name: JobName): Observable<boolean>; // (undocumented) scheduleBuilder(name: string, options: json.JsonObject, scheduleOptions?: ScheduleOptions): Promise<BuilderRun>; // (undocumented) scheduleTarget(target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions): Promise<BuilderRun>; } // @public export interface BuilderContext { addTeardown(teardown: () => Promise<void> | void): void; builder: BuilderInfo; currentDirectory: string; getBuilderNameForTarget(target: Target): Promise<string>; // (undocumented) getProjectMetadata(projectName: string): Promise<json.JsonObject>; // (undocumented) getProjectMetadata(target: Target): Promise<json.JsonObject>; getTargetOptions(target: Target): Promise<json.JsonObject>; id: number; logger: logging.LoggerApi; reportProgress(current: number, total?: number, status?: string): void; reportRunning(): void; reportStatus(status: string): void; scheduleBuilder(builderName: string, options?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Promise<BuilderRun>; scheduleTarget(target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Promise<BuilderRun>; target?: Target; validateOptions<T extends json.JsonObject = json.JsonObject>(options: json.JsonObject, builderName: string): Promise<T>; workspaceRoot: string; } // @public export interface BuilderHandlerFn<A> { (input: A, context: BuilderContext): BuilderOutputLike; } // @public export type BuilderInfo = json.JsonObject & { builderName: string; description: string; optionSchema: json.schema.JsonSchema; }; // @public export type BuilderInput = json.JsonObject & Schema; // @public (undocumented) export type BuilderOutput = json.JsonObject & Schema_2; // @public export type BuilderOutputLike = ObservableInput<BuilderOutput> | BuilderOutput; // @public (undocumented) export type BuilderProgress = json.JsonObject & Schema_3 & TypedBuilderProgress; // @public export type BuilderProgressReport = BuilderProgress & { target?: Target; builder: BuilderInfo; }; // @public (undocumented) export enum BuilderProgressState { // (undocumented) Error = "error", // (undocumented) Running = "running", // (undocumented) Stopped = "stopped", // (undocumented) Waiting = "waiting" } // @public (undocumented) export type BuilderRegistry = Registry<json.JsonObject, BuilderInput, BuilderOutput>; // @public export interface BuilderRun { id: number; info: BuilderInfo; lastOutput: Promise<BuilderOutput>; output: Observable<BuilderOutput>; progress: Observable<BuilderProgressReport>; result: Promise<BuilderOutput>; stop(): Promise<void>; } // @public (undocumented) class ChannelAlreadyExistException extends BaseException { constructor(name: string); } // @public (undocumented) export function createBuilder<OptT = json.JsonObject, OutT extends BuilderOutput = BuilderOutput>(fn: BuilderHandlerFn<OptT>): Builder<OptT & json.JsonObject>; // @public function createDispatcher<A extends JsonValue, I extends JsonValue, O extends JsonValue>(options?: Partial<Readwrite<JobDescription>>): JobDispatcher<A, I, O>; // @public function createJobFactory<A extends JsonValue, I extends JsonValue, O extends JsonValue>(loader: () => Promise<JobHandler<A, I, O>>, options?: Partial<JobDescription>): JobHandler<A, I, O>; // @public function createJobHandler<A extends JsonValue, I extends JsonValue, O extends JsonValue>(fn: SimpleJobHandlerFn<A, I, O>, options?: Partial<JobDescription>): JobHandler<A, I, O>; // @public function createLoggerJob<A extends JsonValue, I extends JsonValue, O extends JsonValue>(job: JobHandler<A, I, O>, logger: logging.LoggerApi): JobHandler<A, I, O>; // @public class FallbackRegistry<MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue> implements Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> { constructor(_fallbacks?: Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT>[]); // (undocumented) addFallback(registry: Registry): void; // (undocumented) protected _fallbacks: Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT>[]; // (undocumented) get<A extends MinimumArgumentValueT = MinimumArgumentValueT, I extends MinimumInputValueT = MinimumInputValueT, O extends MinimumOutputValueT = MinimumOutputValueT>(name: JobName): Observable<JobHandler<A, I, O> | null>; } // @public (undocumented) export function fromAsyncIterable<T>(iterable: AsyncIterable<T>): Observable<T>; // @public (undocumented) export function isBuilderOutput(obj: any): obj is BuilderOutput; // @public (undocumented) function isJobHandler<A extends JsonValue, I extends JsonValue, O extends JsonValue>(value: unknown): value is JobHandler<A, I, O>; // @public interface Job<ArgumentT extends JsonValue = JsonValue, InputT extends JsonValue = JsonValue, OutputT extends JsonValue = JsonValue> { readonly argument: ArgumentT; readonly description: Observable<JobDescription>; getChannel<T extends JsonValue>(name: string, schema?: schema.JsonSchema): Observable<T>; readonly inboundBus: Observer<JobInboundMessage<InputT>>; readonly input: Observer<InputT>; readonly outboundBus: Observable<JobOutboundMessage<OutputT>>; readonly output: Observable<OutputT>; ping(): Observable<never>; readonly state: JobState; stop(): void; } // @public (undocumented) class JobArgumentSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]); } // @public interface JobDescription extends JsonObject { // (undocumented) readonly argument: DeepReadonly<schema.JsonSchema>; // (undocumented) readonly input: DeepReadonly<schema.JsonSchema>; // (undocumented) readonly name: JobName; // (undocumented) readonly output: DeepReadonly<schema.JsonSchema>; } // @public interface JobDispatcher<A extends JsonValue, I extends JsonValue, O extends JsonValue> extends JobHandler<A, I, O> { addConditionalJob(predicate: (args: A) => boolean, name: string): void; setDefaultJob(name: JobName | null | JobHandler<JsonValue, JsonValue, JsonValue>): void; } // @public (undocumented) class JobDoesNotExistException extends BaseException { constructor(name: JobName); } // @public interface JobHandler<ArgT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue> { // (undocumented) (argument: ArgT, context: JobHandlerContext<ArgT, InputT, OutputT>): Observable<JobOutboundMessage<OutputT>>; // (undocumented) jobDescription: Partial<JobDescription>; } // @public interface JobHandlerContext<MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue> { // (undocumented) readonly dependencies: Job<JsonValue, JsonValue, JsonValue>[]; // (undocumented) readonly description: JobDescription; // (undocumented) readonly inboundBus: Observable<JobInboundMessage<MinimumInputValueT>>; // (undocumented) readonly scheduler: Scheduler<JsonValue, JsonValue, JsonValue>; } // @public (undocumented) type JobInboundMessage<InputT extends JsonValue> = JobInboundMessagePing | JobInboundMessageStop | JobInboundMessageInput<InputT>; // @public interface JobInboundMessageBase extends JsonObject { readonly kind: JobInboundMessageKind; } // @public interface JobInboundMessageInput<InputT extends JsonValue> extends JobInboundMessageBase { // (undocumented) readonly kind: JobInboundMessageKind.Input; readonly value: InputT; } // @public enum JobInboundMessageKind {
{ "end_byte": 8658, "start_byte": 158, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/architect/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/architect/index.api.md_8659_17172
// (undocumented) Input = "in", // (undocumented) Ping = "ip", // (undocumented) Stop = "is" } // @public interface JobInboundMessagePing extends JobInboundMessageBase { readonly id: number; // (undocumented) readonly kind: JobInboundMessageKind.Ping; } // @public (undocumented) class JobInboundMessageSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]); } // @public interface JobInboundMessageStop extends JobInboundMessageBase { // (undocumented) readonly kind: JobInboundMessageKind.Stop; } // @public type JobName = string; // @public (undocumented) class JobNameAlreadyRegisteredException extends BaseException { constructor(name: JobName); } // @public type JobOutboundMessage<OutputT extends JsonValue> = JobOutboundMessageOnReady | JobOutboundMessageStart | JobOutboundMessageOutput<OutputT> | JobOutboundMessageChannelCreate | JobOutboundMessageChannelMessage | JobOutboundMessageChannelError | JobOutboundMessageChannelComplete | JobOutboundMessageEnd | JobOutboundMessagePong; // @public interface JobOutboundMessageBase { readonly description: JobDescription; readonly kind: JobOutboundMessageKind; } // @public interface JobOutboundMessageChannelBase extends JobOutboundMessageBase { readonly name: string; } // @public interface JobOutboundMessageChannelComplete extends JobOutboundMessageChannelBase { // (undocumented) readonly kind: JobOutboundMessageKind.ChannelComplete; } // @public interface JobOutboundMessageChannelCreate extends JobOutboundMessageChannelBase { // (undocumented) readonly kind: JobOutboundMessageKind.ChannelCreate; } // @public interface JobOutboundMessageChannelError extends JobOutboundMessageChannelBase { readonly error: JsonValue; // (undocumented) readonly kind: JobOutboundMessageKind.ChannelError; } // @public interface JobOutboundMessageChannelMessage extends JobOutboundMessageChannelBase { // (undocumented) readonly kind: JobOutboundMessageKind.ChannelMessage; readonly message: JsonValue; } // @public interface JobOutboundMessageEnd extends JobOutboundMessageBase { // (undocumented) readonly kind: JobOutboundMessageKind.End; } // @public enum JobOutboundMessageKind { // (undocumented) ChannelComplete = "cc", // (undocumented) ChannelCreate = "cn", // (undocumented) ChannelError = "ce", // (undocumented) ChannelMessage = "cm", // (undocumented) End = "e", // (undocumented) OnReady = "c", // (undocumented) Output = "o", // (undocumented) Pong = "p", // (undocumented) Start = "s" } // @public interface JobOutboundMessageOnReady extends JobOutboundMessageBase { // (undocumented) readonly kind: JobOutboundMessageKind.OnReady; } // @public interface JobOutboundMessageOutput<OutputT extends JsonValue> extends JobOutboundMessageBase { // (undocumented) readonly kind: JobOutboundMessageKind.Output; readonly value: OutputT; } // @public interface JobOutboundMessagePong extends JobOutboundMessageBase { readonly id: number; // (undocumented) readonly kind: JobOutboundMessageKind.Pong; } // @public interface JobOutboundMessageStart extends JobOutboundMessageBase { // (undocumented) readonly kind: JobOutboundMessageKind.Start; } // @public (undocumented) class JobOutputSchemaValidationError extends schema.SchemaValidationException { constructor(errors?: schema.SchemaValidatorError[]); } declare namespace jobs { export { strategy, isJobHandler, JobName, JobHandler, JobHandlerContext, JobDescription, JobInboundMessageKind, JobInboundMessageBase, JobInboundMessagePing, JobInboundMessageStop, JobInboundMessageInput, JobInboundMessage, JobOutboundMessageKind, JobOutboundMessageBase, JobOutboundMessageOnReady, JobOutboundMessageStart, JobOutboundMessageOutput, JobOutboundMessageChannelBase, JobOutboundMessageChannelMessage, JobOutboundMessageChannelError, JobOutboundMessageChannelCreate, JobOutboundMessageChannelComplete, JobOutboundMessageEnd, JobOutboundMessagePong, JobOutboundMessage, JobState, Job, ScheduleJobOptions, Registry, Scheduler, createJobHandler, createJobFactory, createLoggerJob, ChannelAlreadyExistException, SimpleJobHandlerContext, SimpleJobHandlerFn, JobNameAlreadyRegisteredException, JobDoesNotExistException, createDispatcher, JobDispatcher, FallbackRegistry, RegisterJobOptions, SimpleJobRegistry, JobArgumentSchemaValidationError, JobInboundMessageSchemaValidationError, JobOutputSchemaValidationError, SimpleScheduler } } export { jobs } // @public enum JobState { Ended = "ended", Errored = "errored", Queued = "queued", Ready = "ready", Started = "started" } // @public (undocumented) type JobStrategy<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue> = (handler: JobHandler<A, I, O>, options?: Partial<Readonly<JobDescription>>) => JobHandler<A, I, O>; // @public function memoize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>; // @public interface RegisterJobOptions extends Partial<JobDescription> { } // @public (undocumented) interface Registry<MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue> { get<A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT>(name: JobName): Observable<JobHandler<A, I, O> | null>; } // @public function reuse<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>; // @public interface ScheduleJobOptions { dependencies?: Job | Job[]; } // @public (undocumented) export interface ScheduleOptions { // (undocumented) logger?: logging.Logger; } // @public interface Scheduler<MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue> { getDescription(name: JobName): Observable<JobDescription | null>; has(name: JobName): Observable<boolean>; pause(): () => void; schedule<A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT>(name: JobName, argument: A, options?: ScheduleJobOptions): Job<A, I, O>; } // @public export function scheduleTargetAndForget(context: BuilderContext, target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Observable<BuilderOutput>; // @public function serialize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(): JobStrategy<A, I, O>; // @public interface SimpleJobHandlerContext<A extends JsonValue, I extends JsonValue, O extends JsonValue> extends JobHandlerContext<A, I, O> { // (undocumented) addTeardown(teardown: () => Promise<void> | void): void; // (undocumented) createChannel: (name: string) => Observer<JsonValue>; // (undocumented) input: Observable<I>; } // @public type SimpleJobHandlerFn<A extends JsonValue, I extends JsonValue, O extends JsonValue> = (input: A, context: SimpleJobHandlerContext<A, I, O>) => O | Promise<O> | Observable<O>; // @public class SimpleJobRegistry<MinimumArgumentValueT extends JsonValue = JsonValue, MinimumInputValueT extends JsonValue = JsonValue, MinimumOutputValueT extends JsonValue = JsonValue> implements Registry<MinimumArgumentValueT, MinimumInputValueT, MinimumOutputValueT> { // (undocumented) get<A extends MinimumArgumentValueT = MinimumArgumentValueT, I extends MinimumInputValueT = MinimumInputValueT, O extends MinimumOutputValueT = MinimumOutputValueT>(name: JobName): Observable<JobHandler<A, I, O> | null>; getJobNames(): JobName[]; register<A extends MinimumArgumentValueT, I extends MinimumInputValueT, O extends MinimumOutputValueT>(name: JobName, handler: JobHandler<A, I, O>
{ "end_byte": 17172, "start_byte": 8659, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/architect/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/architect/index.api.md_17172_19599
, options?: RegisterJobOptions): void; register<ArgumentT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue>(handler: JobHandler<ArgumentT, InputT, OutputT>, options?: RegisterJobOptions & { name: string; }): void; // (undocumented) protected _register<ArgumentT extends JsonValue, InputT extends JsonValue, OutputT extends JsonValue>(name: JobName, handler: JobHandler<ArgumentT, InputT, OutputT>, options: RegisterJobOptions): void; } // @public class SimpleScheduler<MinimumArgumentT extends JsonValue = JsonValue, MinimumInputT extends JsonValue = JsonValue, MinimumOutputT extends JsonValue = JsonValue> implements Scheduler<MinimumArgumentT, MinimumInputT, MinimumOutputT> { constructor(_jobRegistry: Registry<MinimumArgumentT, MinimumInputT, MinimumOutputT>, _schemaRegistry?: schema.SchemaRegistry); getDescription(name: JobName): Observable<JobDescription | null>; has(name: JobName): Observable<boolean>; // (undocumented) protected _jobRegistry: Registry<MinimumArgumentT, MinimumInputT, MinimumOutputT>; pause(): () => void; schedule<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>(name: JobName, argument: A, options?: ScheduleJobOptions): Job<A, I, O>; // (undocumented) protected _scheduleJob<A extends MinimumArgumentT, I extends MinimumInputT, O extends MinimumOutputT>(name: JobName, argument: A, options: ScheduleJobOptions, waitable: Observable<never>): Job<A, I, O>; // (undocumented) protected _schemaRegistry: schema.SchemaRegistry; } declare namespace strategy { export { serialize, reuse, memoize, JobStrategy } } // @public (undocumented) export type Target = json.JsonObject & Target_2; // @public export function targetFromTargetString(specifier: string, abbreviatedProjectName?: string, abbreviatedTargetName?: string): Target; // @public export function targetStringFromTarget({ project, target, configuration }: Target): string; // @public export type TypedBuilderProgress = { state: BuilderProgressState.Stopped; } | { state: BuilderProgressState.Error; error: json.JsonValue; } | { state: BuilderProgressState.Waiting; status?: string; } | { state: BuilderProgressState.Running; status?: string; current: number; total?: number; }; // (No @packageDocumentation comment for this package) ```
{ "end_byte": 19599, "start_byte": 17172, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/architect/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/build_webpack/index.api.md_0_2226
## API Report File for "@angular-devkit/build-webpack" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts import { BuilderContext } from '@angular-devkit/architect'; import { BuilderOutput } from '@angular-devkit/architect'; import { Observable } from 'rxjs'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; // @public (undocumented) export type BuildResult = BuilderOutput & { emittedFiles?: EmittedFiles[]; webpackStats?: webpack.StatsCompilation; outputPath: string; }; // @public (undocumented) export type DevServerBuildOutput = BuildResult & { port: number; family: string; address: string; }; // @public (undocumented) export interface EmittedFiles { // (undocumented) asset?: boolean; // (undocumented) extension: string; // (undocumented) file: string; // (undocumented) id?: string; // (undocumented) initial: boolean; // (undocumented) name?: string; } // @public (undocumented) export function runWebpack(config: webpack.Configuration, context: BuilderContext, options?: { logging?: WebpackLoggingCallback; webpackFactory?: WebpackFactory; shouldProvideStats?: boolean; }): Observable<BuildResult>; // @public (undocumented) export function runWebpackDevServer(config: webpack.Configuration, context: BuilderContext, options?: { shouldProvideStats?: boolean; devServerConfig?: WebpackDevServer.Configuration; logging?: WebpackLoggingCallback; webpackFactory?: WebpackFactory; webpackDevServerFactory?: WebpackDevServerFactory; }): Observable<DevServerBuildOutput>; // @public (undocumented) export type WebpackBuilderSchema = Schema; // @public (undocumented) export type WebpackDevServerFactory = typeof WebpackDevServer; // @public (undocumented) export interface WebpackFactory { // (undocumented) (config: webpack.Configuration): Observable<webpack.Compiler> | webpack.Compiler; } // @public (undocumented) export interface WebpackLoggingCallback { // (undocumented) (stats: webpack.Stats, config: webpack.Configuration): void; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 2226, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/build_webpack/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/index.api.md_0_158
## API Report File for "@angular-devkit/schematics" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts
{ "end_byte": 158, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/index.api.md_159_8552
import { BaseException } from '@angular-devkit/core'; import { JsonValue } from '@angular-devkit/core'; import { logging } from '@angular-devkit/core'; import { Observable } from 'rxjs'; import { Path } from '@angular-devkit/core'; import { PathFragment } from '@angular-devkit/core'; import { schema } from '@angular-devkit/core'; import { strings } from '@angular-devkit/core'; import { Subject } from 'rxjs'; import { Url } from 'url'; import { virtualFs } from '@angular-devkit/core'; // @public (undocumented) export type Action = CreateFileAction | OverwriteFileAction | RenameFileAction | DeleteFileAction; // @public (undocumented) export interface ActionBase { // (undocumented) readonly id: number; // (undocumented) readonly parent: number; // (undocumented) readonly path: Path; } // @public (undocumented) export class ActionList implements Iterable<Action> { // (undocumented) [Symbol.iterator](): IterableIterator<Action>; // (undocumented) protected _action(action: Partial<Action>): void; // (undocumented) create(path: Path, content: Buffer): void; // (undocumented) delete(path: Path): void; // (undocumented) find(predicate: (value: Action) => boolean): Action | null; // (undocumented) forEach(fn: (value: Action, index: number, array: Action[]) => void, thisArg?: {}): void; // (undocumented) get(i: number): Action; // (undocumented) has(action: Action): boolean; // (undocumented) get length(): number; // (undocumented) optimize(): void; // (undocumented) overwrite(path: Path, content: Buffer): void; // (undocumented) push(action: Action): void; // (undocumented) rename(path: Path, to: Path): void; } // @public export function apply(source: Source, rules: Rule[]): Source; // @public (undocumented) export function applyContentTemplate<T>(options: T): FileOperator; // @public (undocumented) export function applyPathTemplate<T extends PathTemplateData>(data: T, options?: PathTemplateOptions): FileOperator; // @public (undocumented) export function applyTemplates<T extends object>(options: T): Rule; // @public (undocumented) export function applyToSubtree(path: string, rules: Rule[]): Rule; // @public (undocumented) export function asSource(rule: Rule): Source; // @public (undocumented) export type AsyncFileOperator = (tree: FileEntry) => Observable<FileEntry | null>; // @public abstract class BaseWorkflow implements Workflow { constructor(options: BaseWorkflowOptions); // (undocumented) get context(): Readonly<WorkflowExecutionContext>; // (undocumented) protected _context: WorkflowExecutionContext[]; // (undocumented) protected _createSinks(): Sink[]; // (undocumented) protected _dryRun: boolean; // (undocumented) get engine(): Engine<{}, {}>; // (undocumented) protected _engine: Engine<{}, {}>; // (undocumented) get engineHost(): EngineHost<{}, {}>; // (undocumented) protected _engineHost: EngineHost<{}, {}>; // (undocumented) execute(options: Partial<WorkflowExecutionContext> & RequiredWorkflowExecutionContext): Observable<void>; // (undocumented) protected _force: boolean; // (undocumented) protected _host: virtualFs.Host; // (undocumented) get lifeCycle(): Observable<LifeCycleEvent>; // (undocumented) protected _lifeCycle: Subject<LifeCycleEvent>; // (undocumented) get registry(): schema.SchemaRegistry; // (undocumented) protected _registry: schema.CoreSchemaRegistry; // (undocumented) get reporter(): Observable<DryRunEvent>; // (undocumented) protected _reporter: Subject<DryRunEvent>; } // @public (undocumented) interface BaseWorkflowOptions { // (undocumented) dryRun?: boolean; // (undocumented) engineHost: EngineHost<{}, {}>; // (undocumented) force?: boolean; // (undocumented) host: virtualFs.Host; // (undocumented) registry?: schema.CoreSchemaRegistry; } // @public (undocumented) export function branchAndMerge(rule: Rule, strategy?: MergeStrategy): Rule; // @public (undocumented) export function callRule(rule: Rule, input: Tree_2 | Observable<Tree_2>, context: SchematicContext): Observable<Tree_2>; // @public (undocumented) export function callSource(source: Source, context: SchematicContext): Observable<Tree_2>; // @public export function chain(rules: Iterable<Rule> | AsyncIterable<Rule>): Rule; // @public (undocumented) export class CircularCollectionException extends BaseException { constructor(name: string); } // @public export interface Collection<CollectionMetadataT extends object, SchematicMetadataT extends object> { // (undocumented) readonly baseDescriptions?: Array<CollectionDescription<CollectionMetadataT>>; // (undocumented) createSchematic(name: string, allowPrivate?: boolean): Schematic<CollectionMetadataT, SchematicMetadataT>; // (undocumented) readonly description: CollectionDescription<CollectionMetadataT>; // (undocumented) listSchematicNames(includeHidden?: boolean): string[]; } // @public export type CollectionDescription<CollectionMetadataT extends object> = CollectionMetadataT & { readonly name: string; readonly extends?: string[]; }; // @public (undocumented) export class CollectionImpl<CollectionT extends object, SchematicT extends object> implements Collection<CollectionT, SchematicT> { constructor(_description: CollectionDescription<CollectionT>, _engine: SchematicEngine<CollectionT, SchematicT>, baseDescriptions?: Array<CollectionDescription<CollectionT>> | undefined); // (undocumented) readonly baseDescriptions?: Array<CollectionDescription<CollectionT>> | undefined; // (undocumented) createSchematic(name: string, allowPrivate?: boolean): Schematic<CollectionT, SchematicT>; // (undocumented) get description(): CollectionDescription<CollectionT>; // (undocumented) listSchematicNames(includeHidden?: boolean): string[]; // (undocumented) get name(): string; } // @public (undocumented) export function composeFileOperators(operators: FileOperator[]): FileOperator; // @public (undocumented) export class ContentHasMutatedException extends BaseException { constructor(path: string); } // @public (undocumented) export function contentTemplate<T>(options: T): Rule; // @public (undocumented) export interface CreateFileAction extends ActionBase { // (undocumented) readonly content: Buffer; // (undocumented) readonly kind: 'c'; } // @public (undocumented) export class DelegateTree implements Tree_2 { constructor(_other: Tree_2); // (undocumented) get actions(): Action[]; // (undocumented) apply(action: Action, strategy?: MergeStrategy): void; // (undocumented) beginUpdate(path: string): UpdateRecorder; // (undocumented) branch(): Tree_2; // (undocumented) commitUpdate(record: UpdateRecorder): void; // (undocumented) create(path: string, content: Buffer | string): void; // (undocumented) delete(path: string): void; // (undocumented) exists(path: string): boolean; // (undocumented) get(path: string): FileEntry | null; // (undocumented) getDir(path: string): DirEntry; // (undocumented) merge(other: Tree_2, strategy?: MergeStrategy): void; // (undocumented) protected _other: Tree_2; // (undocumented) overwrite(path: string, content: Buffer | string): void; // (undocumented) read(path: string): Buffer | null; // (undocumented) readJson(path: string): JsonValue; // (undocumented) readText(path: string): string; // (undocumented) rename(from: string, to: string): void; // (undocumented) get root(): DirEntry; // (undocumented) visit(visitor: FileVisitor): void; } // @public (undocumented) export interface DeleteFileAction extends ActionBase { // (undocumented) readonly kind: 'd'; } // @public (undocumented) export interface DirEntry { // (undocumented) dir(name: PathFragment): DirEntry; // (undocumented) file(name: PathFragment): FileEntry | null; // (undocumented) readonly parent: DirEntry | null; // (undocumented) readonly path: Path; // (undocumented) readonly subdirs: PathFragment[
{ "end_byte": 8552, "start_byte": 159, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/index.api.md_8552_17160
]; // (undocumented) readonly subfiles: PathFragment[]; // (undocumented) visit(visitor: FileVisitor): void; } // @public (undocumented) export interface DryRunCreateEvent { // (undocumented) content: Buffer; // (undocumented) kind: 'create'; // (undocumented) path: string; } // @public (undocumented) export interface DryRunDeleteEvent { // (undocumented) kind: 'delete'; // (undocumented) path: string; } // @public (undocumented) export interface DryRunErrorEvent { // (undocumented) description: 'alreadyExist' | 'doesNotExist'; // (undocumented) kind: 'error'; // (undocumented) path: string; } // @public (undocumented) export type DryRunEvent = DryRunErrorEvent | DryRunDeleteEvent | DryRunCreateEvent | DryRunUpdateEvent | DryRunRenameEvent; // @public (undocumented) export interface DryRunRenameEvent { // (undocumented) kind: 'rename'; // (undocumented) path: string; // (undocumented) to: string; } // @public (undocumented) export class DryRunSink extends HostSink { constructor(host: virtualFs.Host, force?: boolean); // (undocumented) _done(): Observable<void>; // (undocumented) protected _fileAlreadyExistException(path: string): void; // (undocumented) protected _fileAlreadyExistExceptionSet: Set<string>; // (undocumented) protected _fileDoesNotExistException(path: string): void; // (undocumented) protected _fileDoesNotExistExceptionSet: Set<string>; // (undocumented) readonly reporter: Observable<DryRunEvent>; // (undocumented) protected _subject: Subject<DryRunEvent>; } // @public (undocumented) export interface DryRunUpdateEvent { // (undocumented) content: Buffer; // (undocumented) kind: 'update'; // (undocumented) path: string; } // @public export function empty(): Source; // @public (undocumented) export class EmptyTree extends HostTree { constructor(); } // @public export interface Engine<CollectionMetadataT extends object, SchematicMetadataT extends object> { // (undocumented) createCollection(name: string, requester?: Collection<CollectionMetadataT, SchematicMetadataT>): Collection<CollectionMetadataT, SchematicMetadataT>; // (undocumented) createContext(schematic: Schematic<CollectionMetadataT, SchematicMetadataT>, parent?: Partial<TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>>, executionOptions?: Partial<ExecutionOptions>): TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>; // (undocumented) createSchematic(name: string, collection: Collection<CollectionMetadataT, SchematicMetadataT>): Schematic<CollectionMetadataT, SchematicMetadataT>; // (undocumented) createSourceFromUrl(url: Url, context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>): Source; // (undocumented) readonly defaultMergeStrategy: MergeStrategy; // (undocumented) executePostTasks(): Observable<void>; // (undocumented) transformOptions<OptionT extends object, ResultT extends object>(schematic: Schematic<CollectionMetadataT, SchematicMetadataT>, options: OptionT, context?: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>): Observable<ResultT>; // (undocumented) readonly workflow: Workflow | null; } // @public export interface EngineHost<CollectionMetadataT extends object, SchematicMetadataT extends object> { // (undocumented) createCollectionDescription(name: string, requester?: CollectionDescription<CollectionMetadataT>): CollectionDescription<CollectionMetadataT>; // (undocumented) createSchematicDescription(name: string, collection: CollectionDescription<CollectionMetadataT>): SchematicDescription<CollectionMetadataT, SchematicMetadataT> | null; // (undocumented) createSourceFromUrl(url: Url, context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>): Source | null; // (undocumented) createTaskExecutor(name: string): Observable<TaskExecutor>; // (undocumented) readonly defaultMergeStrategy?: MergeStrategy; // (undocumented) getSchematicRuleFactory<OptionT extends object>(schematic: SchematicDescription<CollectionMetadataT, SchematicMetadataT>, collection: CollectionDescription<CollectionMetadataT>): RuleFactory<OptionT>; // (undocumented) hasTaskExecutor(name: string): boolean; // (undocumented) listSchematicNames(collection: CollectionDescription<CollectionMetadataT>, includeHidden?: boolean): string[]; // (undocumented) transformContext(context: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>): TypedSchematicContext<CollectionMetadataT, SchematicMetadataT> | void; // (undocumented) transformOptions<OptionT extends object, ResultT extends object>(schematic: SchematicDescription<CollectionMetadataT, SchematicMetadataT>, options: OptionT, context?: TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>): Observable<ResultT>; } // @public (undocumented) export interface ExecutionOptions { // (undocumented) interactive: boolean; // (undocumented) scope: string; } // @public export function externalSchematic<OptionT extends object>(collectionName: string, schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>): Rule; // @public (undocumented) export class FileAlreadyExistException extends BaseException { constructor(path: string); } // @public (undocumented) export class FileDoesNotExistException extends BaseException { constructor(path: string); } // @public (undocumented) export interface FileEntry { // (undocumented) readonly content: Buffer; // (undocumented) readonly path: Path; } // @public export type FileOperator = (entry: FileEntry) => FileEntry | null; // @public (undocumented) export interface FilePredicate<T> { // (undocumented) (path: Path, entry?: Readonly<FileEntry> | null): T; } // @public (undocumented) export type FileVisitor = FilePredicate<void>; // @public (undocumented) export const FileVisitorCancelToken: symbol; // @public (undocumented) export function filter(predicate: FilePredicate<boolean>): Rule; // @public (undocumented) export class FilterHostTree extends HostTree { constructor(tree: HostTree, filter?: FilePredicate<boolean>); } // @public (undocumented) export function forEach(operator: FileOperator): Rule; declare namespace formats { export { htmlSelectorFormat, pathFormat, standardFormats } } export { formats } // @public (undocumented) export class HostCreateTree extends HostTree { constructor(host: virtualFs.ReadonlyHost); } // @public (undocumented) export class HostDirEntry implements DirEntry { constructor(parent: DirEntry | null, path: Path, _host: virtualFs.SyncDelegateHost, _tree: Tree_2); // (undocumented) dir(name: PathFragment): DirEntry; // (undocumented) file(name: PathFragment): FileEntry | null; // (undocumented) protected _host: virtualFs.SyncDelegateHost; // (undocumented) readonly parent: DirEntry | null; // (undocumented) readonly path: Path; // (undocumented) get subdirs(): PathFragment[]; // (undocumented) get subfiles(): PathFragment[]; // (undocumented) protected _tree: Tree_2; // (undocumented) visit(visitor: FileVisitor): void; } // @public (undocumented) export class HostSink extends SimpleSinkBase { constructor(_host: virtualFs.Host, _force?: boolean); // (undocumented) protected _createFile(path: Path, content: Buffer): Observable<void>; // (undocumented) protected _deleteFile(path: Path): Observable<void>; // (undocumented) _done(): Observable<void>; // (undocumented) protected _filesToCreate: Map<Path, Buffer<ArrayBufferLike>>; // (undocumented) protected _filesToDelete: Set<Path>; // (undocumented) protected _filesToRename: Set<[Path, Path]>; // (undocumented) protected _filesToUpdate: Map<Path, Buffer<ArrayBufferLike>>; // (undocumented) protected _force: boolean; // (undocumented) protected _host: virtualFs.Host; // (undocumented) protected _overwriteFile(path: Path, content: Buffer): Observable<void>; // (undocumented) protected _renameFile(from: Path, to: Path): Observable<void>; // (undocumented) protected _validateCreateAction(action: CreateFileAction): Observable<void>; // (undocumented) protected _validateFileExists(p: Path): Observable<boolean>; }
{ "end_byte": 17160, "start_byte": 8552, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/index.api.md_17160_25635
// @public (undocumented) export class HostTree implements Tree_2 { constructor(_backend?: virtualFs.ReadonlyHost<{}>); // (undocumented) get actions(): Action[]; // (undocumented) apply(action: Action, strategy?: MergeStrategy): void; // (undocumented) protected _backend: virtualFs.ReadonlyHost<{}>; // (undocumented) beginUpdate(path: string): UpdateRecorder; // (undocumented) branch(): Tree_2; // (undocumented) commitUpdate(record: UpdateRecorder): void; // (undocumented) create(path: string, content: Buffer | string): void; // (undocumented) delete(path: string): void; // (undocumented) exists(path: string): boolean; // (undocumented) get(path: string): FileEntry | null; // (undocumented) getDir(path: string): DirEntry; // (undocumented) static isHostTree(tree: Tree_2): tree is HostTree; // (undocumented) merge(other: Tree_2, strategy?: MergeStrategy): void; // (undocumented) protected _normalizePath(path: string): Path; // (undocumented) overwrite(path: string, content: Buffer | string): void; // (undocumented) read(path: string): Buffer | null; // (undocumented) readJson(path: string): JsonValue; // (undocumented) readText(path: string): string; // (undocumented) rename(from: string, to: string): void; // (undocumented) get root(): DirEntry; // (undocumented) visit(visitor: FileVisitor): void; // (undocumented) protected _willCreate(path: Path): boolean; // (undocumented) protected _willDelete(path: Path): boolean; // (undocumented) protected _willOverwrite(path: Path): boolean; // (undocumented) protected _willRename(path: Path): boolean; } // @public (undocumented) const htmlSelectorFormat: schema.SchemaFormat; // @public (undocumented) export class InvalidPipeException extends BaseException { constructor(name: string); } // @public export class InvalidRuleResultException extends BaseException { constructor(value?: {}); } // @public (undocumented) export class InvalidSchematicsNameException extends BaseException { constructor(name: string); } // @public (undocumented) export class InvalidSourceResultException extends BaseException { constructor(value?: {}); } // @public (undocumented) export class InvalidUpdateRecordException extends BaseException { constructor(); } // @public (undocumented) export function isContentAction(action: Action): action is CreateFileAction | OverwriteFileAction; // @public (undocumented) interface LifeCycleEvent { // (undocumented) kind: 'start' | 'end' | 'workflow-start' | 'workflow-end' | 'post-tasks-start' | 'post-tasks-end'; } // @public (undocumented) export class MergeConflictException extends BaseException { constructor(path: string); } // @public (undocumented) export enum MergeStrategy { // (undocumented) AllowCreationConflict = 4, // (undocumented) AllowDeleteConflict = 8, // (undocumented) AllowOverwriteConflict = 2, // (undocumented) ContentOnly = 2, // (undocumented) Default = 0, // (undocumented) Error = 1, // (undocumented) Overwrite = 14 } // @public export function mergeWith(source: Source, strategy?: MergeStrategy): Rule; // @public (undocumented) export function move(from: string, to?: string): Rule; // @public (undocumented) export function noop(): Rule; // @public (undocumented) export class OptionIsNotDefinedException extends BaseException { constructor(name: string); } // @public (undocumented) export interface OverwriteFileAction extends ActionBase { // (undocumented) readonly content: Buffer; // (undocumented) readonly kind: 'o'; } // @public (undocumented) export function partitionApplyMerge(predicate: FilePredicate<boolean>, ruleYes: Rule, ruleNo?: Rule): Rule; // @public (undocumented) const pathFormat: schema.SchemaFormat; // @public (undocumented) export function pathTemplate<T extends PathTemplateData>(options: T): Rule; // @public (undocumented) export type PathTemplateData = { [key: string]: PathTemplateValue | PathTemplateData | PathTemplatePipeFunction; }; // @public (undocumented) export interface PathTemplateOptions { // (undocumented) interpolationEnd: string; // (undocumented) interpolationStart: string; // (undocumented) pipeSeparator?: string; } // @public (undocumented) export type PathTemplatePipeFunction = (x: string) => PathTemplateValue; // @public (undocumented) export type PathTemplateValue = boolean | string | number | undefined; // @public (undocumented) export class PrivateSchematicException extends BaseException { constructor(name: string, collection: CollectionDescription<{}>); } // @public (undocumented) export interface RandomOptions { // (undocumented) multi?: boolean | number; // (undocumented) multiFiles?: boolean | number; // (undocumented) root?: string; } // @public (undocumented) export interface RenameFileAction extends ActionBase { // (undocumented) readonly kind: 'r'; // (undocumented) readonly to: Path; } // @public export function renameTemplateFiles(): Rule; // @public (undocumented) interface RequiredWorkflowExecutionContext { // (undocumented) collection: string; // (undocumented) options: object; // (undocumented) schematic: string; } // @public (undocumented) export type Rule = (tree: Tree_2, context: SchematicContext) => Tree_2 | Observable<Tree_2> | Rule | Promise<void | Rule> | void; // @public export type RuleFactory<T extends object> = (options: T) => Rule; // @public export interface Schematic<CollectionMetadataT extends object, SchematicMetadataT extends object> { // (undocumented) call<OptionT extends object>(options: OptionT, host: Observable<Tree_2>, parentContext?: Partial<TypedSchematicContext<CollectionMetadataT, SchematicMetadataT>>, executionOptions?: Partial<ExecutionOptions>): Observable<Tree_2>; // (undocumented) readonly collection: Collection<CollectionMetadataT, SchematicMetadataT>; // (undocumented) readonly description: SchematicDescription<CollectionMetadataT, SchematicMetadataT>; } // @public export function schematic<OptionT extends object>(schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>): Rule; // @public export type SchematicContext = TypedSchematicContext<{}, {}>; // @public export type SchematicDescription<CollectionMetadataT extends object, SchematicMetadataT extends object> = SchematicMetadataT & { readonly collection: CollectionDescription<CollectionMetadataT>; readonly name: string; readonly private?: boolean; readonly hidden?: boolean; }; // @public (undocumented) export class SchematicEngine<CollectionT extends object, SchematicT extends object> implements Engine<CollectionT, SchematicT> { constructor(_host: EngineHost<CollectionT, SchematicT>, _workflow?: Workflow | undefined); // (undocumented) createCollection(name: string, requester?: Collection<CollectionT, SchematicT>): Collection<CollectionT, SchematicT>; // (undocumented) createContext(schematic: Schematic<CollectionT, SchematicT>, parent?: Partial<TypedSchematicContext<CollectionT, SchematicT>>, executionOptions?: Partial<ExecutionOptions>): TypedSchematicContext<CollectionT, SchematicT>; // (undocumented) createSchematic(name: string, collection: Collection<CollectionT, SchematicT>, allowPrivate?: boolean): Schematic<CollectionT, SchematicT>; // (undocumented) createSourceFromUrl(url: Url, context: TypedSchematicContext<CollectionT, SchematicT>): Source; // (undocumented) get defaultMergeStrategy(): MergeStrategy; // (undocumented) executePostTasks(): Observable<void>; // (undocumented) listSchematicNames(collection: Collection<CollectionT, SchematicT>, includeHidden?: boolean): string[]; // (undocumented) transformOptions<OptionT extends object, ResultT extends object>(schematic: Schematic<CollectionT, SchematicT>, options: OptionT, context?: TypedSchematicContext<CollectionT, SchematicT>): Observable<ResultT>; // (undocumented) get workflow(): Workflow | null; // (undocumented) protected _workflow?: Workflow | undefined; } // @public (undocumented) export class SchematicEngineConflictingException extends BaseException {
{ "end_byte": 25635, "start_byte": 17160, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/index.api.md_25636_34096
constructor(); } // @public (undocumented) export class SchematicImpl<CollectionT extends object, SchematicT extends object> implements Schematic<CollectionT, SchematicT> { constructor(_description: SchematicDescription<CollectionT, SchematicT>, _factory: RuleFactory<{}>, _collection: Collection<CollectionT, SchematicT>, _engine: Engine<CollectionT, SchematicT>); // (undocumented) call<OptionT extends object>(options: OptionT, host: Observable<Tree_2>, parentContext?: Partial<TypedSchematicContext<CollectionT, SchematicT>>, executionOptions?: Partial<ExecutionOptions>): Observable<Tree_2>; // (undocumented) get collection(): Collection<CollectionT, SchematicT>; // (undocumented) get description(): SchematicDescription<CollectionT, SchematicT>; } // @public (undocumented) export class SchematicsException extends BaseException { } // @public (undocumented) export abstract class SimpleSinkBase implements Sink { // (undocumented) commit(tree: Tree_2): Observable<void>; // (undocumented) commitSingleAction(action: Action): Observable<void>; // (undocumented) protected abstract _createFile(path: string, content: Buffer): Observable<void>; // (undocumented) protected abstract _deleteFile(path: string): Observable<void>; // (undocumented) protected abstract _done(): Observable<void>; // (undocumented) protected _fileAlreadyExistException(path: string): void; // (undocumented) protected _fileDoesNotExistException(path: string): void; // (undocumented) protected abstract _overwriteFile(path: string, content: Buffer): Observable<void>; // (undocumented) postCommit: () => void | Observable<void>; // (undocumented) postCommitAction: (action: Action) => void | Observable<void>; // (undocumented) preCommit: () => void | Observable<void>; // (undocumented) preCommitAction: (action: Action) => void | Action | PromiseLike<Action> | Observable<Action>; // (undocumented) protected abstract _renameFile(path: string, to: string): Observable<void>; // (undocumented) protected _validateCreateAction(action: CreateFileAction): Observable<void>; // (undocumented) protected _validateDeleteAction(action: DeleteFileAction): Observable<void>; // (undocumented) protected abstract _validateFileExists(p: string): Observable<boolean>; // (undocumented) protected _validateOverwriteAction(action: OverwriteFileAction): Observable<void>; // (undocumented) protected _validateRenameAction(action: RenameFileAction): Observable<void>; // (undocumented) validateSingleAction(action: Action): Observable<void>; } // @public (undocumented) export interface Sink { // (undocumented) commit(tree: Tree_2): Observable<void>; } // @public export type Source = (context: SchematicContext) => Tree_2 | Observable<Tree_2>; // @public export function source(tree: Tree_2): Source; // @public (undocumented) const standardFormats: schema.SchemaFormat[]; export { strings } // @public (undocumented) export interface TaskConfiguration<T = {}> { // (undocumented) dependencies?: Array<TaskId>; // (undocumented) name: string; // (undocumented) options?: T; } // @public (undocumented) export interface TaskConfigurationGenerator<T = {}> { // (undocumented) toConfiguration(): TaskConfiguration<T>; } // @public (undocumented) export type TaskExecutor<T = {}> = (options: T | undefined, context: SchematicContext) => Promise<void> | Observable<void>; // @public (undocumented) export interface TaskExecutorFactory<T> { // (undocumented) create(options?: T): Promise<TaskExecutor> | Observable<TaskExecutor>; // (undocumented) readonly name: string; } // @public (undocumented) export interface TaskId { // (undocumented) readonly id: number; } // @public (undocumented) export interface TaskInfo { // (undocumented) readonly configuration: TaskConfiguration; // (undocumented) readonly context: SchematicContext; // (undocumented) readonly id: number; // (undocumented) readonly priority: number; } // @public (undocumented) export class TaskScheduler { constructor(_context: SchematicContext); // (undocumented) finalize(): ReadonlyArray<TaskInfo>; // (undocumented) schedule<T extends object>(taskConfiguration: TaskConfiguration<T>): TaskId; } // @public (undocumented) export function template<T extends object>(options: T): Rule; // @public (undocumented) export const TEMPLATE_FILENAME_RE: RegExp; // @public (undocumented) export type Tree = Tree_2; // @public (undocumented) export const Tree: TreeConstructor; // @public (undocumented) export interface TreeConstructor { // (undocumented) branch(tree: Tree_2): Tree_2; // (undocumented) empty(): Tree_2; // (undocumented) merge(tree: Tree_2, other: Tree_2, strategy?: MergeStrategy): Tree_2; // (undocumented) optimize(tree: Tree_2): Tree_2; // (undocumented) partition(tree: Tree_2, predicate: FilePredicate<boolean>): [Tree_2, Tree_2]; } // @public (undocumented) export const TreeSymbol: symbol; // @public export interface TypedSchematicContext<CollectionMetadataT extends object, SchematicMetadataT extends object> { // (undocumented) addTask<T extends object>(task: TaskConfigurationGenerator<T>, dependencies?: Array<TaskId>): TaskId; // (undocumented) readonly debug: boolean; // (undocumented) readonly engine: Engine<CollectionMetadataT, SchematicMetadataT>; // (undocumented) readonly interactive: boolean; // (undocumented) readonly logger: logging.LoggerApi; // (undocumented) readonly schematic: Schematic<CollectionMetadataT, SchematicMetadataT>; // (undocumented) readonly strategy: MergeStrategy; } // @public (undocumented) export class UnimplementedException extends BaseException { constructor(); } // @public (undocumented) export class UnknownActionException extends BaseException { constructor(action: Action); } // @public (undocumented) export class UnknownCollectionException extends BaseException { constructor(name: string); } // @public (undocumented) export class UnknownPipeException extends BaseException { constructor(name: string); } // @public (undocumented) export class UnknownSchematicException extends BaseException { constructor(name: string, collection: CollectionDescription<{}>); } // @public (undocumented) export class UnknownTaskDependencyException extends BaseException { constructor(id: TaskId); } // @public (undocumented) export class UnknownUrlSourceProtocol extends BaseException { constructor(url: string); } // @public (undocumented) export class UnregisteredTaskException extends BaseException { constructor(name: string, schematic?: SchematicDescription<{}, {}>); } // @public (undocumented) export class UnsuccessfulWorkflowExecution extends BaseException { constructor(); } // @public (undocumented) export interface UpdateRecorder { // (undocumented) insertLeft(index: number, content: Buffer | string): UpdateRecorder; // (undocumented) insertRight(index: number, content: Buffer | string): UpdateRecorder; // (undocumented) remove(index: number, length: number): UpdateRecorder; } // @public (undocumented) export function url(urlString: string): Source; // @public (undocumented) export function when(predicate: FilePredicate<boolean>, operator: FileOperator): FileOperator; // @public (undocumented) interface Workflow { // (undocumented) readonly context: Readonly<WorkflowExecutionContext>; // (undocumented) execute(options: Partial<WorkflowExecutionContext> & RequiredWorkflowExecutionContext): Observable<void>; } declare namespace workflow { export { BaseWorkflowOptions, BaseWorkflow, RequiredWorkflowExecutionContext, WorkflowExecutionContext, LifeCycleEvent, Workflow } } export { workflow } // @public (undocumented) interface WorkflowExecutionContext extends RequiredWorkflowExecutionContext { // (undocumented) allowPrivate?: boolean; // (undocumented) debug: boolean; // (undocumented) logger: logging.Logger; // (undocumented) parentContext?: Readonly<WorkflowExecutionContext>; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 34096, "start_byte": 25636, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/index.api.md" }
angular-cli/goldens/public-api/angular_devkit/schematics/tasks/index.api.md_0_2259
## API Report File for "@angular-devkit/schematics_tasks" > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts // @public (undocumented) export class NodePackageInstallTask implements TaskConfigurationGenerator<NodePackageTaskOptions> { constructor(workingDirectory?: string); constructor(options: NodePackageInstallTaskOptions); // (undocumented) allowScripts: boolean; // (undocumented) hideOutput: boolean; // (undocumented) packageManager?: string; // (undocumented) packageName?: string; // (undocumented) quiet: boolean; // (undocumented) toConfiguration(): TaskConfiguration<NodePackageTaskOptions>; // (undocumented) workingDirectory?: string; } // @public @deprecated (undocumented) export class NodePackageLinkTask implements TaskConfigurationGenerator<NodePackageTaskOptions> { constructor(packageName?: string | undefined, workingDirectory?: string | undefined); // (undocumented) packageName?: string | undefined; // (undocumented) quiet: boolean; // (undocumented) toConfiguration(): TaskConfiguration<NodePackageTaskOptions>; // (undocumented) workingDirectory?: string | undefined; } // @public (undocumented) export class RepositoryInitializerTask implements TaskConfigurationGenerator<RepositoryInitializerTaskOptions> { constructor(workingDirectory?: string | undefined, commitOptions?: CommitOptions | undefined); // (undocumented) commitOptions?: CommitOptions | undefined; // (undocumented) toConfiguration(): TaskConfiguration<RepositoryInitializerTaskOptions>; // (undocumented) workingDirectory?: string | undefined; } // @public (undocumented) export class RunSchematicTask<T> implements TaskConfigurationGenerator<RunSchematicTaskOptions<T>> { constructor(s: string, o: T); constructor(c: string, s: string, o: T); // (undocumented) protected _collection: string | null; // (undocumented) protected _options: T; // (undocumented) protected _schematic: string; // (undocumented) toConfiguration(): TaskConfiguration<RunSchematicTaskOptions<T>>; } // (No @packageDocumentation comment for this package) ```
{ "end_byte": 2259, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/goldens/public-api/angular_devkit/schematics/tasks/index.api.md" }