@bemoje/template 0.0.1

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.
Files changed (3) hide show
  1. package/index.d.ts +159 -0
  2. package/index.mjs +154 -0
  3. package/package.json +34 -0
package/index.d.ts ADDED
@@ -0,0 +1,159 @@
1
+ import { TSchema, Static, TObject, TString, TArray } from '@sinclair/typebox';
2
+
3
+ /**
4
+ * Strategy interface for template processing operations.
5
+ *
6
+ * @template TemplateSchema - The schema type that defines the structure of templates,
7
+ * must extend TSchema.
8
+ */
9
+ interface TemplateStrategy<TemplateSchema extends TSchema> {
10
+ /**
11
+ * The schema definition for templates handled by this strategy.
12
+ */
13
+ readonly templateSchema: TemplateSchema;
14
+ /**
15
+ * Converts a template object to its string representation.
16
+ *
17
+ * @param template - The template object conforming to the template schema
18
+ * @returns The string representation of the template
19
+ */
20
+ templateToString(template: Static<TemplateSchema>): string;
21
+ /**
22
+ * Renders a populated template string back into a structured template object.
23
+ *
24
+ * @param populated - The populated template string
25
+ * @returns The structured template object that conforms to the template schema
26
+ */
27
+ render(populated: string): Static<TemplateSchema>;
28
+ }
29
+
30
+ interface TemplateOptions<TemplateSchema extends TSchema, OptionsSchema extends TObject> {
31
+ readonly strategy: TemplateStrategy<TemplateSchema>;
32
+ readonly optionsSchema?: OptionsSchema;
33
+ readonly template: Static<TemplateSchema>;
34
+ }
35
+ /**
36
+ * A generic template engine that supports variable substitution using the Strategy pattern.
37
+ * Validates templates and options against TypeBox schemas and renders templates with provided data.
38
+ *
39
+ * Supports mustache-style `{{variable}}` syntax for variable substitution.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const strategy = new StringTemplateStrategy()
44
+ * const optionsSchema = Type.Object({
45
+ * name: Type.String({ default: 'World' }),
46
+ * greeting: Type.String({ default: 'Hello' })
47
+ * })
48
+ *
49
+ * const template = new Template({
50
+ * strategy,
51
+ * optionsSchema,
52
+ * template: "{{greeting}} {{name}}!"
53
+ * })
54
+ *
55
+ * const result = template.render({ name: 'TypeScript' })
56
+ * // Returns: "Hello TypeScript!"
57
+ * ```
58
+ */
59
+ declare class Template<TemplateSchema extends TSchema, OptionsSchema extends TObject> {
60
+ protected readonly strategy: TemplateStrategy<TemplateSchema>;
61
+ protected readonly optionsSchema: OptionsSchema;
62
+ protected readonly template: Static<TemplateSchema>;
63
+ constructor(options: TemplateOptions<TemplateSchema, OptionsSchema>);
64
+ /**
65
+ * Returns the template schema with the template set as the default value.
66
+ */
67
+ createSchema(): TemplateSchema;
68
+ /**
69
+ * Renders the template with the provided data, returning the result in the template schema format.
70
+ *
71
+ * Variables in the template using `{{variableName}}` syntax are replaced with corresponding
72
+ * values from the data object. Data is validated against the options schema before rendering.
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const result = template.render({ name: 'John', age: 30 })
77
+ * ```
78
+ */
79
+ render(data?: Static<OptionsSchema>): Static<TemplateSchema>;
80
+ /**
81
+ * Renders the template and returns the result as a string representation.
82
+ * Convenience method that combines `render()` and `templateToString()`.
83
+ */
84
+ renderString(data?: Static<OptionsSchema>): string;
85
+ /**
86
+ * Validates that the template contains all variables defined in the options schema.
87
+ *
88
+ * @throws {Error} When a variable defined in the options schema is not found in the template
89
+ */
90
+ protected assertValidTemplate(): void;
91
+ }
92
+
93
+ /**
94
+ * Template strategy for handling JSON file templates with structured object schemas.
95
+ *
96
+ * Converts structured objects to formatted JSON strings and parses JSON strings
97
+ * back to typed objects. Uses pretty-printing with 2-space indentation for
98
+ * human-readable output.
99
+ *
100
+ * @template Schema - Object schema type extending TObject, defaults to empty object
101
+ */
102
+ declare class JsonFileTemplateStrategy<Schema extends TObject = TObject> implements TemplateStrategy<Schema> {
103
+ readonly templateSchema: Schema;
104
+ /**
105
+ * Creates a JSON file template strategy with optional schema validation.
106
+ *
107
+ * @param templateSchema - TypeBox object schema for template validation.
108
+ * Defaults to empty object schema if not provided.
109
+ */
110
+ constructor(templateSchema?: Schema);
111
+ /**
112
+ * Converts a template object to pretty-printed JSON string.
113
+ */
114
+ templateToString(template: Static<Schema>): string;
115
+ /**
116
+ * Parses JSON string back to typed object conforming to schema.
117
+ */
118
+ render(populated: string): Static<Schema>;
119
+ }
120
+
121
+ /**
122
+ * Template strategy for handling simple string templates.
123
+ *
124
+ * Provides pass-through behavior for string templates where the template
125
+ * and rendered output are both plain strings. Useful for text-based templates
126
+ * that don't require parsing or complex structure.
127
+ */
128
+ declare class StringTemplateStrategy implements TemplateStrategy<TString> {
129
+ readonly templateSchema: TString;
130
+ /**
131
+ * Returns the template string as-is (pass-through).
132
+ */
133
+ templateToString(template: Static<TString>): string;
134
+ /**
135
+ * Returns the populated string as-is (pass-through).
136
+ */
137
+ render(populated: string): Static<TString>;
138
+ }
139
+
140
+ /**
141
+ * Template strategy for handling multi-line text file templates.
142
+ *
143
+ * Converts arrays of strings to newline-separated text and parses text files
144
+ * back to string arrays by splitting on newlines. Ideal for processing
145
+ * configuration files, scripts, or any line-based text content.
146
+ */
147
+ declare class TextFileTemplateStrategy implements TemplateStrategy<TArray<TString>> {
148
+ readonly templateSchema: TArray<TString>;
149
+ /**
150
+ * Joins string array into newline-separated text.
151
+ */
152
+ templateToString(template: Static<TArray<TString>>): string;
153
+ /**
154
+ * Splits text content into string array by newlines.
155
+ */
156
+ render(populated: string): Static<TArray<TString>>;
157
+ }
158
+
159
+ export { JsonFileTemplateStrategy, StringTemplateStrategy, Template, type TemplateOptions, type TemplateStrategy, TextFileTemplateStrategy };
package/index.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { Value } from '@sinclair/typebox/value';
3
+ import { ValueErrorIterator } from '@sinclair/typebox/compiler';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var SchemaValidationError = class extends Error {
8
+ static {
9
+ __name(this, "SchemaValidationError");
10
+ }
11
+ value;
12
+ errors;
13
+ constructor(errors, value, message) {
14
+ super(message);
15
+ this.value = value;
16
+ this.errors = Array.isArray(errors) ? errors : errors instanceof ValueErrorIterator ? Array.from(errors) : Array.from(Value.Errors(errors, value));
17
+ }
18
+ };
19
+ function assertValidSchema(schema, data, message) {
20
+ const isValid = Value.Check(schema, data);
21
+ if (!isValid) {
22
+ throw new SchemaValidationError(Value.Errors(schema, data), data, message);
23
+ }
24
+ }
25
+ __name(assertValidSchema, "assertValidSchema");
26
+
27
+ // src/Template/Template.ts
28
+ var Template = class {
29
+ static {
30
+ __name(this, "Template");
31
+ }
32
+ strategy;
33
+ optionsSchema;
34
+ template;
35
+ constructor(options) {
36
+ this.strategy = options.strategy;
37
+ this.optionsSchema = options.optionsSchema ?? Type.Object({});
38
+ this.template = options.template;
39
+ this.strategy.templateSchema.default = this.template;
40
+ this.assertValidTemplate();
41
+ }
42
+ /**
43
+ * Returns the template schema with the template set as the default value.
44
+ */
45
+ createSchema() {
46
+ return this.strategy.templateSchema;
47
+ }
48
+ /**
49
+ * Renders the template with the provided data, returning the result in the template schema format.
50
+ *
51
+ * Variables in the template using `{{variableName}}` syntax are replaced with corresponding
52
+ * values from the data object. Data is validated against the options schema before rendering.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const result = template.render({ name: 'John', age: 30 })
57
+ * ```
58
+ */
59
+ render(data = {}) {
60
+ const stringTemplate = this.strategy.templateToString(this.template);
61
+ const merged = Value.Cast(this.optionsSchema, data);
62
+ assertValidSchema(this.optionsSchema, merged, "Invalid options");
63
+ const populated = stringTemplate.replace(/{{(\w+)}}/g, (_, key) => {
64
+ return String(merged[key]);
65
+ });
66
+ return this.strategy.render(populated);
67
+ }
68
+ /**
69
+ * Renders the template and returns the result as a string representation.
70
+ * Convenience method that combines `render()` and `templateToString()`.
71
+ */
72
+ renderString(data = {}) {
73
+ return this.strategy.templateToString(this.render(data));
74
+ }
75
+ /**
76
+ * Validates that the template contains all variables defined in the options schema.
77
+ *
78
+ * @throws {Error} When a variable defined in the options schema is not found in the template
79
+ */
80
+ assertValidTemplate() {
81
+ const string = this.strategy.templateToString(this.template);
82
+ const variables = Object.keys(this.optionsSchema.properties);
83
+ for (const variable of variables) {
84
+ if (!string.includes(`{{${variable}}}`)) {
85
+ throw new Error(`Template does not include variable: ${variable}`);
86
+ }
87
+ }
88
+ }
89
+ };
90
+ var JsonFileTemplateStrategy = class {
91
+ static {
92
+ __name(this, "JsonFileTemplateStrategy");
93
+ }
94
+ templateSchema;
95
+ /**
96
+ * Creates a JSON file template strategy with optional schema validation.
97
+ *
98
+ * @param templateSchema - TypeBox object schema for template validation.
99
+ * Defaults to empty object schema if not provided.
100
+ */
101
+ constructor(templateSchema) {
102
+ this.templateSchema = templateSchema ?? Type.Object({});
103
+ }
104
+ /**
105
+ * Converts a template object to pretty-printed JSON string.
106
+ */
107
+ templateToString(template) {
108
+ return JSON.stringify(template, null, 2);
109
+ }
110
+ /**
111
+ * Parses JSON string back to typed object conforming to schema.
112
+ */
113
+ render(populated) {
114
+ return JSON.parse(populated);
115
+ }
116
+ };
117
+ var StringTemplateStrategy = class {
118
+ static {
119
+ __name(this, "StringTemplateStrategy");
120
+ }
121
+ templateSchema = Type.String();
122
+ /**
123
+ * Returns the template string as-is (pass-through).
124
+ */
125
+ templateToString(template) {
126
+ return template;
127
+ }
128
+ /**
129
+ * Returns the populated string as-is (pass-through).
130
+ */
131
+ render(populated) {
132
+ return populated;
133
+ }
134
+ };
135
+ var TextFileTemplateStrategy = class {
136
+ static {
137
+ __name(this, "TextFileTemplateStrategy");
138
+ }
139
+ templateSchema = Type.Array(Type.String());
140
+ /**
141
+ * Joins string array into newline-separated text.
142
+ */
143
+ templateToString(template) {
144
+ return template.join("\n");
145
+ }
146
+ /**
147
+ * Splits text content into string array by newlines.
148
+ */
149
+ render(populated) {
150
+ return populated.split("\n");
151
+ }
152
+ };
153
+
154
+ export { JsonFileTemplateStrategy, StringTemplateStrategy, Template, TextFileTemplateStrategy };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@bemoje/template",
3
+ "version": "0.0.1",
4
+ "description": "template",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "keywords": [
8
+ "template"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "import": "./index.mjs",
14
+ "default": "./index.mjs"
15
+ }
16
+ },
17
+ "dependencies": {
18
+ "@sinclair/typebox": "^0.34.37"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "license": "MIT",
24
+ "author": {
25
+ "name": "Benjamin Møller Jensen",
26
+ "email": "bemoje@bemoje.net",
27
+ "url": "https://github.com/bemoje/"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/bemoje/mono.git",
32
+ "directory": "libs/template"
33
+ }
34
+ }