@jakubmazanec/template 1.0.0 → 1.0.1-11dd4a3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
package/dist/Template.js
CHANGED
|
@@ -25,6 +25,11 @@ import { templateAttributesSchema } from './types.js';
|
|
|
25
25
|
* @typeParam A A Zod schema type used to define the custom template attributes type.
|
|
26
26
|
* @typeParam D A Zod schema type used to define the template datatype.
|
|
27
27
|
*/ export class Template {
|
|
28
|
+
/** Template content. Templates are written in [EJS](https://ejs.co/). */ content;
|
|
29
|
+
/** Template attributes. These control how the template is rendered. Some attributes can be written in [EJS](https://ejs.co/) and are rendered before the template content is rendered. It is expected that attribute `if` renders to a string that can be parsed as YAML value; if that value is `false`, the rendering is cancelled. Attribute `to` is also rendered and it represents the path of file the resulting template render is supposed to be written into (by the user). Attribute `variables` is an object that is merged with the data object before rendering. If attribute `variables` is an array of objects, that leads to multiple renders, each with different variables object merged with the data. Each variable that is a string is also rendered. */ attributes;
|
|
30
|
+
/** Template function. */ fn;
|
|
31
|
+
/** Zod schema for custom template attributes. */ attributesSchema;
|
|
32
|
+
/** Zod schema for template data. */ dataSchema;
|
|
28
33
|
constructor({ content , attributes , attributesSchema , dataSchema }){
|
|
29
34
|
this.content = content;
|
|
30
35
|
this.attributes = attributes;
|
|
@@ -135,10 +140,10 @@ import { templateAttributesSchema } from './types.js';
|
|
|
135
140
|
...options === null || options === void 0 ? void 0 : options.prettierOptions,
|
|
136
141
|
filepath: renderedAttributes.to
|
|
137
142
|
});
|
|
138
|
-
} catch (
|
|
139
|
-
if (!NO_INFERRED_PARSER_REGEXP.test(
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (!NO_INFERRED_PARSER_REGEXP.test(error.message)) {
|
|
140
145
|
throw new TemplateError('FAILED_FORMAT', {
|
|
141
|
-
cause:
|
|
146
|
+
cause: error
|
|
142
147
|
});
|
|
143
148
|
}
|
|
144
149
|
}
|
package/dist/Template.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Template.ts"],"sourcesContent":["import ejs from 'ejs';\nimport fs from 'fs-extra';\nimport matter from 'gray-matter';\nimport omit from 'lodash.omit';\nimport prettier from 'prettier';\nimport yaml from 'yaml';\nimport {type z, type AnyZodObject} from 'zod';\n\nimport {NO_INFERRED_PARSER_REGEXP} from './constants.js';\nimport {TemplateError} from './TemplateError.js';\nimport {\n templateAttributesSchema,\n type TemplateAttributes,\n type TemplateFunction,\n type TemplateRender,\n type TemplateRenders,\n} from './types.js';\n\nexport type TemplateOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Template content. */\n content: string;\n\n /** Template attributes. */\n attributes: A extends undefined\n ? TemplateAttributes\n : TemplateAttributes & z.infer<NonNullable<A>>;\n\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateReadOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateReadAndRenderOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Prettier options. */\n prettierOptions?: prettier.Options | undefined;\n\n /** Disable formatting the rendered template using Prettier. */\n disablePrettier?: boolean | undefined;\n\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateRenderOptions = {\n /** Prettier options. */\n prettierOptions?: prettier.Options | undefined;\n\n /** Disable formatting the rendered template using Prettier. */\n disablePrettier?: boolean | undefined;\n};\n\n/**\n * The `Template` object stores all information about a template and has methods for reading and rendering.\n *\n * ```TypeScript\n * let template = new Template({\n * content: '<%- value %>',\n * attributes: {\n * to: 'value.txt',\n * },\n * dataSchema: z.object({value: z.number()}),\n * });\n *\n * console.log(await template.render({value: 42})); // -> [{attributes: {to: 'value.txt'}, data: {value: 42}, content: '42'}]\n * ```\n *\n * @typeParam A A Zod schema type used to define the custom template attributes type.\n * @typeParam D A Zod schema type used to define the template datatype.\n */\nexport class Template<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> {\n /** Template content. Templates are written in [EJS](https://ejs.co/). */\n readonly content: string;\n\n /** Template attributes. These control how the template is rendered. Some attributes can be written in [EJS](https://ejs.co/) and are rendered before the template content is rendered. It is expected that attribute `if` renders to a string that can be parsed as YAML value; if that value is `false`, the rendering is cancelled. Attribute `to` is also rendered and it represents the path of file the resulting template render is supposed to be written into (by the user). Attribute `variables` is an object that is merged with the data object before rendering. If attribute `variables` is an array of objects, that leads to multiple renders, each with different variables object merged with the data. Each variable that is a string is also rendered. */\n readonly attributes: A extends undefined\n ? TemplateAttributes\n : TemplateAttributes & z.infer<NonNullable<A>>;\n\n /** Template function. */\n private readonly fn: TemplateFunction;\n\n /** Zod schema for custom template attributes. */\n readonly attributesSchema: A extends AnyZodObject ? A : null;\n\n /** Zod schema for template data. */\n readonly dataSchema: D extends AnyZodObject ? D : null;\n\n constructor({content, attributes, attributesSchema, dataSchema}: TemplateOptions<A, D>) {\n this.content = content;\n this.attributes = attributes;\n this.fn = ejs.compile(this.content);\n\n if (attributesSchema) {\n this.attributesSchema = attributesSchema as A extends AnyZodObject ? A : null;\n } else {\n this.attributesSchema = null as A extends AnyZodObject ? A : null;\n }\n\n if (dataSchema) {\n this.dataSchema = dataSchema as D extends AnyZodObject ? D : null;\n } else {\n this.dataSchema = null as D extends AnyZodObject ? D : null;\n }\n }\n\n /**\n * Reads a template from a file.\n *\n * @param templateFilePath Path to the template file.\n */\n static async read<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n >(templateFilePath: string, options?: TemplateReadOptions<A, D>): Promise<Template<A, D>> {\n let {data: attributes, content} = matter(await fs.readFile(templateFilePath, 'utf8'));\n let attributesSchema = options?.attributesSchema\n ? templateAttributesSchema.merge(options.attributesSchema)\n : templateAttributesSchema;\n let attributesParseResult = attributesSchema.safeParse(attributes);\n\n if (!attributesParseResult.success) {\n throw new TemplateError('INVALID_ATTRIBUTES', {\n cause: attributesParseResult.error,\n data: {\n path: templateFilePath,\n zodIssues: attributesParseResult.error.issues,\n },\n });\n }\n\n return new this({\n attributes,\n content,\n attributesSchema: options?.attributesSchema,\n dataSchema: options?.dataSchema,\n } as TemplateOptions<A, D>);\n }\n\n /**\n * Reads a template from a file and then renders it.\n *\n * @param templateFilePath Path to the template file.\n * @param data Data used for rendering the template.\n * @param options Options object.\n * @return Template renders.\n */\n static async readAndRender<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n >(\n templateFilePath: string,\n data: D extends undefined ? null : z.infer<NonNullable<D>>,\n options?: TemplateReadAndRenderOptions<A, D>,\n ) {\n let template = await Template.read<A, D>(templateFilePath, {\n attributesSchema: options?.attributesSchema,\n dataSchema: options?.dataSchema,\n });\n\n return template.render(data, {\n prettierOptions: options?.prettierOptions,\n disablePrettier: options?.disablePrettier,\n });\n }\n\n /**\n * Renders the template using data.\n *\n * @param data Data used for rendering the template.\n * @param options Options object.\n * @return Template renders.\n */\n async render(\n data: D extends undefined ? null : z.infer<NonNullable<D>>,\n options?: TemplateRenderOptions,\n ): Promise<TemplateRenders<A, D>> {\n let renders: TemplateRenders<A, D> = [];\n\n for (let variables of Array.isArray(this.attributes.variables)\n ? this.attributes.variables\n : [this.attributes.variables]) {\n let renderedAttributes = omit(this.attributes, ['if']);\n let renderedVariables = variables;\n\n if (renderedVariables) {\n for (let [variableName, variableValue] of Object.entries(renderedVariables)) {\n if (typeof variableValue === 'string') {\n renderedVariables[variableName] = ejs.render(variableValue, {...data});\n } else {\n renderedVariables[variableName] = variableValue;\n }\n }\n\n renderedAttributes.variables = renderedVariables;\n }\n\n let dataWithAttributes = {...data, attributes: renderedAttributes};\n\n if (this.attributes.if) {\n let renderedIf = ejs.render(this.attributes.if, dataWithAttributes);\n let parsedIf = yaml.parse(renderedIf) as unknown;\n\n if (parsedIf === false) {\n continue;\n }\n }\n\n renderedAttributes.to = ejs.render(renderedAttributes.to, dataWithAttributes);\n dataWithAttributes.attributes = renderedAttributes;\n\n let content;\n\n try {\n content = this.fn(dataWithAttributes);\n } catch (error: unknown) {\n throw new TemplateError('FAILED_RENDER', {cause: error});\n }\n\n if (!options?.disablePrettier) {\n try {\n content = prettier.format(content, {\n ...options?.prettierOptions,\n filepath: renderedAttributes.to,\n });\n } catch (error: unknown) {\n if (!NO_INFERRED_PARSER_REGEXP.test((error as Error).message)) {\n throw new TemplateError('FAILED_FORMAT', {cause: error});\n }\n }\n }\n\n renders.push({\n attributes: renderedAttributes,\n data: data ?? null,\n content,\n } as TemplateRender<A, D>);\n }\n\n return renders;\n }\n}\n"],"names":["ejs","fs","matter","omit","prettier","yaml","NO_INFERRED_PARSER_REGEXP","TemplateError","templateAttributesSchema","Template","constructor","content","attributes","attributesSchema","dataSchema","fn","compile","read","templateFilePath","options","data","readFile","merge","attributesParseResult","safeParse","success","cause","error","path","zodIssues","issues","readAndRender","template","render","prettierOptions","disablePrettier","renders","variables","Array","isArray","renderedAttributes","renderedVariables","variableName","variableValue","Object","entries","dataWithAttributes","if","renderedIf","parsedIf","parse","to","format","filepath","test","message","push"],"mappings":"AAAA,OAAOA,SAAS,MAAM;AACtB,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,YAAY,cAAc;AACjC,OAAOC,UAAU,cAAc;AAC/B,OAAOC,cAAc,WAAW;AAChC,OAAOC,UAAU,OAAO;AAGxB,SAAQC,yBAAyB,QAAO,iBAAiB;AACzD,SAAQC,aAAa,QAAO,qBAAqB;AACjD,SACEC,wBAAwB,QAKnB,aAAa;AAyDpB;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC;IAq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AIiC,MAAM,CAAC,IAAI,CAACrB,UAAU,CAACmC,EAAE,EAAED;gBAChD,IAAIG,WAAW5C,KAAK6C,KAAK,CAACF;gBAE1B,IAAIC,aAAa,KAAK,EAAE;oBACtB,QAAS;gBACX,CAAC;YACH,CAAC;YAEDT,mBAAmBW,EAAE,GAAGnD,IAAIiC,MAAM,CAACO,mBAAmBW,EAAE,EAAEL;YAC1DA,mBAAmBlC,UAAU,GAAG4B;YAEhC,IAAI7B;YAEJ,IAAI;gBACFA,UAAU,IAAI,CAACI,EAAE,CAAC+B;YACpB,EAAE,OAAOnB,OAAgB;gBACvB,MAAM,IAAIpB,cAAc,iBAAiB;oBAACmB,OAAOC;gBAAK,GAAG;YAC3D;YAEA,IAAI,CAACR,CAAAA,oBAAAA,qBAAAA,KAAAA,IAAAA,QAASgB,eAAe,AAAD,GAAG;gBAC7B,IAAI;oBACFxB,UAAUP,SAASgD,MAAM,CAACzC,SAAS;wBACjC,GAAGQ,oBAAAA,qBAAAA,KAAAA,IAAAA,QAASe,eAAe;wBAC3BmB,UAAUb,mBAAmBW,EAAE;oBACjC;gBACF,EAAE,OAAOxB,QAAgB;oBACvB,IAAI,CAACrB,0BAA0BgD,IAAI,CAAC,AAAC3B,OAAgB4B,OAAO,GAAG;wBAC7D,MAAM,IAAIhD,cAAc,iBAAiB;4BAACmB,OAAOC;wBAAK,GAAG;oBAC3D,CAAC;gBACH;YACF,CAAC;YAEDS,QAAQoB,IAAI,CAAC;gBACX5C,YAAY4B;gBACZpB,MAAMA,QAAQ,IAAI;gBAClBT;YACF;QACF;QAEA,OAAOyB;IACT;AACF,CAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/Template.ts"],"sourcesContent":["import ejs from 'ejs';\nimport fs from 'fs-extra';\nimport matter from 'gray-matter';\nimport omit from 'lodash.omit';\nimport prettier from 'prettier';\nimport yaml from 'yaml';\nimport {type z, type AnyZodObject} from 'zod';\n\nimport {NO_INFERRED_PARSER_REGEXP} from './constants.js';\nimport {TemplateError} from './TemplateError.js';\nimport {\n templateAttributesSchema,\n type TemplateAttributes,\n type TemplateFunction,\n type TemplateRender,\n type TemplateRenders,\n} from './types.js';\n\nexport type TemplateOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Template content. */\n content: string;\n\n /** Template attributes. */\n attributes: A extends undefined\n ? TemplateAttributes\n : TemplateAttributes & z.infer<NonNullable<A>>;\n\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateReadOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateReadAndRenderOptions<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> = {\n /** Prettier options. */\n prettierOptions?: prettier.Options | undefined;\n\n /** Disable formatting the rendered template using Prettier. */\n disablePrettier?: boolean | undefined;\n\n /** Zod schema for custom template attributes. */\n attributesSchema?: A | undefined;\n\n /** Zod schema for template data. */\n dataSchema?: D | undefined;\n};\n\nexport type TemplateRenderOptions = {\n /** Prettier options. */\n prettierOptions?: prettier.Options | undefined;\n\n /** Disable formatting the rendered template using Prettier. */\n disablePrettier?: boolean | undefined;\n};\n\n/**\n * The `Template` object stores all information about a template and has methods for reading and rendering.\n *\n * ```TypeScript\n * let template = new Template({\n * content: '<%- value %>',\n * attributes: {\n * to: 'value.txt',\n * },\n * dataSchema: z.object({value: z.number()}),\n * });\n *\n * console.log(await template.render({value: 42})); // -> [{attributes: {to: 'value.txt'}, data: {value: 42}, content: '42'}]\n * ```\n *\n * @typeParam A A Zod schema type used to define the custom template attributes type.\n * @typeParam D A Zod schema type used to define the template datatype.\n */\nexport class Template<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n> {\n /** Template content. Templates are written in [EJS](https://ejs.co/). */\n readonly content: string;\n\n /** Template attributes. These control how the template is rendered. Some attributes can be written in [EJS](https://ejs.co/) and are rendered before the template content is rendered. It is expected that attribute `if` renders to a string that can be parsed as YAML value; if that value is `false`, the rendering is cancelled. Attribute `to` is also rendered and it represents the path of file the resulting template render is supposed to be written into (by the user). Attribute `variables` is an object that is merged with the data object before rendering. If attribute `variables` is an array of objects, that leads to multiple renders, each with different variables object merged with the data. Each variable that is a string is also rendered. */\n readonly attributes: A extends undefined\n ? TemplateAttributes\n : TemplateAttributes & z.infer<NonNullable<A>>;\n\n /** Template function. */\n private readonly fn: TemplateFunction;\n\n /** Zod schema for custom template attributes. */\n readonly attributesSchema: A extends AnyZodObject ? A : null;\n\n /** Zod schema for template data. */\n readonly dataSchema: D extends AnyZodObject ? D : null;\n\n constructor({content, attributes, attributesSchema, dataSchema}: TemplateOptions<A, D>) {\n this.content = content;\n this.attributes = attributes;\n this.fn = ejs.compile(this.content);\n\n if (attributesSchema) {\n this.attributesSchema = attributesSchema as A extends AnyZodObject ? A : null;\n } else {\n this.attributesSchema = null as A extends AnyZodObject ? A : null;\n }\n\n if (dataSchema) {\n this.dataSchema = dataSchema as D extends AnyZodObject ? D : null;\n } else {\n this.dataSchema = null as D extends AnyZodObject ? D : null;\n }\n }\n\n /**\n * Reads a template from a file.\n *\n * @param templateFilePath Path to the template file.\n */\n static async read<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n >(templateFilePath: string, options?: TemplateReadOptions<A, D>): Promise<Template<A, D>> {\n let {data: attributes, content} = matter(await fs.readFile(templateFilePath, 'utf8'));\n let attributesSchema = options?.attributesSchema\n ? templateAttributesSchema.merge(options.attributesSchema)\n : templateAttributesSchema;\n let attributesParseResult = attributesSchema.safeParse(attributes);\n\n if (!attributesParseResult.success) {\n throw new TemplateError('INVALID_ATTRIBUTES', {\n cause: attributesParseResult.error,\n data: {\n path: templateFilePath,\n zodIssues: attributesParseResult.error.issues,\n },\n });\n }\n\n return new this({\n attributes,\n content,\n attributesSchema: options?.attributesSchema,\n dataSchema: options?.dataSchema,\n } as TemplateOptions<A, D>);\n }\n\n /**\n * Reads a template from a file and then renders it.\n *\n * @param templateFilePath Path to the template file.\n * @param data Data used for rendering the template.\n * @param options Options object.\n * @return Template renders.\n */\n static async readAndRender<\n A extends AnyZodObject | undefined = undefined,\n D extends AnyZodObject | undefined = undefined,\n >(\n templateFilePath: string,\n data: D extends undefined ? null : z.infer<NonNullable<D>>,\n options?: TemplateReadAndRenderOptions<A, D>,\n ) {\n let template = await Template.read<A, D>(templateFilePath, {\n attributesSchema: options?.attributesSchema,\n dataSchema: options?.dataSchema,\n });\n\n return template.render(data, {\n prettierOptions: options?.prettierOptions,\n disablePrettier: options?.disablePrettier,\n });\n }\n\n /**\n * Renders the template using data.\n *\n * @param data Data used for rendering the template.\n * @param options Options object.\n * @return Template renders.\n */\n async render(\n data: D extends undefined ? null : z.infer<NonNullable<D>>,\n options?: TemplateRenderOptions,\n ): Promise<TemplateRenders<A, D>> {\n let renders: TemplateRenders<A, D> = [];\n\n for (let variables of Array.isArray(this.attributes.variables)\n ? this.attributes.variables\n : [this.attributes.variables]) {\n let renderedAttributes = omit(this.attributes, ['if']);\n let renderedVariables = variables;\n\n if (renderedVariables) {\n for (let [variableName, variableValue] of Object.entries(renderedVariables)) {\n if (typeof variableValue === 'string') {\n renderedVariables[variableName] = ejs.render(variableValue, {...data});\n } else {\n renderedVariables[variableName] = variableValue;\n }\n }\n\n renderedAttributes.variables = renderedVariables;\n }\n\n let dataWithAttributes = {...data, attributes: renderedAttributes};\n\n if (this.attributes.if) {\n let renderedIf = ejs.render(this.attributes.if, dataWithAttributes);\n let parsedIf = yaml.parse(renderedIf) as unknown;\n\n if (parsedIf === false) {\n continue;\n }\n }\n\n renderedAttributes.to = ejs.render(renderedAttributes.to, dataWithAttributes);\n dataWithAttributes.attributes = renderedAttributes;\n\n let content;\n\n try {\n content = this.fn(dataWithAttributes);\n } catch (error: unknown) {\n throw new TemplateError('FAILED_RENDER', {cause: error});\n }\n\n if (!options?.disablePrettier) {\n try {\n content = prettier.format(content, {\n ...options?.prettierOptions,\n filepath: renderedAttributes.to,\n });\n } catch (error: unknown) {\n if (!NO_INFERRED_PARSER_REGEXP.test((error as Error).message)) {\n throw new TemplateError('FAILED_FORMAT', {cause: error});\n }\n }\n }\n\n renders.push({\n attributes: renderedAttributes,\n data: data ?? null,\n content,\n } as TemplateRender<A, D>);\n }\n\n return renders;\n }\n}\n"],"names":["ejs","fs","matter","omit","prettier","yaml","NO_INFERRED_PARSER_REGEXP","TemplateError","templateAttributesSchema","Template","content","attributes","fn","attributesSchema","dataSchema","constructor","compile","read","templateFilePath","options","data","readFile","merge","attributesParseResult","safeParse","success","cause","error","path","zodIssues","issues","readAndRender","template","render","prettierOptions","disablePrettier","renders","variables","Array","isArray","renderedAttributes","renderedVariables","variableName","variableValue","Object","entries","dataWithAttributes","if","renderedIf","parsedIf","parse","to","format","filepath","test","message","push"],"mappings":"AAAA,OAAOA,SAAS,MAAM;AACtB,OAAOC,QAAQ,WAAW;AAC1B,OAAOC,YAAY,cAAc;AACjC,OAAOC,UAAU,cAAc;AAC/B,OAAOC,cAAc,WAAW;AAChC,OAAOC,UAAU,OAAO;AAGxB,SAAQC,yBAAyB,QAAO,iBAAiB;AACzD,SAAQC,aAAa,QAAO,qBAAqB;AACjD,SACEC,wBAAwB,QAKnB,aAAa;AAyDpB;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC;IAIX,uEAAuE,GACvE,AAASC,QAAgB;IAEzB,4uBAA4uB,GAC5uB,AAASC,WAEwC;IAEjD,uBAAuB,GACvB,AAAiBC,GAAqB;IAEtC,+CAA+C,GAC/C,AAASC,iBAAoD;IAE7D,kCAAkC,GAClC,AAASC,WAA8C;IAEvDC,YAAY,EAACL,QAAO,EAAEC,WAAU,EAAEE,iBAAgB,EAAEC,WAAU,EAAwB,CA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;gBAAK;YACxD;YAEA,IAAI,CAACR,CAAAA,oBAAAA,qBAAAA,KAAAA,IAAAA,QAASgB,eAAc,GAAG;gBAC7B,IAAI;oBACFzB,UAAUN,SAASgD,OAAO1C,SAAS;wBACjC,GAAGS,oBAAAA,qBAAAA,KAAAA,IAAAA,QAASe,eAAe;wBAC3BmB,UAAUb,mBAAmBW;oBAC/B;gBACF,EAAE,OAAOxB,OAAgB;oBACvB,IAAI,CAACrB,0BAA0BgD,KAAK,AAAC3B,MAAgB4B,UAAU;wBAC7D,MAAM,IAAIhD,cAAc,iBAAiB;4BAACmB,OAAOC;wBAAK;oBACxD;gBACF;YACF;YAEAS,QAAQoB,KAAK;gBACX7C,YAAY6B;gBACZpB,MAAMA,QAAQ;gBACdV;YACF;QACF;QAEA,OAAO0B;IACT;AACF"}
|
package/dist/TemplateError.js
CHANGED
|
@@ -6,6 +6,9 @@ import { createCustomErrorWithData } from '@jakubmazanec/error';
|
|
|
6
6
|
FAILED_FORMAT: 'Template render formatting has failed.',
|
|
7
7
|
FAILED_RENDER: 'Rendering has failed.'
|
|
8
8
|
}, class TemplateErrorData {
|
|
9
|
+
template;
|
|
10
|
+
path;
|
|
11
|
+
zodIssues;
|
|
9
12
|
});
|
|
10
13
|
|
|
11
14
|
//# sourceMappingURL=TemplateError.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/TemplateError.ts"],"sourcesContent":["import {createCustomErrorWithData} from '@jakubmazanec/error';\nimport {type ZodIssue} from 'zod';\n\nimport {type Template} from './Template.js';\n\n/**\n * A subclass of `Error` that indicates a template failure.\n */\nexport const TemplateError = createCustomErrorWithData(\n 'TemplateError',\n {\n INVALID_ATTRIBUTES: 'Invalid template attributes.',\n FAILED_FORMAT: 'Template render formatting has failed.',\n FAILED_RENDER: 'Rendering has failed.',\n },\n class TemplateErrorData {\n template?: Template;\n path?: string;\n zodIssues?: ZodIssue[];\n },\n);\n"],"names":["createCustomErrorWithData","TemplateError","INVALID_ATTRIBUTES","FAILED_FORMAT","FAILED_RENDER","TemplateErrorData"],"mappings":"AAAA,SAAQA,yBAAyB,QAAO,sBAAsB;AAK9D;;CAEC,GACD,OAAO,MAAMC,gBAAgBD,0BAC3B,iBACA;IACEE,oBAAoB;IACpBC,eAAe;IACfC,eAAe;AACjB,GACA,MAAMC;
|
|
1
|
+
{"version":3,"sources":["../src/TemplateError.ts"],"sourcesContent":["import {createCustomErrorWithData} from '@jakubmazanec/error';\nimport {type ZodIssue} from 'zod';\n\nimport {type Template} from './Template.js';\n\n/**\n * A subclass of `Error` that indicates a template failure.\n */\nexport const TemplateError = createCustomErrorWithData(\n 'TemplateError',\n {\n INVALID_ATTRIBUTES: 'Invalid template attributes.',\n FAILED_FORMAT: 'Template render formatting has failed.',\n FAILED_RENDER: 'Rendering has failed.',\n },\n class TemplateErrorData {\n template?: Template;\n path?: string;\n zodIssues?: ZodIssue[];\n },\n);\n"],"names":["createCustomErrorWithData","TemplateError","INVALID_ATTRIBUTES","FAILED_FORMAT","FAILED_RENDER","TemplateErrorData","template","path","zodIssues"],"mappings":"AAAA,SAAQA,yBAAyB,QAAO,sBAAsB;AAK9D;;CAEC,GACD,OAAO,MAAMC,gBAAgBD,0BAC3B,iBACA;IACEE,oBAAoB;IACpBC,eAAe;IACfC,eAAe;AACjB,GACA,MAAMC;IACJC,SAAoB;IACpBC,KAAc;IACdC,UAAuB;AACzB,GACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/TemplateAttributes.ts"],"sourcesContent":["import {z} from 'zod';\n\nimport {templateVariablesSchema} from './TemplateVariables.js';\n\n/**\n * Zod schema for {@linkcode TemplateAttributes}.\n */\nexport const templateAttributesSchema = z\n .object({\n to: z.string(),\n if: z.string().optional(),\n variables: templateVariablesSchema.optional(),\n })\n .strict();\n\n/**\n * Type representing template attributes.\n */\nexport type TemplateAttributes = z.infer<typeof templateAttributesSchema>;\n"],"names":["z","templateVariablesSchema","templateAttributesSchema","object","to","string","if","optional","variables","strict"],"mappings":"AAAA,SAAQA,CAAC,QAAO,MAAM;AAEtB,SAAQC,uBAAuB,QAAO,yBAAyB;AAE/D;;CAEC,GACD,OAAO,MAAMC,2BAA2BF,EACrCG,
|
|
1
|
+
{"version":3,"sources":["../../src/types/TemplateAttributes.ts"],"sourcesContent":["import {z} from 'zod';\n\nimport {templateVariablesSchema} from './TemplateVariables.js';\n\n/**\n * Zod schema for {@linkcode TemplateAttributes}.\n */\nexport const templateAttributesSchema = z\n .object({\n to: z.string(),\n if: z.string().optional(),\n variables: templateVariablesSchema.optional(),\n })\n .strict();\n\n/**\n * Type representing template attributes.\n */\nexport type TemplateAttributes = z.infer<typeof templateAttributesSchema>;\n"],"names":["z","templateVariablesSchema","templateAttributesSchema","object","to","string","if","optional","variables","strict"],"mappings":"AAAA,SAAQA,CAAC,QAAO,MAAM;AAEtB,SAAQC,uBAAuB,QAAO,yBAAyB;AAE/D;;CAEC,GACD,OAAO,MAAMC,2BAA2BF,EACrCG,OAAO;IACNC,IAAIJ,EAAEK;IACNC,IAAIN,EAAEK,SAASE;IACfC,WAAWP,wBAAwBM;AACrC,GACCE,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/TemplateVariables.ts"],"sourcesContent":["import * as z from 'zod';\n\n/**\n * Zod schema for {@linkcode TemplateAttributesVariables}.\n */\nexport const templateVariablesSchema = z.union([\n z.record(z.unknown()),\n z.array(z.record(z.unknown())),\n]);\n\n/**\n * Type of `variables`` property of {@linkcode TemplateAttributes}.\n */\nexport type TemplateAttributesVariables = z.infer<typeof templateVariablesSchema>;\n"],"names":["z","templateVariablesSchema","union","record","unknown","array"],"mappings":"AAAA,YAAYA,OAAO,MAAM;AAEzB;;CAEC,GACD,OAAO,MAAMC,0BAA0BD,EAAEE,
|
|
1
|
+
{"version":3,"sources":["../../src/types/TemplateVariables.ts"],"sourcesContent":["import * as z from 'zod';\n\n/**\n * Zod schema for {@linkcode TemplateAttributesVariables}.\n */\nexport const templateVariablesSchema = z.union([\n z.record(z.unknown()),\n z.array(z.record(z.unknown())),\n]);\n\n/**\n * Type of `variables`` property of {@linkcode TemplateAttributes}.\n */\nexport type TemplateAttributesVariables = z.infer<typeof templateVariablesSchema>;\n"],"names":["z","templateVariablesSchema","union","record","unknown","array"],"mappings":"AAAA,YAAYA,OAAO,MAAM;AAEzB;;CAEC,GACD,OAAO,MAAMC,0BAA0BD,EAAEE,MAAM;IAC7CF,EAAEG,OAAOH,EAAEI;IACXJ,EAAEK,MAAML,EAAEG,OAAOH,EAAEI;CACpB,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jakubmazanec/template",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1-11dd4a3",
|
|
4
4
|
"description": "TypeScript-first library for working with templates using EJS and Zod.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
|
-
"url": "
|
|
7
|
+
"url": "https://github.com/jakubmazanec/js-tools",
|
|
8
8
|
"directory": "packages/template"
|
|
9
9
|
},
|
|
10
10
|
"license": "LGPL-3.0-only",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"typecheck": "tsc --project tsconfig.typecheck.json"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@jakubmazanec/error": "
|
|
29
|
+
"@jakubmazanec/error": "2.0.1-11dd4a3",
|
|
30
30
|
"ejs": "^3.1.9",
|
|
31
31
|
"fs-extra": "^11.1.1",
|
|
32
32
|
"gray-matter": "^4.0.3",
|