diff --git a/packages/cicero-core/src/metadata.ts b/packages/cicero-core/src/metadata.ts index e5705e2a2..f4c10d76d 100644 --- a/packages/cicero-core/src/metadata.ts +++ b/packages/cicero-core/src/metadata.ts @@ -42,6 +42,7 @@ export default class Metadata { runtime: any; ciceroVersion: any; + templateModelName: string | undefined; logo: any; packageJson: any; readme: any; @@ -125,6 +126,15 @@ export default class Metadata { throw new Error('Unsupported runtime. The supported runtimes are: ' + LANGUAGES.join(', ')); } + // the fully-qualified name of the template model, when the model + // declares more than one candidate (e.g. it carries copies of the + // models of the templates it composes) + this.templateModelName = packageJson.accordproject.templateModel; + + if(this.templateModelName !== undefined && (typeof this.templateModelName !== 'string' || this.templateModelName.length === 0)) { + throw new Error('The accordproject templateModel in package.json must be the fully-qualified name of a type.'); + } + if(!samples || typeof(samples) !== 'object') { throw new Error('sample.md is required'); } @@ -240,6 +250,19 @@ export default class Metadata { return this.runtime; } + /** + * Returns the fully-qualified name of the template model, as named by + * `accordproject.templateModel` in package.json. A template only needs to + * name it when its model declares more than one concrete subtype of + * `org.accordproject.templatedata@1.0.0.TemplateData`, for example + * because it carries copies of the models of the templates it composes. + * @returns {string|undefined} the fully-qualified name of the template + * model, or undefined if package.json does not name one + */ + getTemplateModelName(){ + return this.templateModelName; + } + /** * Returns the version of Cicero that this template is compatible with. * i.e. which version of the runtime was this template built for? diff --git a/packages/cicero-core/src/template.ts b/packages/cicero-core/src/template.ts index a1717320a..02974a6c0 100644 --- a/packages/cicero-core/src/template.ts +++ b/packages/cicero-core/src/template.ts @@ -64,6 +64,39 @@ export default class Template { */ static TEMPLATE_DATA_TYPE = 'org.accordproject.templatedata@1.0.0.TemplateData'; + /** + * The legacy base request type, from `org.accordproject.runtime@0.2.0`. + * + * Templates written before the 1.0 models (for example most of + * cicero-template-library) still declare their requests as subtypes of + * this. Its concrete subtypes are reported alongside those of + * {@link Template.REQUEST_TYPE}, so those templates keep working unchanged. + */ + static LEGACY_REQUEST_TYPE = 'org.accordproject.runtime@0.2.0.Request'; + + /** + * The legacy base response type, from `org.accordproject.runtime@0.2.0`. + * Its concrete subtypes are reported alongside those of + * {@link Template.RESPONSE_TYPE}. + */ + static LEGACY_RESPONSE_TYPE = 'org.accordproject.runtime@0.2.0.Response'; + + /** + * The legacy base emit type, from `org.accordproject.runtime@0.2.0`. It is + * abstract. Its concrete subtypes are reported alongside those of + * {@link Template.EMIT_TYPE}. + */ + static LEGACY_EMIT_TYPE = 'org.accordproject.runtime@0.2.0.Obligation'; + + /** + * The legacy base state type, from `org.accordproject.runtime@0.2.0`. + * Its concrete subtypes are reported alongside those of + * {@link Template.STATE_TYPE}. Unlike `StateData` it is a concrete (empty) + * asset, so {@link Template#isStateful} excludes it explicitly: a legacy + * template is only stateful if it declares a subtype of its own. + */ + static LEGACY_STATE_TYPE = 'org.accordproject.runtime@0.2.0.State'; + metadata: any; logicManager: any; authorSignature: any; @@ -125,21 +158,38 @@ export default class Template { /** * Returns the template model for the template. * - * A template's model declares exactly one concrete subtype of - * {@link Template.TEMPLATE_DATA_TYPE}, and that subtype is the template - * model: extending `TemplateData` is the declaration, so no `@template` - * decorator is required to identify it. Templates whose model does not - * import `templatedata@1.0.0` at all - because it predates this - * convention, or because the namespace simply is not loaded - fall back - * to the legacy `@template` decorator so they keep loading unchanged. - * @throws {Error} if no template model is found, or multiple template models are found + * The template model is resolved in this order: + * + * 1. If package.json names it with `accordproject.templateModel`, that + * type. It must be a concrete subtype of + * {@link Template.TEMPLATE_DATA_TYPE}, or, for legacy templates, a + * concrete type with the `@template` decorator. A template that + * composes other templates carries copies of their models, each with + * its own subtype of `TemplateData`, so it must say which one is its + * own. + * 2. Otherwise, the model's one concrete subtype of + * {@link Template.TEMPLATE_DATA_TYPE}: extending `TemplateData` is the + * declaration, so no `@template` decorator is required to identify it. + * More than one is an error. + * 3. Otherwise - the model does not import `templatedata@1.0.0` at all, + * because it predates this convention or the namespace is simply not + * loaded - the legacy `@template` decorator, so those templates keep + * loading unchanged. + * + * @throws {Error} if no template model is found, multiple template models + * are found, or the named template model is missing or not a template model * @returns {ClassDeclaration} the template model for the template */ getTemplateModel() { + const namedTemplateModel = this.getMetadata().getTemplateModelName(); + if (namedTemplateModel) { + return this.getNamedTemplateModel(namedTemplateModel); + } + const templateModelNames = this.findConcreteSubclassNames(Template.TEMPLATE_DATA_TYPE); if (templateModelNames.length > 1) { - throw new Error(`Found multiple concrete subtypes of ${Template.TEMPLATE_DATA_TYPE}: ${templateModelNames.join(', ')}. A template model must declare exactly one concrete subtype of TemplateData.`); + throw new Error(`Found multiple concrete subtypes of ${Template.TEMPLATE_DATA_TYPE}: ${templateModelNames.join(', ')}. A template model must declare exactly one concrete subtype of TemplateData, or name its template model with "accordproject.templateModel" in package.json.`); } if (templateModelNames.length === 1) { @@ -149,6 +199,32 @@ export default class Template { return templatemarkutil.findTemplateConcept(this.getIntrospector(), 'clause'); } + /** + * Returns the template model named by `accordproject.templateModel` in + * package.json, checking that it is one. + * @param {string} name the fully-qualified name of the template model + * @throws {Error} if the type is not found, or is not a concrete subtype of + * TemplateData or a concrete type with the `@template` decorator + * @returns {ClassDeclaration} the template model for the template + * @private + */ + getNamedTemplateModel(name) { + let templateModel; + try { + templateModel = this.getModelManager().getType(name); + } catch (err) { + throw new Error(`The template model "${name}" named by accordproject.templateModel in package.json was not found in the template's model: ${err.message}`); + } + + const isTemplateData = Template.instanceOf(templateModel, Template.TEMPLATE_DATA_TYPE); + const isDecorated = !!templateModel.getDecorator('template'); + if (templateModel.isAbstract() || (!isTemplateData && !isDecorated)) { + throw new Error(`The template model "${name}" named by accordproject.templateModel in package.json must be a concrete subtype of ${Template.TEMPLATE_DATA_TYPE}, or a concrete type with the @template decorator.`); + } + + return templateModel; + } + /** * Returns the identifier for this template * @return {String} the identifier of this template @@ -489,10 +565,11 @@ export default class Template { * emits nothing, does not import the namespace that base type lives in. * * @param {String} type The fully-qualified type to search for + * @param {boolean} excludeBaseType Exclude the base parameter type, even if it is concrete * @return {String[]} An array of fully-qualified types * @private */ - findConcreteSubclassNames(type) { + findConcreteSubclassNames(type, excludeBaseType = false) { let baseType; try { baseType = this.getModelManager().getType(type); @@ -505,39 +582,68 @@ export default class Template { return baseType .getAssignableClassDeclarations() .filter(subclass => !subclass.isAbstract()) + .filter(subclass => !excludeBaseType || subclass.getFullyQualifiedName() !== type) .map(decl => decl.getFullyQualifiedName()); } + /** + * Returns the concrete sub-classes of each of the given base types, in the + * order the base types are given, without duplicates. Base types whose + * namespace is not loaded contribute nothing. + * + * This is how the runtime type lookups report the 1.0 models and the + * legacy `runtime@0.2.0` models side by side. + * + * @param {String[]} types The fully-qualified base types to search for + * @param {boolean} excludeBaseType Exclude each base parameter type, even if it is concrete + * @return {String[]} An array of fully-qualified types + * @private + */ + findConcreteSubclassNamesOfAny(types: string[], excludeBaseType = false): string[] { + const names: string[] = types.flatMap(type => this.findConcreteSubclassNames(type, excludeBaseType)); + return Array.from(new Set(names)); + } + /** * Provides a list of the input types that are accepted by this Template. Types use the fully-qualified form. + * Includes the concrete subtypes of both {@link Template.REQUEST_TYPE} and + * the legacy {@link Template.LEGACY_REQUEST_TYPE}, 1.0 types first. * @return {String[]} a list of the request types */ - getRequestTypes() { - return this.findConcreteSubclassNames(Template.REQUEST_TYPE); + getRequestTypes(): string[] { + return this.findConcreteSubclassNamesOfAny([Template.REQUEST_TYPE, Template.LEGACY_REQUEST_TYPE]); } /** * Provides a list of the response types that are returned by this Template. Types use the fully-qualified form. + * Includes the concrete subtypes of both {@link Template.RESPONSE_TYPE} and + * the legacy {@link Template.LEGACY_RESPONSE_TYPE}, 1.0 types first. * @return {String[]} a list of the response types */ - getResponseTypes() { - return this.findConcreteSubclassNames(Template.RESPONSE_TYPE); + getResponseTypes(): string[] { + return this.findConcreteSubclassNamesOfAny([Template.RESPONSE_TYPE, Template.LEGACY_RESPONSE_TYPE]); } /** * Provides a list of the emit types that are emitted by this Template. Types use the fully-qualified form. - * @return {Array} a list of the emit types + * Includes the concrete subtypes of both {@link Template.EMIT_TYPE} and + * the legacy {@link Template.LEGACY_EMIT_TYPE}, 1.0 types first. + * @return {String[]} a list of the emit types */ - getEmitTypes() { - return this.findConcreteSubclassNames(Template.EMIT_TYPE); + getEmitTypes(): string[] { + return this.findConcreteSubclassNamesOfAny([Template.EMIT_TYPE, Template.LEGACY_EMIT_TYPE]); } /** * Provides a list of the state types that are expected by this Template. Types use the fully-qualified form. + * Includes the concrete subtypes of both {@link Template.STATE_TYPE} and + * the legacy {@link Template.LEGACY_STATE_TYPE}, 1.0 types first. As + * before 1.0, a legacy template's list includes the concrete base + * `runtime@0.2.0.State` itself. * @return {String[]} a list of the state types */ - getStateTypes() { - return this.findConcreteSubclassNames(Template.STATE_TYPE); + getStateTypes(): string[] { + return this.findConcreteSubclassNamesOfAny([Template.STATE_TYPE, Template.LEGACY_STATE_TYPE]); } /** @@ -549,11 +655,15 @@ export default class Template { } /** - * Returns true if the template declares one or more state types. + * Returns true if the template declares one or more state types of its + * own: a concrete subtype of {@link Template.STATE_TYPE}, or of the + * legacy {@link Template.LEGACY_STATE_TYPE}. Neither base type counts: + * `StateData` is abstract, and the legacy `State` is excluded explicitly + * because it is a concrete asset. * @return {boolean} true if the template is stateful */ isStateful() { - return this.getStateTypes().length > 0; + return this.findConcreteSubclassNamesOfAny([Template.STATE_TYPE, Template.LEGACY_STATE_TYPE], true).length > 0; } /** diff --git a/packages/cicero-core/test/data/composed-template-model/README.md b/packages/cicero-core/test/data/composed-template-model/README.md new file mode 100644 index 000000000..7c2610d3a --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/README.md @@ -0,0 +1,6 @@ +# Composed Template Model + +A licence template that composes a late-payment clause. It carries a copy of +the late-payment template's model, so its model declares two concrete +subtypes of `TemplateData`. `accordproject.templateModel` in package.json names +the licence's own one as the template model. diff --git a/packages/cicero-core/test/data/composed-template-model/model/@models.accordproject.org.accordproject.templatedata@1.0.0.cto b/packages/cicero-core/test/data/composed-template-model/model/@models.accordproject.org.accordproject.templatedata@1.0.0.cto new file mode 100644 index 000000000..51413f8de --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/model/@models.accordproject.org.accordproject.templatedata@1.0.0.cto @@ -0,0 +1,40 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// A reduced copy of org.accordproject.templatedata@1.0.0, carrying only the +// two extension points cicero-core resolves by name. The published namespace +// defines nothing else and imports nothing. Kept local because the namespace +// is not published yet. + +concerto version "^3.0.0" + +namespace org.accordproject.templatedata@1.0.0 + +/** + * The extension point for a template's own data model. + * + * A template's model declares exactly one concrete subtype, and that + * subtype is the template model: extending TemplateData is the + * declaration, so no `@template` decorator is required to identify it. + */ +abstract concept TemplateData {} + +/** + * The extension point for template-specific runtime state. + * + * A template declares one concrete subtype and it is carried in the runtime + * state envelope: state is composed into the envelope rather than subclassing + * it, which is why this is an abstract concept and not an asset. + */ +abstract concept StateData {} diff --git a/packages/cicero-core/test/data/composed-template-model/model/latepayment.cto b/packages/cicero-core/test/data/composed-template-model/model/latepayment.cto new file mode 100644 index 000000000..e4811f838 --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/model/latepayment.cto @@ -0,0 +1,11 @@ +namespace org.accordproject.composedlatepayment@1.0.0 + +import org.accordproject.templatedata@1.0.0.TemplateData from https://models.accordproject.org/accordproject/templatedata@1.0.0.cto + +/** + * A copy of the composed late-payment clause's template model. It is a + * concrete subtype of TemplateData too, but it is not this template's model. + */ +concept LatePaymentData extends TemplateData { + o Double penaltyPercentage +} diff --git a/packages/cicero-core/test/data/composed-template-model/model/model.cto b/packages/cicero-core/test/data/composed-template-model/model/model.cto new file mode 100644 index 000000000..e533be9b2 --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/model/model.cto @@ -0,0 +1,13 @@ +namespace org.accordproject.composedlicence@1.0.0 + +import org.accordproject.templatedata@1.0.0.TemplateData from https://models.accordproject.org/accordproject/templatedata@1.0.0.cto +import org.accordproject.composedlatepayment@1.0.0.LatePaymentData + +/** + * The template model of the licence, named by accordproject.templateModel + * in package.json. + */ +concept LicenceData extends TemplateData { + o String licensee + o LatePaymentData latePayment optional +} diff --git a/packages/cicero-core/test/data/composed-template-model/package.json b/packages/cicero-core/test/data/composed-template-model/package.json new file mode 100644 index 000000000..15020e7d3 --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/package.json @@ -0,0 +1,19 @@ +{ + "name": "composed-template-model", + "displayName": "Composed Template Model", + "version": "0.1.0", + "description": "A template that composes another template and so carries a copy of its model, giving two concrete subtypes of TemplateData. Used to check that accordproject.templateModel picks the template's own model.", + "author": "Accord Project", + "license": "Apache-2.0", + "accordproject": { + "template": "clause", + "cicero": "^2.0.0", + "runtime": "es6", + "templateModel": "org.accordproject.composedlicence@1.0.0.LicenceData" + }, + "keywords": [ + "template", + "templatedata", + "composition" + ] +} diff --git a/packages/cicero-core/test/data/composed-template-model/text/grammar.tem.md b/packages/cicero-core/test/data/composed-template-model/text/grammar.tem.md new file mode 100644 index 000000000..57bc2f9d0 --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/text/grammar.tem.md @@ -0,0 +1 @@ +Licensee: {{licensee}}. diff --git a/packages/cicero-core/test/data/composed-template-model/text/sample.md b/packages/cicero-core/test/data/composed-template-model/text/sample.md new file mode 100644 index 000000000..7ea4dc2c9 --- /dev/null +++ b/packages/cicero-core/test/data/composed-template-model/text/sample.md @@ -0,0 +1 @@ +Licensee: "Acme Corp". diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/README.md b/packages/cicero-core/test/data/legacy-runtime-cicero2/README.md new file mode 100644 index 000000000..792ec994b --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/README.md @@ -0,0 +1,7 @@ +# Legacy Runtime Cicero 2 + +A template that targets cicero 2.x (`accordproject.cicero` is `^2.0.0`) but +whose model still imports `org.accordproject.runtime@0.2.0` for its request, +response, state and obligation types, as most templates in +cicero-template-library do. cicero-core reports these legacy runtime types +alongside the 1.0 ones, so the template keeps working. diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.contract@0.2.0.cto b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.contract@0.2.0.cto new file mode 100644 index 000000000..e51352581 --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.contract@0.2.0.cto @@ -0,0 +1,32 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +concerto version "^3.0.0" + +namespace org.accordproject.contract@0.2.0 + +/** + * Contract Data + * -- Describes the structure of contracts and clauses + */ + +/* A contract is a asset -- This contains the contract data */ +abstract asset Contract identified by contractId { + o String contractId +} + +/* A clause is an asset -- This contains the clause data */ +abstract asset Clause identified by clauseId { + o String clauseId +} diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.runtime@0.2.0.cto b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.runtime@0.2.0.cto new file mode 100644 index 000000000..a313a79fc --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/@models.accordproject.org.accordproject.runtime@0.2.0.cto @@ -0,0 +1,51 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +concerto version "^3.0.0" + +namespace org.accordproject.runtime@0.2.0 + +import org.accordproject.contract@0.2.0.Contract from https://models.accordproject.org/accordproject/contract@0.2.0.cto + +/** + * Runtime API + * -- Describes input and output of calls to a contract's clause + */ + +/* A request is a transaction */ +transaction Request { +} + +/* A response is a transaction */ +transaction Response { +} + +/* An event that represents an obligation that needs to be fulfilled */ +abstract event Obligation identified { + /* A back reference to the governing contract that emitted this obligation */ + --> Contract contract + + /* The party that is obligated */ + --> Participant promisor optional + + /* The party that receives the performance */ + --> Participant promisee optional + + /* The time before which the obligation is fulfilled */ + o DateTime deadline optional +} + +/* A contract state is an asset -- The runtime state of the contract */ +asset State { +} diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/model/model.cto b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/model.cto new file mode 100644 index 000000000..89b3e4065 --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/model/model.cto @@ -0,0 +1,31 @@ +namespace org.accordproject.legacyruntime@1.0.0 + +import org.accordproject.contract@0.2.0.{Clause, Contract} from https://models.accordproject.org/accordproject/contract@0.2.0.cto +import org.accordproject.runtime@0.2.0.{Request, Response, State, Obligation} from https://models.accordproject.org/accordproject/runtime@0.2.0.cto + +transaction MyRequest extends Request { + o String input +} + +transaction MyResponse extends Response { + o String output +} + +asset HelloWorldState extends State { + o Double counter +} + +event Greeting extends Obligation { + o String message +} + +/** + * The template model + */ +@template +asset HelloWorldClause extends Clause { + /** + * The name for the clause + */ + o String name +} diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/package.json b/packages/cicero-core/test/data/legacy-runtime-cicero2/package.json new file mode 100644 index 000000000..c69d83caf --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/package.json @@ -0,0 +1,17 @@ +{ + "name": "legacy-runtime-cicero2", + "displayName": "Legacy Runtime Cicero 2", + "version": "0.1.0", + "description": "A template that targets cicero 2.x but still models its request, response, state and obligations with org.accordproject.runtime@0.2.0, as most of cicero-template-library does. Used to check that its runtime types are still reported alongside the 1.0 ones.", + "author": "Accord Project", + "license": "Apache-2.0", + "accordproject": { + "template": "clause", + "cicero": "^2.0.0", + "runtime": "es6" + }, + "keywords": [ + "legacy", + "runtime" + ] +} diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/text/grammar.tem.md b/packages/cicero-core/test/data/legacy-runtime-cicero2/text/grammar.tem.md new file mode 100644 index 000000000..ca6201fa0 --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/text/grammar.tem.md @@ -0,0 +1,2 @@ +Name of the person to greet: {{name}}. +Thank you! \ No newline at end of file diff --git a/packages/cicero-core/test/data/legacy-runtime-cicero2/text/sample.md b/packages/cicero-core/test/data/legacy-runtime-cicero2/text/sample.md new file mode 100644 index 000000000..86b1c4666 --- /dev/null +++ b/packages/cicero-core/test/data/legacy-runtime-cicero2/text/sample.md @@ -0,0 +1,2 @@ +Name of the person to greet: "Fred Blogs". +Thank you! \ No newline at end of file diff --git a/packages/cicero-core/test/metadata.test.ts b/packages/cicero-core/test/metadata.test.ts index 02db1835d..d79c70768 100644 --- a/packages/cicero-core/test/metadata.test.ts +++ b/packages/cicero-core/test/metadata.test.ts @@ -520,6 +520,43 @@ describe('Metadata', () => { }); }); + describe('#getTemplateModelName', () => { + it('should return undefined when package.json does not name a template model', () => { + const md = new Metadata({ + name: 'template', + version: '1.0.0', + accordproject: {cicero:caretRange(ciceroVersion)} + }, null, {}); + expect(md.getTemplateModelName()).toBeUndefined(); + }); + + it('should return the template model named in package.json', () => { + const md = new Metadata({ + name: 'template', + version: '1.0.0', + accordproject: {cicero:caretRange(ciceroVersion), templateModel: 'org.example@1.0.0.Data'} + }, null, {}); + expect(md.getTemplateModelName()).toBe('org.example@1.0.0.Data'); + }); + + it('should keep the named template model in the metadata for a target runtime', () => { + const md = new Metadata({ + name: 'template', + version: '1.0.0', + accordproject: {cicero:caretRange(ciceroVersion), templateModel: 'org.example@1.0.0.Data'} + }, null, {}); + expect(md.createTargetMetadata('es6').getTemplateModelName()).toBe('org.example@1.0.0.Data'); + }); + + it('should throw if the named template model is not a string', () => { + expect(() => new Metadata({ + name: 'template', + version: '1.0.0', + accordproject: {cicero:caretRange(ciceroVersion), templateModel: 42} + }, null, {})).toThrow('The accordproject templateModel in package.json must be the fully-qualified name of a type.'); + }); + }); + describe('#checkImage', () => { it('should not throw for correct png with correct dimensions', async () => { const buffer = await TemplateLoader.loadFileBuffer('./test/data', 'logo_128_128.png', true); diff --git a/packages/cicero-core/test/template.test.ts b/packages/cicero-core/test/template.test.ts index fc602eb9f..2dc590185 100644 --- a/packages/cicero-core/test/template.test.ts +++ b/packages/cicero-core/test/template.test.ts @@ -648,6 +648,96 @@ describe('Template', () => { it('should throw an error if multiple concrete subtypes of TemplateData are found', async () => { await expect(Template.fromDirectory('./test/data/multiple-concepts', options)).rejects.toThrow('Found multiple concrete subtypes of org.accordproject.templatedata@1.0.0.TemplateData: org.accordproject.conga@1.0.0.TemplateModel, org.accordproject.conga@1.0.0.TemplateModel2.'); }); + + it('should suggest accordproject.templateModel when multiple concrete subtypes of TemplateData are found', async () => { + await expect(Template.fromDirectory('./test/data/multiple-concepts', options)).rejects.toThrow('name its template model with "accordproject.templateModel" in package.json'); + }); + }); + + describe('#getTemplateModel with accordproject.templateModel', () => { + + /** + * Returns a copy of the template's package.json naming a template model + * @param {Template} template the template + * @param {string} templateModel the fully-qualified name to set + * @returns {object} the new package.json + */ + function withTemplateModel(template, templateModel) { + const packageJson = JSON.parse(JSON.stringify(template.getMetadata().getPackageJson())); + packageJson.accordproject.templateModel = templateModel; + return packageJson; + } + + // the fixture carries a copy of a composed template's model, so it + // declares two concrete subtypes of TemplateData + it('should pick the template model named in package.json when there are several TemplateData subtypes', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + expect(template.getMetadata().getTemplateModelName()).toBe('org.accordproject.composedlicence@1.0.0.LicenceData'); + expect(template.getTemplateModel().getFullyQualifiedName()).toBe('org.accordproject.composedlicence@1.0.0.LicenceData'); + }); + + it('should parse and set data against the named template model', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + const clause = new Clause(template); + const data = { + $class: 'org.accordproject.composedlicence@1.0.0.LicenceData', + licensee: 'Acme Corp' + }; + clause.setData(data); + expect(clause.getDataAsConcertoObject().getFullyQualifiedType()).toBe('org.accordproject.composedlicence@1.0.0.LicenceData'); + }); + + it('should keep the named template model through an archive round-trip', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + const buffer = await template.toArchive('es6'); + const template2 = await Template.fromArchive(buffer, options); + expect(template2.getMetadata().getTemplateModelName()).toBe('org.accordproject.composedlicence@1.0.0.LicenceData'); + expect(template2.getTemplateModel().getFullyQualifiedName()).toBe('org.accordproject.composedlicence@1.0.0.LicenceData'); + }); + + it('should still throw, mentioning accordproject.templateModel, when no template model is named', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, undefined)); + expect(() => template.getTemplateModel()).toThrow('Found multiple concrete subtypes of org.accordproject.templatedata@1.0.0.TemplateData: org.accordproject.composedlatepayment@1.0.0.LatePaymentData, org.accordproject.composedlicence@1.0.0.LicenceData.'); + expect(() => template.getTemplateModel()).toThrow('accordproject.templateModel'); + }); + + it('should throw if the named template model is not in the model', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, 'org.accordproject.composedlicence@1.0.0.Missing')); + expect(() => template.getTemplateModel()).toThrow('The template model "org.accordproject.composedlicence@1.0.0.Missing" named by accordproject.templateModel in package.json was not found in the template\'s model'); + }); + + it('should throw if the named template model is in a namespace the template does not load', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, 'org.example.missing@1.0.0.Data')); + expect(() => template.getTemplateModel()).toThrow('named by accordproject.templateModel in package.json was not found'); + }); + + it('should throw if the named type is not a template model', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, 'org.accordproject.templatedata@1.0.0.StateData')); + expect(() => template.getTemplateModel()).toThrow('must be a concrete subtype of org.accordproject.templatedata@1.0.0.TemplateData, or a concrete type with the @template decorator'); + }); + + it('should throw if the named type is the abstract TemplateData itself', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, 'org.accordproject.templatedata@1.0.0.TemplateData')); + expect(() => template.getTemplateModel()).toThrow('must be a concrete subtype of org.accordproject.templatedata@1.0.0.TemplateData'); + }); + + it('should accept a named legacy template model with the @template decorator', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + template.setPackageJson(withTemplateModel(template, 'org.accordproject.legacyruntime@1.0.0.HelloWorldClause')); + expect(template.getTemplateModel().getFullyQualifiedName()).toBe('org.accordproject.legacyruntime@1.0.0.HelloWorldClause'); + }); + + it('should reject a template whose package.json names a missing template model when it is loaded', async () => { + const template = await Template.fromDirectory('./test/data/composed-template-model', options); + template.setPackageJson(withTemplateModel(template, 'org.accordproject.composedlicence@1.0.0.Missing')); + const buffer = await template.toArchive('es6'); + await expect(Template.fromArchive(buffer, options)).rejects.toThrow('was not found in the template\'s model'); + }); }); describe('a template written against the 0.2.0 runtime', () => { @@ -658,6 +748,88 @@ describe('Template', () => { }); }); + describe('a cicero 2.x template still written against the 0.2.0 runtime', () => { + + // most of cicero-template-library is shaped like this: it targets + // cicero ^2.0.0 but imports org.accordproject.runtime@0.2.0 + it('should report its legacy request types', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.getRequestTypes()).toEqual([ + 'org.accordproject.runtime@0.2.0.Request', + 'org.accordproject.legacyruntime@1.0.0.MyRequest', + ]); + }); + + it('should report its legacy response types', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.getResponseTypes()).toEqual([ + 'org.accordproject.runtime@0.2.0.Response', + 'org.accordproject.legacyruntime@1.0.0.MyResponse', + ]); + }); + + it('should report its legacy emit types, without the abstract base Obligation', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.getEmitTypes()).toEqual([ + 'org.accordproject.legacyruntime@1.0.0.Greeting', + ]); + }); + + // the legacy State is a concrete asset, so it is listed, as it was + // before the 1.0 models + it('should report its legacy state types', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.getStateTypes()).toEqual([ + 'org.accordproject.runtime@0.2.0.State', + 'org.accordproject.legacyruntime@1.0.0.HelloWorldState', + ]); + }); + + it('should be recognised as stateful', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.isStateful()).toBe(true); + }); + + it('should still find its template model via the @template decorator', async () => { + const template = await Template.fromDirectory('./test/data/legacy-runtime-cicero2', options); + expect(template.getTemplateModel().getFullyQualifiedName()).toBe('org.accordproject.legacyruntime@1.0.0.HelloWorldClause'); + }); + }); + + describe('a template written against the 1.0 runtime', () => { + + it('should report its 1.0 runtime types', async () => { + const template = await Template.fromDirectory('./test/data/helloemit', options); + expect(template.getRequestTypes()).toEqual([ + 'org.accordproject.runtime@1.0.0.Request', + 'org.accordproject.helloemit@1.0.0.MyRequest', + ]); + expect(template.getResponseTypes()).toEqual([ + 'org.accordproject.runtime@1.0.0.Response', + 'org.accordproject.helloemit@1.0.0.MyResponse', + ]); + expect(template.getEmitTypes()).toEqual([ + 'org.accordproject.helloemit@1.0.0.Greeting', + ]); + expect(template.getStateTypes()).toEqual([ + 'org.accordproject.helloemit@1.0.0.HelloWorldState', + ]); + }); + + it('should be stateful when it declares a subtype of StateData', async () => { + const template = await Template.fromDirectory('./test/data/helloemit', options); + expect(template.isStateful()).toBe(true); + }); + + // this fixture loads templatedata@1.0.0, so the abstract StateData + // resolves, but it declares no subtype of it + it('should be stateless when it loads StateData but declares no subtype of it', async () => { + const template = await Template.fromDirectory('./test/data/no-template-decorator', options); + expect(template.getStateTypes()).toEqual([]); + expect(template.isStateful()).toBe(false); + }); + }); + describe('a template that loads no runtime namespace', () => { it('should report no runtime types rather than throwing', async () => {