diff --git a/packages/concerto-core/src/introspect/decorator.ts b/packages/concerto-core/src/introspect/decorator.ts index bb847cbd9..074b0ce26 100644 --- a/packages/concerto-core/src/introspect/decorator.ts +++ b/packages/concerto-core/src/introspect/decorator.ts @@ -15,6 +15,7 @@ import { MetaModelNamespace } from '@accordproject/concerto-metamodel'; import { Logger } from '@accordproject/concerto-util'; import ModelUtil from '../modelutil'; +import dayjs from '../dayjs-setup'; import IllegalModelException from './illegalmodelexception'; // Types needed for TypeScript generation. @@ -123,7 +124,10 @@ class Decorator { } /** - * Validate the decorator + * Validate the decorator. + * If the final property of a decorator declaration is an array, + * remaining positional arguments are validated against that property's + * element type. * @throws {IllegalModelException} * @private */ @@ -151,66 +155,122 @@ class Decorator { } const decoratorDecl = mf.getType(this.getName()); - const requiredProperties = decoratorDecl.getProperties().filter(p => !p.isOptional()); - const optionalProperties = decoratorDecl.getProperties().filter(p => p.isOptional()); - const allProperties = [...requiredProperties, ...optionalProperties]; - if (this.getArguments().length < requiredProperties.length) { + const declaredProperties = decoratorDecl.getProperties(); + + const trailingArrayProperty = declaredProperties.length > 0 && declaredProperties[declaredProperties.length - 1].isArray() + ? declaredProperties[declaredProperties.length - 1] + : undefined; + + const requiredProperties = declaredProperties.filter(p => !p.isOptional()); + const optionalProperties = declaredProperties.filter(p => p.isOptional()); + + const requiredPropertiesWithoutTrailingArray = trailingArrayProperty + ? requiredProperties.filter(p => p !== trailingArrayProperty) + : requiredProperties; + + // Preserve required-first binding. A required trailing array must + // receive its position before optional properties. + const allProperties = trailingArrayProperty && !trailingArrayProperty.isOptional() + ? [ + ...requiredPropertiesWithoutTrailingArray, + trailingArrayProperty, + ...optionalProperties.filter(p => p !== trailingArrayProperty) + ] + : [ + ...requiredPropertiesWithoutTrailingArray, + ...optionalProperties.filter(p => p !== trailingArrayProperty), + ...(trailingArrayProperty ? [trailingArrayProperty] : []) + ]; + + const trailingArrayIndex = trailingArrayProperty + ? allProperties.indexOf(trailingArrayProperty) + : -1; + + const args = this.getArguments(); + + const minimumRequiredArguments = requiredPropertiesWithoutTrailingArray.length + + (trailingArrayProperty && !trailingArrayProperty.isOptional() ? 1 : 0); + + if (args.length < minimumRequiredArguments) { const err = `Decorator ${this.getName()} has too few arguments. Required properties are: [${requiredProperties.map(p => p.getName()).join()}]`; this.handleError(validationOptions.invalidDecorator, err); } - const args = this.getArguments(); + for (let n = 0; n < args.length; n++) { const arg = args[n]; - if (n > allProperties.length - 1) { + const argumentPosition = n + 1; + const isTrailingArrayArgument = Boolean(trailingArrayProperty && n >= trailingArrayIndex); + + if (n >= allProperties.length && !trailingArrayProperty) { const err = `Decorator ${this.getName()} has too many arguments. Properties are: [${allProperties.map(p => p.getName()).join()}]`; this.handleError(validationOptions.invalidDecorator, err); + continue; } - else { - const property = allProperties[n]; - const argType = typeof arg; - switch (property.getType()) { - case 'Integer': - case 'Double': - case 'Long': - if (argType !== 'number') { - const err = `Decorator ${this.getName()} has invalid decorator argument. Expected number. Found ${argType}, with value ${JSON.stringify(arg)}`; - this.handleError(validationOptions.invalidDecorator, err); - } - break; - case 'String': - if (argType !== 'string') { - const err = `Decorator ${this.getName()} has invalid decorator argument. Expected string. Found ${argType}, with value ${JSON.stringify(arg)}`; - this.handleError(validationOptions.invalidDecorator, err); - } - break; - case 'Boolean': - if (argType !== 'boolean') { - const err = `Decorator ${this.getName()} has invalid decorator argument. Expected boolean. Found ${argType}, with value ${JSON.stringify(arg)}`; - this.handleError(validationOptions.invalidDecorator, err); - } - break; - default: { - if (typeof arg !== 'object' || arg?.type !== 'Identifier') { - const err = `Decorator ${this.getName()} has invalid decorator argument. Expected object. Found ${argType}, with value ${JSON.stringify(arg)}`; - this.handleError(validationOptions.invalidDecorator, err); - } - // handleError above only throws when the decorator - // validation option is set to 'error', so arg may still - // be something other than a type reference here - const typeReference = arg as DecoratorTypeReferenceArgument; - const typeDecl = mf.getType(typeReference.name); - if (!typeDecl) { - const err = `Decorator ${this.getName()} references a type ${typeReference.name} which has not been defined/imported.`; - this.handleError(validationOptions.invalidDecorator, err); - } - else { - if (!ModelUtil.isAssignableTo(typeDecl.getModelFile(), typeDecl.getFullyQualifiedName(), property)) { - const err = `Decorator ${this.getName()} references a type ${typeReference.name} which cannot be assigned to the declared type ${property.getFullyQualifiedTypeName()}`; - this.handleError(validationOptions.invalidDecorator, err); - } - } - break; + + const property = isTrailingArrayArgument + ? trailingArrayProperty + : allProperties[n]; + + const argType = typeof arg; + + switch (property.getType()) { + case 'Integer': + case 'Double': + case 'Long': + if (argType !== 'number') { + const err = isTrailingArrayArgument ? `Decorator ${this.getName()} argument ${argumentPosition} is invalid. Expected number. Found ${argType}, with value ${JSON.stringify(arg)}` : `Decorator ${this.getName()} has invalid decorator argument. Expected number. Found ${argType}, with value ${JSON.stringify(arg)}`; + this.handleError(validationOptions.invalidDecorator, err); + } + break; + + case 'String': + if (argType !== 'string') { + const err = isTrailingArrayArgument ? `Decorator ${this.getName()} argument ${argumentPosition} is invalid. Expected string. Found ${argType}, with value ${JSON.stringify(arg)}` : `Decorator ${this.getName()} has invalid decorator argument. Expected string. Found ${argType}, with value ${JSON.stringify(arg)}`; + this.handleError(validationOptions.invalidDecorator, err); + } + break; + + case 'Boolean': + if (argType !== 'boolean') { + const err = isTrailingArrayArgument ? `Decorator ${this.getName()} argument ${argumentPosition} is invalid. Expected boolean. Found ${argType}, with value ${JSON.stringify(arg)}` : `Decorator ${this.getName()} has invalid decorator argument. Expected boolean. Found ${argType}, with value ${JSON.stringify(arg)}`; + this.handleError(validationOptions.invalidDecorator, err); + } + break; + + case 'DateTime': + if (typeof arg !== 'string' || !dayjs.utc(arg).isValid()) { + const err = isTrailingArrayArgument + ? `Decorator ${this.getName()} argument ${argumentPosition} is invalid. Expected valid DateTime. Found ${JSON.stringify(arg)}` + : `Decorator ${this.getName()} has invalid decorator argument. Expected valid DateTime. Found ${JSON.stringify(arg)}`; + this.handleError(validationOptions.invalidDecorator, err); + } + break; + + default: { + if (!arg || typeof arg !== 'object' || arg.type !== 'Identifier') { + const err = isTrailingArrayArgument ? `Decorator ${this.getName()} argument ${argumentPosition} is invalid. Expected a type reference. Found ${argType}, with value ${JSON.stringify(arg)}` : `Decorator ${this.getName()} has invalid decorator argument. Expected object. Found ${argType}, with value ${JSON.stringify(arg)}`; + this.handleError(validationOptions.invalidDecorator, err); + continue; + } + + const typeReference = arg as DecoratorTypeReferenceArgument; + const typeDecl = mf.getType(typeReference.name); + + if (!typeDecl) { + const err = isTrailingArrayArgument + ? `Decorator ${this.getName()} argument ${argumentPosition} references a type ${typeReference.name} which has not been defined/imported.` + : `Decorator ${this.getName()} references a type ${typeReference.name} which has not been defined/imported.`; + this.handleError(validationOptions.invalidDecorator, err); + continue; + } + + if (typeof typeDecl === 'string' || !ModelUtil.isAssignableTo(typeDecl.getModelFile(), typeDecl.getFullyQualifiedName(), property)) { + const err = isTrailingArrayArgument + ? `Decorator ${this.getName()} argument ${argumentPosition} references a type ${typeReference.name} which cannot be assigned to the declared type ${property.getFullyQualifiedTypeName()}` + : `Decorator ${this.getName()} references a type ${typeReference.name} which cannot be assigned to the declared type ${property.getFullyQualifiedTypeName()}`; + this.handleError(validationOptions.invalidDecorator, err); } + break; } } } diff --git a/packages/concerto-core/test/introspect/decorators.js b/packages/concerto-core/test/introspect/decorators.js index 617f9dfdc..9e0393c30 100644 --- a/packages/concerto-core/test/introspect/decorators.js +++ b/packages/concerto-core/test/introspect/decorators.js @@ -275,8 +275,445 @@ concept A {}`, 'test.cto'); modelDefinitions = fs.readFileSync('test/data/decorators/valid-typeref-imported.cto', 'utf8'); modelManager.addCTOModel(modelDefinitions); }); + it('should preserve the non-array decorator type error message', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept Implements { + o Interface interface +} +concept NotAnInterface {} +@Implements(NotAnInterface) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/Decorator Implements references a type NotAnInterface which cannot be assigned to the declared type/); + }); + it('should validate remaining arguments against a trailing array property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept A extends Interface {} +concept B extends Interface {} +concept Implements { + o Interface[] interfaces +} +@Implements(A, B) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + + it('should reject an invalid type in a trailing array argument', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept A extends Interface {} +concept Implements { + o Interface[] interfaces +} +concept NotAnInterface {} +@Implements(A, NotAnInterface) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/NotAnInterface/); + }); + + it('should reject an undefined type in a trailing array argument', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept A extends Interface {} +concept Implements { + o Interface[] interfaces +} +@Implements(A, Undefined) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/Undefined.*has not been defined\/imported/); + }); + it('should reject a missing required trailing array when earlier properties are optional', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept Implements { + o String label optional + o Interface[] interfaces +} +@Implements() +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/too few arguments/); + }); + it('should accept a required trailing array declared after an optional property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String label optional + o String[] values +} +@Tags("one", "two") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + it('should validate a trailing array after a regular decorator property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept A extends Interface {} +concept B extends Interface {} +concept Implements { + o String label + o Interface[] interfaces +} +@Implements("example", A, B) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + it('should validate multiple primitive arguments against a trailing array property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values +} +@Tags("one", "two", "three") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + + it('should reject an invalid primitive in a trailing array argument', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values +} +@Tags("one", 42) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/Expected string/); + }); + }); + + it('should accept valid DateTime values in a trailing array property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +concept Dates { + o DateTime[] values +} +@Dates("2026-11-16T10:30:00.000Z", "2026-11-16T11:30:00.000Z") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + + it('should reject invalid DateTime values in a trailing array property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Dates { + o DateTime[] values +} +@Dates("not-a-valid-date") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/argument 1 is invalid\. Expected valid DateTime/); + }); + + it('should reject invalid DateTime values in a non-array decorator property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Dates { + o DateTime value +} +@Dates("not-a-valid-date") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/Expected valid DateTime/); + }); + it('should allow an optional trailing array property with no arguments', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values optional +} +@Tags +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); + + it('should reject no arguments for a required trailing array property', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values +} +@Tags +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/too few arguments/); }); + it('should report the position of an invalid trailing array argument', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values +} +@Tags("one", 42) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.throw(/argument 2.*Expected string/); + }); + + it('should not crash on an invalid trailing array argument in warning mode', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'warning' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String[] values +} +@Tags("one", 42, "three") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.not.throw(); + }); + it('should not crash on a non-type trailing array argument in warning mode', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'warning' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept Implements { + o Interface[] interfaces +} +@Implements(42) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.not.throw(); + }); + + it('should not crash on a primitive type reference in warning mode', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'warning' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept Implements { + o Interface[] interfaces +} +@Implements(String) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.not.throw(); + }); + it('should not crash on an undefined trailing array type in warning mode', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'warning' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +abstract concept Interface {} +concept Implements { + o Interface[] interfaces +} +@Implements(Undefined) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.not.throw(); + }); + it('should not crash when a non-array decorator has too many arguments in warning mode', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'warning' + } + }); + + (() => { + modelManager.addCTOModel(`namespace t@1.0.0 +concept Tags { + o String value +} +@Tags("one", "two") +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }).should.not.throw(); + }); + it('should preserve required-first ordering when optional properties are declared first', () => { + const modelManager = new ModelManager({ + strict: true, + decoratorValidation: { + missingDecorator: 'error', + invalidDecorator: 'error' + } + }); + + modelManager.addCTOModel(`namespace t@1.0.0 +import concerto.decorator@1.0.0.Decorator +concept Options extends Decorator { + o String description optional + o Boolean enabled +} +@Options(true) +concept C {}`, 'test.cto'); + + modelManager.validateModelFiles(); + }); describe('#factories', () => { it('should let a factory specify a decorator implementation', () => {