@lp-labs/template-document 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +63 -2
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +216 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +212 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Libin Prasanth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lp-labs/template-document
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A bounded renderer for plain-text templates with own-property paths, simple conditionals, and
|
|
4
|
+
array loops. There is no expression evaluator, function invocation, or HTML escaping.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @lp-labs/template-document
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import { renderTemplate } from '@lp-labs/template-document';
|
|
14
|
+
|
|
15
|
+
const text = renderTemplate(
|
|
16
|
+
'Hello {{user.name}}!{{#if user.active}} Active.{{else}} Inactive.{{/if}} {{#each user.tags as tag}}#{{tag}} {{/each}}',
|
|
17
|
+
{ user: { name: 'Ada', active: true, tags: ['math', 'history'] } },
|
|
18
|
+
);
|
|
19
|
+
console.log(text); // Hello Ada! Active. #math #history
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Syntax and API
|
|
23
|
+
|
|
24
|
+
- `{{user.name}}` reads a safe dotted path. Missing or null values render as an empty string.
|
|
25
|
+
- `{{#if path}}...{{else}}...{{/if}}` selects a branch. `else` is optional.
|
|
26
|
+
- `{{#each path as item}}...{{/each}}` iterates an array and exposes the current item through
|
|
27
|
+
`item`, including safe paths such as `item.name`. Loops can be nested.
|
|
28
|
+
- `compileTemplate(source, limits?)` validates and returns a reusable `TemplateProgram`.
|
|
29
|
+
- `renderTemplate(sourceOrProgram, data, limits?)` compiles string input or renders a compiled
|
|
30
|
+
program.
|
|
31
|
+
- `TemplateProgram` and `TemplateLimits` are exported types.
|
|
32
|
+
|
|
33
|
+
Only own data properties are traversed; accessors are not invoked. Unsafe path segments such as
|
|
34
|
+
`constructor`, `prototype`, and `__proto__` are rejected. Interpolations allow finite numbers,
|
|
35
|
+
booleans, strings, null, and missing values; objects/arrays cannot be stringified implicitly.
|
|
36
|
+
Conditions use a small truthiness rule:
|
|
37
|
+
false, zero, empty string, null/missing, and empty arrays are false; other values are true.
|
|
38
|
+
Conditions do not parse comparisons or expressions.
|
|
39
|
+
|
|
40
|
+
Default limits: 100,000 source characters, nesting depth 32, 1,000,000 output characters, 100,000
|
|
41
|
+
render operations, and 10,000 total loop iterations. Each may be lowered with a positive integer.
|
|
42
|
+
Malformed tags, unsafe paths, non-array loop values, object interpolation, and exceeded limits fail
|
|
43
|
+
with `SyntaxError`, `TypeError`, or `RangeError`.
|
|
44
|
+
|
|
45
|
+
**Output is plain text.** Substitution is not HTML-escaped. Do not insert this output into HTML,
|
|
46
|
+
JavaScript, CSS, URLs, or other interpreted contexts without applying that context's escaping and
|
|
47
|
+
validation in the consuming application.
|
|
48
|
+
|
|
49
|
+
## Module formats and customization
|
|
50
|
+
|
|
51
|
+
ESM, CommonJS, and TypeScript declarations are included. CommonJS:
|
|
52
|
+
`const { renderTemplate } = require('@lp-labs/template-document')`. Add application-specific
|
|
53
|
+
formatting only through trusted preprocessed data or a separate renderer; templates cannot call
|
|
54
|
+
code or helper functions.
|
|
55
|
+
|
|
56
|
+
There are no runtime or peer dependencies. TypeScript and Prettier are development-only.
|
|
57
|
+
|
|
58
|
+
## Support
|
|
59
|
+
|
|
60
|
+
If this library is useful to you, consider supporting its maintenance with a [donation via PayPal](https://www.paypal.me/LibinPrasanth).
|
|
61
|
+
|
|
62
|
+
## Author
|
|
63
|
+
|
|
64
|
+
Created by [Libin Prasanth](https://www.linkedin.com/in/libinprasanth/). Connect on LinkedIn for updates and discussion.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface TemplateProgram {
|
|
2
|
+
readonly source: string;
|
|
3
|
+
}
|
|
4
|
+
export interface TemplateLimits {
|
|
5
|
+
maxSourceLength?: number;
|
|
6
|
+
maxDepth?: number;
|
|
7
|
+
maxOutputLength?: number;
|
|
8
|
+
maxOperations?: number;
|
|
9
|
+
maxIterations?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare function compileTemplate(source: string, limits?: TemplateLimits): TemplateProgram;
|
|
12
|
+
export declare function renderTemplate(template: string | TemplateProgram, data: unknown, limits?: TemplateLimits): string;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.compileTemplate = compileTemplate;
|
|
4
|
+
exports.renderTemplate = renderTemplate;
|
|
5
|
+
const MAX_SOURCE = 100_000;
|
|
6
|
+
const MAX_DEPTH = 32;
|
|
7
|
+
const MAX_OUTPUT = 1_000_000;
|
|
8
|
+
const MAX_OPERATIONS = 100_000;
|
|
9
|
+
const MAX_ITERATIONS = 10_000;
|
|
10
|
+
const compiled = new WeakMap();
|
|
11
|
+
const forbiddenKeys = new Set(['__proto__', 'prototype', 'constructor']);
|
|
12
|
+
function configuredLimit(value, fallback, name) {
|
|
13
|
+
const result = value ?? fallback;
|
|
14
|
+
if (!Number.isSafeInteger(result) || result < 1 || result > fallback) {
|
|
15
|
+
throw new RangeError(`${name} must be an integer from 1 to ${fallback}.`);
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
function parsePath(value) {
|
|
20
|
+
const path = value.trim().split('.');
|
|
21
|
+
if (path.length === 0 || path.length > 32)
|
|
22
|
+
throw new SyntaxError('Template path is invalid.');
|
|
23
|
+
for (const part of path) {
|
|
24
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part) || forbiddenKeys.has(part)) {
|
|
25
|
+
throw new SyntaxError(`Unsafe or invalid template path segment: ${part}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return path;
|
|
29
|
+
}
|
|
30
|
+
function tokenize(source) {
|
|
31
|
+
const tokens = [];
|
|
32
|
+
let cursor = 0;
|
|
33
|
+
while (cursor < source.length) {
|
|
34
|
+
const opening = source.indexOf('{{', cursor);
|
|
35
|
+
const strayClosing = source.indexOf('}}', cursor);
|
|
36
|
+
if (strayClosing >= 0 && (opening < 0 || strayClosing < opening)) {
|
|
37
|
+
throw new SyntaxError('Unexpected closing template tag.');
|
|
38
|
+
}
|
|
39
|
+
if (opening < 0) {
|
|
40
|
+
tokens.push({ value: source.slice(cursor) });
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
if (opening > cursor) {
|
|
44
|
+
tokens.push({ value: source.slice(cursor, opening) });
|
|
45
|
+
}
|
|
46
|
+
const closing = source.indexOf('}}', opening + 2);
|
|
47
|
+
if (closing < 0)
|
|
48
|
+
throw new SyntaxError('Unclosed template tag.');
|
|
49
|
+
tokens.push({
|
|
50
|
+
value: `\u0000${source.slice(opening + 2, closing).trim()}`,
|
|
51
|
+
});
|
|
52
|
+
cursor = closing + 2;
|
|
53
|
+
}
|
|
54
|
+
return tokens;
|
|
55
|
+
}
|
|
56
|
+
function parseNodes(tokens, cursor, limits, depth, stop = []) {
|
|
57
|
+
if (depth > configuredLimit(limits.maxDepth, MAX_DEPTH, 'maxDepth')) {
|
|
58
|
+
throw new RangeError('Template nesting limit exceeded.');
|
|
59
|
+
}
|
|
60
|
+
const nodes = [];
|
|
61
|
+
while (cursor.index < tokens.length) {
|
|
62
|
+
const token = tokens[cursor.index++];
|
|
63
|
+
if (!token.value.startsWith('\u0000')) {
|
|
64
|
+
if (token.value)
|
|
65
|
+
nodes.push({ kind: 'text', value: token.value });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const tag = token.value.slice(1);
|
|
69
|
+
if (stop.includes(tag))
|
|
70
|
+
return { nodes, stop: tag };
|
|
71
|
+
if (tag.startsWith('#if ')) {
|
|
72
|
+
const path = parsePath(tag.slice(4));
|
|
73
|
+
const yes = parseNodes(tokens, cursor, limits, depth + 1, ['else', '/if']);
|
|
74
|
+
let no = [];
|
|
75
|
+
if (yes.stop === 'else') {
|
|
76
|
+
const result = parseNodes(tokens, cursor, limits, depth + 1, ['/if']);
|
|
77
|
+
if (result.stop !== '/if')
|
|
78
|
+
throw new SyntaxError('Missing {{/if}}.');
|
|
79
|
+
no = result.nodes;
|
|
80
|
+
}
|
|
81
|
+
else if (yes.stop !== '/if') {
|
|
82
|
+
throw new SyntaxError('Missing {{/if}}.');
|
|
83
|
+
}
|
|
84
|
+
nodes.push({ kind: 'if', path, yes: yes.nodes, no });
|
|
85
|
+
}
|
|
86
|
+
else if (tag.startsWith('#each ')) {
|
|
87
|
+
const match = /^#each\s+(.+?)\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(tag);
|
|
88
|
+
if (!match)
|
|
89
|
+
throw new SyntaxError('Each syntax is {{#each path as name}}.');
|
|
90
|
+
if (forbiddenKeys.has(match[2]))
|
|
91
|
+
throw new SyntaxError('Unsafe loop alias.');
|
|
92
|
+
const parsed = parseNodes(tokens, cursor, limits, depth + 1, ['/each']);
|
|
93
|
+
if (parsed.stop !== '/each')
|
|
94
|
+
throw new SyntaxError('Missing {{/each}}.');
|
|
95
|
+
nodes.push({
|
|
96
|
+
kind: 'each',
|
|
97
|
+
path: parsePath(match[1]),
|
|
98
|
+
alias: match[2],
|
|
99
|
+
body: parsed.nodes,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
else if (tag.startsWith('/') || tag === 'else') {
|
|
103
|
+
throw new SyntaxError(`Unexpected template control tag: ${tag}`);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
nodes.push({ kind: 'value', path: parsePath(tag) });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { nodes };
|
|
110
|
+
}
|
|
111
|
+
function compileTemplate(source, limits = {}) {
|
|
112
|
+
if (typeof source !== 'string')
|
|
113
|
+
throw new TypeError('Template source must be a string.');
|
|
114
|
+
const maxSourceLength = configuredLimit(limits.maxSourceLength, MAX_SOURCE, 'maxSourceLength');
|
|
115
|
+
if (source.length > maxSourceLength)
|
|
116
|
+
throw new RangeError('Template source capacity exceeded.');
|
|
117
|
+
const tokens = tokenize(source);
|
|
118
|
+
const parsed = parseNodes(tokens, { index: 0 }, limits, 0);
|
|
119
|
+
if (parsed.stop)
|
|
120
|
+
throw new SyntaxError(`Unexpected template control tag: ${parsed.stop}`);
|
|
121
|
+
const program = Object.freeze({ source });
|
|
122
|
+
compiled.set(program, parsed.nodes);
|
|
123
|
+
return program;
|
|
124
|
+
}
|
|
125
|
+
function resolve(root, scopes, path) {
|
|
126
|
+
let current;
|
|
127
|
+
let offset = 0;
|
|
128
|
+
const scope = [...scopes].reverse().find((item) => item.alias === path[0]);
|
|
129
|
+
if (scope) {
|
|
130
|
+
current = scope.value;
|
|
131
|
+
offset = 1;
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
current = root;
|
|
135
|
+
}
|
|
136
|
+
for (let index = offset; index < path.length; index += 1) {
|
|
137
|
+
const part = path[index];
|
|
138
|
+
if (current === null || typeof current !== 'object' || !Object.hasOwn(current, part))
|
|
139
|
+
return undefined;
|
|
140
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, part);
|
|
141
|
+
if (!descriptor || !Object.hasOwn(descriptor, 'value'))
|
|
142
|
+
return undefined;
|
|
143
|
+
current = descriptor.value;
|
|
144
|
+
}
|
|
145
|
+
return current;
|
|
146
|
+
}
|
|
147
|
+
function asText(value, path) {
|
|
148
|
+
if (value === undefined || value === null)
|
|
149
|
+
return '';
|
|
150
|
+
if (typeof value === 'string' || typeof value === 'boolean')
|
|
151
|
+
return String(value);
|
|
152
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
153
|
+
return String(value);
|
|
154
|
+
throw new TypeError(`Template value ${path.join('.')} must resolve to a scalar.`);
|
|
155
|
+
}
|
|
156
|
+
function truthy(value) {
|
|
157
|
+
if (value === null || value === undefined || value === false || value === 0 || value === '')
|
|
158
|
+
return false;
|
|
159
|
+
if (Array.isArray(value))
|
|
160
|
+
return value.length > 0;
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
function renderTemplate(template, data, limits = {}) {
|
|
164
|
+
const program = typeof template === 'string' ? compileTemplate(template, limits) : template;
|
|
165
|
+
const nodes = program && typeof program === 'object' ? compiled.get(program) : undefined;
|
|
166
|
+
if (!nodes)
|
|
167
|
+
throw new TypeError('Template program was not created by compileTemplate.');
|
|
168
|
+
const maxOutputLength = configuredLimit(limits.maxOutputLength, MAX_OUTPUT, 'maxOutputLength');
|
|
169
|
+
const maxOperations = configuredLimit(limits.maxOperations, MAX_OPERATIONS, 'maxOperations');
|
|
170
|
+
const maxIterations = configuredLimit(limits.maxIterations, MAX_ITERATIONS, 'maxIterations');
|
|
171
|
+
let operations = 0;
|
|
172
|
+
let iterations = 0;
|
|
173
|
+
let outputLength = 0;
|
|
174
|
+
const chunks = [];
|
|
175
|
+
const scopes = [];
|
|
176
|
+
const render = (items) => {
|
|
177
|
+
for (const node of items) {
|
|
178
|
+
operations += 1;
|
|
179
|
+
if (operations > maxOperations)
|
|
180
|
+
throw new RangeError('Template operation limit exceeded.');
|
|
181
|
+
if (node.kind === 'text') {
|
|
182
|
+
chunks.push(node.value);
|
|
183
|
+
outputLength += node.value.length;
|
|
184
|
+
}
|
|
185
|
+
else if (node.kind === 'value') {
|
|
186
|
+
const value = asText(resolve(data, scopes, node.path), node.path);
|
|
187
|
+
chunks.push(value);
|
|
188
|
+
outputLength += value.length;
|
|
189
|
+
}
|
|
190
|
+
else if (node.kind === 'if') {
|
|
191
|
+
render(truthy(resolve(data, scopes, node.path)) ? node.yes : node.no);
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const value = resolve(data, scopes, node.path);
|
|
195
|
+
if (value !== undefined && value !== null && !Array.isArray(value)) {
|
|
196
|
+
throw new TypeError(`Loop value ${node.path.join('.')} must be an array.`);
|
|
197
|
+
}
|
|
198
|
+
const array = (value ?? []);
|
|
199
|
+
for (let index = 0; index < array.length; index += 1) {
|
|
200
|
+
iterations += 1;
|
|
201
|
+
if (iterations > maxIterations)
|
|
202
|
+
throw new RangeError('Template iteration limit exceeded.');
|
|
203
|
+
const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
|
|
204
|
+
const item = descriptor && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined;
|
|
205
|
+
scopes.push({ alias: node.alias, value: item });
|
|
206
|
+
render(node.body);
|
|
207
|
+
scopes.pop();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (outputLength > maxOutputLength)
|
|
211
|
+
throw new RangeError('Template output capacity exceeded.');
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
render(nodes);
|
|
215
|
+
return chunks.join('');
|
|
216
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface TemplateProgram {
|
|
2
|
+
readonly source: string;
|
|
3
|
+
}
|
|
4
|
+
export interface TemplateLimits {
|
|
5
|
+
maxSourceLength?: number;
|
|
6
|
+
maxDepth?: number;
|
|
7
|
+
maxOutputLength?: number;
|
|
8
|
+
maxOperations?: number;
|
|
9
|
+
maxIterations?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare function compileTemplate(source: string, limits?: TemplateLimits): TemplateProgram;
|
|
12
|
+
export declare function renderTemplate(template: string | TemplateProgram, data: unknown, limits?: TemplateLimits): string;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
const MAX_SOURCE = 100_000;
|
|
2
|
+
const MAX_DEPTH = 32;
|
|
3
|
+
const MAX_OUTPUT = 1_000_000;
|
|
4
|
+
const MAX_OPERATIONS = 100_000;
|
|
5
|
+
const MAX_ITERATIONS = 10_000;
|
|
6
|
+
const compiled = new WeakMap();
|
|
7
|
+
const forbiddenKeys = new Set(['__proto__', 'prototype', 'constructor']);
|
|
8
|
+
function configuredLimit(value, fallback, name) {
|
|
9
|
+
const result = value ?? fallback;
|
|
10
|
+
if (!Number.isSafeInteger(result) || result < 1 || result > fallback) {
|
|
11
|
+
throw new RangeError(`${name} must be an integer from 1 to ${fallback}.`);
|
|
12
|
+
}
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
function parsePath(value) {
|
|
16
|
+
const path = value.trim().split('.');
|
|
17
|
+
if (path.length === 0 || path.length > 32)
|
|
18
|
+
throw new SyntaxError('Template path is invalid.');
|
|
19
|
+
for (const part of path) {
|
|
20
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part) || forbiddenKeys.has(part)) {
|
|
21
|
+
throw new SyntaxError(`Unsafe or invalid template path segment: ${part}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return path;
|
|
25
|
+
}
|
|
26
|
+
function tokenize(source) {
|
|
27
|
+
const tokens = [];
|
|
28
|
+
let cursor = 0;
|
|
29
|
+
while (cursor < source.length) {
|
|
30
|
+
const opening = source.indexOf('{{', cursor);
|
|
31
|
+
const strayClosing = source.indexOf('}}', cursor);
|
|
32
|
+
if (strayClosing >= 0 && (opening < 0 || strayClosing < opening)) {
|
|
33
|
+
throw new SyntaxError('Unexpected closing template tag.');
|
|
34
|
+
}
|
|
35
|
+
if (opening < 0) {
|
|
36
|
+
tokens.push({ value: source.slice(cursor) });
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
if (opening > cursor) {
|
|
40
|
+
tokens.push({ value: source.slice(cursor, opening) });
|
|
41
|
+
}
|
|
42
|
+
const closing = source.indexOf('}}', opening + 2);
|
|
43
|
+
if (closing < 0)
|
|
44
|
+
throw new SyntaxError('Unclosed template tag.');
|
|
45
|
+
tokens.push({
|
|
46
|
+
value: `\u0000${source.slice(opening + 2, closing).trim()}`,
|
|
47
|
+
});
|
|
48
|
+
cursor = closing + 2;
|
|
49
|
+
}
|
|
50
|
+
return tokens;
|
|
51
|
+
}
|
|
52
|
+
function parseNodes(tokens, cursor, limits, depth, stop = []) {
|
|
53
|
+
if (depth > configuredLimit(limits.maxDepth, MAX_DEPTH, 'maxDepth')) {
|
|
54
|
+
throw new RangeError('Template nesting limit exceeded.');
|
|
55
|
+
}
|
|
56
|
+
const nodes = [];
|
|
57
|
+
while (cursor.index < tokens.length) {
|
|
58
|
+
const token = tokens[cursor.index++];
|
|
59
|
+
if (!token.value.startsWith('\u0000')) {
|
|
60
|
+
if (token.value)
|
|
61
|
+
nodes.push({ kind: 'text', value: token.value });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const tag = token.value.slice(1);
|
|
65
|
+
if (stop.includes(tag))
|
|
66
|
+
return { nodes, stop: tag };
|
|
67
|
+
if (tag.startsWith('#if ')) {
|
|
68
|
+
const path = parsePath(tag.slice(4));
|
|
69
|
+
const yes = parseNodes(tokens, cursor, limits, depth + 1, ['else', '/if']);
|
|
70
|
+
let no = [];
|
|
71
|
+
if (yes.stop === 'else') {
|
|
72
|
+
const result = parseNodes(tokens, cursor, limits, depth + 1, ['/if']);
|
|
73
|
+
if (result.stop !== '/if')
|
|
74
|
+
throw new SyntaxError('Missing {{/if}}.');
|
|
75
|
+
no = result.nodes;
|
|
76
|
+
}
|
|
77
|
+
else if (yes.stop !== '/if') {
|
|
78
|
+
throw new SyntaxError('Missing {{/if}}.');
|
|
79
|
+
}
|
|
80
|
+
nodes.push({ kind: 'if', path, yes: yes.nodes, no });
|
|
81
|
+
}
|
|
82
|
+
else if (tag.startsWith('#each ')) {
|
|
83
|
+
const match = /^#each\s+(.+?)\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(tag);
|
|
84
|
+
if (!match)
|
|
85
|
+
throw new SyntaxError('Each syntax is {{#each path as name}}.');
|
|
86
|
+
if (forbiddenKeys.has(match[2]))
|
|
87
|
+
throw new SyntaxError('Unsafe loop alias.');
|
|
88
|
+
const parsed = parseNodes(tokens, cursor, limits, depth + 1, ['/each']);
|
|
89
|
+
if (parsed.stop !== '/each')
|
|
90
|
+
throw new SyntaxError('Missing {{/each}}.');
|
|
91
|
+
nodes.push({
|
|
92
|
+
kind: 'each',
|
|
93
|
+
path: parsePath(match[1]),
|
|
94
|
+
alias: match[2],
|
|
95
|
+
body: parsed.nodes,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
else if (tag.startsWith('/') || tag === 'else') {
|
|
99
|
+
throw new SyntaxError(`Unexpected template control tag: ${tag}`);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
nodes.push({ kind: 'value', path: parsePath(tag) });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { nodes };
|
|
106
|
+
}
|
|
107
|
+
export function compileTemplate(source, limits = {}) {
|
|
108
|
+
if (typeof source !== 'string')
|
|
109
|
+
throw new TypeError('Template source must be a string.');
|
|
110
|
+
const maxSourceLength = configuredLimit(limits.maxSourceLength, MAX_SOURCE, 'maxSourceLength');
|
|
111
|
+
if (source.length > maxSourceLength)
|
|
112
|
+
throw new RangeError('Template source capacity exceeded.');
|
|
113
|
+
const tokens = tokenize(source);
|
|
114
|
+
const parsed = parseNodes(tokens, { index: 0 }, limits, 0);
|
|
115
|
+
if (parsed.stop)
|
|
116
|
+
throw new SyntaxError(`Unexpected template control tag: ${parsed.stop}`);
|
|
117
|
+
const program = Object.freeze({ source });
|
|
118
|
+
compiled.set(program, parsed.nodes);
|
|
119
|
+
return program;
|
|
120
|
+
}
|
|
121
|
+
function resolve(root, scopes, path) {
|
|
122
|
+
let current;
|
|
123
|
+
let offset = 0;
|
|
124
|
+
const scope = [...scopes].reverse().find((item) => item.alias === path[0]);
|
|
125
|
+
if (scope) {
|
|
126
|
+
current = scope.value;
|
|
127
|
+
offset = 1;
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
current = root;
|
|
131
|
+
}
|
|
132
|
+
for (let index = offset; index < path.length; index += 1) {
|
|
133
|
+
const part = path[index];
|
|
134
|
+
if (current === null || typeof current !== 'object' || !Object.hasOwn(current, part))
|
|
135
|
+
return undefined;
|
|
136
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, part);
|
|
137
|
+
if (!descriptor || !Object.hasOwn(descriptor, 'value'))
|
|
138
|
+
return undefined;
|
|
139
|
+
current = descriptor.value;
|
|
140
|
+
}
|
|
141
|
+
return current;
|
|
142
|
+
}
|
|
143
|
+
function asText(value, path) {
|
|
144
|
+
if (value === undefined || value === null)
|
|
145
|
+
return '';
|
|
146
|
+
if (typeof value === 'string' || typeof value === 'boolean')
|
|
147
|
+
return String(value);
|
|
148
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
149
|
+
return String(value);
|
|
150
|
+
throw new TypeError(`Template value ${path.join('.')} must resolve to a scalar.`);
|
|
151
|
+
}
|
|
152
|
+
function truthy(value) {
|
|
153
|
+
if (value === null || value === undefined || value === false || value === 0 || value === '')
|
|
154
|
+
return false;
|
|
155
|
+
if (Array.isArray(value))
|
|
156
|
+
return value.length > 0;
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
export function renderTemplate(template, data, limits = {}) {
|
|
160
|
+
const program = typeof template === 'string' ? compileTemplate(template, limits) : template;
|
|
161
|
+
const nodes = program && typeof program === 'object' ? compiled.get(program) : undefined;
|
|
162
|
+
if (!nodes)
|
|
163
|
+
throw new TypeError('Template program was not created by compileTemplate.');
|
|
164
|
+
const maxOutputLength = configuredLimit(limits.maxOutputLength, MAX_OUTPUT, 'maxOutputLength');
|
|
165
|
+
const maxOperations = configuredLimit(limits.maxOperations, MAX_OPERATIONS, 'maxOperations');
|
|
166
|
+
const maxIterations = configuredLimit(limits.maxIterations, MAX_ITERATIONS, 'maxIterations');
|
|
167
|
+
let operations = 0;
|
|
168
|
+
let iterations = 0;
|
|
169
|
+
let outputLength = 0;
|
|
170
|
+
const chunks = [];
|
|
171
|
+
const scopes = [];
|
|
172
|
+
const render = (items) => {
|
|
173
|
+
for (const node of items) {
|
|
174
|
+
operations += 1;
|
|
175
|
+
if (operations > maxOperations)
|
|
176
|
+
throw new RangeError('Template operation limit exceeded.');
|
|
177
|
+
if (node.kind === 'text') {
|
|
178
|
+
chunks.push(node.value);
|
|
179
|
+
outputLength += node.value.length;
|
|
180
|
+
}
|
|
181
|
+
else if (node.kind === 'value') {
|
|
182
|
+
const value = asText(resolve(data, scopes, node.path), node.path);
|
|
183
|
+
chunks.push(value);
|
|
184
|
+
outputLength += value.length;
|
|
185
|
+
}
|
|
186
|
+
else if (node.kind === 'if') {
|
|
187
|
+
render(truthy(resolve(data, scopes, node.path)) ? node.yes : node.no);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
const value = resolve(data, scopes, node.path);
|
|
191
|
+
if (value !== undefined && value !== null && !Array.isArray(value)) {
|
|
192
|
+
throw new TypeError(`Loop value ${node.path.join('.')} must be an array.`);
|
|
193
|
+
}
|
|
194
|
+
const array = (value ?? []);
|
|
195
|
+
for (let index = 0; index < array.length; index += 1) {
|
|
196
|
+
iterations += 1;
|
|
197
|
+
if (iterations > maxIterations)
|
|
198
|
+
throw new RangeError('Template iteration limit exceeded.');
|
|
199
|
+
const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
|
|
200
|
+
const item = descriptor && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined;
|
|
201
|
+
scopes.push({ alias: node.alias, value: item });
|
|
202
|
+
render(node.body);
|
|
203
|
+
scopes.pop();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (outputLength > maxOutputLength)
|
|
207
|
+
throw new RangeError('Template output capacity exceeded.');
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
render(nodes);
|
|
211
|
+
return chunks.join('');
|
|
212
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lp-labs/template-document",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Bounded safe-path text templates with loops and conditions.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/cjs/index.js",
|
|
8
|
+
"module": "./dist/esm/index.js",
|
|
9
|
+
"types": "./dist/esm/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": {
|
|
13
|
+
"types": "./dist/esm/index.d.ts",
|
|
14
|
+
"default": "./dist/esm/index.js"
|
|
15
|
+
},
|
|
16
|
+
"require": {
|
|
17
|
+
"types": "./dist/cjs/index.d.ts",
|
|
18
|
+
"default": "./dist/cjs/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": "\u003e=18"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "node scripts/build.mjs",
|
|
34
|
+
"typecheck": "npm run build \u0026\u0026 node scripts/check-types.mjs",
|
|
35
|
+
"test": "npm run build \u0026\u0026 node --test tests/*.test.mjs",
|
|
36
|
+
"format": "prettier --write src scripts tests *.json README.md",
|
|
37
|
+
"format:check": "prettier --check src scripts tests *.json README.md",
|
|
38
|
+
"prepack": "npm run build"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"typescript": "^5.9.3",
|
|
42
|
+
"prettier": "^3.6.2"
|
|
43
|
+
},
|
|
44
|
+
"prettier": {
|
|
45
|
+
"singleQuote": true,
|
|
46
|
+
"semi": true,
|
|
47
|
+
"trailingComma": "all",
|
|
48
|
+
"printWidth": 100,
|
|
49
|
+
"endOfLine": "lf"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public",
|
|
53
|
+
"registry": "https://registry.npmjs.org/"
|
|
54
|
+
},
|
|
55
|
+
"author": {
|
|
56
|
+
"name": "Libin Prasanth",
|
|
57
|
+
"url": "https://www.linkedin.com/in/libinprasanth/"
|
|
58
|
+
},
|
|
59
|
+
"funding": {
|
|
60
|
+
"type": "paypal",
|
|
61
|
+
"url": "https://www.paypal.me/LibinPrasanth"
|
|
62
|
+
}
|
|
63
|
+
}
|