diff --git a/packages/angular_devkit/core/src/exception.ts b/packages/angular_devkit/core/src/exception.ts index cd55d27e8a9a..7c439528dc6f 100644 --- a/packages/angular_devkit/core/src/exception.ts +++ b/packages/angular_devkit/core/src/exception.ts @@ -39,3 +39,13 @@ export class PathIsFileException extends BaseException { super(`Path "${path}" is a file.`); } } +export class DependencyNotFoundException extends BaseException { + constructor() { + super('One of the dependencies is not part of the set.'); + } +} +export class CircularDependencyFoundException extends BaseException { + constructor() { + super('Circular dependencies found.'); + } +} diff --git a/packages/angular_devkit/core/src/json/schema/registry.ts b/packages/angular_devkit/core/src/json/schema/registry.ts index bd862a0e5f17..891259e03ee0 100644 --- a/packages/angular_devkit/core/src/json/schema/registry.ts +++ b/packages/angular_devkit/core/src/json/schema/registry.ts @@ -12,8 +12,11 @@ import * as http from 'node:http'; import * as https from 'node:https'; import * as Url from 'node:url'; import { Observable, from, isObservable, lastValueFrom } from 'rxjs'; -import { BaseException } from '../../exception'; -import { PartiallyOrderedSet } from '../../utils'; +import { + BaseException, + CircularDependencyFoundException, + DependencyNotFoundException, +} from '../../exception'; import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../utils'; import { JsonPointer, @@ -93,12 +96,46 @@ interface SchemaInfo { promptDefinitions: Array; } +/** + * Adds a transform to an ordered list of transforms. + * + * Transforms run in insertion order and each transform is only present once. Dependencies + * must already be in the list, which guarantees that they run before the added transform. + */ +function addTransform( + transforms: JsonVisitor[], + visitor: JsonVisitor, + deps: JsonVisitor[] = [], +): void { + const existingIndex = transforms.indexOf(visitor); + const position = existingIndex === -1 ? transforms.length : existingIndex; + + for (const dep of deps) { + const depIndex = transforms.indexOf(dep); + if (depIndex === -1) { + throw new DependencyNotFoundException(); + } + if (depIndex === position) { + throw new CircularDependencyFoundException(); + } + if (depIndex > position) { + throw new Error( + 'The transform is already registered and runs before one of the provided dependencies.', + ); + } + } + + if (existingIndex === -1) { + transforms.push(visitor); + } +} + export class CoreSchemaRegistry implements SchemaRegistry { private _ajv: Ajv; private _uriCache = new Map(); private _uriHandlers = new Set(); - private _pre = new PartiallyOrderedSet(); - private _post = new PartiallyOrderedSet(); + private _pre: JsonVisitor[] = []; + private _post: JsonVisitor[] = []; private _currentCompilationSchemaInfo?: SchemaInfo; @@ -181,7 +218,7 @@ export class CoreSchemaRegistry implements SchemaRegistry { * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void { - this._pre.add(visitor, deps); + addTransform(this._pre, visitor, deps); } /** @@ -192,7 +229,7 @@ export class CoreSchemaRegistry implements SchemaRegistry { * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void { - this._post.add(visitor, deps); + addTransform(this._post, visitor, deps); } protected _resolver( @@ -326,7 +363,7 @@ export class CoreSchemaRegistry implements SchemaRegistry { // Apply pre-validation transforms if (validationOptions.applyPreTransforms) { - for (const visitor of this._pre.values()) { + for (const visitor of this._pre) { data = await lastValueFrom( visitJson(data, visitor, schema, this._resolver.bind(this), validator), ); @@ -378,7 +415,7 @@ export class CoreSchemaRegistry implements SchemaRegistry { // Apply post-validation transforms if (validationOptions.applyPostTransforms) { - for (const visitor of this._post.values()) { + for (const visitor of this._post) { data = await lastValueFrom( visitJson(data, visitor, schema, this._resolver.bind(this), validator), ); diff --git a/packages/angular_devkit/core/src/json/schema/registry_spec.ts b/packages/angular_devkit/core/src/json/schema/registry_spec.ts index 022588036d3b..82b0b44b9947 100644 --- a/packages/angular_devkit/core/src/json/schema/registry_spec.ts +++ b/packages/angular_devkit/core/src/json/schema/registry_spec.ts @@ -7,8 +7,9 @@ */ /* eslint-disable @typescript-eslint/no-explicit-any */ +import { CircularDependencyFoundException, DependencyNotFoundException } from '../../exception'; import { JsonValue } from '../utils'; -import { SchemaFormat } from './interface'; +import { JsonVisitor, SchemaFormat } from './interface'; import { CoreSchemaRegistry, SchemaValidationException } from './registry'; import { JsonSchema } from './schema'; import { addUndefinedDefaults } from './transforms'; @@ -454,4 +455,92 @@ describe('CoreSchemaRegistry', () => { expect(messages).toEqual(['Data path "/outputPath" must be string.']); }); }); + + describe('transform ordering', () => { + function createVisitor(name: string, calls: string[]): JsonVisitor { + return (value) => { + calls.push(name); + + return value; + }; + } + + async function run(registry: CoreSchemaRegistry): Promise { + const validator = await registry.compile({ type: 'string' }); + const result = await validator('value'); + expect(result.success).toBe(true); + } + + it('runs transforms in the order they were added', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(createVisitor('pre1', calls)); + registry.addPreTransform(createVisitor('pre2', calls)); + registry.addPostTransform(createVisitor('post1', calls)); + registry.addPostTransform(createVisitor('post2', calls)); + + await run(registry); + + expect(calls).toEqual(['pre1', 'pre2', 'post1', 'post2']); + }); + + it('only runs a transform once when it is added multiple times', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', calls); + registry.addPostTransform(first); + registry.addPostTransform(createVisitor('second', calls)); + registry.addPostTransform(first); + + await run(registry); + + expect(calls).toEqual(['first', 'second']); + }); + + it('runs a transform after its dependencies', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', calls); + const second = createVisitor('second', calls); + registry.addPostTransform(first); + registry.addPostTransform(second, [first]); + // Adding again with dependencies that already run earlier is a no-op. + registry.addPostTransform(second, [first]); + + await run(registry); + + expect(calls).toEqual(['first', 'second']); + }); + + it('throws when a dependency has not been added', () => { + const registry = new CoreSchemaRegistry(); + const missing = createVisitor('missing', []); + + expect(() => registry.addPreTransform(createVisitor('visitor', []), [missing])).toThrowError( + DependencyNotFoundException, + ); + }); + + it('throws when a transform depends on itself', () => { + const registry = new CoreSchemaRegistry(); + const visitor = createVisitor('visitor', []); + registry.addPreTransform(visitor); + + expect(() => registry.addPreTransform(visitor, [visitor])).toThrowError( + CircularDependencyFoundException, + ); + }); + + it('throws when an existing transform is given a dependency that runs after it', () => { + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', []); + const second = createVisitor('second', []); + registry.addPreTransform(first); + registry.addPreTransform(second); + + expect(() => registry.addPreTransform(first, [second])).toThrowError( + /already registered and runs before/, + ); + }); + }); }); diff --git a/packages/angular_devkit/core/src/utils/partially-ordered-set.ts b/packages/angular_devkit/core/src/utils/partially-ordered-set.ts index 258b6138f66f..2e5b124c61ed 100644 --- a/packages/angular_devkit/core/src/utils/partially-ordered-set.ts +++ b/packages/angular_devkit/core/src/utils/partially-ordered-set.ts @@ -6,18 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import { BaseException } from '../exception'; - -export class DependencyNotFoundException extends BaseException { - constructor() { - super('One of the dependencies is not part of the set.'); - } -} -export class CircularDependencyFoundException extends BaseException { - constructor() { - super('Circular dependencies found.'); - } -} +import { CircularDependencyFoundException, DependencyNotFoundException } from '../exception'; /** * @deprecated Use standard arrays and ensure correct insertion order instead.