sjabloon 0.6.0 → 0.8.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/README.md +61 -23
- package/lib/core.js +446 -0
- package/lib/html.d.ts +17 -0
- package/lib/html.js +21 -0
- package/lib/index.d.ts +23 -0
- package/lib/index.js +35 -0
- package/lib/text.d.ts +17 -0
- package/lib/text.js +19 -0
- package/lib/types.d.ts +83 -0
- package/package.json +51 -33
- package/dist/index.cjs +0 -1
- package/dist/index.js +0 -1
- package/index.d.ts +0 -82
- package/src/index.js +0 -291
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# sjabloon
|
|
2
2
|
|
|
3
|
-
A tiny, CSP-safe template engine for JavaScript. **~1.
|
|
3
|
+
A tiny, CSP-safe, target-neutral template engine for JavaScript. **~1.9KB min+brotli (~3.7KB with [xprsn](https://www.npmjs.com/package/xprsn)), one dependency.**
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/sjabloon)
|
|
6
6
|
[](https://github.com/getquario/sjabloon/actions/workflows/test.yml)
|
|
@@ -13,16 +13,24 @@ A tiny, CSP-safe template engine for JavaScript. **~1.8KB min+gzip (~3.6KB with
|
|
|
13
13
|
</picture>
|
|
14
14
|
</a>
|
|
15
15
|
|
|
16
|
-
*Sjabloon* is Dutch for "template". It renders
|
|
16
|
+
*Sjabloon* is Dutch for "template". It renders templates with full [xprsn](https://github.com/getquario/xprsn) expressions inside every tag, without turning template text into JavaScript. There is no `eval` and no `new Function`, so it runs under a strict Content Security Policy where engines that compile templates to code cannot.
|
|
17
|
+
|
|
18
|
+
The engine emits **tokens**, not text. A render gives you the literal runs and the interpolated values, interleaved in render order — because different targets need different things from the same template. HTML wants escaped text; a spreadsheet wants the number `1000` and a cell format; a PDF wants styled runs. Escaping belongs at the output edge, not in the engine, so a string is just one way to consume the stream.
|
|
17
19
|
|
|
18
20
|
```js
|
|
19
|
-
import { template,
|
|
21
|
+
import { template, text } from 'sjabloon';
|
|
22
|
+
|
|
23
|
+
const cell = template('{{ total * 1.21 }}');
|
|
20
24
|
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
25
|
+
cell({ total: 1000 }); // => [{ value: 1210 }] — still a number
|
|
26
|
+
text(cell({ total: 1000 })); // => '1210' — when you want the string
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
If you only want a string, import the edition that produces one directly:
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { render } from 'sjabloon/html'; // {{ }} HTML-escapes, {{{ }}} is raw
|
|
24
33
|
|
|
25
|
-
// Blocks, expressions, and custom functions:
|
|
26
34
|
render(
|
|
27
35
|
`<ul>{{#each items as it, i}}
|
|
28
36
|
<li>{{ i + 1 }}. {{ it.name }}: {{ fmt(it.price * it.qty) }}</li>
|
|
@@ -33,11 +41,25 @@ render(
|
|
|
33
41
|
);
|
|
34
42
|
```
|
|
35
43
|
|
|
44
|
+
## Editions
|
|
45
|
+
|
|
46
|
+
Three entry points, one engine. They share a parser, a syntax, and a diagnostics contract, and differ only in what a render produces.
|
|
47
|
+
|
|
48
|
+
| Import | `template(str, funcs?)` returns | `{{ expr }}` | `{{{ expr }}}` |
|
|
49
|
+
| --- | --- | --- | --- |
|
|
50
|
+
| `sjabloon` | `(values?, scope?) => Token[]` | value token | `SyntaxError` |
|
|
51
|
+
| `sjabloon/text` | `(values?, scope?) => string` | unescaped | `SyntaxError` |
|
|
52
|
+
| `sjabloon/html` | `(values?, scope?) => string` | HTML-escaped | raw |
|
|
53
|
+
|
|
54
|
+
`{{{ }}}` exists only in the HTML edition, where "raw" means something. Everywhere else `{{ }}` is already raw, so the triple form is a compile-time `SJABLOON_RAW_TAG` error rather than a silent synonym.
|
|
55
|
+
|
|
56
|
+
Every edition exports `template`, `render`, and `isDiagnostic`. They all resolve to one shared core, so a diagnostic thrown through any of them authenticates through all of them.
|
|
57
|
+
|
|
36
58
|
## API
|
|
37
59
|
|
|
38
60
|
### `template(str, functions?)`
|
|
39
61
|
|
|
40
|
-
Compiles the template and returns a renderer
|
|
62
|
+
Compiles the template and returns a renderer. What it renders to depends on the edition you imported from (see [Editions](#editions)); everything else on this page is identical across all three. Malformed tags, unclosed blocks, and invalid expressions throw a `SyntaxError` at compile time.
|
|
41
63
|
|
|
42
64
|
The anchors `$` (root) and `@` (current `{{#each}}` item) work as [described below](#syntax) with no extra arguments — at the root, before any loop, both point at `values`. If you're embedding sjabloon under an engine with its own scope model, pass `{ root, item }` as the second argument to seed the two root anchors from distinct objects: `$` becomes `root` and `@` becomes `item`. Omit `item` and `@` stays unbound at the root, so reading `@.x` throws where there is no current item. Either way, `{{#each}}` still re-points `@` to the current item inside its body.
|
|
43
65
|
|
|
@@ -47,14 +69,7 @@ tpl(base, { root: reportRoot, item: currentRow }); // $ = reportRoot, @ = curren
|
|
|
47
69
|
tpl(base, { root: reportRoot }); // no item → @.x throws
|
|
48
70
|
```
|
|
49
71
|
|
|
50
|
-
The renderer
|
|
51
|
-
|
|
52
|
-
```js
|
|
53
|
-
const cell = template('{{ total * 1.21 }}');
|
|
54
|
-
cell.withRaw({ total: 1000 }); // => { text: '1210', raws: [1210] } — still a number
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
The renderer also carries `names` (every variable the template reads from your values, loop variables excluded) and `functions` (the registry functions it calls, methods excluded), both deduplicated. Check a stored template against your data model and its allowed functions before you render it, or fetch only the fields it needs.
|
|
72
|
+
The renderer carries `names` (every variable the template reads from your values, loop variables excluded) and `functions` (the registry functions it calls, methods excluded), both deduplicated. Check a stored template against your data model and its allowed functions before you render it, or fetch only the fields it needs.
|
|
58
73
|
|
|
59
74
|
```js
|
|
60
75
|
const tpl = template('{{ fmt(title) }}{{#each items as it}}{{ it.name }}{{/each}}', { fmt: s => s });
|
|
@@ -64,7 +79,28 @@ tpl.functions; // => ['fmt']
|
|
|
64
79
|
|
|
65
80
|
### `render(str, values?, functions?)`
|
|
66
81
|
|
|
67
|
-
Shorthand for `template(str, functions)(values)
|
|
82
|
+
Shorthand for `template(str, functions)(values)`, returning whatever its edition renders.
|
|
83
|
+
|
|
84
|
+
### `text(tokens)` — root entry only
|
|
85
|
+
|
|
86
|
+
Joins a token stream the way `sjabloon/text` would have rendered it: literals verbatim, values as `String(value ?? '')`. `text(template(str)(values))` and `sjabloon/text`'s `template(str)(values)` are equal for every template and every set of values — a property the test suite and the fuzzer both check.
|
|
87
|
+
|
|
88
|
+
```js
|
|
89
|
+
import { template, text } from 'sjabloon';
|
|
90
|
+
|
|
91
|
+
const tokens = template('{{ qty }} × {{ name }}')({ qty: 2, name: 'Koffie' });
|
|
92
|
+
// => [{ value: 2 }, { literal: ' × ' }, { value: 'Koffie' }]
|
|
93
|
+
|
|
94
|
+
text(tokens); // => '2 × Koffie'
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
A `Token` is either `{ literal: string }` or `{ value: unknown }`:
|
|
98
|
+
|
|
99
|
+
- **Values are pre-stringify.** `{{ total }}` holding `1000` yields the number `1000`, not `"1000"`, and nullish stays nullish. Stringification is deferred to `text()` — so a value with no primitive conversion reaches the stream intact and only fails when something asks for text.
|
|
100
|
+
- **Order is render order.** Loop bodies append once per iteration, untaken branches append nothing, and block expressions (`#if` conditions, `#each` collections) never appear — they steer the render rather than being part of it.
|
|
101
|
+
- **Literals are the template's static runs**, one token each, never merged and never empty. So the interleaving tells you the shape: a bare `{{ amount }}` is exactly one value token, while `Total: {{ amount }}` is a literal followed by a value. That distinction is why the engine emits tokens instead of a string plus a list of values — a spreadsheet cell that is *only* a number is a different thing from one that happens to contain one.
|
|
102
|
+
|
|
103
|
+
Literal tokens are frozen and shared across loop iterations; value tokens are fresh per emit.
|
|
68
104
|
|
|
69
105
|
### Error diagnostics
|
|
70
106
|
|
|
@@ -75,18 +111,18 @@ Sjabloon errors keep their native `SyntaxError` or `TypeError` class and expose:
|
|
|
75
111
|
- `end`: the exclusive template offset;
|
|
76
112
|
- `blocks`: a frozen, outermost-first array of `{ type, start, end }` opener spans.
|
|
77
113
|
|
|
78
|
-
Parser codes are `SJABLOON_EACH_SYNTAX`, `SJABLOON_BLOCKED_BINDING`, `SJABLOON_UNEXPECTED_TAG`, `SJABLOON_UNKNOWN_BLOCK`, `SJABLOON_UNCLOSED_BLOCK`, and `SJABLOON_TOO_DEEP` (block nesting past 256 levels, located at the opener that crossed the cap). A missing closer uses an empty span at the end of the template. Expression offsets refer to the original template, so surrounding braces, whitespace, and trim markers contribute to their absolute position.
|
|
114
|
+
Parser codes are `SJABLOON_EACH_SYNTAX`, `SJABLOON_BLOCKED_BINDING`, `SJABLOON_UNEXPECTED_TAG`, `SJABLOON_UNKNOWN_BLOCK`, `SJABLOON_UNCLOSED_BLOCK`, `SJABLOON_RAW_TAG` (a `{{{ }}}` tag outside the HTML edition, located at the whole tag), and `SJABLOON_TOO_DEEP` (block nesting past 256 levels, located at the opener that crossed the cap). A missing closer uses an empty span at the end of the template. Expression offsets refer to the original template, so surrounding braces, whitespace, and trim markers contribute to their absolute position.
|
|
79
115
|
|
|
80
116
|
Unauthenticated errors thrown by registered functions, getters, methods, or value coercion hooks are host errors. Sjabloon passes them through unchanged and does not attach template diagnostic fields.
|
|
81
117
|
|
|
82
|
-
Use `isDiagnostic(error)` when a host needs to distinguish those errors. It returns `true` only for errors produced or translated by the same sjabloon module instance. Copying a documented `code`, `start`, `end`, and `blocks` onto another error does not authenticate it. A diagnostic from another installed copy or module instance
|
|
118
|
+
Use `isDiagnostic(error)` when a host needs to distinguish those errors. It returns `true` only for errors produced or translated by the same sjabloon module instance. Copying a documented `code`, `start`, `end`, and `blocks` onto another error does not authenticate it. A diagnostic from another installed copy or module instance returns `false`. All three editions share one core, so mixing them in a single process is safe: an error thrown through `sjabloon/html` authenticates through `sjabloon`.
|
|
83
119
|
|
|
84
120
|
## Syntax
|
|
85
121
|
|
|
86
122
|
| Tag | Meaning |
|
|
87
123
|
| --- | --- |
|
|
88
|
-
| `{{ expr }}` | Interpolate an expression,
|
|
89
|
-
| `{{{ expr }}}` | Interpolate
|
|
124
|
+
| `{{ expr }}` | Interpolate an expression — a value token, or text escaped per edition |
|
|
125
|
+
| `{{{ expr }}}` | Interpolate raw. **`sjabloon/html` only**; a `SyntaxError` elsewhere |
|
|
90
126
|
| `{{#if expr}} … {{#elif expr}} … {{#else}} … {{/if}}` | Conditional block, with as many `{{#elif}}` links as you need |
|
|
91
127
|
| `{{#each expr as item}} … {{/each}}` | Loop over an array or an object's values |
|
|
92
128
|
| `{{#each expr as item, key}} … {{/each}}` | Second name binds the index (arrays) or the key (objects) |
|
|
@@ -126,14 +162,16 @@ That runtime CSP support costs some render speed. Handlebars and tempura generat
|
|
|
126
162
|
|
|
127
163
|
## Safety
|
|
128
164
|
|
|
129
|
-
- `
|
|
165
|
+
- `sjabloon/html` escapes `& < > " '` in `{{ }}`; unescaped output requires the explicit `{{{ }}}` form. **If you are rendering HTML, import that edition.** The other two are output-neutral by design and escape nothing, on the assumption that you escape at your own output edge.
|
|
130
166
|
- Expressions inherit all of xprsn's guards: no `__proto__`/`constructor`/`prototype` access, null-prototype hash literals, and functions resolved only from your registry.
|
|
131
167
|
- Templates read your values; they cannot assign to them.
|
|
132
168
|
- Registered functions are host-provided capabilities, not a sandbox boundary. Only register helpers that template authors are allowed to invoke; likewise, treat explicit raw output as trusted HTML.
|
|
133
169
|
|
|
134
170
|
## Environments
|
|
135
171
|
|
|
136
|
-
Node.js 22 and newer
|
|
172
|
+
Node.js 22.12 and newer, ESM only. Browser use is supported through a standards-based ESM bundler in environments supporting ES2024. Direct `<script>` globals, UMD, and CommonJS builds are not provided.
|
|
173
|
+
|
|
174
|
+
Shipping CommonJS alongside ESM would put two copies of the core in any process that mixed `require` and `import`, and therefore two diagnostic identities — `isDiagnostic` would silently return `false` across the seam. One format removes that failure mode instead of documenting it.
|
|
137
175
|
|
|
138
176
|
## License
|
|
139
177
|
|
package/lib/core.js
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny, CSP-safe template engine powered by xprsn expressions.
|
|
3
|
+
* Templates compile to a composition of closures; template text is never
|
|
4
|
+
* turned into JavaScript, so strict CSP is satisfied.
|
|
5
|
+
*
|
|
6
|
+
* This is the shared core: the lexer, parser and diagnostics, with output left
|
|
7
|
+
* to the profile each entry passes to `make()`. Exactly one copy of this module
|
|
8
|
+
* backs every entry, so the WeakSet below authenticates diagnostics across all
|
|
9
|
+
* of them.
|
|
10
|
+
*/
|
|
11
|
+
import { compile, isDiagnostic as isXprsnDiagnostic } from 'xprsn';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @import { SjabloonDiagnostic, SjabloonErrorCode, SjabloonFunctions, SjabloonRenderer, SjabloonValues } from './types.js'
|
|
15
|
+
* @template A
|
|
16
|
+
* @typedef {(scope: any, acc: A, scratch?: any) => void} Node One compiled node: appends into
|
|
17
|
+
* `acc` and returns nothing. The third slot is a scratch local some editions declare as a
|
|
18
|
+
* parameter to save a `let`; callers pass two arguments.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One lexer token: `[0, text]` for a static run, or
|
|
23
|
+
* `[1|2, body, start, end, bodyStart]` for a raw or normal tag.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately loose — the two kinds have different arities and the parser
|
|
26
|
+
* indexes them positionally on the hot path.
|
|
27
|
+
*
|
|
28
|
+
* @internal
|
|
29
|
+
* @typedef {any[]} Tok
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const BLOCKED = /^(?:__proto__|constructor|prototype)$/;
|
|
33
|
+
/** @type {WeakSet<any>} */
|
|
34
|
+
const DIAGNOSTICS = new WeakSet();
|
|
35
|
+
const mark = DIAGNOSTICS.add.bind(DIAGNOSTICS);
|
|
36
|
+
const owns = DIAGNOSTICS.has.bind(DIAGNOSTICS);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Check whether an error was produced or translated by sjabloon.
|
|
40
|
+
*
|
|
41
|
+
* Every entry shares one core, so a diagnostic thrown through any of them
|
|
42
|
+
* authenticates through all of them.
|
|
43
|
+
*
|
|
44
|
+
* @param {unknown} error Any thrown value.
|
|
45
|
+
* @returns {error is SjabloonDiagnostic} Whether `error` is an authentic sjabloon diagnostic.
|
|
46
|
+
*/
|
|
47
|
+
export const isDiagnostic = error => owns(error);
|
|
48
|
+
|
|
49
|
+
// Linear scan into text/tag/raw tokens. Dashes hug braces (`{{- x -}}` trims;
|
|
50
|
+
// `{{ -x }}` stays unary minus). Prefer {{{ }}} over {{ }}. `triple` latches
|
|
51
|
+
// off once }}} is gone so {{{...}}×N does not rescan to EOF (stays O(n)).
|
|
52
|
+
/**
|
|
53
|
+
* @param {string} s
|
|
54
|
+
* @returns {Tok[]}
|
|
55
|
+
*/
|
|
56
|
+
let lex = s => {
|
|
57
|
+
const out = /** @type {Tok[]} */ ([]);
|
|
58
|
+
for (let i = 0, triple = 1; i < s.length; ) {
|
|
59
|
+
const a = s.indexOf('{{', i);
|
|
60
|
+
if (a < 0) { out.push([0, s.slice(i)]); break; }
|
|
61
|
+
if (a > i) out.push([0, s.slice(i, a)]);
|
|
62
|
+
let raw = +(s[a + 2] === '{'), p = a + 2 + raw, l = s[p] === '-', b = -1;
|
|
63
|
+
if (l) p++;
|
|
64
|
+
if (raw && triple) { b = s.indexOf('}}}', p); if (b < 0) triple = 0; }
|
|
65
|
+
if (b < 0) {
|
|
66
|
+
if (raw) { raw = 0; p = a + 2; l = s[p] === '-'; if (l) p++; }
|
|
67
|
+
b = s.indexOf('}}', p);
|
|
68
|
+
}
|
|
69
|
+
if (b < 0) { out.push([0, s.slice(a)]); break; }
|
|
70
|
+
const r = b > p && s[b - 1] === '-';
|
|
71
|
+
const q = r ? b - 1 : b, whole = s.slice(p, q), body = whole.trim();
|
|
72
|
+
const start = p + whole.length - whole.trimStart().length, end = b + 2 + raw;
|
|
73
|
+
const t = [raw ? 1 : 2, body, a, end, start];
|
|
74
|
+
const prev = out.at(-1);
|
|
75
|
+
if (l && prev?.[0] === 0 && prev[1]) prev[1] = prev[1].trimEnd();
|
|
76
|
+
out.push(t);
|
|
77
|
+
i = end;
|
|
78
|
+
if (r) while (/\s/.test(s[i])) i++;
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// One shared prototype for renders that omit `values` — the shape an embedder
|
|
84
|
+
// passing `{ root, item }` hits on every cell. A fresh `{}` here would give each
|
|
85
|
+
// wrapper its own hidden class, so lookups go megamorphic and such a render
|
|
86
|
+
// costs ~12x one that passes values. Frozen: nothing may write to a prototype
|
|
87
|
+
// shared across renders.
|
|
88
|
+
const EMPTY = Object.freeze({});
|
|
89
|
+
|
|
90
|
+
// Shared parser state; parsing is synchronous so this is safe.
|
|
91
|
+
// `nms` collects free variables, `fnms` the registry functions called.
|
|
92
|
+
// LIT/VAL/RAW are the compiling profile's node builders — read only while
|
|
93
|
+
// parsing, never at render time, so the hot path stays free of indirection.
|
|
94
|
+
/** @type {Tok[]} */
|
|
95
|
+
let toks;
|
|
96
|
+
/** @type {number} */
|
|
97
|
+
let i;
|
|
98
|
+
/** @type {SjabloonFunctions | undefined} */
|
|
99
|
+
let fns;
|
|
100
|
+
/** @type {Tok} */
|
|
101
|
+
let last;
|
|
102
|
+
/** @type {string[]} */
|
|
103
|
+
let bound;
|
|
104
|
+
/** @type {Set<string>} */
|
|
105
|
+
let nms;
|
|
106
|
+
/** @type {Set<string>} */
|
|
107
|
+
let fnms;
|
|
108
|
+
/** @type {string} */
|
|
109
|
+
let src;
|
|
110
|
+
/** @type {any[]} */
|
|
111
|
+
let blocks;
|
|
112
|
+
// The profile's node builders. `any` rather than `Node<A>`: `make()` is generic
|
|
113
|
+
// per edition, but these are module-level and shared across all three, so no
|
|
114
|
+
// single A applies here.
|
|
115
|
+
/** @type {any} */
|
|
116
|
+
let LIT;
|
|
117
|
+
/** @type {any} */
|
|
118
|
+
let VAL;
|
|
119
|
+
/** @type {any} */
|
|
120
|
+
let RAW;
|
|
121
|
+
|
|
122
|
+
let snap = () => Object.freeze(blocks.slice());
|
|
123
|
+
// Block nesting is capped so a pathological template fails as a deterministic
|
|
124
|
+
// SyntaxError at the offending opener, far below the native stack limit.
|
|
125
|
+
const DEPTH = 256;
|
|
126
|
+
/**
|
|
127
|
+
* @param {string} type
|
|
128
|
+
* @param {Tok} t
|
|
129
|
+
*/
|
|
130
|
+
let opener = (type, t) => {
|
|
131
|
+
blocks.length < DEPTH || fault('Template too deeply nested', 'SJABLOON_TOO_DEEP', t);
|
|
132
|
+
return Object.freeze({ type, start: t[2], end: t[3] });
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* @template {object} E
|
|
136
|
+
* @param {E} e
|
|
137
|
+
* @param {any} context
|
|
138
|
+
* @returns {E}
|
|
139
|
+
*/
|
|
140
|
+
let attach = (e, context) => {
|
|
141
|
+
Object.defineProperty(e, 'blocks', { value: context, enumerable: true });
|
|
142
|
+
mark(e);
|
|
143
|
+
return e;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Throw a located compile-time diagnostic. `code` is typed to the published
|
|
147
|
+
* union, so a code that is not declared in `types.d.ts` fails to compile here
|
|
148
|
+
* rather than shipping undeclared — which is exactly how SJABLOON_TOO_DEEP got
|
|
149
|
+
* out for two releases.
|
|
150
|
+
*
|
|
151
|
+
* @param {string} msg
|
|
152
|
+
* @param {SjabloonErrorCode} code
|
|
153
|
+
* @param {any[]} [t] The token to point at; omitted for end-of-source faults.
|
|
154
|
+
* @returns {never}
|
|
155
|
+
*/
|
|
156
|
+
const fault = (msg, code, t, start = t?.[2] ?? src.length, end = t?.[3] ?? src.length) => {
|
|
157
|
+
const e = /** @type {SyntaxError & { code: SjabloonErrorCode, start: number, end: number }} */ (SyntaxError(msg));
|
|
158
|
+
e.code = code;
|
|
159
|
+
e.start = start;
|
|
160
|
+
e.end = end;
|
|
161
|
+
throw attach(e, snap());
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Re-locate a diagnostic thrown by a nested compile or render into this
|
|
165
|
+
* template's coordinates, then rethrow it as ours. Always throws.
|
|
166
|
+
*
|
|
167
|
+
* `owns` is a plain predicate rather than a type guard: `e` is retyped here,
|
|
168
|
+
* not narrowed. `const` with an explicit `never` type is what lets callers
|
|
169
|
+
* treat the catch block as terminal.
|
|
170
|
+
*
|
|
171
|
+
* @type {(e: any, start: number, context: any, owns?: (e: unknown) => boolean) => never}
|
|
172
|
+
*/
|
|
173
|
+
const translated = (e, start, context, owns = isXprsnDiagnostic) => {
|
|
174
|
+
if (!owns(e)) throw e;
|
|
175
|
+
e.start += start;
|
|
176
|
+
e.end += start;
|
|
177
|
+
throw attach(e, context);
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* @param {Tok} t
|
|
181
|
+
* @returns {never}
|
|
182
|
+
*/
|
|
183
|
+
let unexpected = t => fault('Unexpected {{' + t[1] + '}}', 'SJABLOON_UNEXPECTED_TAG', t);
|
|
184
|
+
|
|
185
|
+
// Append every node's output into the accumulator `o`, which the root wrapper
|
|
186
|
+
// creates once per render and threads all the way down. Nodes return nothing:
|
|
187
|
+
// no intermediate array per node list, no join, and render order is just push
|
|
188
|
+
// order.
|
|
189
|
+
/**
|
|
190
|
+
* @param {Node<any>[]} nodes
|
|
191
|
+
* @param {any} v
|
|
192
|
+
* @param {any} o
|
|
193
|
+
*/
|
|
194
|
+
let run = (nodes, v, o) => { for (const n of nodes) n(v, o); };
|
|
195
|
+
|
|
196
|
+
// A leaf interpolation node: compile the expression, then let the profile turn
|
|
197
|
+
// the evaluated value into output. `k` is VAL for `{{ }}`, RAW for `{{{ }}}`.
|
|
198
|
+
/**
|
|
199
|
+
* @param {Tok} t
|
|
200
|
+
* @param {any} k
|
|
201
|
+
* @returns {Node<any>}
|
|
202
|
+
*/
|
|
203
|
+
let interp = (t, k) => k(cp(t[1], t[4], snap()));
|
|
204
|
+
|
|
205
|
+
// Compile one expression and collect its free variables (minus the loop
|
|
206
|
+
// variables currently in scope, which belong to the template) and the registry
|
|
207
|
+
// functions it calls.
|
|
208
|
+
/**
|
|
209
|
+
* @param {string} s
|
|
210
|
+
* @param {number} start
|
|
211
|
+
* @param {any} context
|
|
212
|
+
* @returns {(v: any) => any}
|
|
213
|
+
*/
|
|
214
|
+
let cp = (s, start, context) => {
|
|
215
|
+
/** @type {ReturnType<typeof compile>} */
|
|
216
|
+
let e;
|
|
217
|
+
try {
|
|
218
|
+
// `SjabloonFunctions` is `Record<string, Function>`; xprsn's registry wants
|
|
219
|
+
// `Record<string, (...args: any[]) => any>`, and TypeScript deliberately
|
|
220
|
+
// refuses `Function` against a call signature. The registry is passed
|
|
221
|
+
// straight through untouched, so this is a published-type mismatch rather
|
|
222
|
+
// than a real one — narrowing `SjabloonFunctions` would change the API.
|
|
223
|
+
e = compile(s, /** @type {any} */ (fns));
|
|
224
|
+
} catch (x) {
|
|
225
|
+
translated(x, start, context);
|
|
226
|
+
}
|
|
227
|
+
for (const n of e.names) bound.includes(n) || nms.add(n);
|
|
228
|
+
for (const fn of e.functions) fnms.add(fn);
|
|
229
|
+
return v => {
|
|
230
|
+
try {
|
|
231
|
+
return e(v);
|
|
232
|
+
} catch (x) {
|
|
233
|
+
translated(x, start, context, e.isDiagnostic);
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// One `#if`/`#elif` link: parse its branch, then recurse on the chain tail.
|
|
239
|
+
/**
|
|
240
|
+
* @param {(v: any) => any} cond
|
|
241
|
+
* @returns {Node<any>}
|
|
242
|
+
*/
|
|
243
|
+
let branch = cond => {
|
|
244
|
+
const then = parse(['#elif', '#else', '/if']);
|
|
245
|
+
const tag = last[1];
|
|
246
|
+
let els = /** @type {Node<any>[]} */ ([]);
|
|
247
|
+
if (tag.startsWith('#elif ')) els = [branch(cp(tag.slice(6), last[4] + 6, snap()))];
|
|
248
|
+
else if (tag === '#else') {
|
|
249
|
+
els = parse(['/if']);
|
|
250
|
+
last[1] === '/if' || unexpected(last);
|
|
251
|
+
} else if (tag !== '/if') unexpected(last);
|
|
252
|
+
return (v, o) => run(cond(v) ? then : els, v, o);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* @param {string[]} stops
|
|
257
|
+
* @returns {Node<any>[]}
|
|
258
|
+
*/
|
|
259
|
+
let parse = stops => {
|
|
260
|
+
const nodes = /** @type {Node<any>[]} */ ([]);
|
|
261
|
+
for (let t; (t = toks[i++]); ) {
|
|
262
|
+
const tag = t[1];
|
|
263
|
+
if (!t[0]) {
|
|
264
|
+
// Left-trim can shave a text run down to nothing; never emit it.
|
|
265
|
+
tag && nodes.push(LIT(tag));
|
|
266
|
+
} else if (t[0] === 1) {
|
|
267
|
+
// The lexer always tokenizes `}}}` — dropping it would cost the
|
|
268
|
+
// `triple` latch that keeps lexing linear — so editions without a
|
|
269
|
+
// raw form reject it here, at the parser, with a located span.
|
|
270
|
+
RAW || fault('Raw {{{' + tag + '}}} is not available here; {{ ' + tag + ' }} is already raw', 'SJABLOON_RAW_TAG', t);
|
|
271
|
+
nodes.push(interp(t, RAW));
|
|
272
|
+
} else if (stops.includes(tag.split(' ')[0])) {
|
|
273
|
+
last = t;
|
|
274
|
+
return nodes;
|
|
275
|
+
} else if (tag[0] === '!') {
|
|
276
|
+
// comment
|
|
277
|
+
} else if (tag.startsWith('#if ')) {
|
|
278
|
+
blocks.push(opener('if', t));
|
|
279
|
+
nodes.push(branch(cp(tag.slice(4), t[4] + 4, snap())));
|
|
280
|
+
blocks.pop();
|
|
281
|
+
} else if (/^#each(?:\s|$)/.test(tag)) {
|
|
282
|
+
blocks.push(opener('each', t));
|
|
283
|
+
// `|| fault()` in the initializer, not as a follow-up statement: fault
|
|
284
|
+
// returns never, so `m` is non-null from here without a second check.
|
|
285
|
+
const m = /^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(tag) || fault('Bad {{' + tag + '}}', 'SJABLOON_EACH_SYNTAX', t);
|
|
286
|
+
const name = m[3], idx = m[4], at = t[4] + tag.length - m[2].length;
|
|
287
|
+
if (BLOCKED.test(name)) fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, at, at + name.length);
|
|
288
|
+
if (idx && BLOCKED.test(idx)) {
|
|
289
|
+
const p = t[4] + tag.length - idx.length;
|
|
290
|
+
fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, p, p + idx.length);
|
|
291
|
+
}
|
|
292
|
+
const list = cp(m[1], t[4] + 6, snap());
|
|
293
|
+
// `name`, `idx`, and `loop` are engine-bound inside the body, so
|
|
294
|
+
// exclude them from names there and restore outer bindings after.
|
|
295
|
+
const mark = bound.length;
|
|
296
|
+
bound.push(name);
|
|
297
|
+
if (idx) bound.push(idx);
|
|
298
|
+
bound.push('loop');
|
|
299
|
+
const body = parse(['#else', '/each']);
|
|
300
|
+
bound.length = mark;
|
|
301
|
+
let empty = /** @type {Node<any>[]} */ ([]);
|
|
302
|
+
if (last[1] === '#else') {
|
|
303
|
+
empty = parse(['/each']);
|
|
304
|
+
last[1] === '/each' || unexpected(last);
|
|
305
|
+
} else if (last[1] !== '/each') unexpected(last);
|
|
306
|
+
blocks.pop();
|
|
307
|
+
// Child scopes inherit the parent via the prototype chain, so outer
|
|
308
|
+
// variables stay visible inside the loop body. `@` re-points to the
|
|
309
|
+
// current item at each level, `$` (root) rides the chain, and `loop`
|
|
310
|
+
// carries the iteration metadata (index/first/last/length).
|
|
311
|
+
nodes.push((v, o) => {
|
|
312
|
+
const lv = list(v), arr = Array.isArray(lv);
|
|
313
|
+
const ps = arr ? lv.slice() : lv && typeof lv === 'object' ? Object.keys(lv).map(k => [lv[k], k]) : [];
|
|
314
|
+
if (!ps.length) return run(empty, v, o);
|
|
315
|
+
// forEach, not a counted loop: `slice()` keeps holes and forEach
|
|
316
|
+
// skips them exactly as the `.map()` this replaced did, so sparse
|
|
317
|
+
// arrays iterate the same way with surrounding indexes unshifted.
|
|
318
|
+
ps.forEach((x, j) => {
|
|
319
|
+
const item = arr ? x : x[0], key = arr ? j : x[1];
|
|
320
|
+
const s = Object.create(v);
|
|
321
|
+
s[name] = item;
|
|
322
|
+
if (idx) s[idx] = key;
|
|
323
|
+
s['@'] = item;
|
|
324
|
+
s.loop = { index: j + 1, index0: j, first: !j, last: j === ps.length - 1, length: ps.length };
|
|
325
|
+
run(body, s, o);
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
} else if (/^#(?:if|elif|else)(?:\s|$)/.test(tag) || tag[0] === '/') {
|
|
329
|
+
unexpected(t);
|
|
330
|
+
} else if (tag[0] === '#') {
|
|
331
|
+
fault('Unknown {{' + tag + '}}', 'SJABLOON_UNKNOWN_BLOCK', t);
|
|
332
|
+
} else {
|
|
333
|
+
nodes.push(interp(t, VAL));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
stops.length && fault('Missing {{' + stops[stops.length - 1] + '}}', 'SJABLOON_UNCLOSED_BLOCK');
|
|
337
|
+
return nodes;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Bind the parser to an output profile. Each edition calls this once at module
|
|
342
|
+
* load and gets back its own `template` and `render`; the parser itself stays
|
|
343
|
+
* module-level and shared, so there is exactly one diagnostics WeakSet.
|
|
344
|
+
*
|
|
345
|
+
* `template(str, funcs?)` compiles a template once, to render it many times.
|
|
346
|
+
*
|
|
347
|
+
* The returned renderer exposes `names`: the variables the template reads
|
|
348
|
+
* from your values, deduplicated. Loop variables the template introduces are
|
|
349
|
+
* not included. It also exposes `functions`: the registry functions the
|
|
350
|
+
* template calls, deduplicated.
|
|
351
|
+
*
|
|
352
|
+
* Two anchors are always in scope: `$` is the root values, and `@` is the
|
|
353
|
+
* current `#each` item (the root outside any loop). They let a nested loop
|
|
354
|
+
* reach the root (`$.company`) or the current item (`@.total`) explicitly,
|
|
355
|
+
* past any shadowing. Neither counts as a `name`.
|
|
356
|
+
*
|
|
357
|
+
* An embedder with its own scope model can override the anchors per render by
|
|
358
|
+
* passing `{ root, item }` as the renderer's second argument: `$` becomes
|
|
359
|
+
* `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
|
|
360
|
+
* `@` unbound, so reading `@.x` throws through xprsn's guard.
|
|
361
|
+
*
|
|
362
|
+
* Render order is push order into a single accumulator: loop bodies append once
|
|
363
|
+
* per iteration, untaken branches append nothing, and block expressions (`#if`
|
|
364
|
+
* conditions, `#each` collections) never append at all. The token edition
|
|
365
|
+
* exposes that ordering directly; the string editions collapse it to text.
|
|
366
|
+
*
|
|
367
|
+
* A profile is `[lit, val, raw, seed, take]`:
|
|
368
|
+
* lit(text) node emitting one static text run
|
|
369
|
+
* val(expr) node emitting a `{{ }}` interpolation
|
|
370
|
+
* raw(expr) node emitting a `{{{ }}}` interpolation
|
|
371
|
+
* seed() a fresh output accumulator, one per render
|
|
372
|
+
* take(acc) the render's return value
|
|
373
|
+
* Nodes are `(scope, acc) => void`; see run().
|
|
374
|
+
*
|
|
375
|
+
* @template A The accumulator this edition threads through its nodes.
|
|
376
|
+
* @template T What one render returns.
|
|
377
|
+
* @param {[
|
|
378
|
+
* lit: (text: string) => Node<A>,
|
|
379
|
+
* val: (expr: (scope: any) => any) => Node<A>,
|
|
380
|
+
* raw: ((expr: (scope: any) => any) => Node<A>) | 0,
|
|
381
|
+
* seed: () => A,
|
|
382
|
+
* take: (acc: A) => T,
|
|
383
|
+
* ]} profile The output profile, as above.
|
|
384
|
+
* @returns {{
|
|
385
|
+
* template: (str: string, funcs?: SjabloonFunctions) => SjabloonRenderer<T>,
|
|
386
|
+
* render: (str: string, values?: SjabloonValues, funcs?: SjabloonFunctions) => T,
|
|
387
|
+
* }} That edition's API.
|
|
388
|
+
* @throws {SyntaxError} `template` throws on malformed tags, unclosed blocks,
|
|
389
|
+
* or bad expressions.
|
|
390
|
+
*/
|
|
391
|
+
export let make = ([lit, val, raw, seed, take]) => {
|
|
392
|
+
/**
|
|
393
|
+
* @param {string} str
|
|
394
|
+
* @param {SjabloonFunctions} [funcs]
|
|
395
|
+
* @returns {SjabloonRenderer<T>}
|
|
396
|
+
*/
|
|
397
|
+
function template(str, funcs) {
|
|
398
|
+
LIT = lit, VAL = val, RAW = raw;
|
|
399
|
+
fns = funcs;
|
|
400
|
+
// `$` (root) and `@` (current item) are engine-bound anchors, always in
|
|
401
|
+
// scope, so they never count as caller-supplied `names`.
|
|
402
|
+
bound = ['$', '@'];
|
|
403
|
+
nms = new Set();
|
|
404
|
+
fnms = new Set();
|
|
405
|
+
src = String(str);
|
|
406
|
+
blocks = [];
|
|
407
|
+
toks = lex(src);
|
|
408
|
+
i = 0;
|
|
409
|
+
// Deeply nested blocks overflow the recursive-descent parser; surface that
|
|
410
|
+
// as a SyntaxError so malformed input keeps its documented compile-time
|
|
411
|
+
// contract (mirroring xprsn's XPRSN_TOO_DEEP for expressions).
|
|
412
|
+
let nodes;
|
|
413
|
+
try {
|
|
414
|
+
nodes = parse([]);
|
|
415
|
+
} catch (x) {
|
|
416
|
+
// An empty span at the end, like an unclosed block.
|
|
417
|
+
if (x instanceof RangeError) fault('Template too deeply nested', 'SJABLOON_TOO_DEEP');
|
|
418
|
+
throw x;
|
|
419
|
+
}
|
|
420
|
+
// Wrap the values in a root scope carrying the anchors, without mutating
|
|
421
|
+
// what the caller passed: by default `$` and `@` both point at the root.
|
|
422
|
+
// An embedder can override the anchors with a `{ root, item }` second arg:
|
|
423
|
+
// `$` = root, `@` = item (distinct objects). Omitting `item` leaves `@`
|
|
424
|
+
// unbound, so `@.x` throws through xprsn's guard — a group-header band that
|
|
425
|
+
// has no current row wants exactly that.
|
|
426
|
+
const f = (/** @type {any} */ v, /** @type {any} */ o) => {
|
|
427
|
+
v = v || EMPTY;
|
|
428
|
+
const r = Object.create(v);
|
|
429
|
+
r['$'] = o ? o.root : v;
|
|
430
|
+
if (!o) r['@'] = v;
|
|
431
|
+
else if ('item' in o) r['@'] = o.item;
|
|
432
|
+
// One accumulator per render, owned here and threaded down. A registry
|
|
433
|
+
// function that renders another template gets its own, so re-entrancy
|
|
434
|
+
// needs no bookkeeping.
|
|
435
|
+
const acc = seed();
|
|
436
|
+
run(nodes, r, acc);
|
|
437
|
+
return take(acc);
|
|
438
|
+
};
|
|
439
|
+
// Array.from, not a spread: the bundler's transpile turns `[...set]` into
|
|
440
|
+
// `[].concat(set)`, which wraps the Set instead of unpacking it.
|
|
441
|
+
f.names = Array.from(nms);
|
|
442
|
+
f.functions = Array.from(fnms);
|
|
443
|
+
return f;
|
|
444
|
+
}
|
|
445
|
+
return { template, render: (str, values, funcs) => template(str, funcs)(values) };
|
|
446
|
+
};
|
package/lib/html.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
import type { SjabloonFunctions, SjabloonRenderer, SjabloonValues } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compile a template once, render it many times to an HTML string.
|
|
6
|
+
*
|
|
7
|
+
* `{{ expr }}` HTML-escapes (`& < > " '`) and `{{{ expr }}}` interpolates raw.
|
|
8
|
+
* This is the only edition that knows what HTML is; the rest of sjabloon leaves
|
|
9
|
+
* escaping to the output edge.
|
|
10
|
+
*
|
|
11
|
+
* @see SjabloonRenderer for `names`/`functions`, SjabloonScope for `$` and `@`.
|
|
12
|
+
* @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
|
|
13
|
+
*/
|
|
14
|
+
export function template(str: string, funcs?: SjabloonFunctions): SjabloonRenderer<string>;
|
|
15
|
+
|
|
16
|
+
/** Compile and render in one go. Shorthand for `template(str, funcs)(values)`. */
|
|
17
|
+
export function render(str: string, values?: SjabloonValues, funcs?: SjabloonFunctions): string;
|
package/lib/html.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTML edition: `{{ }}` HTML-escapes, `{{{ }}}` interpolates raw. This is
|
|
3
|
+
* 0.6's behaviour, kept for templates that target HTML directly. Everything
|
|
4
|
+
* else in sjabloon is output-neutral; escaping lives here and nowhere else.
|
|
5
|
+
*/
|
|
6
|
+
import { make } from './core.js';
|
|
7
|
+
|
|
8
|
+
/** @type {Record<string, string>} */
|
|
9
|
+
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
10
|
+
/** @param {any} s */
|
|
11
|
+
const esc = s => String(s).replace(/[&<>"']/g, c => ESC[c]);
|
|
12
|
+
|
|
13
|
+
export { isDiagnostic } from './core.js';
|
|
14
|
+
|
|
15
|
+
export const { template, render } = make([
|
|
16
|
+
s => (v, o) => { o.s += s; },
|
|
17
|
+
e => (v, o, x) => (x = e(v), o.s += esc(x ?? '')),
|
|
18
|
+
e => (v, o, x) => (x = e(v), o.s += String(x ?? '')),
|
|
19
|
+
() => ({ s: '' }),
|
|
20
|
+
o => o.s,
|
|
21
|
+
]);
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
import type { SjabloonFunctions, SjabloonRenderer, SjabloonValues, Token } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compile a template once, render it many times to a token stream.
|
|
6
|
+
*
|
|
7
|
+
* `{{ expr }}` emits a value token; escaping belongs to whoever consumes the
|
|
8
|
+
* stream, so `{{{ expr }}}` has no meaning here and is a compile-time
|
|
9
|
+
* `SJABLOON_RAW_TAG` error.
|
|
10
|
+
*
|
|
11
|
+
* @see SjabloonRenderer for `names`/`functions`, SjabloonScope for `$` and `@`.
|
|
12
|
+
* @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
|
|
13
|
+
*/
|
|
14
|
+
export function template(str: string, funcs?: SjabloonFunctions): SjabloonRenderer<Token[]>;
|
|
15
|
+
|
|
16
|
+
/** Compile and render in one go. Shorthand for `template(str, funcs)(values)`. */
|
|
17
|
+
export function render(str: string, values?: SjabloonValues, funcs?: SjabloonFunctions): Token[];
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Join a token stream into the string `sjabloon/text` would have produced:
|
|
21
|
+
* literals verbatim, values as `String(value ?? '')`.
|
|
22
|
+
*/
|
|
23
|
+
export function text(tokens: readonly Token[]): string;
|