UNPKG

@sprucelabs/spruce-templates

Version:

Templates used for code generation in skills!

74 lines (73 loc) 3.18 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const schema_1 = require("@sprucelabs/schema"); const handlebars_1 = __importDefault(require("handlebars")); /** Renders field options */ handlebars_1.default.registerHelper('fieldDefinitionOptions', function (namespace, schemaNameCamel, version, fieldName, fieldDefinition, renderAs, options) { if (typeof namespace !== 'string') { throw new Error('fieldDefinitionOptions helper needs namespace first'); } if (typeof schemaNameCamel !== 'string') { throw new Error('fieldDefinitionOptions helper needs schemaNameCamel 2nd.'); } if (typeof fieldName !== 'string') { throw new Error('fieldDefinitionOptions helper needs fieldName 3rd'); } if (!fieldDefinition) { throw new Error('fieldDefinitionOptions helper needs a FieldDefinition as the 4th argument'); } if (!options || (renderAs !== schema_1.TemplateRenderAs.Type && renderAs !== schema_1.TemplateRenderAs.Value)) { throw new Error("fieldDefinitionOptions helper's second arg as type|value"); } const { data: { root }, } = options; const schemaTemplateItems = root && root.schemaTemplateItems; if (!schemaTemplateItems) { throw new Error('fieldDefinitionOptions needs schemaTemplateItems passed to parent template'); } const updatedOptions = fieldDefinition.options && { ...fieldDefinition.options, }; // If this is a schema type, we need to map it to it's proper value type if (fieldDefinition.type === 'schema' && updatedOptions) { const value = handlebars_1.default.helpers.valueTypeLiteral(namespace, schemaNameCamel, version, fieldName, renderAs === schema_1.TemplateRenderAs.Type ? schema_1.TemplateRenderAs.SchemaType : schema_1.TemplateRenderAs.Value, options); // Swap out id for reference delete updatedOptions.schemaId; delete updatedOptions.schema; delete updatedOptions.schemaIds; delete updatedOptions.schemas; if (value.substr(-1) === ']') { updatedOptions.schemas = value; } else { updatedOptions.schema = value; } } // No options, undefined is acceptable if (Object.keys(updatedOptions !== null && updatedOptions !== void 0 ? updatedOptions : {}).length === 0) { return 'undefined'; } let template = `{`; Object.keys(updatedOptions !== null && updatedOptions !== void 0 ? updatedOptions : {}).forEach((key) => { // @ts-ignore TODO how to type this const value = updatedOptions[key]; template += `${key}: `; if (key === 'schemas' || key === 'schema') { template += `${value},`; } else if (typeof value !== 'string') { template += `${JSON.stringify(value)},`; } else { template += `\`${value.replace(/([`])/g, '\\$1')}\`,`; } }); template += '}'; return template; });