@orkestrel/template 0.0.16 → 0.0.18

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.
@@ -1,4 +1,6 @@
1
- import { INTRINSICS, createContract, holds, isArray, isFiniteNumber, isFunction, isObject, isString, objectShape, optionalShape, resolveField, schemaToParameters, stringShape } from "@orkestrel/contract";
1
+ import { INTRINSICS, attempt, createContract, holds, isArray, isBoolean, isFiniteNumber, isFunction, isMap, isNonNegativeInteger, isObject, isRecord, isString, keyOf, objectShape, optionalShape, resolveField, schemaToParameters, stringShape } from "@orkestrel/contract";
2
+ import { HTML, MAX_DEPTH, SAFE_URL_SCHEMES, createHTML, isHTMLDocument, isHTMLNode, mergeText, renderHTML, sanitizeURL } from "@orkestrel/html";
3
+ import { coalesceText, flattenText, htmlToMarkdown, isBlockNode, isInlineNode, isMarkdownDocument, isMarkdownNode, markdownToHTML, parseMarkdown, renderMarkdown } from "@orkestrel/markdown";
2
4
  import { Emitter } from "@orkestrel/emitter";
3
5
  // src/core/constants.ts
4
6
  /**
@@ -7,19 +9,10 @@ import { Emitter } from "@orkestrel/emitter";
7
9
  *
8
10
  * @remarks
9
11
  * Global-flagged, two-alternative pattern: a match of the first alternative
10
- * (`\{{` — a literal backslash followed by `{{`) means "emit a literal
11
- * `{{`" — the escape hatch for content that must show `{{` without
12
- * triggering substitution. A match that instead populates capture group 1
13
- * (`\{{([^{}]+?)\}\}`) means "substitute the named token" — group 1 is the
14
- * untrimmed token text between the braces; every call site trims it
15
- * (`token.trim()`) before using it as a lookup name, so `'{{ name }}'` still
16
- * resolves `'name'`. The pattern deliberately does not wrap the token in
17
- * `\s*` — an unclosed `'{{' + ' '.repeat(n)` with no closing `}}` would
18
- * otherwise force the regex engine into catastrophic backtracking over the
19
- * whitespace run (O(n^2)); trimming after the match keeps the same
20
- * whitespace tolerance without the backtracking hazard. Every call site
21
- * builds a fresh `RegExp` from `.source` / `.flags` rather than sharing this
22
- * instance's mutable `lastIndex` across scans.
12
+ * (`\{{` — a literal backslash followed by `{{`) emits a literal `{{`. A match
13
+ * populating capture group 1 (`\{\{([^{}]+?)\}\}`) resolves the trimmed token
14
+ * name without backtracking on unclosed whitespace runs. Every call site builds
15
+ * a fresh `RegExp` from `.source` and `.flags`.
23
16
  */
24
17
  var FILL_PATTERN = /\\\{\{|\{\{([^{}]+?)\}\}/g;
25
18
  /**
@@ -42,18 +35,242 @@ var UNSAFE_FIELD_SEGMENTS = Object.freeze([
42
35
  "constructor",
43
36
  "prototype"
44
37
  ]);
38
+ /**
39
+ * Lists every machine-readable error code admitted on a {@link TemplateError}.
40
+ */
41
+ var TEMPLATE_ERROR_CODES = Object.freeze([
42
+ "MISSING",
43
+ "NOTFOUND",
44
+ "INVALID",
45
+ "CONFLICT",
46
+ "FORMAT",
47
+ "EVALUATION",
48
+ "RAISE"
49
+ ]);
50
+ /**
51
+ * Holds the regular-expression character class Python's `str.isspace` reports
52
+ * as whitespace for Jinja whitespace markers, `lstrip_blocks`, `trim`, `rstrip`,
53
+ * `lstrip`, and default `split`.
54
+ */
55
+ var TEMPLATE_SPACE = "[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
56
+ /**
57
+ * Matches one root-level segment of a Jinja template source: a run of literal
58
+ * text and the tag, comment, or unclosed delimiter that follows it.
59
+ */
60
+ var TEMPLATE_SEGMENT_PATTERN = /((?:[^{]|\{(?![{%#]))*)(?:(\{%[-+]?)((?:'(?:[^'\\]|\\[^])*'|"(?:[^"\\]|\\[^])*"|[^'"])*?)([-+]?%\})|(\{\{[-+]?)((?:'(?:[^'\\]|\\[^])*'|"(?:[^"\\]|\\[^])*"|[^'"])*?)(-?\}\})|(\{#[-+]?)([^]*?)([-+]?#\})|(\{[{%#])[^]*|$)/gy;
61
+ /**
62
+ * Matches one lexical token inside a Jinja template tag in lexer precedence
63
+ * order: whitespace, float, integer, name, string literal, operator, or fault.
64
+ */
65
+ var TEMPLATE_TOKEN_PATTERN = new RegExp(`(${TEMPLATE_SPACE}+)|((?<!\\.)(?:\\d+_)*\\d+(?:(?:\\.(?:\\d+_)*\\d+)?[eE][-+]?(?:\\d+_)*\\d+|\\.(?:\\d+_)*\\d+))|(0[bB](?:_?[01])+|0[oO](?:_?[0-7])+|0[xX](?:_?[\\da-fA-F])+|[1-9](?:_?\\d)*|0(?:_?0)*)|([\\p{XID_Start}_]\\p{XID_Continue}*)|('(?:[^'\\\\]|\\\\[^])*'|"(?:[^"\\\\]|\\\\[^])*")|(\\/\\/|\\*\\*|==|!=|>=|<=|[-+/*%~[\\](){}<>=.:|,;])|([^])`, "gyu");
66
+ /**
67
+ * Maps each Jinja built-in constant spelling to its runtime literal value.
68
+ */
69
+ var TEMPLATE_LITERALS = Object.freeze({
70
+ true: true,
71
+ false: false,
72
+ none: null,
73
+ True: true,
74
+ False: false,
75
+ None: null
76
+ });
77
+ /**
78
+ * Lists the single-token comparison operators admitted in template expressions.
79
+ */
80
+ var TEMPLATE_COMPARISONS = Object.freeze([
81
+ "==",
82
+ "!=",
83
+ "<",
84
+ ">",
85
+ "<=",
86
+ ">="
87
+ ]);
88
+ /**
89
+ * Maps each single-character Python `unicode-escape` sequence after `\` to its
90
+ * decoded character.
91
+ */
92
+ var TEMPLATE_ESCAPES = Object.freeze({
93
+ "\\": "\\",
94
+ "'": "'",
95
+ "\"": "\"",
96
+ a: "\x07",
97
+ b: "\b",
98
+ f: "\f",
99
+ n: "\n",
100
+ r: "\r",
101
+ t: " ",
102
+ v: "\v"
103
+ });
104
+ /**
105
+ * Lists the global Jinja and Hugging Face chat-template function names
106
+ * recognized by the compiler, of which `raise_exception` and `namespace` are
107
+ * admitted as calls.
108
+ */
109
+ var TEMPLATE_FUNCTIONS = Object.freeze([
110
+ "raise_exception",
111
+ "namespace",
112
+ "strftime_now",
113
+ "dict",
114
+ "range",
115
+ "lipsum",
116
+ "cycler",
117
+ "joiner"
118
+ ]);
119
+ /**
120
+ * Lists the Jinja `|` filters admitted by the template compiler and evaluator.
121
+ */
122
+ var TEMPLATE_FILTERS = Object.freeze([
123
+ "trim",
124
+ "length",
125
+ "tojson",
126
+ "items",
127
+ "safe",
128
+ "string"
129
+ ]);
130
+ /**
131
+ * Lists the Jinja `is` / `is not` tests admitted by the template compiler and
132
+ * evaluator.
133
+ */
134
+ var TEMPLATE_TESTS = Object.freeze([
135
+ "defined",
136
+ "undefined",
137
+ "none",
138
+ "string",
139
+ "mapping",
140
+ "iterable",
141
+ "sequence",
142
+ "true",
143
+ "false"
144
+ ]);
145
+ /**
146
+ * Lists the Python `str` methods admitted on string receivers in template
147
+ * expressions.
148
+ */
149
+ var TEMPLATE_STRING_METHODS = Object.freeze([
150
+ "startswith",
151
+ "endswith",
152
+ "split",
153
+ "strip",
154
+ "rstrip",
155
+ "lstrip"
156
+ ]);
157
+ /**
158
+ * Lists Python attribute and method names on strings, lists, and mappings that
159
+ * refuse bare property reads rather than returning unbound method objects.
160
+ */
161
+ var TEMPLATE_METHODS = Object.freeze({
162
+ string: Object.freeze([
163
+ "capitalize",
164
+ "casefold",
165
+ "center",
166
+ "count",
167
+ "encode",
168
+ "endswith",
169
+ "expandtabs",
170
+ "find",
171
+ "format",
172
+ "format_map",
173
+ "index",
174
+ "isalnum",
175
+ "isalpha",
176
+ "isascii",
177
+ "isdecimal",
178
+ "isdigit",
179
+ "isidentifier",
180
+ "islower",
181
+ "isnumeric",
182
+ "isprintable",
183
+ "isspace",
184
+ "istitle",
185
+ "isupper",
186
+ "join",
187
+ "ljust",
188
+ "lower",
189
+ "lstrip",
190
+ "maketrans",
191
+ "partition",
192
+ "removeprefix",
193
+ "removesuffix",
194
+ "replace",
195
+ "rfind",
196
+ "rindex",
197
+ "rjust",
198
+ "rpartition",
199
+ "rsplit",
200
+ "rstrip",
201
+ "split",
202
+ "splitlines",
203
+ "startswith",
204
+ "strip",
205
+ "swapcase",
206
+ "title",
207
+ "translate",
208
+ "upper",
209
+ "zfill"
210
+ ]),
211
+ list: Object.freeze([
212
+ "append",
213
+ "clear",
214
+ "copy",
215
+ "count",
216
+ "extend",
217
+ "index",
218
+ "insert",
219
+ "pop",
220
+ "remove",
221
+ "reverse",
222
+ "sort"
223
+ ]),
224
+ mapping: Object.freeze([
225
+ "clear",
226
+ "copy",
227
+ "fromkeys",
228
+ "get",
229
+ "items",
230
+ "keys",
231
+ "pop",
232
+ "popitem",
233
+ "setdefault",
234
+ "update",
235
+ "values"
236
+ ])
237
+ });
238
+ /**
239
+ * Lists the Jinja `loop` members refused by the template subset; `index`,
240
+ * `index0`, `first`, `last`, `length`, `previtem`, and `nextitem` are admitted.
241
+ */
242
+ var TEMPLATE_LOOP_REFUSALS = Object.freeze([
243
+ "revindex",
244
+ "revindex0",
245
+ "depth",
246
+ "depth0",
247
+ "cycle",
248
+ "changed"
249
+ ]);
250
+ /**
251
+ * Maps each arithmetic operator outside the admitted template subset to the
252
+ * feature label carried in its refusal context.
253
+ */
254
+ var TEMPLATE_OPERATOR_FEATURES = Object.freeze({
255
+ "*": "multiplication",
256
+ "/": "division",
257
+ "//": "floor division",
258
+ "%": "modulo",
259
+ "**": "power"
260
+ });
45
261
  // src/core/errors.ts
46
262
  /**
47
263
  * Represents an error thrown by the template layer — a machine-readable
48
264
  * {@link TemplateErrorCode} and an optional `context` record naming the
49
- * offending id or placeholder name.
265
+ * offending id, placeholder name, source position, or feature.
50
266
  *
51
267
  * @remarks
52
- * Thrown for: a required placeholder staying unresolved under the `error`
53
- * {@link MissingPolicy} (`MISSING`), an unknown template id
54
- * (`NOTFOUND`), `createTemplate` handed invalid data (`INVALID`), and
55
- * `TemplateManagerInterface#register` handed an id already present without
56
- * `options.replace` (`CONFLICT`).
268
+ * Thrown for: an unresolved required placeholder under `'error'` (`MISSING`),
269
+ * an unknown registry id (`NOTFOUND`), invalid construction or AST input
270
+ * (`INVALID`), a duplicate registration id without `options.replace`
271
+ * (`CONFLICT`), malformed or unadmitted template syntax or exceeded nesting
272
+ * depth (`FORMAT`), a runtime operation error (`EVALUATION`), and a
273
+ * template-authored `raise_exception(message)` call (`RAISE`).
57
274
  */
58
275
  var TemplateError = class extends Error {
59
276
  code;
@@ -65,194 +282,4001 @@ var TemplateError = class extends Error {
65
282
  this.code = code;
66
283
  if (context !== void 0) this.context = context;
67
284
  }
68
- };
285
+ };
286
+ /**
287
+ * Narrows an unknown caught value to a {@link TemplateError}.
288
+ *
289
+ * @remarks
290
+ * Recognizes self-branded errors from other package copies and subclasses, and
291
+ * refuses transparent proxies and unbranded look-alikes.
292
+ *
293
+ * @param value - The value to test (typically a `catch` binding)
294
+ * @returns True if `value` is a {@link TemplateError}; false otherwise
295
+ *
296
+ * @example
297
+ * ```ts
298
+ * import { isTemplateError, TemplateError } from '@orkestrel/template'
299
+ *
300
+ * try {
301
+ * throw new TemplateError('NOTFOUND', 'Unknown template id: missing', { id: 'missing' })
302
+ * } catch (error) {
303
+ * if (isTemplateError(error) && error.code === 'NOTFOUND') return
304
+ * }
305
+ * ```
306
+ */
307
+ function isTemplateError(value) {
308
+ return holds(() => {
309
+ if (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false;
310
+ if (INTRINSICS.describe(value, Symbol.for("@orkestrel/template.TemplateError"))?.value !== value) return false;
311
+ const code = INTRINSICS.reflect.read(value, "code");
312
+ const context = INTRINSICS.reflect.read(value, "context");
313
+ return TEMPLATE_ERROR_CODES.some((admitted) => admitted === code) && (context === void 0 || isObject(context) || isFunction(context));
314
+ });
315
+ }
316
+ // src/core/validators.ts
317
+ /**
318
+ * Checks whether an unknown value is a declared {@link TemplateErrorCode}.
319
+ *
320
+ * @param value - The value to test
321
+ * @returns True if `value` is one of `TEMPLATE_ERROR_CODES`; false otherwise
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * import { isTemplateErrorCode } from '@orkestrel/template'
326
+ *
327
+ * isTemplateErrorCode('FORMAT') // true
328
+ * isTemplateErrorCode('OTHER') // false
329
+ * ```
330
+ */
331
+ function isTemplateErrorCode(value) {
332
+ return holds(() => isString(value) && TEMPLATE_ERROR_CODES.some((code) => code === value));
333
+ }
334
+ /**
335
+ * Checks whether an unknown value is a valid half-open {@link TemplateSpan}.
336
+ *
337
+ * @param value - The value to test
338
+ * @returns True if `value` carries non-negative integer `start <= end`; false otherwise
339
+ *
340
+ * @example
341
+ * ```ts
342
+ * import { isTemplateSpan } from '@orkestrel/template'
343
+ *
344
+ * isTemplateSpan({ start: 0, end: 5 }) // true
345
+ * isTemplateSpan({ start: 5, end: 2 }) // false
346
+ * ```
347
+ */
348
+ function isTemplateSpan(value) {
349
+ return holds(() => {
350
+ if (!isRecord(value)) return false;
351
+ if (Object.keys(value).length !== 2) return false;
352
+ const start = value.start;
353
+ const end = value.end;
354
+ return isNonNegativeInteger(start) && isNonNegativeInteger(end) && start <= end;
355
+ });
356
+ }
357
+ /**
358
+ * Checks whether a string token is one of the single-token {@link TemplateComparison} operators.
359
+ *
360
+ * @param value - The value to test
361
+ * @returns True if `value` is in `TEMPLATE_COMPARISONS`; false otherwise
362
+ *
363
+ * @example
364
+ * ```ts
365
+ * import { isTemplateComparison } from '@orkestrel/template'
366
+ *
367
+ * isTemplateComparison('==') // true
368
+ * isTemplateComparison('in') // false
369
+ * ```
370
+ */
371
+ function isTemplateComparison(value) {
372
+ return holds(() => isString(value) && TEMPLATE_COMPARISONS.some((operator) => operator === value));
373
+ }
374
+ /**
375
+ * Checks whether an unknown value is a runtime {@link TemplateNamespace} container.
376
+ *
377
+ * @param value - The value to test
378
+ * @returns True if `value` is a namespace container with a `Map` of bindings; false otherwise
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * import { isTemplateNamespace } from '@orkestrel/template'
383
+ *
384
+ * isTemplateNamespace({ namespace: true, values: new Map() }) // true
385
+ * isTemplateNamespace(new Map()) // false
386
+ * ```
387
+ */
388
+ function isTemplateNamespace(value) {
389
+ return holds(() => {
390
+ if (!isObject(value) || isArray(value) || isMap(value)) return false;
391
+ return Reflect.get(value, "namespace") === true && isMap(Reflect.get(value, "values"));
392
+ });
393
+ }
394
+ /**
395
+ * Checks whether an unknown value is a valid {@link TemplateTarget} (`local` or `attribute`).
396
+ *
397
+ * @param value - The value to test
398
+ * @returns True if `value` is a well-formed assignment target; false otherwise
399
+ *
400
+ * @example
401
+ * ```ts
402
+ * import { isTemplateTarget } from '@orkestrel/template'
403
+ *
404
+ * isTemplateTarget({ scope: 'local', name: 'x' }) // true
405
+ * isTemplateTarget({ scope: 'attribute', object: 'ns', name: 'count' }) // true
406
+ * ```
407
+ */
408
+ function isTemplateTarget(value) {
409
+ return holds(() => {
410
+ if (!isRecord(value)) return false;
411
+ const scope = value.scope;
412
+ if (scope === "local") return Object.keys(value).length === 2 && isString(value.name) && value.name.length > 0;
413
+ if (scope === "attribute") return Object.keys(value).length === 3 && isString(value.object) && value.object.length > 0 && isString(value.name) && value.name.length > 0;
414
+ return false;
415
+ });
416
+ }
417
+ /**
418
+ * Checks whether an unknown value is a valid {@link TemplateExpression} within `MAX_DEPTH` and free of cycles.
419
+ *
420
+ * @param value - The value to test
421
+ * @param depth - Current recursion depth. Default: `0`
422
+ * @param ancestors - Ancestor set used to refuse reference cycles
423
+ * @returns True if `value` is a well-formed expression; false otherwise
424
+ *
425
+ * @example
426
+ * ```ts
427
+ * import { isTemplateExpression } from '@orkestrel/template'
428
+ *
429
+ * isTemplateExpression({ term: 'literal', value: 'Hi' }) // true
430
+ * isTemplateExpression({ term: 'unknown' }) // false
431
+ * ```
432
+ */
433
+ function isTemplateExpression(value, depth = 0, ancestors = /* @__PURE__ */ new WeakSet()) {
434
+ return holds(() => {
435
+ if (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false;
436
+ const term = value.term;
437
+ if (!isString(term)) return false;
438
+ ancestors.add(value);
439
+ try {
440
+ const keys = Object.keys(value);
441
+ const next = depth + 1;
442
+ switch (term) {
443
+ case "literal": {
444
+ const literal = value.value;
445
+ return keys.length === 2 && (literal === null || isString(literal) || isBoolean(literal) || isFiniteNumber(literal));
446
+ }
447
+ case "name": return keys.length === 2 && isString(value.name) && value.name.length > 0;
448
+ case "member": return keys.length === 3 && isTemplateExpression(value.object, next, ancestors) && isTemplateExpression(value.key, next, ancestors);
449
+ case "slice": return keys.every((key) => key === "term" || key === "object" || key === "start" || key === "stop" || key === "step") && isTemplateExpression(value.object, next, ancestors) && (value.start === void 0 || isTemplateExpression(value.start, next, ancestors)) && (value.stop === void 0 || isTemplateExpression(value.stop, next, ancestors)) && (value.step === void 0 || isTemplateExpression(value.step, next, ancestors));
450
+ case "call": {
451
+ const rawValues = value.values;
452
+ const rawKeywords = value.keywords;
453
+ return keys.length === 4 && isTemplateExpression(value.callee, next, ancestors) && isArray(rawValues) && rawValues.every((item) => isTemplateExpression(item, next, ancestors)) && isArray(rawKeywords) && rawKeywords.every((keyword) => isRecord(keyword) && Object.keys(keyword).length === 2 && isString(keyword.name) && keyword.name.length > 0 && isTemplateExpression(keyword.value, next, ancestors));
454
+ }
455
+ case "filter": return keys.length === 3 && isString(value.name) && value.name.length > 0 && isTemplateExpression(value.value, next, ancestors);
456
+ case "test": return keys.length === 4 && isString(value.name) && value.name.length > 0 && isBoolean(value.negated) && isTemplateExpression(value.value, next, ancestors);
457
+ case "unary": {
458
+ const operator = value.operator;
459
+ return keys.length === 3 && isString(operator) && [
460
+ "not",
461
+ "-",
462
+ "+"
463
+ ].some((candidate) => candidate === operator) && isTemplateExpression(value.value, next, ancestors);
464
+ }
465
+ case "binary": {
466
+ const operator = value.operator;
467
+ return keys.length === 4 && isString(operator) && [
468
+ "+",
469
+ "-",
470
+ "~",
471
+ "==",
472
+ "!=",
473
+ "<",
474
+ ">",
475
+ "<=",
476
+ ">=",
477
+ "in",
478
+ "not in",
479
+ "and",
480
+ "or"
481
+ ].some((candidate) => candidate === operator) && isTemplateExpression(value.left, next, ancestors) && isTemplateExpression(value.right, next, ancestors);
482
+ }
483
+ case "conditional": return keys.length === 4 && isTemplateExpression(value.condition, next, ancestors) && isTemplateExpression(value.consequent, next, ancestors) && isTemplateExpression(value.alternate, next, ancestors);
484
+ default: return false;
485
+ }
486
+ } finally {
487
+ ancestors.delete(value);
488
+ }
489
+ });
490
+ }
491
+ /**
492
+ * Checks whether an unknown value is a valid {@link TemplateNode} within `MAX_DEPTH` and free of cycles.
493
+ *
494
+ * @param value - The value to test
495
+ * @param depth - Current recursion depth. Default: `0`
496
+ * @param ancestors - Ancestor set used to refuse reference cycles
497
+ * @returns True if `value` is a structurally valid template AST node; false otherwise
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * import { isTemplateNode } from '@orkestrel/template'
502
+ *
503
+ * isTemplateNode({ syntax: 'text', value: 'Hello' }) // true
504
+ * isTemplateNode({ syntax: 'unknown' }) // false
505
+ * ```
506
+ */
507
+ function isTemplateNode(value, depth = 0, ancestors = /* @__PURE__ */ new WeakSet()) {
508
+ return holds(() => {
509
+ if (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false;
510
+ const syntax = value.syntax;
511
+ if (!isString(syntax)) return false;
512
+ ancestors.add(value);
513
+ try {
514
+ const keys = Object.keys(value);
515
+ const next = depth + 1;
516
+ switch (syntax) {
517
+ case "document": {
518
+ const children = value.children;
519
+ return keys.length === 2 && isArray(children) && children.every((child) => isTemplateNode(child, next, ancestors) && child.syntax !== "document");
520
+ }
521
+ case "text": return keys.length === 2 && isString(value.value);
522
+ case "placeholder": return keys.length === 3 && isString(value.name) && isString(value.raw);
523
+ case "output": return keys.length === 2 && isTemplateExpression(value.value, next, ancestors);
524
+ case "if": {
525
+ const body = value.body;
526
+ const alternate = value.alternate;
527
+ return keys.every((key) => key === "syntax" || key === "condition" || key === "body" || key === "alternate") && isTemplateExpression(value.condition, next, ancestors) && isArray(body) && body.every((child) => isTemplateNode(child, next, ancestors) && child.syntax !== "document") && (alternate === void 0 || isArray(alternate) && alternate.every((child) => isTemplateNode(child, next, ancestors) && child.syntax !== "document"));
528
+ }
529
+ case "for": {
530
+ const targets = value.targets;
531
+ const body = value.body;
532
+ return keys.length === 4 && isArray(targets) && targets.length > 0 && targets.every((target) => isString(target) && target.length > 0) && isTemplateExpression(value.sequence, next, ancestors) && isArray(body) && body.every((child) => isTemplateNode(child, next, ancestors) && child.syntax !== "document");
533
+ }
534
+ case "set": return keys.length === 3 && isTemplateTarget(value.target) && isTemplateExpression(value.value, next, ancestors);
535
+ case "macro": {
536
+ const parameters = value.parameters;
537
+ const body = value.body;
538
+ return keys.length === 4 && isString(value.name) && value.name.length > 0 && isArray(parameters) && parameters.every((parameter) => isRecord(parameter) && Object.keys(parameter).every((key) => key === "name" || key === "fallback") && isString(parameter.name) && parameter.name.length > 0 && (parameter.fallback === void 0 || isTemplateExpression(parameter.fallback, next, ancestors))) && isArray(body) && body.every((child) => isTemplateNode(child, next, ancestors) && child.syntax !== "document");
539
+ }
540
+ case "control": return keys.length === 2 && (value.action === "break" || value.action === "continue");
541
+ case "comment": return keys.length === 2 && isString(value.value);
542
+ case "html": return keys.length === 2 && isHTMLDocument(value.document);
543
+ case "markdown": return keys.length === 2 && isMarkdownDocument(value.document);
544
+ default: return false;
545
+ }
546
+ } finally {
547
+ ancestors.delete(value);
548
+ }
549
+ });
550
+ }
551
+ /**
552
+ * Checks whether an unknown value is a structurally valid root {@link TemplateDocument}.
553
+ *
554
+ * @param value - The value to test
555
+ * @returns True if `value` is a complete, cycle-free document within `MAX_DEPTH`; false otherwise
556
+ *
557
+ * @example
558
+ * ```ts
559
+ * import { isTemplateDocument } from '@orkestrel/template'
560
+ *
561
+ * isTemplateDocument({ syntax: 'document', children: [] }) // true
562
+ * isTemplateDocument({ syntax: 'text', value: 'Hi' }) // false
563
+ * ```
564
+ */
565
+ function isTemplateDocument(value) {
566
+ return isTemplateNode(value) && value.syntax === "document";
567
+ }
568
+ // src/core/helpers.ts
569
+ /**
570
+ * Formats a resolved fill value for substitution into a template's `content`.
571
+ *
572
+ * @remarks
573
+ * A finite number renders with the given locale's thousand grouping through
574
+ * `toLocaleString`. An `@orkestrel/html` node passes through `@orkestrel/html`'s
575
+ * sanitize floor before rendering with `renderHTML`, and an `@orkestrel/markdown`
576
+ * node renders with `renderMarkdown`. Every other value — including `null` —
577
+ * String-coerces.
578
+ *
579
+ * @param value - The resolved value to format
580
+ * @param locale - The locale used for finite-number formatting
581
+ * @returns The formatted string
582
+ *
583
+ * @example
584
+ * ```ts
585
+ * import { formatValue } from '@orkestrel/template'
586
+ *
587
+ * formatValue(5010, 'en-US') // '5,010'
588
+ * formatValue(null, 'en-US') // 'null'
589
+ * ```
590
+ */
591
+ function formatValue(value, locale) {
592
+ if (isFiniteNumber(value)) return value.toLocaleString(locale);
593
+ if (isHTMLNode(value)) {
594
+ const document = value.category === "document" ? value : {
595
+ category: "document",
596
+ children: [value]
597
+ };
598
+ return renderHTML(createHTML(document).sanitize().document);
599
+ }
600
+ if (isMarkdownNode(value)) return renderMarkdown(value);
601
+ return String(value);
602
+ }
603
+ /**
604
+ * Resolves a field path against a fill-values record, refusing any path that
605
+ * touches a prototype-pollution-unsafe segment.
606
+ *
607
+ * @param record - The fill-values record to resolve against
608
+ * @param path - The field path — a single segment or a segment array
609
+ * @returns The resolved value, or `undefined` when unresolved or the path is unsafe
610
+ *
611
+ * @example
612
+ * ```ts
613
+ * import { resolveSafeField } from '@orkestrel/template'
614
+ *
615
+ * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1
616
+ * resolveSafeField({}, ['__proto__', 'polluted']) // undefined
617
+ * ```
618
+ */
619
+ function resolveSafeField(record, path) {
620
+ if ((isArray(path) ? path : [path]).some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return void 0;
621
+ return resolveField(record, path);
622
+ }
623
+ /**
624
+ * Resolves one `{{name}}` token against the declared placeholders and the
625
+ * fill-values record.
626
+ *
627
+ * @param record - The fill-values record the token resolves against
628
+ * @param placeholders - The declared placeholders the token matches by name
629
+ * @param token - The trimmed token text, without its `{{` / `}}` delimiters
630
+ * @returns The {@link TemplateTokenResolution} for the token
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * import { resolveToken } from '@orkestrel/template'
635
+ *
636
+ * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'
637
+ * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false
638
+ * ```
639
+ */
640
+ function resolveToken(record, placeholders, token) {
641
+ const declared = placeholders.find((placeholder) => placeholder.name === token);
642
+ return {
643
+ value: resolveSafeField(record, declared?.path ?? token.split(".")),
644
+ declared,
645
+ required: declared === void 0 || declared.required !== false
646
+ };
647
+ }
648
+ /**
649
+ * Substitutes every `{{name}}` token in `content` in a single pass.
650
+ *
651
+ * @param content - The template content carrying `{{name}}` tokens
652
+ * @param values - The values tokens resolve against
653
+ * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and declared `placeholders`
654
+ * @returns The substituted content
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * import { fillTemplate } from '@orkestrel/template'
659
+ *
660
+ * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'
661
+ * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'
662
+ * ```
663
+ */
664
+ function fillTemplate(content, values, options) {
665
+ const placeholders = options?.placeholders ?? [];
666
+ const missing = options?.missing ?? "error";
667
+ const locale = options?.locale ?? "en-US";
668
+ const record = values ?? {};
669
+ const missingNames = [];
670
+ const pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags);
671
+ const result = content.replace(pattern, (matchText, rawToken) => {
672
+ if (rawToken === void 0) return "{{";
673
+ const token = rawToken.trim();
674
+ const { value, declared, required } = resolveToken(record, placeholders, token);
675
+ if (value !== void 0) return formatValue(value, locale);
676
+ if (declared?.fallback !== void 0) return formatValue(declared.fallback, locale);
677
+ if (missing === "literal") return matchText;
678
+ if (missing === "empty") return "";
679
+ if (required && !missingNames.includes(token)) missingNames.push(token);
680
+ return "";
681
+ });
682
+ if (missing === "error" && missingNames.length > 0) throw new TemplateError("MISSING", `Missing required placeholder(s): ${missingNames.join(", ")}`, { missing: missingNames });
683
+ return result;
684
+ }
685
+ /**
686
+ * Quotes untrusted text for a template error message as a length-capped JSON
687
+ * string literal.
688
+ *
689
+ * @param value - The raw text to quote
690
+ * @returns The quoted diagnostic text
691
+ *
692
+ * @example
693
+ * ```ts
694
+ * import { quoteTemplateText } from '@orkestrel/template'
695
+ *
696
+ * quoteTemplateText('tojson') // '"tojson"'
697
+ * ```
698
+ */
699
+ function quoteTemplateText(value) {
700
+ const clipped = value.length > 120 ? `${value.slice(0, 120)}...` : value;
701
+ return JSON.stringify(clipped);
702
+ }
703
+ /**
704
+ * Normalizes a Jinja template source by converting every line ending to `\n`
705
+ * and dropping one trailing line ending when present.
706
+ *
707
+ * @param source - The raw template source
708
+ * @returns The normalized source text
709
+ *
710
+ * @example
711
+ * ```ts
712
+ * import { normalizeTemplateSource } from '@orkestrel/template'
713
+ *
714
+ * normalizeTemplateSource('Hi\r\n\r\n') // 'Hi\n'
715
+ * ```
716
+ */
717
+ function normalizeTemplateSource(source) {
718
+ const lines = source.split(/\r\n|\r|\n/);
719
+ return (lines.at(-1) === "" ? lines.slice(0, -1) : lines).join("\n");
720
+ }
721
+ /**
722
+ * Trims literal template text between adjacent Jinja tags under `trim_blocks`
723
+ * and `lstrip_blocks`, honoring `-` and `+` delimiter markers.
724
+ *
725
+ * @param text - The text between the two tags
726
+ * @param closer - The closing delimiter of the preceding tag, or `''` at start
727
+ * @param opener - The opening delimiter of the following tag, or `''` at end
728
+ * @returns The trimmed text
729
+ *
730
+ * @example
731
+ * ```ts
732
+ * import { trimTemplateText } from '@orkestrel/template'
733
+ *
734
+ * trimTemplateText('\n ', '%}', '{%') // ''
735
+ * trimTemplateText('Hi \n', '}}', '{{-') // 'Hi'
736
+ * ```
737
+ */
738
+ function trimTemplateText(text, closer, opener) {
739
+ const kept = closer.startsWith("-") ? text.replace(new RegExp(`^${TEMPLATE_SPACE}+`, "u"), "") : (closer === "%}" || closer === "#}") && text.startsWith("\n") ? text.slice(1) : text;
740
+ if (opener.endsWith("-")) return kept.replace(new RegExp(`${TEMPLATE_SPACE}+$`, "u"), "");
741
+ if (opener !== "{%" && opener !== "{#") return kept;
742
+ const start = kept.lastIndexOf("\n") + 1;
743
+ const starting = closer === "" || text.slice(0, text.length - kept.length).endsWith("\n");
744
+ return (start > 0 || starting) && new RegExp(`^[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]+$`, "u").test(kept.slice(start)) ? kept.slice(0, start) : kept;
745
+ }
746
+ /**
747
+ * Locates a UTF-16 offset in a template source as a 1-based `[line, column]` pair.
748
+ *
749
+ * @param starts - The starting offset of each line in ascending order
750
+ * @param offset - The offset to locate
751
+ * @returns The 1-based line and column
752
+ *
753
+ * @example
754
+ * ```ts
755
+ * import { locateTemplateOffset } from '@orkestrel/template'
756
+ *
757
+ * locateTemplateOffset([0, 4], 5) // [2, 2]
758
+ * ```
759
+ */
760
+ function locateTemplateOffset(starts, offset) {
761
+ const line = Math.max(0, starts.findLastIndex((start) => start <= offset));
762
+ return [line + 1, offset - (starts[line] ?? 0) + 1];
763
+ }
764
+ /**
765
+ * Maps each character position of `normalizeTemplateSource(source)` back to its
766
+ * UTF-16 offset in the original unnormalized source.
767
+ *
768
+ * @param source - The original unnormalized template source
769
+ * @returns The normalized text and its boundary-to-original offset array
770
+ *
771
+ * @example
772
+ * ```ts
773
+ * import { mapTemplateOffsets } from '@orkestrel/template'
774
+ *
775
+ * mapTemplateOffsets('a\r\nb')[1] // [0, 1, 3, 4]
776
+ * ```
777
+ */
778
+ function mapTemplateOffsets(source) {
779
+ const chars = [];
780
+ const offsets = [];
781
+ for (let index = 0; index < source.length; index += 1) {
782
+ const code = source.charCodeAt(index);
783
+ if (code === 10 && source.charCodeAt(index - 1) === 13) continue;
784
+ offsets.push(index);
785
+ chars.push(code === 13 ? "\n" : source[index] ?? "");
786
+ }
787
+ const trailing = chars.at(-1) === "\n";
788
+ const keptChars = trailing ? chars.slice(0, -1) : chars;
789
+ const keptOffsets = trailing ? offsets.slice(0, -1) : offsets;
790
+ const finalOffset = trailing ? offsets.at(-1) ?? source.length : source.length;
791
+ return [keptChars.join(""), [...keptOffsets, finalOffset]];
792
+ }
793
+ /**
794
+ * Scans the interior of one Jinja tag into lexical tokens with original UTF-16
795
+ * offsets and 1-based line and column positions.
796
+ *
797
+ * @param text - The tag interior between delimiters
798
+ * @param offset - The normalized-source offset of the tag interior's start
799
+ * @param starts - Line-start offsets in the normalized source
800
+ * @param offsets - Boundary map from normalized offsets to original UTF-16 offsets
801
+ * @returns The scanned tokens inside the tag
802
+ *
803
+ * @example
804
+ * ```ts
805
+ * import { scanTemplateTag } from '@orkestrel/template'
806
+ *
807
+ * scanTemplateTag(' loop.first ', 2, [0]).map((token) => token.text) // ['loop', '.', 'first']
808
+ * ```
809
+ */
810
+ function scanTemplateTag(text, offset, starts, offsets) {
811
+ const pattern = new RegExp(TEMPLATE_TOKEN_PATTERN.source, TEMPLATE_TOKEN_PATTERN.flags);
812
+ return Array.from(text.matchAll(pattern)).flatMap((match) => {
813
+ const normalizedStart = offset + match.index;
814
+ const normalizedEnd = normalizedStart + match[0].length;
815
+ const [line, column] = locateTemplateOffset(starts, normalizedStart);
816
+ const start = offsets?.[normalizedStart] ?? normalizedStart;
817
+ const end = offsets?.[normalizedEnd] ?? normalizedEnd;
818
+ if (match[1] !== void 0) return [];
819
+ if (match[7] !== void 0) return [{
820
+ token: "fault",
821
+ text: `holds the character ${quoteTemplateText(match[0])}, which starts no token`,
822
+ line,
823
+ column,
824
+ start,
825
+ end
826
+ }];
827
+ return [{
828
+ token: match[2] !== void 0 ? "float" : match[3] !== void 0 ? "integer" : match[4] !== void 0 ? "name" : match[5] !== void 0 ? "string" : "operator",
829
+ text: match[0],
830
+ line,
831
+ column,
832
+ start,
833
+ end
834
+ }];
835
+ });
836
+ }
837
+ /**
838
+ * Scans a raw Jinja template source into its token stream, including trimmed
839
+ * text, comments, tag delimiters, inner tokens, and a closing `end` token.
840
+ *
841
+ * @param source - The template source
842
+ * @returns The scanned tokens, ending with an `end` token
843
+ *
844
+ * @example
845
+ * ```ts
846
+ * import { scanTemplateTokens } from '@orkestrel/template'
847
+ *
848
+ * scanTemplateTokens('Hi {{ name }}').map((token) => token.token)
849
+ * // ['text', 'variable', 'name', 'close', 'end']
850
+ * ```
851
+ */
852
+ function scanTemplateTokens(source) {
853
+ const [normalized, offsets] = mapTemplateOffsets(source);
854
+ const starts = [0, ...Array.from(normalized.matchAll(/\n/g), (match) => match.index + 1)];
855
+ const pattern = new RegExp(TEMPLATE_SEGMENT_PATTERN.source, TEMPLATE_SEGMENT_PATTERN.flags);
856
+ const segments = Array.from(normalized.matchAll(pattern));
857
+ const tokens = segments.flatMap((segment, index) => {
858
+ const previous = segments[index - 1];
859
+ const text = segment[1] ?? "";
860
+ const opener = segment[2] ?? segment[5] ?? segment[8] ?? segment[11] ?? "";
861
+ const kept = trimTemplateText(text, previous?.[4] ?? previous?.[7] ?? previous?.[10] ?? "", opener);
862
+ const [line, column] = locateTemplateOffset(starts, segment.index);
863
+ const textStart = offsets[segment.index] ?? segment.index;
864
+ const textEnd = offsets[segment.index + text.length] ?? segment.index + text.length;
865
+ const leading = kept === "" ? [] : [{
866
+ token: "text",
867
+ text: kept,
868
+ line,
869
+ column,
870
+ start: textStart,
871
+ end: textEnd
872
+ }];
873
+ const tag = segment.index + text.length;
874
+ const [tagLine, tagColumn] = locateTemplateOffset(starts, tag);
875
+ const tagStart = offsets[tag] ?? tag;
876
+ if (segment[11] !== void 0) {
877
+ const subject = segment[11] === "{#" ? "comment" : "tag";
878
+ return [...leading, {
879
+ token: "fault",
880
+ text: `opens a ${subject} that never closes`,
881
+ line: tagLine,
882
+ column: tagColumn,
883
+ start: tagStart,
884
+ end: source.length
885
+ }];
886
+ }
887
+ if (segment[8] !== void 0 && segment[9] !== void 0 && segment[10] !== void 0) {
888
+ const commentEnd = tag + segment[8].length + segment[9].length + segment[10].length;
889
+ return [...leading, {
890
+ token: "comment",
891
+ text: segment[9],
892
+ line: tagLine,
893
+ column: tagColumn,
894
+ start: tagStart,
895
+ end: offsets[commentEnd] ?? commentEnd
896
+ }];
897
+ }
898
+ const inside = segment[3] ?? segment[6];
899
+ const closer = segment[4] ?? segment[7];
900
+ if (inside === void 0 || closer === void 0) return leading;
901
+ const closeOffset = tag + opener.length + inside.length;
902
+ const [closeLine, closeColumn] = locateTemplateOffset(starts, closeOffset);
903
+ const openEnd = offsets[tag + opener.length] ?? tag + opener.length;
904
+ const closeStart = offsets[closeOffset] ?? closeOffset;
905
+ const closeEnd = offsets[closeOffset + closer.length] ?? closeOffset + closer.length;
906
+ return [
907
+ ...leading,
908
+ {
909
+ token: segment[2] === void 0 ? "variable" : "block",
910
+ text: opener,
911
+ line: tagLine,
912
+ column: tagColumn,
913
+ start: tagStart,
914
+ end: openEnd
915
+ },
916
+ ...scanTemplateTag(inside, tag + opener.length, starts, offsets),
917
+ {
918
+ token: "close",
919
+ text: closer,
920
+ line: closeLine,
921
+ column: closeColumn,
922
+ start: closeStart,
923
+ end: closeEnd
924
+ }
925
+ ];
926
+ });
927
+ const [line, column] = locateTemplateOffset(starts, normalized.length);
928
+ return [...tokens, {
929
+ token: "end",
930
+ text: "",
931
+ line,
932
+ column,
933
+ start: source.length,
934
+ end: source.length
935
+ }];
936
+ }
937
+ /**
938
+ * Builds a `FORMAT`-coded {@link TemplateError} anchored at a token's source location.
939
+ *
940
+ * @param token - The token locating the syntax or subset refusal
941
+ * @param message - The diagnostic clause after "the template"
942
+ * @param context - Additional context members carried beside `line`, `column`, `start`, and `end`
943
+ * @returns The constructed {@link TemplateError}
944
+ *
945
+ * @example
946
+ * ```ts
947
+ * import { buildTemplateFormatError, scanTemplateTokens } from '@orkestrel/template'
948
+ *
949
+ * const [token] = scanTemplateTokens('{{ x }}')
950
+ * buildTemplateFormatError(token, 'uses an unknown filter', { feature: 'unknown' }).code // 'FORMAT'
951
+ * ```
952
+ */
953
+ function buildTemplateFormatError(token, message, context) {
954
+ return new TemplateError("FORMAT", `At line ${token.line}, column ${token.column}, the template ${message}.`, {
955
+ ...context,
956
+ line: token.line,
957
+ column: token.column,
958
+ start: token.start,
959
+ end: token.end
960
+ });
961
+ }
962
+ /**
963
+ * Builds an `EVALUATION`-coded {@link TemplateError} for runtime evaluation refusals.
964
+ *
965
+ * @param message - The diagnostic clause after "The template"
966
+ * @param context - Additional context members describing the failure
967
+ * @returns The constructed {@link TemplateError}
968
+ *
969
+ * @example
970
+ * ```ts
971
+ * import { buildTemplateEvaluationError } from '@orkestrel/template'
972
+ *
973
+ * buildTemplateEvaluationError('adds a string to an integer').code // 'EVALUATION'
974
+ * ```
975
+ */
976
+ function buildTemplateEvaluationError(message, context) {
977
+ return new TemplateError("EVALUATION", `The template ${message}.`, context);
978
+ }
979
+ /**
980
+ * Renders a scanned token into a readable label for syntax diagnostics.
981
+ *
982
+ * @param token - The token to describe
983
+ * @returns The human-readable token description
984
+ *
985
+ * @example
986
+ * ```ts
987
+ * import { renderTemplateToken } from '@orkestrel/template'
988
+ *
989
+ * renderTemplateToken({ token: 'end', text: '', line: 1, column: 1, start: 0, end: 0 }) // 'the end of the template'
990
+ * ```
991
+ */
992
+ function renderTemplateToken(token) {
993
+ if (token.token === "end") return "the end of the template";
994
+ if (token.token === "text") return "template text";
995
+ if (token.token === "comment") return "a comment";
996
+ return quoteTemplateText(token.text);
997
+ }
998
+ /**
999
+ * Checks whether a scanned token matches an expected form and optional text.
1000
+ *
1001
+ * @param token - The token to inspect
1002
+ * @param form - The required token form
1003
+ * @param text - Optional exact text to match
1004
+ * @returns True if `token` matches; false otherwise
1005
+ *
1006
+ * @example
1007
+ * ```ts
1008
+ * import { matchesTemplateToken } from '@orkestrel/template'
1009
+ *
1010
+ * matchesTemplateToken({ token: 'name', text: 'in', line: 1, column: 1, start: 0, end: 2 }, 'name', 'in') // true
1011
+ * ```
1012
+ */
1013
+ function matchesTemplateToken(token, form, text) {
1014
+ return token.token === form && (text === void 0 || token.text === text);
1015
+ }
1016
+ /**
1017
+ * Reads the token at an index of a token stream, throwing on `fault` tokens or
1018
+ * an empty stream.
1019
+ *
1020
+ * @param tokens - The token stream
1021
+ * @param index - The index to read
1022
+ * @returns The resolved token
1023
+ *
1024
+ * @example
1025
+ * ```ts
1026
+ * import { readTemplateToken, scanTemplateTokens } from '@orkestrel/template'
1027
+ *
1028
+ * readTemplateToken(scanTemplateTokens('{{ x }}'), 1).text // 'x'
1029
+ * ```
1030
+ */
1031
+ function readTemplateToken(tokens, index) {
1032
+ const token = tokens[index] ?? tokens.at(-1);
1033
+ if (token === void 0) throw new TemplateError("INVALID", "A template compiles from at least its end token.");
1034
+ if (token.token === "fault") throw buildTemplateFormatError(token, token.text);
1035
+ return token;
1036
+ }
1037
+ /**
1038
+ * Refuses a token that does not match an expected form and optional text with a
1039
+ * `FORMAT`-coded {@link TemplateError}.
1040
+ *
1041
+ * @param tokens - The token stream
1042
+ * @param index - The index to validate
1043
+ * @param form - The required token form
1044
+ * @param text - Optional exact text to require
1045
+ *
1046
+ * @example
1047
+ * ```ts
1048
+ * import { checkTemplateToken, scanTemplateTokens } from '@orkestrel/template'
1049
+ *
1050
+ * checkTemplateToken(scanTemplateTokens('{{ x }}'), 1, 'name', 'x')
1051
+ * ```
1052
+ */
1053
+ function checkTemplateToken(tokens, index, form, text) {
1054
+ const token = readTemplateToken(tokens, index);
1055
+ if (matchesTemplateToken(token, form, text)) return;
1056
+ throw buildTemplateFormatError(token, `expects ${form === "close" ? "the tag to close" : text === void 0 ? `a ${form}` : quoteTemplateText(text)} and finds ${renderTemplateToken(token)}`);
1057
+ }
1058
+ /**
1059
+ * Consumes an optional trailing colon (where admitted) and closing tag delimiter.
1060
+ *
1061
+ * @param tokens - The token stream
1062
+ * @param index - The position after the tag's expression
1063
+ * @param colon - If `true`, admits one trailing colon before the closer; if `false`, requires the closer immediately
1064
+ * @returns The index after the closing delimiter
1065
+ *
1066
+ * @example
1067
+ * ```ts
1068
+ * import { checkTemplateClose, scanTemplateTokens } from '@orkestrel/template'
1069
+ *
1070
+ * checkTemplateClose(scanTemplateTokens('{% else: %}'), 2, true) // 4
1071
+ * ```
1072
+ */
1073
+ function checkTemplateClose(tokens, index, colon) {
1074
+ const token = readTemplateToken(tokens, index);
1075
+ if (matchesTemplateToken(token, "operator", ",")) throw buildTemplateFormatError(token, "writes a tuple, which the subset does not admit", { feature: "tuple" });
1076
+ const start = colon && matchesTemplateToken(token, "operator", ":") ? index + 1 : index;
1077
+ checkTemplateToken(tokens, start, "close");
1078
+ return start + 1;
1079
+ }
1080
+ /**
1081
+ * Refuses template nesting deeper than `MAX_DEPTH` (`64`) with a `FORMAT`-coded
1082
+ * {@link TemplateError}.
1083
+ *
1084
+ * @param depth - The nesting level reached
1085
+ * @param token - The token locating the refusal
1086
+ *
1087
+ * @example
1088
+ * ```ts
1089
+ * import { checkTemplateDepth, scanTemplateTokens } from '@orkestrel/template'
1090
+ *
1091
+ * checkTemplateDepth(4, scanTemplateTokens('{{ x }}')[0])
1092
+ * ```
1093
+ */
1094
+ function checkTemplateDepth(depth, token) {
1095
+ if (depth <= MAX_DEPTH) return;
1096
+ throw buildTemplateFormatError(token, `nests deeper than ${MAX_DEPTH} levels`, { limit: MAX_DEPTH });
1097
+ }
1098
+ /**
1099
+ * Refuses an invalid assignment target name such as a literal, reserved global
1100
+ * function, or private `__`-prefixed identifier.
1101
+ *
1102
+ * @param token - The target token to validate
1103
+ *
1104
+ * @example
1105
+ * ```ts
1106
+ * import { checkTemplateTarget, scanTemplateTokens } from '@orkestrel/template'
1107
+ *
1108
+ * checkTemplateTarget(scanTemplateTokens('{% set count = 1 %}')[2])
1109
+ * ```
1110
+ */
1111
+ function checkTemplateTarget(token) {
1112
+ if (token.token !== "name" || keyOf(TEMPLATE_LITERALS)(token.text)) throw buildTemplateFormatError(token, `assigns to ${renderTemplateToken(token)}, which is not a name`);
1113
+ if (token.text.startsWith("__")) throw buildTemplateFormatError(token, `assigns to the private name ${quoteTemplateText(token.text)}`, { feature: "private" });
1114
+ if (TEMPLATE_FUNCTIONS.some((name) => name === token.text)) throw buildTemplateFormatError(token, `assigns to the function ${quoteTemplateText(token.text)}, which the subset does not admit`, { feature: token.text });
1115
+ }
1116
+ /**
1117
+ * Refuses a compile-time read of a `loop` member listed in `TEMPLATE_LOOP_REFUSALS`.
1118
+ *
1119
+ * @param object - The target expression being indexed
1120
+ * @param key - The member key expression
1121
+ * @param token - The token locating the refusal
1122
+ *
1123
+ * @example
1124
+ * ```ts
1125
+ * import { checkTemplateLoopMember, scanTemplateTokens } from '@orkestrel/template'
1126
+ *
1127
+ * checkTemplateLoopMember(
1128
+ * { term: 'name', name: 'loop' },
1129
+ * { term: 'literal', value: 'previtem' },
1130
+ * scanTemplateTokens('{{ loop.previtem }}')[1],
1131
+ * )
1132
+ * ```
1133
+ */
1134
+ function checkTemplateLoopMember(object, key, token) {
1135
+ if (object.term !== "name" || object.name !== "loop" || key.term !== "literal") return;
1136
+ const name = key.value;
1137
+ if (!TEMPLATE_LOOP_REFUSALS.some((member) => member === name)) return;
1138
+ throw buildTemplateFormatError(token, `reads ${quoteTemplateText(`loop.${String(name)}`)}, which the subset does not admit`, { feature: `loop.${String(name)}` });
1139
+ }
1140
+ /**
1141
+ * Decodes a quoted Jinja string token using Python `unicode-escape` rules.
1142
+ *
1143
+ * @param token - The string literal token including quotes
1144
+ * @returns The decoded string value
1145
+ *
1146
+ * @example
1147
+ * ```ts
1148
+ * import { decodeTemplateString, scanTemplateTokens } from '@orkestrel/template'
1149
+ *
1150
+ * decodeTemplateString(scanTemplateTokens("{{ 'a\\nb' }}")[1]) // 'a\nb'
1151
+ * ```
1152
+ */
1153
+ function decodeTemplateString(token) {
1154
+ return token.text.slice(1, -1).replace(/\\(x[\da-fA-F]{2}|u[\da-fA-F]{4}|U[\da-fA-F]{8}|[0-7]{1,3}|N\{[^}]*\}|[^])/gu, (escape, body) => {
1155
+ const lead = body[0] ?? "";
1156
+ if (body.length > 1 && lead === "N") throw buildTemplateFormatError(token, `writes the named escape ${quoteTemplateText(escape)}, which the subset does not admit`, { feature: "named escape" });
1157
+ if (body.length > 1 && (lead === "x" || lead === "u" || lead === "U")) {
1158
+ const point = Number.parseInt(body.slice(1), 16);
1159
+ if (point > 1114111) throw buildTemplateFormatError(token, `writes the escape ${quoteTemplateText(escape)}, past U+10FFFF`);
1160
+ return String.fromCodePoint(point);
1161
+ }
1162
+ if (/^[0-7]/u.test(body)) return String.fromCodePoint(Number.parseInt(body, 8));
1163
+ if (body === "x" || body === "u" || body === "U" || body === "N") throw buildTemplateFormatError(token, `writes the truncated escape ${quoteTemplateText(escape)}`);
1164
+ if (body === "\n") return "";
1165
+ if (keyOf(TEMPLATE_ESCAPES)(body)) return TEMPLATE_ESCAPES[body];
1166
+ const point = body.codePointAt(0) ?? 0;
1167
+ if (point < 128) return escape;
1168
+ const hex = point.toString(16);
1169
+ return point < 256 ? `\\x${hex.padStart(2, "0")}` : point < 65536 ? `\\u${hex.padStart(4, "0")}` : `\\U${hex.padStart(8, "0")}`;
1170
+ });
1171
+ }
1172
+ /**
1173
+ * Decodes an `integer` or `float` token as Jinja reads numeric literals.
1174
+ *
1175
+ * @param token - The numeric literal token
1176
+ * @returns The decoded finite number
1177
+ *
1178
+ * @example
1179
+ * ```ts
1180
+ * import { decodeTemplateNumber, scanTemplateTokens } from '@orkestrel/template'
1181
+ *
1182
+ * decodeTemplateNumber(scanTemplateTokens('{{ 0x1F }}')[1]) // 31
1183
+ * ```
1184
+ */
1185
+ function decodeTemplateNumber(token) {
1186
+ const value = Number(token.text.replaceAll("_", ""));
1187
+ if (token.token === "integer" && !Number.isSafeInteger(value)) throw buildTemplateFormatError(token, `writes the integer ${quoteTemplateText(token.text)}, past the integers JavaScript holds exactly`, { feature: "big integer" });
1188
+ if (token.token === "float" && Number.isInteger(value)) throw buildTemplateFormatError(token, `writes the float ${quoteTemplateText(token.text)}, whose whole value the subset holds as an integer`, { feature: "whole float" });
1189
+ if (Number.isNaN(value)) throw buildTemplateFormatError(token, `expects a number and finds ${renderTemplateToken(token)}`);
1190
+ return value;
1191
+ }
1192
+ /**
1193
+ * Normalizes a caller-supplied value into a runtime {@link TemplateRuntimeValue},
1194
+ * converting plain objects to string-keyed `Map`s while preserving `HTMLNode`,
1195
+ * `MarkdownNode`, and `TemplateNamespace` instances and capping depth at `MAX_DEPTH`.
1196
+ *
1197
+ * @param value - The value to normalize
1198
+ * @param depth - Current recursion depth. Default: `0`
1199
+ * @param ancestors - Ancestor set used to guard against cycles
1200
+ * @returns The normalized runtime value
1201
+ *
1202
+ * @example
1203
+ * ```ts
1204
+ * import { normalizeTemplateValue } from '@orkestrel/template'
1205
+ *
1206
+ * normalizeTemplateValue({ role: 'user' }) // Map { 'role' => 'user' }
1207
+ * ```
1208
+ */
1209
+ function normalizeTemplateValue(value, depth = 0, ancestors = /* @__PURE__ */ new WeakSet()) {
1210
+ if (value === void 0 || value === null || isBoolean(value) || typeof value === "number" || isString(value)) return value;
1211
+ if (isHTMLNode(value) || isMarkdownNode(value) || isTemplateNamespace(value)) return value;
1212
+ if (depth > MAX_DEPTH) throw buildTemplateEvaluationError(`nests runtime values deeper than ${MAX_DEPTH} levels`, { limit: MAX_DEPTH });
1213
+ if (isArray(value)) {
1214
+ if (ancestors.has(value)) throw buildTemplateEvaluationError("encounters a cyclic list in runtime values", { feature: "cycle" });
1215
+ ancestors.add(value);
1216
+ try {
1217
+ return value.map((item) => normalizeTemplateValue(item, depth + 1, ancestors));
1218
+ } finally {
1219
+ ancestors.delete(value);
1220
+ }
1221
+ }
1222
+ if (isMap(value)) {
1223
+ if (ancestors.has(value)) throw buildTemplateEvaluationError("encounters a cyclic mapping in runtime values", { feature: "cycle" });
1224
+ ancestors.add(value);
1225
+ try {
1226
+ const entries = [];
1227
+ for (const [entryKey, entryValue] of value.entries()) if (isString(entryKey) && entryValue !== void 0) entries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)]);
1228
+ return new Map(entries);
1229
+ } finally {
1230
+ ancestors.delete(value);
1231
+ }
1232
+ }
1233
+ if (isRecord(value)) {
1234
+ if (ancestors.has(value)) throw buildTemplateEvaluationError("encounters a cyclic record in runtime values", { feature: "cycle" });
1235
+ ancestors.add(value);
1236
+ try {
1237
+ const entries = [];
1238
+ for (const [entryKey, entryValue] of Object.entries(value)) if (entryValue !== void 0) entries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)]);
1239
+ return new Map(entries);
1240
+ } finally {
1241
+ ancestors.delete(value);
1242
+ }
1243
+ }
1244
+ return String(value);
1245
+ }
1246
+ /**
1247
+ * Checks whether a runtime value is a compiled {@link TemplateMacro} closure.
1248
+ *
1249
+ * @param value - The runtime value to inspect
1250
+ * @returns True if `value` is a macro closure; false otherwise
1251
+ *
1252
+ * @example
1253
+ * ```ts
1254
+ * import { isTemplateMacro } from '@orkestrel/template'
1255
+ *
1256
+ * isTemplateMacro('text') // false
1257
+ * ```
1258
+ */
1259
+ function isTemplateMacro(value) {
1260
+ return isObject(value) && !isArray(value) && !isMap(value) && Reflect.get(value, "macro") === true && isString(Reflect.get(value, "name"));
1261
+ }
1262
+ /**
1263
+ * Checks whether a runtime value is a `for` {@link TemplateLoop} state record.
1264
+ *
1265
+ * @param value - The runtime value to inspect
1266
+ * @returns True if `value` is a loop state record; false otherwise
1267
+ *
1268
+ * @example
1269
+ * ```ts
1270
+ * import { isTemplateLoop } from '@orkestrel/template'
1271
+ *
1272
+ * isTemplateLoop({ index0: 0, length: 1, previtem: undefined, nextitem: undefined }) // true
1273
+ * ```
1274
+ */
1275
+ function isTemplateLoop(value) {
1276
+ return isObject(value) && !isArray(value) && !isMap(value) && !isTemplateNamespace(value) && !isTemplateMacro(value) && !isHTMLNode(value) && !isMarkdownNode(value) && typeof Reflect.get(value, "index0") === "number" && typeof Reflect.get(value, "length") === "number";
1277
+ }
1278
+ /**
1279
+ * Renders the Python-equivalent type label of a runtime value for diagnostics.
1280
+ *
1281
+ * @param value - The runtime value to describe
1282
+ * @returns The type description
1283
+ *
1284
+ * @example
1285
+ * ```ts
1286
+ * import { renderTemplateType } from '@orkestrel/template'
1287
+ *
1288
+ * renderTemplateType(new Map()) // 'a mapping'
1289
+ * ```
1290
+ */
1291
+ function renderTemplateType(value) {
1292
+ if (value === void 0) return "an undefined value";
1293
+ if (value === null) return "none";
1294
+ if (typeof value === "boolean") return "a boolean";
1295
+ if (typeof value === "number") return Number.isInteger(value) ? "an integer" : "a float";
1296
+ if (typeof value === "string") return "a string";
1297
+ if (isHTMLNode(value)) return "an HTML node";
1298
+ if (isMarkdownNode(value)) return "a Markdown node";
1299
+ if (isArray(value)) return "a list";
1300
+ if (isMap(value)) return "a mapping";
1301
+ if (isTemplateNamespace(value)) return "a namespace";
1302
+ if (isTemplateMacro(value)) return "a macro";
1303
+ return "a loop";
1304
+ }
1305
+ /**
1306
+ * Renders a finite or special number using Python `str` formatting.
1307
+ *
1308
+ * @param value - The number to format
1309
+ * @returns The Python-formatted numeric text
1310
+ *
1311
+ * @example
1312
+ * ```ts
1313
+ * import { renderTemplateNumber } from '@orkestrel/template'
1314
+ *
1315
+ * renderTemplateNumber(0.00001) // '1e-05'
1316
+ * ```
1317
+ */
1318
+ function renderTemplateNumber(value) {
1319
+ if (Number.isNaN(value)) return "nan";
1320
+ if (value === Infinity) return "inf";
1321
+ if (value === -Infinity) return "-inf";
1322
+ if (Number.isInteger(value)) return Object.is(value, -0) ? "0" : String(value);
1323
+ const [digits = "", power = "0"] = value.toExponential().split("e");
1324
+ const exponent = Number(power);
1325
+ if (exponent >= -4 && exponent < 16) return String(value);
1326
+ return `${digits}e${exponent < 0 ? "-" : "+"}${String(Math.abs(exponent)).padStart(2, "0")}`;
1327
+ }
1328
+ /**
1329
+ * Renders a runtime template value as string output using Python/Jinja rules,
1330
+ * sanitizing `HTMLNode`s through `@orkestrel/html` and rendering `MarkdownNode`s
1331
+ * through `@orkestrel/markdown`.
1332
+ *
1333
+ * @param value - The runtime value to render
1334
+ * @returns The rendered text
1335
+ *
1336
+ * @example
1337
+ * ```ts
1338
+ * import { renderTemplateValue } from '@orkestrel/template'
1339
+ *
1340
+ * renderTemplateValue(true) // 'True'
1341
+ * renderTemplateValue(null) // 'None'
1342
+ * ```
1343
+ */
1344
+ function renderTemplateValue(value) {
1345
+ if (typeof value === "string") return value;
1346
+ if (value === void 0) return "";
1347
+ if (value === null) return "None";
1348
+ if (typeof value === "boolean") return value ? "True" : "False";
1349
+ if (typeof value === "number") return renderTemplateNumber(value);
1350
+ if (isHTMLNode(value)) {
1351
+ const document = value.category === "document" ? value : {
1352
+ category: "document",
1353
+ children: [value]
1354
+ };
1355
+ return renderHTML(createHTML(document).sanitize().document);
1356
+ }
1357
+ if (isMarkdownNode(value)) return renderMarkdown(value);
1358
+ throw buildTemplateEvaluationError(`prints ${renderTemplateType(value)}, which Python prints as its repr and the subset does not`, { feature: "repr" });
1359
+ }
1360
+ /**
1361
+ * Serializes a runtime template value to deterministic JSON matching `minja`
1362
+ * and Python `json.dumps` (`", "` and `": "` separators, insertion key order,
1363
+ * unescaped non-ASCII Unicode).
1364
+ *
1365
+ * @param value - The runtime value to serialize
1366
+ * @param depth - Current recursion depth. Default: `0`
1367
+ * @param ancestors - Ancestor set used to guard against cycles
1368
+ * @returns The serialized JSON string
1369
+ *
1370
+ * @example
1371
+ * ```ts
1372
+ * import { serializeTemplateJSON } from '@orkestrel/template'
1373
+ *
1374
+ * serializeTemplateJSON(new Map([['b', true], ['a', [1, 2]]])) // '{"b": true, "a": [1, 2]}'
1375
+ * ```
1376
+ */
1377
+ function serializeTemplateJSON(value, depth = 0, ancestors = /* @__PURE__ */ new WeakSet()) {
1378
+ if (depth > MAX_DEPTH) throw buildTemplateEvaluationError(`serializes JSON deeper than ${MAX_DEPTH} levels`, { limit: MAX_DEPTH });
1379
+ if (value === null || value === void 0) return "null";
1380
+ if (typeof value === "boolean") return value ? "true" : "false";
1381
+ if (typeof value === "number") {
1382
+ if (!Number.isFinite(value)) throw buildTemplateEvaluationError("serializes a non-finite number to JSON", { feature: "tojson" });
1383
+ return Object.is(value, -0) ? "0" : String(value);
1384
+ }
1385
+ if (typeof value === "string") return JSON.stringify(value);
1386
+ if (isArray(value)) {
1387
+ if (ancestors.has(value)) throw buildTemplateEvaluationError("serializes a cyclic list to JSON", { feature: "tojson" });
1388
+ ancestors.add(value);
1389
+ try {
1390
+ return `[${value.map((item) => serializeTemplateJSON(item, depth + 1, ancestors)).join(", ")}]`;
1391
+ } finally {
1392
+ ancestors.delete(value);
1393
+ }
1394
+ }
1395
+ if (isMap(value) || isTemplateNamespace(value)) {
1396
+ const map = isTemplateNamespace(value) ? value.values : value;
1397
+ if (ancestors.has(map)) throw buildTemplateEvaluationError("serializes a cyclic mapping to JSON", { feature: "tojson" });
1398
+ ancestors.add(map);
1399
+ try {
1400
+ return `{${Array.from(map.entries()).map(([entryKey, entryValue]) => `${JSON.stringify(entryKey)}: ${serializeTemplateJSON(entryValue, depth + 1, ancestors)}`).join(", ")}}`;
1401
+ } finally {
1402
+ ancestors.delete(map);
1403
+ }
1404
+ }
1405
+ throw buildTemplateEvaluationError(`serializes ${renderTemplateType(value)} to JSON, which is not JSON-serializable`, { feature: "tojson" });
1406
+ }
1407
+ /**
1408
+ * Checks whether a runtime template value is truthy under Python `bool` rules.
1409
+ *
1410
+ * @param value - The value to test
1411
+ * @returns True if truthy; false otherwise
1412
+ *
1413
+ * @example
1414
+ * ```ts
1415
+ * import { matchesTemplateTruth } from '@orkestrel/template'
1416
+ *
1417
+ * matchesTemplateTruth('') // false
1418
+ * matchesTemplateTruth([0]) // true
1419
+ * ```
1420
+ */
1421
+ function matchesTemplateTruth(value) {
1422
+ if (value === void 0 || value === null) return false;
1423
+ if (typeof value === "boolean") return value;
1424
+ if (typeof value === "number") return value !== 0;
1425
+ if (typeof value === "string") return value.length > 0;
1426
+ if (isHTMLNode(value) || isMarkdownNode(value) || isTemplateMacro(value)) return true;
1427
+ if (isArray(value)) return value.length > 0;
1428
+ if (isMap(value)) return value.size > 0;
1429
+ if (isTemplateNamespace(value)) return value.values.size > 0;
1430
+ return value.length > 0;
1431
+ }
1432
+ /**
1433
+ * Checks whether two runtime template values are equal under Python `==` rules.
1434
+ *
1435
+ * @param left - The first value
1436
+ * @param right - The second value
1437
+ * @returns True if equal; false otherwise
1438
+ *
1439
+ * @example
1440
+ * ```ts
1441
+ * import { matchesTemplateEqual } from '@orkestrel/template'
1442
+ *
1443
+ * matchesTemplateEqual(true, 1) // true
1444
+ * matchesTemplateEqual('1', 1) // false
1445
+ * ```
1446
+ */
1447
+ function matchesTemplateEqual(left, right) {
1448
+ if ((typeof left === "number" || typeof left === "boolean") && (typeof right === "number" || typeof right === "boolean")) return Number(left) === Number(right);
1449
+ if (isArray(left)) return isArray(right) && left.length === right.length && left.every((item, index) => matchesTemplateEqual(item, right[index]));
1450
+ if (isMap(left)) return isMap(right) && left.size === right.size && Array.from(left).every(([key, item]) => right.has(key) && matchesTemplateEqual(item, right.get(key)));
1451
+ return left === right;
1452
+ }
1453
+ /**
1454
+ * Compares two runtime template values for ordering under Python `<` rules.
1455
+ *
1456
+ * @param left - The first value
1457
+ * @param right - The second value
1458
+ * @returns Negative when `left < right`, positive when `left > right`, and `0` when equal
1459
+ *
1460
+ * @example
1461
+ * ```ts
1462
+ * import { compareTemplateValues } from '@orkestrel/template'
1463
+ *
1464
+ * compareTemplateValues(1, 2) < 0 // true
1465
+ * ```
1466
+ */
1467
+ function compareTemplateValues(left, right) {
1468
+ if ((typeof left === "number" || typeof left === "boolean") && (typeof right === "number" || typeof right === "boolean")) return Number(left) < Number(right) ? -1 : Number(left) > Number(right) ? 1 : 0;
1469
+ if (typeof left === "string" && typeof right === "string") {
1470
+ const one = Array.from(left, (character) => character.codePointAt(0) ?? 0);
1471
+ const two = Array.from(right, (character) => character.codePointAt(0) ?? 0);
1472
+ const index = one.findIndex((point, position) => point !== two[position]);
1473
+ if (index === -1) return one.length - two.length;
1474
+ return (one[index] ?? 0) - (two[index] ?? -1);
1475
+ }
1476
+ throw buildTemplateEvaluationError(`orders ${renderTemplateType(left)} against ${renderTemplateType(right)}, which the subset does not admit`, { feature: "ordering" });
1477
+ }
1478
+ /**
1479
+ * Checks whether a container holds a value under Python `in` rules.
1480
+ *
1481
+ * @param value - The value to look for
1482
+ * @param container - The container to inspect
1483
+ * @returns True if `container` contains `value`; false otherwise
1484
+ *
1485
+ * @example
1486
+ * ```ts
1487
+ * import { matchesTemplateMember } from '@orkestrel/template'
1488
+ *
1489
+ * matchesTemplateMember('tool', 'tool_calls') // true
1490
+ * ```
1491
+ */
1492
+ function matchesTemplateMember(value, container) {
1493
+ if (container === void 0) return false;
1494
+ if (typeof container === "string" && typeof value === "string") {
1495
+ if (value.isWellFormed()) return container.includes(value);
1496
+ return `,${Array.from(container, (character) => character.codePointAt(0)).join(",")},`.includes(`,${Array.from(value, (character) => character.codePointAt(0)).join(",")},`);
1497
+ }
1498
+ if (isArray(container)) return container.some((item) => matchesTemplateEqual(value, item));
1499
+ if (isMap(container) && !isArray(value) && !isMap(value) && !isTemplateNamespace(value)) return typeof value === "string" && container.has(value);
1500
+ if (isTemplateNamespace(container) && !isArray(value) && !isMap(value) && !isTemplateNamespace(value)) return typeof value === "string" && container.values.has(value);
1501
+ throw buildTemplateEvaluationError(`looks for ${renderTemplateType(value)} in ${renderTemplateType(container)}, which the subset does not admit`, { feature: "membership" });
1502
+ }
1503
+ /**
1504
+ * Adds two runtime template values under Python `+` rules for strings, numbers, and lists.
1505
+ *
1506
+ * @param left - The first operand
1507
+ * @param right - The second operand
1508
+ * @returns The sum or concatenation
1509
+ *
1510
+ * @example
1511
+ * ```ts
1512
+ * import { addTemplateValues } from '@orkestrel/template'
1513
+ *
1514
+ * addTemplateValues('<|im_start|>', 'user') // '<|im_start|>user'
1515
+ * ```
1516
+ */
1517
+ function addTemplateValues(left, right) {
1518
+ if (typeof left === "string" && typeof right === "string") return left + right;
1519
+ if (isArray(left) && isArray(right)) return [...left, ...right];
1520
+ if (typeof left === "number" && typeof right === "number") {
1521
+ const sum = left + right;
1522
+ if (Number.isInteger(left) && Number.isInteger(right)) {
1523
+ if (Number.isSafeInteger(sum)) return sum;
1524
+ throw buildTemplateEvaluationError("adds integers past the integers JavaScript holds exactly", { feature: "big integer" });
1525
+ }
1526
+ if (!Number.isInteger(sum)) return sum;
1527
+ throw buildTemplateEvaluationError(`adds floats to the whole value ${String(sum)}, which Python prints as a float`, { feature: "whole float" });
1528
+ }
1529
+ throw buildTemplateEvaluationError(`adds ${renderTemplateType(right)} to ${renderTemplateType(left)}, which the subset does not admit`, { feature: "addition" });
1530
+ }
1531
+ /**
1532
+ * Subtracts two numeric runtime template values under Python `-` rules.
1533
+ *
1534
+ * @param left - The left numeric operand
1535
+ * @param right - The right numeric operand
1536
+ * @returns The numeric difference
1537
+ *
1538
+ * @example
1539
+ * ```ts
1540
+ * import { subtractTemplateValues } from '@orkestrel/template'
1541
+ *
1542
+ * subtractTemplateValues(5, 1) // 4
1543
+ * ```
1544
+ */
1545
+ function subtractTemplateValues(left, right) {
1546
+ if (typeof left === "number" && typeof right === "number") {
1547
+ const difference = left - right;
1548
+ if (Number.isInteger(left) && Number.isInteger(right)) {
1549
+ if (Number.isSafeInteger(difference)) return Object.is(difference, -0) ? 0 : difference;
1550
+ throw buildTemplateEvaluationError("subtracts integers past the integers JavaScript holds exactly", { feature: "big integer" });
1551
+ }
1552
+ if (!Number.isInteger(difference)) return difference;
1553
+ throw buildTemplateEvaluationError(`subtracts floats to the whole value ${String(difference)}, which Python prints as a float`, { feature: "whole float" });
1554
+ }
1555
+ throw buildTemplateEvaluationError(`subtracts ${renderTemplateType(right)} from ${renderTemplateType(left)}, which the subset does not admit`, { feature: "subtraction" });
1556
+ }
1557
+ /**
1558
+ * Applies unary `-` or `+` to a numeric runtime template value.
1559
+ *
1560
+ * @param operator - `'-'` for negation or `'+'` for numeric identity
1561
+ * @param value - The numeric operand
1562
+ * @returns The resulting number
1563
+ *
1564
+ * @example
1565
+ * ```ts
1566
+ * import { negateTemplateValue } from '@orkestrel/template'
1567
+ *
1568
+ * negateTemplateValue('-', 1) // -1
1569
+ * ```
1570
+ */
1571
+ function negateTemplateValue(operator, value) {
1572
+ if (typeof value !== "number") {
1573
+ const feature = operator === "-" ? "unary minus" : "unary plus";
1574
+ throw buildTemplateEvaluationError(`applies ${feature} to ${renderTemplateType(value)}, which the subset does not admit`, { feature });
1575
+ }
1576
+ if (operator === "+") return value;
1577
+ const negated = -value;
1578
+ if (Number.isInteger(value) && !Number.isSafeInteger(negated)) throw buildTemplateEvaluationError("negates an integer past the integers JavaScript holds exactly", { feature: "big integer" });
1579
+ return Object.is(negated, -0) ? 0 : negated;
1580
+ }
1581
+ /**
1582
+ * Reads a member or index of a runtime template value under sandboxed Jinja rules,
1583
+ * supporting negative sequence indexing, `TemplateNamespace` properties, and
1584
+ * `loop.previtem` / `loop.nextitem`.
1585
+ *
1586
+ * @param object - The object or sequence to read from
1587
+ * @param key - The member name or integer index
1588
+ * @returns The resolved member value, or `undefined` when absent
1589
+ *
1590
+ * @example
1591
+ * ```ts
1592
+ * import { readTemplateMember } from '@orkestrel/template'
1593
+ *
1594
+ * readTemplateMember(['a', 'b'], -1) // 'b'
1595
+ * ```
1596
+ */
1597
+ function readTemplateMember(object, key) {
1598
+ if (object === void 0) throw buildTemplateEvaluationError(`reads the member ${typeof key === "string" ? quoteTemplateText(key) : renderTemplateType(key)} of an undefined value, which Jinja refuses`, { feature: "undefined" });
1599
+ if (typeof key === "string" && key.startsWith("__")) throw buildTemplateEvaluationError(`reads the private member ${quoteTemplateText(key)}`, { feature: "private" });
1600
+ if (object === null) return void 0;
1601
+ if (typeof object === "number" || typeof object === "boolean") {
1602
+ if (typeof key !== "string") return void 0;
1603
+ throw buildTemplateEvaluationError(`reads the attribute ${quoteTemplateText(key)} of ${renderTemplateType(object)}`, { feature: "attribute" });
1604
+ }
1605
+ if (isTemplateNamespace(object)) return typeof key === "string" ? object.values.get(key) : void 0;
1606
+ const methods = typeof object === "string" ? TEMPLATE_METHODS.string : isArray(object) ? TEMPLATE_METHODS.list : isMap(object) ? TEMPLATE_METHODS.mapping : [];
1607
+ if (typeof key === "string" && methods.includes(key)) throw buildTemplateEvaluationError(`reads the method ${quoteTemplateText(key)} of ${renderTemplateType(object)}, which the subset does not admit`, { feature: "method" });
1608
+ if (isMap(object)) return typeof key === "string" ? object.get(key) : void 0;
1609
+ if (typeof object === "string" || isArray(object)) {
1610
+ const index = typeof key === "boolean" ? Number(key) : key;
1611
+ if (typeof index !== "number" || !Number.isInteger(index)) return void 0;
1612
+ const items = typeof object === "string" ? Array.from(object) : object;
1613
+ const resolved = index < 0 ? items.length + index : index;
1614
+ return resolved >= 0 && resolved < items.length ? items[resolved] : void 0;
1615
+ }
1616
+ if (!isTemplateLoop(object) || typeof key !== "string") return void 0;
1617
+ if (TEMPLATE_LOOP_REFUSALS.some((member) => member === key)) throw buildTemplateEvaluationError(`reads ${quoteTemplateText(`loop.${key}`)}, which the subset does not admit`, { feature: `loop.${key}` });
1618
+ switch (key) {
1619
+ case "index": return object.index0 + 1;
1620
+ case "index0": return object.index0;
1621
+ case "first": return object.index0 === 0;
1622
+ case "last": return object.index0 === object.length - 1;
1623
+ case "length": return object.length;
1624
+ case "previtem": return object.previtem;
1625
+ case "nextitem": return object.nextitem;
1626
+ default: return;
1627
+ }
1628
+ }
1629
+ /**
1630
+ * Slices a string (by Unicode code points) or list under Python
1631
+ * `seq[start:stop:step]` semantics, including negative bounds and `[::-1]`.
1632
+ *
1633
+ * @param object - The string or list to slice
1634
+ * @param start - Optional inclusive start index (`undefined` or `null` for default)
1635
+ * @param stop - Optional exclusive stop index (`undefined` or `null` for default)
1636
+ * @param step - Optional non-zero stride (`undefined` or `null` for `1`)
1637
+ * @returns The sliced string or list
1638
+ *
1639
+ * @example
1640
+ * ```ts
1641
+ * import { sliceTemplateSequence } from '@orkestrel/template'
1642
+ *
1643
+ * sliceTemplateSequence(['a', 'b', 'c'], undefined, undefined, -1) // ['c', 'b', 'a']
1644
+ * ```
1645
+ */
1646
+ function sliceTemplateSequence(object, start, stop, step) {
1647
+ if (typeof object !== "string" && !isArray(object)) throw buildTemplateEvaluationError(`slices ${renderTemplateType(object)}, which is not a sequence`, { feature: "slice" });
1648
+ const rawStep = step === void 0 || step === null ? 1 : typeof step === "boolean" ? Number(step) : step;
1649
+ if (typeof rawStep !== "number" || !Number.isInteger(rawStep)) throw buildTemplateEvaluationError("slices with a non-integer step", { feature: "slice" });
1650
+ if (rawStep === 0) throw buildTemplateEvaluationError("slices with a step of 0", { feature: "slice" });
1651
+ const rawStart = start === void 0 || start === null ? void 0 : typeof start === "boolean" ? Number(start) : start;
1652
+ const rawStop = stop === void 0 || stop === null ? void 0 : typeof stop === "boolean" ? Number(stop) : stop;
1653
+ if (rawStart !== void 0 && (typeof rawStart !== "number" || !Number.isInteger(rawStart)) || rawStop !== void 0 && (typeof rawStop !== "number" || !Number.isInteger(rawStop))) throw buildTemplateEvaluationError("slices with a non-integer bound", { feature: "slice" });
1654
+ const items = typeof object === "string" ? Array.from(object) : object;
1655
+ const length = items.length;
1656
+ const from = rawStep > 0 ? rawStart === void 0 ? 0 : rawStart < 0 ? Math.max(0, length + rawStart) : Math.min(length, rawStart) : rawStart === void 0 ? length - 1 : rawStart < 0 ? Math.max(-1, length + rawStart) : Math.min(length - 1, rawStart);
1657
+ const to = rawStep > 0 ? rawStop === void 0 ? length : rawStop < 0 ? Math.max(0, length + rawStop) : Math.min(length, rawStop) : rawStop === void 0 ? -1 : rawStop < 0 ? Math.max(-1, length + rawStop) : Math.min(length - 1, rawStop);
1658
+ const picked = [];
1659
+ if (rawStep > 0) for (let index = from; index < to; index += rawStep) picked.push(items[index]);
1660
+ else for (let index = from; index > to; index += rawStep) picked.push(items[index]);
1661
+ return typeof object === "string" ? picked.join("") : picked;
1662
+ }
1663
+ /**
1664
+ * Collects the iterable elements of a runtime value for a `for` loop.
1665
+ *
1666
+ * @param value - The value to iterate
1667
+ * @returns The elements in iteration order
1668
+ *
1669
+ * @example
1670
+ * ```ts
1671
+ * import { collectTemplateItems } from '@orkestrel/template'
1672
+ *
1673
+ * collectTemplateItems(new Map([['role', 'user']])) // ['role']
1674
+ * ```
1675
+ */
1676
+ function collectTemplateItems(value) {
1677
+ if (value === void 0) return [];
1678
+ if (typeof value === "string") return Array.from(value);
1679
+ if (isArray(value)) return value;
1680
+ if (isMap(value)) return Array.from(value.keys());
1681
+ if (isTemplateNamespace(value)) return Array.from(value.values.keys());
1682
+ throw buildTemplateEvaluationError(`iterates ${renderTemplateType(value)}, which the subset does not admit`, { feature: "iteration" });
1683
+ }
1684
+ /**
1685
+ * Applies one of the admitted Jinja `|` filters (`trim`, `length`, `tojson`,
1686
+ * `items`, `safe`, `string`) to a runtime value.
1687
+ *
1688
+ * @param name - The filter name
1689
+ * @param value - The value to transform
1690
+ * @returns The filtered runtime value
1691
+ *
1692
+ * @example
1693
+ * ```ts
1694
+ * import { applyTemplateFilter } from '@orkestrel/template'
1695
+ *
1696
+ * applyTemplateFilter('trim', ' Hi\n') // 'Hi'
1697
+ * applyTemplateFilter('length', 'héllo') // 5
1698
+ * ```
1699
+ */
1700
+ function applyTemplateFilter(name, value) {
1701
+ if (!TEMPLATE_FILTERS.some((filter) => filter === name)) throw buildTemplateEvaluationError(`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`, { feature: name });
1702
+ switch (name) {
1703
+ case "trim": return renderTemplateValue(value).replace(new RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, "gu"), "");
1704
+ case "length":
1705
+ if (value === void 0) return 0;
1706
+ if (typeof value === "string") return Array.from(value).length;
1707
+ if (isArray(value)) return value.length;
1708
+ if (isMap(value)) return value.size;
1709
+ if (isTemplateNamespace(value)) return value.values.size;
1710
+ throw buildTemplateEvaluationError(`measures the length of ${renderTemplateType(value)}, which the subset does not admit`, { feature: "length" });
1711
+ case "tojson": return serializeTemplateJSON(value);
1712
+ case "items":
1713
+ if (value === void 0) return [];
1714
+ if (isMap(value)) return Array.from(value.entries(), ([entryKey, entryValue]) => [entryKey, entryValue]);
1715
+ if (isTemplateNamespace(value)) return Array.from(value.values.entries(), ([entryKey, entryValue]) => [entryKey, entryValue]);
1716
+ throw buildTemplateEvaluationError(`reads items of ${renderTemplateType(value)}, which is not a mapping`, { feature: "items" });
1717
+ case "safe": return value;
1718
+ case "string": return renderTemplateValue(value);
1719
+ default: throw buildTemplateEvaluationError(`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`, { feature: name });
1720
+ }
1721
+ }
1722
+ /**
1723
+ * Applies one of the admitted Jinja `is` tests (`defined`, `undefined`, `none`,
1724
+ * `string`, `mapping`, `iterable`, `sequence`, `true`, `false`) to a runtime value.
1725
+ *
1726
+ * @param name - The test name
1727
+ * @param value - The value to inspect
1728
+ * @returns True if `value` satisfies the test; false otherwise
1729
+ *
1730
+ * @example
1731
+ * ```ts
1732
+ * import { applyTemplateTest } from '@orkestrel/template'
1733
+ *
1734
+ * applyTemplateTest('true', true) // true
1735
+ * applyTemplateTest('true', 1) // false
1736
+ * ```
1737
+ */
1738
+ function applyTemplateTest(name, value) {
1739
+ if (!TEMPLATE_TESTS.some((test) => test === name)) throw buildTemplateEvaluationError(`applies the test ${quoteTemplateText(name)}, which the subset does not admit`, { feature: name });
1740
+ switch (name) {
1741
+ case "defined": return value !== void 0;
1742
+ case "undefined": return value === void 0;
1743
+ case "none": return value === null;
1744
+ case "string": return typeof value === "string";
1745
+ case "mapping": return isMap(value) || isTemplateNamespace(value);
1746
+ case "iterable": return typeof value === "string" || isArray(value) || isMap(value) || isTemplateNamespace(value);
1747
+ case "sequence": return typeof value === "string" || isArray(value);
1748
+ case "true": return value === true;
1749
+ case "false": return value === false;
1750
+ default: return false;
1751
+ }
1752
+ }
1753
+ /**
1754
+ * Invokes one of the admitted Python `str` methods (`startswith`, `endswith`,
1755
+ * `split`, `strip`, `rstrip`, `lstrip`) on a string receiver with exact Python
1756
+ * character-set and splitting semantics.
1757
+ *
1758
+ * @param receiver - The string receiver
1759
+ * @param method - The string method name
1760
+ * @param positional - Positional arguments
1761
+ * @param keywords - Named keyword arguments
1762
+ * @returns The method's return value
1763
+ *
1764
+ * @example
1765
+ * ```ts
1766
+ * import { callTemplateMethod } from '@orkestrel/template'
1767
+ *
1768
+ * callTemplateMethod('hello\n\n', 'rstrip', ['\n'], []) // 'hello'
1769
+ * callTemplateMethod('a</think>b', 'split', ['</think>'], []) // ['a', 'b']
1770
+ * ```
1771
+ */
1772
+ function callTemplateMethod(receiver, method, positional, keywords) {
1773
+ if (!TEMPLATE_STRING_METHODS.some((admitted) => admitted === method)) throw buildTemplateEvaluationError(`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`, { feature: method });
1774
+ switch (method) {
1775
+ case "startswith":
1776
+ case "endswith": {
1777
+ if (keywords.length > 0 || positional.length < 1 || positional.length > 3) throw buildTemplateEvaluationError(`calls ${method} with invalid arguments`, { feature: method });
1778
+ const [needle, start, end] = positional;
1779
+ const target = start === void 0 && end === void 0 ? receiver : String(sliceTemplateSequence(receiver, start, end, 1));
1780
+ const candidates = isArray(needle) ? needle : [needle];
1781
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw buildTemplateEvaluationError(`calls ${method} with a non-string prefix or suffix`, { feature: method });
1782
+ return candidates.some((candidate) => method === "startswith" ? target.startsWith(candidate) : target.endsWith(candidate));
1783
+ }
1784
+ case "strip": {
1785
+ const trimmedLeft = callTemplateMethod(receiver, "lstrip", positional, keywords);
1786
+ return typeof trimmedLeft === "string" ? callTemplateMethod(trimmedLeft, "rstrip", positional, keywords) : "";
1787
+ }
1788
+ case "rstrip":
1789
+ case "lstrip": {
1790
+ if (keywords.length > 0 || positional.length > 1) throw buildTemplateEvaluationError(`calls ${method} with invalid arguments`, { feature: method });
1791
+ const [chars] = positional;
1792
+ if (chars === void 0 || chars === null) {
1793
+ const stripPattern = method === "rstrip" ? new RegExp(`${TEMPLATE_SPACE}+$`, "u") : new RegExp(`^${TEMPLATE_SPACE}+`, "u");
1794
+ return receiver.replace(stripPattern, "");
1795
+ }
1796
+ if (typeof chars !== "string") throw buildTemplateEvaluationError(`calls ${method} with a non-string character set`, { feature: method });
1797
+ const charSet = new Set(Array.from(chars));
1798
+ const points = Array.from(receiver);
1799
+ if (method === "rstrip") {
1800
+ let end = points.length;
1801
+ for (let index = points.length - 1; index >= 0; index -= 1) {
1802
+ if (!charSet.has(points[index] ?? "")) break;
1803
+ end = index;
1804
+ }
1805
+ return points.slice(0, end).join("");
1806
+ }
1807
+ let start = 0;
1808
+ for (let index = 0; index < points.length; index += 1) {
1809
+ if (!charSet.has(points[index] ?? "")) break;
1810
+ start = index + 1;
1811
+ }
1812
+ return points.slice(start).join("");
1813
+ }
1814
+ case "split": {
1815
+ if (keywords.find(([name]) => name !== "sep" && name !== "maxsplit") !== void 0 || positional.length > 2) throw buildTemplateEvaluationError("calls split with invalid arguments", { feature: "split" });
1816
+ const sepKeyword = keywords.find(([name]) => name === "sep");
1817
+ const maxsplitKeyword = keywords.find(([name]) => name === "maxsplit");
1818
+ if (sepKeyword !== void 0 && positional.length >= 1 || maxsplitKeyword !== void 0 && positional.length >= 2) throw buildTemplateEvaluationError("calls split with duplicate arguments", { feature: "split" });
1819
+ const sep = sepKeyword !== void 0 ? sepKeyword[1] : positional[0];
1820
+ const rawMax = maxsplitKeyword !== void 0 ? maxsplitKeyword[1] : positional[1];
1821
+ const maxsplit = rawMax === void 0 ? -1 : typeof rawMax === "boolean" ? Number(rawMax) : rawMax;
1822
+ if (typeof maxsplit !== "number" || !Number.isInteger(maxsplit)) throw buildTemplateEvaluationError("calls split with a non-integer maxsplit", { feature: "split" });
1823
+ if (sep === void 0 || sep === null) {
1824
+ if (maxsplit < 0) {
1825
+ const trimmed = receiver.replace(new RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, "gu"), "");
1826
+ return trimmed === "" ? [] : trimmed.split(new RegExp(`${TEMPLATE_SPACE}+`, "gu"));
1827
+ }
1828
+ const leading = receiver.replace(new RegExp(`^${TEMPLATE_SPACE}+`, "u"), "");
1829
+ if (leading === "") return [];
1830
+ if (maxsplit === 0) return [leading];
1831
+ const gaps = Array.from(leading.matchAll(new RegExp(`${TEMPLATE_SPACE}+`, "gu")));
1832
+ const parts = [];
1833
+ let from = 0;
1834
+ for (let index = 0; index < gaps.length && parts.length < maxsplit; index += 1) {
1835
+ const gap = gaps[index];
1836
+ if (gap === void 0) break;
1837
+ parts.push(leading.slice(from, gap.index));
1838
+ from = gap.index + gap[0].length;
1839
+ }
1840
+ if (from < leading.length) parts.push(leading.slice(from));
1841
+ return parts;
1842
+ }
1843
+ if (typeof sep !== "string") throw buildTemplateEvaluationError("calls split with a non-string separator", { feature: "split" });
1844
+ if (sep.length === 0) throw buildTemplateEvaluationError("calls split with an empty separator", { feature: "split" });
1845
+ if (maxsplit < 0) return receiver.split(sep);
1846
+ if (maxsplit === 0) return [receiver];
1847
+ const parts = [];
1848
+ let from = 0;
1849
+ for (let count = 0; count < maxsplit; count += 1) {
1850
+ const found = receiver.indexOf(sep, from);
1851
+ if (found === -1) break;
1852
+ parts.push(receiver.slice(from, found));
1853
+ from = found + sep.length;
1854
+ }
1855
+ parts.push(receiver.slice(from));
1856
+ return parts;
1857
+ }
1858
+ default: throw buildTemplateEvaluationError(`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`, { feature: method });
1859
+ }
1860
+ }
1861
+ /**
1862
+ * Finds the binding for a variable name across lexical scope frames from innermost
1863
+ * to outermost.
1864
+ *
1865
+ * @param frames - The scope stack, outermost first
1866
+ * @param name - The variable name to resolve
1867
+ * @returns The bound runtime value, or `undefined` when unbound
1868
+ *
1869
+ * @example
1870
+ * ```ts
1871
+ * import { findTemplateName } from '@orkestrel/template'
1872
+ *
1873
+ * findTemplateName([new Map([['bos_token', '<s>']])], 'bos_token') // '<s>'
1874
+ * ```
1875
+ */
1876
+ function findTemplateName(frames, name) {
1877
+ return frames.findLast((frame) => frame.has(name))?.get(name);
1878
+ }
1879
+ /**
1880
+ * Binds a variable name in a copy of the innermost scope frame without mutating
1881
+ * the input frames.
1882
+ *
1883
+ * @param frames - The scope stack, outermost first
1884
+ * @param name - The variable name to bind
1885
+ * @param value - The runtime value to bind
1886
+ * @returns A fresh scope stack carrying the updated innermost frame
1887
+ *
1888
+ * @example
1889
+ * ```ts
1890
+ * import { bindTemplateName, findTemplateName } from '@orkestrel/template'
1891
+ *
1892
+ * findTemplateName(bindTemplateName([new Map()], 'turn', 2), 'turn') // 2
1893
+ * ```
1894
+ */
1895
+ function bindTemplateName(frames, name, value) {
1896
+ const inner = frames.at(-1) ?? /* @__PURE__ */ new Map();
1897
+ return [...frames.slice(0, -1), new Map([...inner, [name, value]])];
1898
+ }
1899
+ /**
1900
+ * Evaluates a single {@link TemplateExpression} against runtime scope frames and
1901
+ * namespace bindings.
1902
+ *
1903
+ * @param expression - The compiled expression to evaluate
1904
+ * @param frames - The lexical scope frames, outermost first
1905
+ * @param namespaces - Evaluation-owned map from `TemplateNamespace` to its mutable backing `Map`
1906
+ * @param options - Optional evaluation settings
1907
+ * @param callDepth - Current macro call depth. Default: `0`
1908
+ * @returns The evaluated runtime value
1909
+ *
1910
+ * @example
1911
+ * ```ts
1912
+ * import { evaluateTemplateExpression } from '@orkestrel/template'
1913
+ *
1914
+ * evaluateTemplateExpression({ term: 'literal', value: 42 }, [new Map()], new Map()) // 42
1915
+ * ```
1916
+ */
1917
+ function evaluateTemplateExpression(expression, frames, namespaces, options, callDepth = 0) {
1918
+ switch (expression.term) {
1919
+ case "literal": return expression.value;
1920
+ case "name": return findTemplateName(frames, expression.name);
1921
+ case "member": return readTemplateMember(evaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth), evaluateTemplateExpression(expression.key, frames, namespaces, options, callDepth));
1922
+ case "slice": return sliceTemplateSequence(evaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth), expression.start === void 0 ? void 0 : evaluateTemplateExpression(expression.start, frames, namespaces, options, callDepth), expression.stop === void 0 ? void 0 : evaluateTemplateExpression(expression.stop, frames, namespaces, options, callDepth), expression.step === void 0 ? void 0 : evaluateTemplateExpression(expression.step, frames, namespaces, options, callDepth));
1923
+ case "call": return callTemplateExpression(expression.callee, expression.values, expression.keywords, frames, namespaces, options, callDepth);
1924
+ case "filter": return applyTemplateFilter(expression.name, evaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth));
1925
+ case "test": {
1926
+ const matched = applyTemplateTest(expression.name, evaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth));
1927
+ return expression.negated ? !matched : matched;
1928
+ }
1929
+ case "unary": {
1930
+ const operand = evaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth);
1931
+ if (expression.operator === "not") return !matchesTemplateTruth(operand);
1932
+ return negateTemplateValue(expression.operator, operand);
1933
+ }
1934
+ case "conditional": return matchesTemplateTruth(evaluateTemplateExpression(expression.condition, frames, namespaces, options, callDepth)) ? evaluateTemplateExpression(expression.consequent, frames, namespaces, options, callDepth) : evaluateTemplateExpression(expression.alternate, frames, namespaces, options, callDepth);
1935
+ case "binary": {
1936
+ const left = evaluateTemplateExpression(expression.left, frames, namespaces, options, callDepth);
1937
+ if (expression.operator === "and") return matchesTemplateTruth(left) ? evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth) : left;
1938
+ if (expression.operator === "or") return matchesTemplateTruth(left) ? left : evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth);
1939
+ const right = evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth);
1940
+ switch (expression.operator) {
1941
+ case "+": return addTemplateValues(left, right);
1942
+ case "-": return subtractTemplateValues(left, right);
1943
+ case "~": return renderTemplateValue(left) + renderTemplateValue(right);
1944
+ case "==": return matchesTemplateEqual(left, right);
1945
+ case "!=": return !matchesTemplateEqual(left, right);
1946
+ case "<": return compareTemplateValues(left, right) < 0;
1947
+ case ">": return compareTemplateValues(left, right) > 0;
1948
+ case "<=": return compareTemplateValues(left, right) <= 0;
1949
+ case ">=": return compareTemplateValues(left, right) >= 0;
1950
+ case "in": return matchesTemplateMember(left, right);
1951
+ case "not in": return !matchesTemplateMember(left, right);
1952
+ }
1953
+ }
1954
+ }
1955
+ }
1956
+ /**
1957
+ * Evaluates a template call expression — dispatching built-in `raise_exception`
1958
+ * and `namespace`, string method calls, and user-defined `TemplateMacro` calls.
1959
+ *
1960
+ * @param callee - The callee expression
1961
+ * @param positionalExpressions - Positional argument expressions
1962
+ * @param keywordExpressions - Named keyword argument expressions
1963
+ * @param frames - Active lexical scope frames
1964
+ * @param namespaces - Evaluation-owned mutable namespace registry
1965
+ * @param options - Optional evaluation settings
1966
+ * @param callDepth - Current macro call depth
1967
+ * @returns The call result
1968
+ *
1969
+ * @example
1970
+ * ```ts
1971
+ * import { callTemplateExpression } from '@orkestrel/template'
1972
+ *
1973
+ * callTemplateExpression({ term: 'name', name: 'namespace' }, [], [{ name: 'n', value: { term: 'literal', value: 1 } }], [new Map()], new Map(), undefined, 0)
1974
+ * ```
1975
+ */
1976
+ function callTemplateExpression(callee, positionalExpressions, keywordExpressions, frames, namespaces, options, callDepth) {
1977
+ if (callee.term === "member") {
1978
+ const receiver = evaluateTemplateExpression(callee.object, frames, namespaces, options, callDepth);
1979
+ const key = evaluateTemplateExpression(callee.key, frames, namespaces, options, callDepth);
1980
+ const positional = positionalExpressions.map((value) => evaluateTemplateExpression(value, frames, namespaces, options, callDepth));
1981
+ const keywords = keywordExpressions.map((keyword) => [keyword.name, evaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth)]);
1982
+ if (typeof receiver === "string" && typeof key === "string") return callTemplateMethod(receiver, key, positional, keywords);
1983
+ throw buildTemplateEvaluationError(`calls method ${typeof key === "string" ? quoteTemplateText(key) : renderTemplateType(key)} on ${renderTemplateType(receiver)}, which the subset does not admit`, { feature: "method call" });
1984
+ }
1985
+ const positional = positionalExpressions.map((value) => evaluateTemplateExpression(value, frames, namespaces, options, callDepth));
1986
+ const keywords = keywordExpressions.map((keyword) => [keyword.name, evaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth)]);
1987
+ if (callee.term === "name" && callee.name === "raise_exception") {
1988
+ if (positional.length !== 1 || keywords.length > 0) throw buildTemplateEvaluationError(`calls raise_exception with ${positional.length} positional and ${keywords.length} keyword arguments; it takes one message`);
1989
+ const text = renderTemplateValue(positional[0]);
1990
+ throw new TemplateError("RAISE", `The template raised an exception: ${quoteTemplateText(text)}.`, { message: text });
1991
+ }
1992
+ if (callee.term === "name" && callee.name === "namespace") {
1993
+ if (positional.length > 1) throw buildTemplateEvaluationError(`calls namespace with ${positional.length} positional arguments; it takes at most one mapping`, { feature: "namespace" });
1994
+ const entries = [];
1995
+ const [initial] = positional;
1996
+ if (initial !== void 0) {
1997
+ if (isMap(initial)) for (const [entryKey, entryValue] of initial.entries()) entries.push([entryKey, entryValue]);
1998
+ else if (isTemplateNamespace(initial)) for (const [entryKey, entryValue] of initial.values.entries()) entries.push([entryKey, entryValue]);
1999
+ else throw buildTemplateEvaluationError(`calls namespace with ${renderTemplateType(initial)} instead of a mapping`, { feature: "namespace" });
2000
+ }
2001
+ for (const [entryKey, entryValue] of keywords) entries.push([entryKey, entryValue]);
2002
+ const backing = new Map(entries);
2003
+ const container = {
2004
+ namespace: true,
2005
+ values: backing
2006
+ };
2007
+ namespaces.set(container, backing);
2008
+ return container;
2009
+ }
2010
+ const target = evaluateTemplateExpression(callee, frames, namespaces, options, callDepth);
2011
+ if (!isTemplateMacro(target)) throw buildTemplateEvaluationError(`calls ${renderTemplateType(target)}, which is not a function`, { feature: "call" });
2012
+ if (callDepth + 1 > MAX_DEPTH) throw buildTemplateEvaluationError(`nests macro calls deeper than ${MAX_DEPTH} levels`, { limit: MAX_DEPTH });
2013
+ if (positional.length > target.parameters.length) throw buildTemplateEvaluationError(`calls macro ${quoteTemplateText(target.name)} with ${positional.length} arguments; it accepts at most ${target.parameters.length}`, { feature: "macro" });
2014
+ const bound = /* @__PURE__ */ new Map();
2015
+ for (const [index, value] of positional.entries()) {
2016
+ const parameter = target.parameters[index];
2017
+ if (parameter !== void 0) bound.set(parameter.name, value);
2018
+ }
2019
+ for (const [keywordName, keywordValue] of keywords) {
2020
+ if (!target.parameters.some((parameter) => parameter.name === keywordName)) throw buildTemplateEvaluationError(`calls macro ${quoteTemplateText(target.name)} with unexpected keyword ${quoteTemplateText(keywordName)}`, { feature: "macro" });
2021
+ if (bound.has(keywordName)) throw buildTemplateEvaluationError(`calls macro ${quoteTemplateText(target.name)} with duplicate argument ${quoteTemplateText(keywordName)}`, { feature: "macro" });
2022
+ bound.set(keywordName, keywordValue);
2023
+ }
2024
+ const rootFrame = frames[0];
2025
+ const baseFrames = rootFrame !== void 0 ? [rootFrame, ...target.closure] : target.closure;
2026
+ for (const parameter of target.parameters) if (!bound.has(parameter.name)) bound.set(parameter.name, parameter.fallback === void 0 ? void 0 : evaluateTemplateExpression(parameter.fallback, baseFrames, namespaces, options, callDepth + 1));
2027
+ const [parts] = executeTemplateNodes(target.body, [...baseFrames, bound], namespaces, options, callDepth + 1);
2028
+ return parts.map((part) => renderTemplatePart(part, options)).join("");
2029
+ }
2030
+ /**
2031
+ * Executes a sequence of compiled {@link TemplateNode}s in order, tagging each
2032
+ * emitted part with whether it came from literal template text (`true`) or a
2033
+ * dynamic expression/placeholder (`false`).
2034
+ *
2035
+ * @param nodes - The nodes to execute in order
2036
+ * @param frames - Active lexical scope frames
2037
+ * @param namespaces - Evaluation-owned mutable namespace registry
2038
+ * @param options - Optional evaluation settings
2039
+ * @param callDepth - Current macro call depth. Default: `0`
2040
+ * @returns The tagged emitted parts, updated scope frames, and optional loop control signal
2041
+ *
2042
+ * @example
2043
+ * ```ts
2044
+ * import { runTemplateNodes } from '@orkestrel/template'
2045
+ *
2046
+ * runTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // [[true, 'Hi']]
2047
+ * ```
2048
+ */
2049
+ function runTemplateNodes(nodes, frames, namespaces, options, callDepth = 0) {
2050
+ const steps = [];
2051
+ for (const node of nodes) {
2052
+ const previous = steps.at(-1);
2053
+ if (previous?.[2] !== void 0) break;
2054
+ const active = previous?.[1] ?? frames;
2055
+ switch (node.syntax) {
2056
+ case "document":
2057
+ steps.push(runTemplateNodes(node.children, active, namespaces, options, callDepth));
2058
+ break;
2059
+ case "text":
2060
+ steps.push([
2061
+ [[true, node.value]],
2062
+ active,
2063
+ void 0
2064
+ ]);
2065
+ break;
2066
+ case "comment":
2067
+ steps.push([
2068
+ [],
2069
+ active,
2070
+ void 0
2071
+ ]);
2072
+ break;
2073
+ case "html": {
2074
+ const sanitized = createHTML(node.document).sanitize(options?.sanitize).document;
2075
+ steps.push([
2076
+ [[false, sanitized]],
2077
+ active,
2078
+ void 0
2079
+ ]);
2080
+ break;
2081
+ }
2082
+ case "markdown":
2083
+ steps.push([
2084
+ [[false, node.document]],
2085
+ active,
2086
+ void 0
2087
+ ]);
2088
+ break;
2089
+ case "placeholder": {
2090
+ const rawRecord = {};
2091
+ const root = active[0];
2092
+ if (root !== void 0) for (const [entryKey, entryValue] of root.entries()) rawRecord[entryKey] = entryValue;
2093
+ const placeholders = options?.placeholders ?? [];
2094
+ const missing = options?.missing ?? "error";
2095
+ const locale = options?.locale ?? "en-US";
2096
+ const { value, declared, required } = resolveToken(rawRecord, placeholders, node.name);
2097
+ const resolved = value !== void 0 ? value : declared?.fallback;
2098
+ if (resolved !== void 0) {
2099
+ if (isHTMLNode(resolved)) {
2100
+ const document = resolved.category === "document" ? resolved : {
2101
+ category: "document",
2102
+ children: [resolved]
2103
+ };
2104
+ steps.push([
2105
+ [[false, createHTML(document).sanitize(options?.sanitize).document]],
2106
+ active,
2107
+ void 0
2108
+ ]);
2109
+ } else if (isMarkdownNode(resolved)) steps.push([
2110
+ [[false, resolved]],
2111
+ active,
2112
+ void 0
2113
+ ]);
2114
+ else steps.push([
2115
+ [[false, formatValue(resolved, locale)]],
2116
+ active,
2117
+ void 0
2118
+ ]);
2119
+ } else if (missing === "literal") steps.push([
2120
+ [[false, node.raw]],
2121
+ active,
2122
+ void 0
2123
+ ]);
2124
+ else if (missing === "empty" || !required) steps.push([
2125
+ [[false, ""]],
2126
+ active,
2127
+ void 0
2128
+ ]);
2129
+ else throw new TemplateError("MISSING", `Missing required placeholder(s): ${node.name}`, { missing: [node.name] });
2130
+ break;
2131
+ }
2132
+ case "output": {
2133
+ const evaluated = evaluateTemplateExpression(node.value, active, namespaces, options, callDepth);
2134
+ if (isHTMLNode(evaluated)) {
2135
+ const document = evaluated.category === "document" ? evaluated : {
2136
+ category: "document",
2137
+ children: [evaluated]
2138
+ };
2139
+ steps.push([
2140
+ [[false, createHTML(document).sanitize(options?.sanitize).document]],
2141
+ active,
2142
+ void 0
2143
+ ]);
2144
+ } else if (isMarkdownNode(evaluated)) steps.push([
2145
+ [[false, evaluated]],
2146
+ active,
2147
+ void 0
2148
+ ]);
2149
+ else steps.push([
2150
+ [[false, renderTemplateValue(evaluated)]],
2151
+ active,
2152
+ void 0
2153
+ ]);
2154
+ break;
2155
+ }
2156
+ case "if": {
2157
+ const branch = matchesTemplateTruth(evaluateTemplateExpression(node.condition, active, namespaces, options, callDepth)) ? node.body : node.alternate ?? [];
2158
+ steps.push(runTemplateNodes(branch, active, namespaces, options, callDepth));
2159
+ break;
2160
+ }
2161
+ case "for": {
2162
+ const items = collectTemplateItems(evaluateTemplateExpression(node.sequence, active, namespaces, options, callDepth));
2163
+ const turns = [];
2164
+ for (const [index0, item] of items.entries()) {
2165
+ if (turns.at(-1)?.[1] === "break") break;
2166
+ const loopFrame = /* @__PURE__ */ new Map();
2167
+ if (node.targets.length === 1) {
2168
+ const [targetName] = node.targets;
2169
+ if (targetName !== void 0) loopFrame.set(targetName, item);
2170
+ } else {
2171
+ const unpacked = collectTemplateItems(item);
2172
+ if (unpacked.length !== node.targets.length) throw buildTemplateEvaluationError(`unpacks ${unpacked.length} values into ${node.targets.length} loop targets`, { feature: "unpacking" });
2173
+ for (const [position, targetName] of node.targets.entries()) loopFrame.set(targetName, unpacked[position]);
2174
+ }
2175
+ loopFrame.set("loop", {
2176
+ index0,
2177
+ length: items.length,
2178
+ previtem: index0 > 0 ? items[index0 - 1] : void 0,
2179
+ nextitem: index0 + 1 < items.length ? items[index0 + 1] : void 0
2180
+ });
2181
+ const [parts, , control] = runTemplateNodes(node.body, [...active, loopFrame], namespaces, options, callDepth);
2182
+ turns.push([parts, control]);
2183
+ }
2184
+ steps.push([
2185
+ turns.flatMap(([parts]) => parts),
2186
+ active,
2187
+ void 0
2188
+ ]);
2189
+ break;
2190
+ }
2191
+ case "set": {
2192
+ const value = evaluateTemplateExpression(node.value, active, namespaces, options, callDepth);
2193
+ if (node.target.scope === "local") steps.push([
2194
+ [],
2195
+ bindTemplateName(active, node.target.name, value),
2196
+ void 0
2197
+ ]);
2198
+ else {
2199
+ const container = findTemplateName(active, node.target.object);
2200
+ if (!isTemplateNamespace(container)) throw buildTemplateEvaluationError(`sets attribute ${quoteTemplateText(node.target.name)} on ${renderTemplateType(container)}, which is not a namespace`, { feature: "namespace" });
2201
+ const backing = namespaces.get(container);
2202
+ if (backing === void 0) throw buildTemplateEvaluationError(`sets attribute ${quoteTemplateText(node.target.name)} on a readonly namespace`, { feature: "namespace" });
2203
+ backing.set(node.target.name, value);
2204
+ steps.push([
2205
+ [],
2206
+ active,
2207
+ void 0
2208
+ ]);
2209
+ }
2210
+ break;
2211
+ }
2212
+ case "macro": {
2213
+ const macro = {
2214
+ macro: true,
2215
+ name: node.name,
2216
+ parameters: node.parameters,
2217
+ body: node.body,
2218
+ closure: active
2219
+ };
2220
+ steps.push([
2221
+ [],
2222
+ bindTemplateName(active, node.name, macro),
2223
+ void 0
2224
+ ]);
2225
+ break;
2226
+ }
2227
+ case "control": steps.push([
2228
+ [],
2229
+ active,
2230
+ node.action
2231
+ ]);
2232
+ }
2233
+ }
2234
+ const last = steps.at(-1);
2235
+ return [
2236
+ steps.flatMap(([parts]) => parts),
2237
+ last?.[1] ?? frames,
2238
+ last?.[2]
2239
+ ];
2240
+ }
2241
+ /**
2242
+ * Executes a sequence of compiled {@link TemplateNode}s in order, threading
2243
+ * lexical `set` and `macro` bindings into subsequent siblings until a loop
2244
+ * control (`break` or `continue`) terminates the run.
2245
+ *
2246
+ * @param nodes - The nodes to execute in order
2247
+ * @param frames - Active lexical scope frames
2248
+ * @param namespaces - Evaluation-owned mutable namespace registry
2249
+ * @param options - Optional evaluation settings
2250
+ * @param callDepth - Current macro call depth. Default: `0`
2251
+ * @returns The emitted parts, updated scope frames, and optional loop control signal
2252
+ *
2253
+ * @example
2254
+ * ```ts
2255
+ * import { executeTemplateNodes } from '@orkestrel/template'
2256
+ *
2257
+ * executeTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // ['Hi']
2258
+ * ```
2259
+ */
2260
+ function executeTemplateNodes(nodes, frames, namespaces, options, callDepth = 0) {
2261
+ const [tagged, updated, control] = runTemplateNodes(nodes, frames, namespaces, options, callDepth);
2262
+ return [
2263
+ tagged.map(([, part]) => part),
2264
+ updated,
2265
+ control
2266
+ ];
2267
+ }
2268
+ /**
2269
+ * Renders one emitted {@link TemplatePart} to string text, sanitizing `HTMLNode`s
2270
+ * through `@orkestrel/html` and rendering `MarkdownNode`s through `@orkestrel/markdown`.
2271
+ *
2272
+ * @param part - The emitted template part
2273
+ * @param options - Optional evaluation and sanitize settings
2274
+ * @returns The rendered string
2275
+ *
2276
+ * @example
2277
+ * ```ts
2278
+ * import { renderTemplatePart } from '@orkestrel/template'
2279
+ *
2280
+ * renderTemplatePart({ category: 'text', value: 'a & b' }) // 'a &amp; b'
2281
+ * ```
2282
+ */
2283
+ function renderTemplatePart(part, options) {
2284
+ if (typeof part === "string") return part;
2285
+ if (isHTMLNode(part)) {
2286
+ const document = part.category === "document" ? part : {
2287
+ category: "document",
2288
+ children: [part]
2289
+ };
2290
+ return renderHTML(createHTML(document).sanitize(options?.sanitize).document);
2291
+ }
2292
+ return renderMarkdown(part);
2293
+ }
2294
+ /**
2295
+ * Evaluates a compiled {@link TemplateDocument} into tagged parts distinguishing
2296
+ * template-authored literal text (`true`) from dynamic fill output (`false`).
2297
+ *
2298
+ * @param document - The compiled template document
2299
+ * @param values - Optional runtime values record
2300
+ * @param options - Optional evaluation, placeholder, and sanitize settings
2301
+ * @returns The ordered list of tagged evaluated parts
2302
+ *
2303
+ * @example
2304
+ * ```ts
2305
+ * import { compileTemplate, evaluateTaggedTemplateParts } from '@orkestrel/template'
2306
+ *
2307
+ * evaluateTaggedTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' })
2308
+ * // [[true, 'Hi '], [false, 'Ada']]
2309
+ * ```
2310
+ */
2311
+ function evaluateTaggedTemplateParts(document, values, options) {
2312
+ if (!isTemplateDocument(document)) throw new TemplateError("INVALID", "A template evaluates a valid TemplateDocument.");
2313
+ const frame = /* @__PURE__ */ new Map();
2314
+ if (values !== void 0) {
2315
+ for (const [entryKey, entryValue] of Object.entries(values)) if (entryValue !== void 0) frame.set(entryKey, normalizeTemplateValue(entryValue));
2316
+ }
2317
+ const namespaces = /* @__PURE__ */ new Map();
2318
+ return runTemplateNodes(document.children, [frame], namespaces, options, 0)[0];
2319
+ }
2320
+ /**
2321
+ * Evaluates a compiled {@link TemplateDocument} into an ordered list of
2322
+ * tree-valued {@link TemplatePart}s (`string`, sanitized `HTMLNode`, or `MarkdownNode`).
2323
+ *
2324
+ * @param document - The compiled template document
2325
+ * @param values - Optional runtime values record
2326
+ * @param options - Optional evaluation, placeholder, and sanitize settings
2327
+ * @returns The ordered list of evaluated parts
2328
+ *
2329
+ * @example
2330
+ * ```ts
2331
+ * import { compileTemplate, evaluateTemplateParts } from '@orkestrel/template'
2332
+ *
2333
+ * evaluateTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // ['Hi ', 'Ada']
2334
+ * ```
2335
+ */
2336
+ function evaluateTemplateParts(document, values, options) {
2337
+ return evaluateTaggedTemplateParts(document, values, options).map(([, part]) => part);
2338
+ }
2339
+ /**
2340
+ * Evaluates a compiled {@link TemplateDocument} against runtime values and
2341
+ * joins every emitted part into a rendered string.
2342
+ *
2343
+ * @param document - The compiled template document
2344
+ * @param values - Optional runtime values record
2345
+ * @param options - Optional evaluation, placeholder, and sanitize settings
2346
+ * @returns The rendered output string
2347
+ *
2348
+ * @example
2349
+ * ```ts
2350
+ * import { compileTemplate, evaluateTemplate } from '@orkestrel/template'
2351
+ *
2352
+ * evaluateTemplate(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // 'Hi Ada'
2353
+ * ```
2354
+ */
2355
+ function evaluateTemplate(document, values, options) {
2356
+ return evaluateTemplateParts(document, values, options).map((part) => renderTemplatePart(part, options)).join("");
2357
+ }
2358
+ /**
2359
+ * Walks a {@link TemplateNode} depth-first in pre-order, yielding the root
2360
+ * first and capping descent at `MAX_DEPTH`.
2361
+ *
2362
+ * @param root - The root node to traverse
2363
+ * @param depth - Current traversal depth. Default: `0`
2364
+ * @returns A lazy generator over every visited node
2365
+ *
2366
+ * @example
2367
+ * ```ts
2368
+ * import { compileTemplate, walkTemplateNodes } from '@orkestrel/template'
2369
+ *
2370
+ * Array.from(walkTemplateNodes(compileTemplate('Hi {{ name }}'))).map((node) => node.syntax)
2371
+ * // ['document', 'text', 'output']
2372
+ * ```
2373
+ */
2374
+ function* walkTemplateNodes(root, depth = 0) {
2375
+ yield root;
2376
+ if (depth >= MAX_DEPTH) return;
2377
+ const next = depth + 1;
2378
+ switch (root.syntax) {
2379
+ case "document":
2380
+ for (const child of root.children) yield* walkTemplateNodes(child, next);
2381
+ return;
2382
+ case "if":
2383
+ for (const child of root.body) yield* walkTemplateNodes(child, next);
2384
+ if (root.alternate !== void 0) for (const child of root.alternate) yield* walkTemplateNodes(child, next);
2385
+ return;
2386
+ case "for":
2387
+ case "macro":
2388
+ for (const child of root.body) yield* walkTemplateNodes(child, next);
2389
+ return;
2390
+ default: return;
2391
+ }
2392
+ }
2393
+ function findTemplateNode(root, predicate) {
2394
+ for (const node of walkTemplateNodes(root)) if (predicate(node)) return node;
2395
+ }
2396
+ function filterTemplateNodes(root, predicate) {
2397
+ return walkTemplateNodes(root).filter((node) => predicate(node)).toArray();
2398
+ }
2399
+ /**
2400
+ * Reduces a {@link TemplateNode} depth-first in pre-order into one accumulated value.
2401
+ *
2402
+ * @param root - The root node to reduce
2403
+ * @param callback - The step combining the accumulated value and each visited node
2404
+ * @param initial - The initial accumulated value
2405
+ * @returns The final accumulated value
2406
+ *
2407
+ * @example
2408
+ * ```ts
2409
+ * import { compileTemplate, reduceTemplateDocument } from '@orkestrel/template'
2410
+ *
2411
+ * reduceTemplateDocument(compileTemplate('Hi {{ name }}'), (count) => count + 1, 0) // 3
2412
+ * ```
2413
+ */
2414
+ function reduceTemplateDocument(root, callback, initial) {
2415
+ return walkTemplateNodes(root).reduce((value, node) => callback(value, node), initial);
2416
+ }
2417
+ /**
2418
+ * Folds a {@link TemplateNode} bottom-up through a total {@link TemplateHandlerMap}
2419
+ * covering every syntax variant, capped at `MAX_DEPTH`.
2420
+ *
2421
+ * @param node - The node to fold
2422
+ * @param handlers - Total handler map keyed by `syntax`
2423
+ * @param depth - Current recursion depth. Default: `0`
2424
+ * @returns The folded result
2425
+ *
2426
+ * @example
2427
+ * ```ts
2428
+ * import { compileTemplate, foldTemplateDocument } from '@orkestrel/template'
2429
+ *
2430
+ * const doc = compileTemplate('Hi')
2431
+ * foldTemplateDocument(doc, {
2432
+ * document: (_, children) => children.reduce((a, b) => a + b, 1),
2433
+ * text: () => 1,
2434
+ * placeholder: () => 1,
2435
+ * output: () => 1,
2436
+ * if: (_, children) => children.reduce((a, b) => a + b, 1),
2437
+ * for: (_, children) => children.reduce((a, b) => a + b, 1),
2438
+ * set: () => 1,
2439
+ * macro: (_, children) => children.reduce((a, b) => a + b, 1),
2440
+ * control: () => 1,
2441
+ * comment: () => 1,
2442
+ * html: () => 1,
2443
+ * markdown: () => 1,
2444
+ * }) // 2
2445
+ * ```
2446
+ */
2447
+ function foldTemplateDocument(node, handlers, depth = 0) {
2448
+ const next = depth + 1;
2449
+ const capped = depth >= MAX_DEPTH;
2450
+ switch (node.syntax) {
2451
+ case "document": return handlers.document(node, capped ? [] : node.children.map((child) => foldTemplateDocument(child, handlers, next)));
2452
+ case "text": return handlers.text(node, []);
2453
+ case "placeholder": return handlers.placeholder(node, []);
2454
+ case "output": return handlers.output(node, []);
2455
+ case "if": {
2456
+ const children = capped ? [] : [...node.body.map((child) => foldTemplateDocument(child, handlers, next)), ...(node.alternate ?? []).map((child) => foldTemplateDocument(child, handlers, next))];
2457
+ return handlers.if(node, children);
2458
+ }
2459
+ case "for": return handlers.for(node, capped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)));
2460
+ case "set": return handlers.set(node, []);
2461
+ case "macro": return handlers.macro(node, capped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)));
2462
+ case "control": return handlers.control(node, []);
2463
+ case "comment": return handlers.comment(node, []);
2464
+ case "html": return handlers.html(node, []);
2465
+ case "markdown": return handlers.markdown(node, []);
2466
+ }
2467
+ }
2468
+ /**
2469
+ * Rewrites one {@link TemplateNode} bottom-up with copy-on-write identity
2470
+ * preservation, recording each rebuilt node's direct source in `derivations`.
2471
+ *
2472
+ * @param node - The node to rewrite
2473
+ * @param rewrite - The bottom-up rewrite callback
2474
+ * @param derivations - Operation-owned derivation map
2475
+ * @param depth - Current recursion depth
2476
+ * @returns The rewritten node
2477
+ *
2478
+ * @example
2479
+ * ```ts
2480
+ * import { rewriteTemplateNode } from '@orkestrel/template'
2481
+ *
2482
+ * rewriteTemplateNode({ syntax: 'text', value: 'hi' }, (node) => node, new Map(), 0)
2483
+ * ```
2484
+ */
2485
+ function rewriteTemplateNode(node, rewrite, derivations, depth) {
2486
+ if (depth >= MAX_DEPTH) return node;
2487
+ const next = depth + 1;
2488
+ if (node.syntax === "if") {
2489
+ const body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next));
2490
+ const alternate = node.alternate?.map((child) => rewriteTemplateNode(child, rewrite, derivations, next));
2491
+ const bodyChanged = body.some((child, index) => child !== node.body[index]);
2492
+ const alternateChanged = alternate !== void 0 && node.alternate !== void 0 && alternate.some((child, index) => child !== node.alternate?.[index]);
2493
+ const rebuilt = !bodyChanged && !alternateChanged ? node : {
2494
+ syntax: "if",
2495
+ condition: node.condition,
2496
+ body,
2497
+ ...alternate !== void 0 ? { alternate } : {}
2498
+ };
2499
+ const candidate = rewrite(rebuilt);
2500
+ const accepted = candidate.syntax === "document" ? rebuilt : candidate;
2501
+ if (accepted !== node) derivations.set(accepted, derivations.has(accepted) ? void 0 : node);
2502
+ return accepted;
2503
+ }
2504
+ if (node.syntax === "for") {
2505
+ const body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next));
2506
+ const rebuilt = body.some((child, index) => child !== node.body[index]) ? {
2507
+ syntax: "for",
2508
+ targets: node.targets,
2509
+ sequence: node.sequence,
2510
+ body
2511
+ } : node;
2512
+ const candidate = rewrite(rebuilt);
2513
+ const accepted = candidate.syntax === "document" ? rebuilt : candidate;
2514
+ if (accepted !== node) derivations.set(accepted, derivations.has(accepted) ? void 0 : node);
2515
+ return accepted;
2516
+ }
2517
+ if (node.syntax === "macro") {
2518
+ const body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next));
2519
+ const rebuilt = body.some((child, index) => child !== node.body[index]) ? {
2520
+ syntax: "macro",
2521
+ name: node.name,
2522
+ parameters: node.parameters,
2523
+ body
2524
+ } : node;
2525
+ const candidate = rewrite(rebuilt);
2526
+ const accepted = candidate.syntax === "document" ? rebuilt : candidate;
2527
+ if (accepted !== node) derivations.set(accepted, derivations.has(accepted) ? void 0 : node);
2528
+ return accepted;
2529
+ }
2530
+ const candidate = rewrite(node);
2531
+ const accepted = candidate.syntax === "document" ? node : candidate;
2532
+ if (accepted !== node) derivations.set(accepted, derivations.has(accepted) ? void 0 : node);
2533
+ return accepted;
2534
+ }
2535
+ /**
2536
+ * Rewrites a {@link TemplateDocument} bottom-up (copy-on-write) and returns the
2537
+ * rewritten document alongside its output-to-input derivation map.
2538
+ *
2539
+ * @param document - The document to rewrite
2540
+ * @param rewrite - The bottom-up node rewrite callback
2541
+ * @returns The rewritten document and its provenance derivations
2542
+ *
2543
+ * @example
2544
+ * ```ts
2545
+ * import { compileTemplate, mapTemplateDocument } from '@orkestrel/template'
2546
+ *
2547
+ * const [rewritten] = mapTemplateDocument(compileTemplate('hi'), (node) =>
2548
+ * node.syntax === 'text' ? { syntax: 'text', value: node.value.toUpperCase() } : node,
2549
+ * )
2550
+ * rewritten.children[0] // { syntax: 'text', value: 'HI' }
2551
+ * ```
2552
+ */
2553
+ function mapTemplateDocument(document, rewrite) {
2554
+ const derivations = /* @__PURE__ */ new Map();
2555
+ const children = document.children.map((child) => rewriteTemplateNode(child, rewrite, derivations, 1));
2556
+ if (!children.some((child, index) => child !== document.children[index])) return [document, derivations];
2557
+ const rebuilt = {
2558
+ syntax: "document",
2559
+ children
2560
+ };
2561
+ derivations.set(rebuilt, document);
2562
+ return [rebuilt, derivations];
2563
+ }
2564
+ /**
2565
+ * Creates a fresh, pull-based `ReadableStream` over a {@link TemplateDocument}'s
2566
+ * direct top-level children in source order.
2567
+ *
2568
+ * @param document - The document whose top-level children to stream
2569
+ * @returns A pull-based stream yielding one top-level node per pull
2570
+ *
2571
+ * @example
2572
+ * ```ts
2573
+ * import { compileTemplate, streamTemplateNodes } from '@orkestrel/template'
2574
+ *
2575
+ * const reader = streamTemplateNodes(compileTemplate('Hi {{ name }}')).getReader()
2576
+ * ```
2577
+ */
2578
+ function streamTemplateNodes(document) {
2579
+ const children = document.children.values();
2580
+ return new ReadableStream({ pull(controller) {
2581
+ const next = children.next();
2582
+ if (!next.done && next.value !== void 0) controller.enqueue(next.value);
2583
+ else controller.close();
2584
+ } });
2585
+ }
2586
+ /**
2587
+ * Renders a {@link TemplateExpression} back to canonical Jinja expression syntax
2588
+ * that compiles back to an equivalent AST.
2589
+ *
2590
+ * @param expression - The expression to render
2591
+ * @returns Canonical Jinja expression text
2592
+ *
2593
+ * @example
2594
+ * ```ts
2595
+ * import { renderTemplateExpression } from '@orkestrel/template'
2596
+ *
2597
+ * renderTemplateExpression({ term: 'name', name: 'messages' }) // 'messages'
2598
+ * ```
2599
+ */
2600
+ function renderTemplateExpression(expression) {
2601
+ switch (expression.term) {
2602
+ case "literal":
2603
+ if (expression.value === null) return "none";
2604
+ if (typeof expression.value === "boolean") return expression.value ? "true" : "false";
2605
+ if (typeof expression.value === "number") return renderTemplateNumber(expression.value);
2606
+ return JSON.stringify(expression.value);
2607
+ case "name": return expression.name;
2608
+ case "member": {
2609
+ const target = expression.object.term === "name" || expression.object.term === "literal" || expression.object.term === "member" || expression.object.term === "slice" || expression.object.term === "call" ? renderTemplateExpression(expression.object) : `(${renderTemplateExpression(expression.object)})`;
2610
+ if (expression.key.term === "literal" && typeof expression.key.value === "string" && /^[\p{XID_Start}_]\p{XID_Continue}*$/u.test(expression.key.value)) return `${target}.${expression.key.value}`;
2611
+ return `${target}[${renderTemplateExpression(expression.key)}]`;
2612
+ }
2613
+ case "slice": return `${expression.object.term === "name" || expression.object.term === "literal" || expression.object.term === "member" || expression.object.term === "slice" || expression.object.term === "call" ? renderTemplateExpression(expression.object) : `(${renderTemplateExpression(expression.object)})`}[${expression.start === void 0 ? "" : renderTemplateExpression(expression.start)}:${expression.stop === void 0 ? "" : renderTemplateExpression(expression.stop)}${expression.step === void 0 ? "" : `:${renderTemplateExpression(expression.step)}`}]`;
2614
+ case "call": return `${expression.callee.term === "name" || expression.callee.term === "member" ? renderTemplateExpression(expression.callee) : `(${renderTemplateExpression(expression.callee)})`}(${[...expression.values.map((value) => renderTemplateExpression(value)), ...expression.keywords.map((keyword) => `${keyword.name}=${renderTemplateExpression(keyword.value)}`)].join(", ")})`;
2615
+ case "filter": return `${expression.value.term === "name" || expression.value.term === "literal" || expression.value.term === "member" || expression.value.term === "slice" || expression.value.term === "call" || expression.value.term === "filter" ? renderTemplateExpression(expression.value) : `(${renderTemplateExpression(expression.value)})`} | ${expression.name}`;
2616
+ case "test": {
2617
+ const inner = expression.value.term === "conditional" || expression.value.term === "test" || expression.value.term === "unary" && expression.value.operator === "not" || expression.value.term === "binary" && (expression.value.operator === "and" || expression.value.operator === "or" || expression.value.operator === "in" || expression.value.operator === "not in" || expression.value.operator === "==" || expression.value.operator === "!=" || expression.value.operator === "<" || expression.value.operator === ">" || expression.value.operator === "<=" || expression.value.operator === ">=") ? `(${renderTemplateExpression(expression.value)})` : renderTemplateExpression(expression.value);
2618
+ return expression.negated ? `${inner} is not ${expression.name}` : `${inner} is ${expression.name}`;
2619
+ }
2620
+ case "unary": {
2621
+ if (expression.operator === "not") return `not ${expression.value.term === "conditional" || expression.value.term === "binary" && (expression.value.operator === "and" || expression.value.operator === "or") ? `(${renderTemplateExpression(expression.value)})` : renderTemplateExpression(expression.value)}`;
2622
+ const inner = expression.value.term === "name" || expression.value.term === "literal" || expression.value.term === "member" || expression.value.term === "slice" || expression.value.term === "call" || expression.value.term === "filter" ? renderTemplateExpression(expression.value) : `(${renderTemplateExpression(expression.value)})`;
2623
+ return `${expression.operator}${inner}`;
2624
+ }
2625
+ case "binary": {
2626
+ const left = expression.left.term === "binary" || expression.left.term === "conditional" || expression.left.term === "test" || expression.left.term === "unary" && expression.left.operator === "not" ? `(${renderTemplateExpression(expression.left)})` : renderTemplateExpression(expression.left);
2627
+ const right = expression.right.term === "binary" || expression.right.term === "conditional" || expression.right.term === "test" || expression.right.term === "unary" && expression.right.operator === "not" ? `(${renderTemplateExpression(expression.right)})` : renderTemplateExpression(expression.right);
2628
+ return `${left} ${expression.operator} ${right}`;
2629
+ }
2630
+ case "conditional": return `(${renderTemplateExpression(expression.consequent)} if ${renderTemplateExpression(expression.condition)} else ${renderTemplateExpression(expression.alternate)})`;
2631
+ }
2632
+ }
2633
+ /**
2634
+ * Checks whether a trailing text node ends with a whitespace-only line that
2635
+ * Jinja's `lstrip_blocks` would strip before a following block or comment tag.
2636
+ *
2637
+ * @param node - The preceding sibling node, if any
2638
+ * @param atLineStart - Whether the text node itself opened at a line start
2639
+ * @returns True if a `+` marker is needed to keep the whitespace verbatim; false otherwise
2640
+ *
2641
+ * @example
2642
+ * ```ts
2643
+ * import { matchesTemplateIndent } from '@orkestrel/template'
2644
+ *
2645
+ * matchesTemplateIndent({ syntax: 'text', value: ' ' }, true) // true
2646
+ * ```
2647
+ */
2648
+ function matchesTemplateIndent(node, atLineStart) {
2649
+ if (node?.syntax !== "text") return false;
2650
+ const breakIndex = node.value.lastIndexOf("\n");
2651
+ const tail = node.value.slice(breakIndex + 1);
2652
+ return (breakIndex !== -1 || atLineStart) && new RegExp(`^[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]+$`, "u").test(tail);
2653
+ }
2654
+ /**
2655
+ * Renders an ordered list of sibling {@link TemplateNode}s into canonical source
2656
+ * text, preserving leading whitespace and trailing newlines against Jinja's
2657
+ * `lstrip_blocks` and `trim_blocks` rules with `+` markers where needed.
2658
+ *
2659
+ * @param nodes - The sibling nodes to render
2660
+ * @param precedingNewline - Whether the list opens at a line boundary
2661
+ * @returns The canonical template source for the node list
2662
+ *
2663
+ * @example
2664
+ * ```ts
2665
+ * import { renderTemplateNodes } from '@orkestrel/template'
2666
+ *
2667
+ * renderTemplateNodes([{ syntax: 'text', value: 'Hi' }], true) // 'Hi'
2668
+ * ```
2669
+ */
2670
+ function renderTemplateNodes(nodes, precedingNewline) {
2671
+ return nodes.map((node, index) => {
2672
+ const previous = nodes[index - 1];
2673
+ const next = nodes[index + 1];
2674
+ const needsOpenPlus = matchesTemplateIndent(previous, index === 1 && precedingNewline);
2675
+ const needsClosePlus = next?.syntax === "text" && next.value.startsWith("\n");
2676
+ const openBlock = needsOpenPlus ? "{%+" : "{%";
2677
+ const closeBlock = needsClosePlus ? "+%}" : "%}";
2678
+ switch (node.syntax) {
2679
+ case "document": return renderTemplateNodes(node.children, true);
2680
+ case "text": return node.value;
2681
+ case "placeholder": return node.raw;
2682
+ case "output": return `{{ ${renderTemplateExpression(node.value)} }}`;
2683
+ case "comment": {
2684
+ const openComment = needsOpenPlus ? "{#+" : "{#";
2685
+ const closeComment = needsClosePlus ? "+#}" : "#}";
2686
+ return `${openComment}${node.value}${closeComment}`;
2687
+ }
2688
+ case "control": return `${openBlock} ${node.action} ${closeBlock}`;
2689
+ case "set": return `${openBlock} set ${node.target.scope === "local" ? node.target.name : `${node.target.object}.${node.target.name}`} = ${renderTemplateExpression(node.value)} ${closeBlock}`;
2690
+ case "html": return renderHTML(node.document);
2691
+ case "markdown": return renderMarkdown(node.document);
2692
+ case "for": {
2693
+ const bodyFirstNewline = node.body[0]?.syntax === "text" && node.body[0].value.startsWith("\n");
2694
+ const endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1) ? "{%+" : "{%";
2695
+ const headerClose = bodyFirstNewline ? "+%}" : "%}";
2696
+ return `${openBlock} for ${node.targets.join(", ")} in ${renderTemplateExpression(node.sequence)} ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endfor ${closeBlock}`;
2697
+ }
2698
+ case "macro": {
2699
+ const parameters = node.parameters.map((parameter) => parameter.fallback === void 0 ? parameter.name : `${parameter.name}=${renderTemplateExpression(parameter.fallback)}`).join(", ");
2700
+ const bodyFirstNewline = node.body[0]?.syntax === "text" && node.body[0].value.startsWith("\n");
2701
+ const endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1) ? "{%+" : "{%";
2702
+ const headerClose = bodyFirstNewline ? "+%}" : "%}";
2703
+ return `${openBlock} macro ${node.name}(${parameters}) ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endmacro ${closeBlock}`;
2704
+ }
2705
+ case "if": {
2706
+ const bodyFirstNewline = node.body[0]?.syntax === "text" && node.body[0].value.startsWith("\n");
2707
+ const branchOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1) ? "{%+" : "{%";
2708
+ const headerClose = bodyFirstNewline ? "+%}" : "%}";
2709
+ const bodyText = renderTemplateNodes(node.body, false);
2710
+ if (node.alternate === void 0) return `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} endif ${closeBlock}`;
2711
+ const altFirstNewline = node.alternate[0]?.syntax === "text" && node.alternate[0].value.startsWith("\n");
2712
+ const endOpen = matchesTemplateIndent(node.alternate.at(-1), node.alternate.length === 1) ? "{%+" : "{%";
2713
+ const elseClose = altFirstNewline ? "+%}" : "%}";
2714
+ return `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} else ${elseClose}${renderTemplateNodes(node.alternate, false)}${endOpen} endif ${closeBlock}`;
2715
+ }
2716
+ }
2717
+ }).join("");
2718
+ }
2719
+ /**
2720
+ * Renders a {@link TemplateNode} back to canonical template source text.
2721
+ *
2722
+ * @remarks
2723
+ * For every compiled pure-Jinja {@link TemplateDocument}, `compileTemplate(renderTemplate(doc))`
2724
+ * produces a structurally equal document and `renderTemplate(compileTemplate(renderTemplate(doc)))`
2725
+ * equals `renderTemplate(doc)`.
2726
+ *
2727
+ * @param node - The node or document to render
2728
+ * @returns The canonical template source text
2729
+ *
2730
+ * @example
2731
+ * ```ts
2732
+ * import { compileTemplate, renderTemplate } from '@orkestrel/template'
2733
+ *
2734
+ * renderTemplate(compileTemplate('Hi {{ name }}')) // 'Hi {{ name }}'
2735
+ * ```
2736
+ */
2737
+ function renderTemplate(node) {
2738
+ const rendered = node.syntax === "document" ? renderTemplateNodes(node.children, true) : renderTemplateNodes([node], true);
2739
+ return node.syntax === "document" && rendered.endsWith("\n") ? `${rendered}\n` : rendered;
2740
+ }
2741
+ /**
2742
+ * Sanitizes a fenced code block language info string to a single token free of
2743
+ * whitespace, line breaks, backticks, and tildes.
2744
+ *
2745
+ * @param lang - The raw fence info-string language value
2746
+ * @returns The sanitized single-token language tag, or `undefined` when empty
2747
+ *
2748
+ * @example
2749
+ * ```ts
2750
+ * import { sanitizeTemplateMarkdownLanguage } from '@orkestrel/template'
2751
+ *
2752
+ * sanitizeTemplateMarkdownLanguage('ts\n```\n[x](javascript:alert(1))') // 'ts'
2753
+ * sanitizeTemplateMarkdownLanguage(' ') // undefined
2754
+ * ```
2755
+ */
2756
+ function sanitizeTemplateMarkdownLanguage(lang) {
2757
+ const token = /^[^\s`~]+/u.exec(lang.trim())?.[0];
2758
+ return token !== void 0 && token.length > 0 ? token : void 0;
2759
+ }
2760
+ /**
2761
+ * Collapses line breaks inside inline markdown text to single spaces so inline
2762
+ * spans stay on one line through round-trip parsing.
2763
+ *
2764
+ * @param value - The inline text string to normalize
2765
+ * @returns The single-line string with `\r\n`, `\r`, and `\n` replaced by `' '`
2766
+ *
2767
+ * @example
2768
+ * ```ts
2769
+ * import { normalizeTemplateMarkdownText } from '@orkestrel/template'
2770
+ *
2771
+ * normalizeTemplateMarkdownText('a\n\nb') // 'a b'
2772
+ * ```
2773
+ */
2774
+ function normalizeTemplateMarkdownText(value) {
2775
+ return value.replace(/\r\n?|\n/gu, " ");
2776
+ }
2777
+ /**
2778
+ * Sanitizes inline `@orkestrel/markdown` nodes recursively by unwrapping unsafe
2779
+ * `LinkNode` elements, dropping unsafe `ImageNode` elements, and collapsing
2780
+ * line breaks inside `CodeSpanNode` values.
2781
+ *
2782
+ * @param nodes - The inline nodes to sanitize
2783
+ * @param options - Optional HTML sanitization allowlist settings
2784
+ * @param depth - Current recursion depth. Default: `0`
2785
+ * @returns The sanitized inline nodes
2786
+ *
2787
+ * @example
2788
+ * ```ts
2789
+ * import { parseInline } from '@orkestrel/markdown'
2790
+ * import { sanitizeTemplateMarkdownInlines } from '@orkestrel/template'
2791
+ *
2792
+ * sanitizeTemplateMarkdownInlines(parseInline('[x](javascript:alert(1))')) // [{ element: 'text', value: 'x' }]
2793
+ * ```
2794
+ */
2795
+ function sanitizeTemplateMarkdownInlines(nodes, options, depth = 0) {
2796
+ if (depth >= MAX_DEPTH) return [];
2797
+ const schemes = options?.schemes ?? SAFE_URL_SCHEMES;
2798
+ const sanitized = [];
2799
+ for (const child of nodes) {
2800
+ if (child.element === "codeSpan") {
2801
+ sanitized.push({
2802
+ element: "codeSpan",
2803
+ value: normalizeTemplateMarkdownText(child.value)
2804
+ });
2805
+ continue;
2806
+ }
2807
+ if (child.element === "link") {
2808
+ const children = sanitizeTemplateMarkdownInlines(child.children, options, depth + 1);
2809
+ const cleanHref = sanitizeURL(child.href, schemes);
2810
+ if (cleanHref === "") for (const inner of children) sanitized.push(inner);
2811
+ else sanitized.push({
2812
+ element: "link",
2813
+ href: cleanHref,
2814
+ children
2815
+ });
2816
+ continue;
2817
+ }
2818
+ if (child.element === "image") {
2819
+ const cleanSrc = sanitizeURL(child.src, schemes);
2820
+ if (cleanSrc !== "") sanitized.push({
2821
+ element: "image",
2822
+ src: cleanSrc,
2823
+ children: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1)
2824
+ });
2825
+ continue;
2826
+ }
2827
+ if (child.element === "emphasis") {
2828
+ sanitized.push({
2829
+ element: "emphasis",
2830
+ strong: child.strong,
2831
+ children: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1)
2832
+ });
2833
+ continue;
2834
+ }
2835
+ sanitized.push(child);
2836
+ }
2837
+ return coalesceText(sanitized);
2838
+ }
2839
+ /**
2840
+ * Sanitizes block `@orkestrel/markdown` nodes recursively through
2841
+ * `sanitizeTemplateMarkdown`, dropping any node that sanitizes to `undefined`.
2842
+ *
2843
+ * @param nodes - The block nodes to sanitize
2844
+ * @param options - Optional HTML sanitization allowlist settings
2845
+ * @param depth - Current recursion depth. Default: `0`
2846
+ * @returns The sanitized block nodes
2847
+ *
2848
+ * @example
2849
+ * ```ts
2850
+ * import { parseMarkdown } from '@orkestrel/markdown'
2851
+ * import { sanitizeTemplateMarkdownBlocks } from '@orkestrel/template'
2852
+ *
2853
+ * sanitizeTemplateMarkdownBlocks(parseMarkdown('Hi').children).length // 1
2854
+ * ```
2855
+ */
2856
+ function sanitizeTemplateMarkdownBlocks(nodes, options, depth = 0) {
2857
+ if (depth >= MAX_DEPTH) return [];
2858
+ const blocks = [];
2859
+ for (const block of nodes) {
2860
+ const clean = sanitizeTemplateMarkdown(block, options, depth);
2861
+ if (clean !== void 0 && isBlockNode(clean)) blocks.push(clean);
2862
+ }
2863
+ return blocks;
2864
+ }
2865
+ /**
2866
+ * Sanitizes a `@orkestrel/markdown` node recursively by unwrapping any
2867
+ * `LinkNode` whose `href` fails `sanitizeURL`, dropping any `ImageNode` whose
2868
+ * `src` fails `sanitizeURL`, collapsing `CodeSpanNode` line breaks, and
2869
+ * sanitizing `CodeBlockNode` fence languages.
2870
+ *
2871
+ * @param node - The markdown AST node to sanitize
2872
+ * @param options - Optional HTML sanitization allowlist settings
2873
+ * @param depth - Current recursion depth. Default: `0`
2874
+ * @returns The sanitized node, or `undefined` when dropped
2875
+ *
2876
+ * @example
2877
+ * ```ts
2878
+ * import { parseMarkdown } from '@orkestrel/markdown'
2879
+ * import { sanitizeTemplateMarkdown } from '@orkestrel/template'
2880
+ *
2881
+ * sanitizeTemplateMarkdown(parseMarkdown('![x](javascript:alert(1))')) // { element: 'document', children: [{ element: 'paragraph', children: [] }] }
2882
+ * ```
2883
+ */
2884
+ function sanitizeTemplateMarkdown(node, options, depth = 0) {
2885
+ if (depth >= MAX_DEPTH) return void 0;
2886
+ const schemes = options?.schemes ?? SAFE_URL_SCHEMES;
2887
+ switch (node.element) {
2888
+ case "text":
2889
+ case "break":
2890
+ case "thematicBreak": return node;
2891
+ case "codeSpan": return {
2892
+ element: "codeSpan",
2893
+ value: normalizeTemplateMarkdownText(node.value)
2894
+ };
2895
+ case "codeBlock": {
2896
+ const lang = node.lang !== void 0 ? sanitizeTemplateMarkdownLanguage(node.lang) : void 0;
2897
+ return {
2898
+ element: "codeBlock",
2899
+ ...lang !== void 0 ? { lang } : {},
2900
+ code: node.code
2901
+ };
2902
+ }
2903
+ case "image": {
2904
+ const cleanSrc = sanitizeURL(node.src, schemes);
2905
+ if (cleanSrc === "") return void 0;
2906
+ return {
2907
+ element: "image",
2908
+ src: cleanSrc,
2909
+ children: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)
2910
+ };
2911
+ }
2912
+ case "link": {
2913
+ const children = sanitizeTemplateMarkdownInlines(node.children, options, depth + 1);
2914
+ const cleanHref = sanitizeURL(node.href, schemes);
2915
+ if (cleanHref === "") {
2916
+ if (children.length === 0) return void 0;
2917
+ if (children.length === 1) return children[0];
2918
+ return {
2919
+ element: "text",
2920
+ value: children.map((child) => flattenText(child)).join("")
2921
+ };
2922
+ }
2923
+ return {
2924
+ element: "link",
2925
+ href: cleanHref,
2926
+ children
2927
+ };
2928
+ }
2929
+ case "emphasis": return {
2930
+ element: "emphasis",
2931
+ strong: node.strong,
2932
+ children: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)
2933
+ };
2934
+ case "heading": return {
2935
+ element: "heading",
2936
+ level: node.level,
2937
+ children: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)
2938
+ };
2939
+ case "paragraph": return {
2940
+ element: "paragraph",
2941
+ children: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)
2942
+ };
2943
+ case "blockquote": return {
2944
+ element: "blockquote",
2945
+ children: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1)
2946
+ };
2947
+ case "listItem": return {
2948
+ element: "listItem",
2949
+ children: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1)
2950
+ };
2951
+ case "list": {
2952
+ const items = node.items.map((item) => ({
2953
+ element: "listItem",
2954
+ children: sanitizeTemplateMarkdownBlocks(item.children, options, depth + 1)
2955
+ }));
2956
+ return {
2957
+ element: "list",
2958
+ ordered: node.ordered,
2959
+ start: node.start,
2960
+ items
2961
+ };
2962
+ }
2963
+ case "table": return {
2964
+ element: "table",
2965
+ header: node.header.map((cell) => sanitizeTemplateMarkdownInlines(cell, options, depth + 1)),
2966
+ rows: node.rows.map((row) => row.map((cell) => sanitizeTemplateMarkdownInlines(cell, options, depth + 1))),
2967
+ align: node.align
2968
+ };
2969
+ case "document": return {
2970
+ element: "document",
2971
+ children: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1)
2972
+ };
2973
+ }
2974
+ }
2975
+ /**
2976
+ * Resolves a Private Use Area sentinel prefix guaranteed absent from `combined`.
2977
+ *
2978
+ * @param combined - Concatenated template text and fill values in one markdown run
2979
+ * @returns The collision-free sentinel prefix
2980
+ *
2981
+ * @example
2982
+ * ```ts
2983
+ * import { resolveMarkdownMarker } from '@orkestrel/template'
2984
+ *
2985
+ * resolveMarkdownMarker('plain text') // '\uE000\uE001'
2986
+ * ```
2987
+ */
2988
+ function resolveMarkdownMarker(combined) {
2989
+ for (let k = 0; k <= combined.length; k += 1) {
2990
+ const candidate = `\uE000${"".repeat(k)}\uE001`;
2991
+ if (!combined.includes(candidate)) return candidate;
2992
+ }
2993
+ return `\uE000${"".repeat(combined.length + 1)}\uE001`;
2994
+ }
2995
+ /**
2996
+ * Replaces every sentinel slot in a parsed markdown leaf string with its
2997
+ * literal dynamic fill string in a single pass.
2998
+ *
2999
+ * @param text - Parsed leaf string possibly holding sentinel slots
3000
+ * @param pattern - RegExp matching sentinel slots for this run
3001
+ * @param fills - Indexed dynamic fill strings
3002
+ * @returns The restored literal string
3003
+ *
3004
+ * @example
3005
+ * ```ts
3006
+ * import { restoreMarkdownText } from '@orkestrel/template'
3007
+ *
3008
+ * restoreMarkdownText('\uE000\uE0010\uE003', /\uE000\uE001(\d+)\uE003/gu, ['Ada']) // 'Ada'
3009
+ * ```
3010
+ */
3011
+ function restoreMarkdownText(text, pattern, fills) {
3012
+ return text.replace(new RegExp(pattern.source, pattern.flags), (match, digits) => {
3013
+ return fills[Number(digits)] ?? match;
3014
+ });
3015
+ }
3016
+ /**
3017
+ * Restores sentinel slots inside a list of parsed inline markdown nodes,
3018
+ * collapsing line breaks inside substituted dynamic fills and `CodeSpanNode`
3019
+ * values so inline content stays single-line across round-trips.
3020
+ *
3021
+ * @param nodes - Inline nodes parsed from sentinel-substituted markdown
3022
+ * @param pattern - RegExp matching sentinel slots
3023
+ * @param fills - Indexed dynamic fill strings
3024
+ * @param depth - Current recursion depth. Default: `0`
3025
+ * @returns The inline nodes with dynamic fills restored as literal leaves
3026
+ *
3027
+ * @example
3028
+ * ```ts
3029
+ * import { restoreMarkdownInlines } from '@orkestrel/template'
3030
+ *
3031
+ * restoreMarkdownInlines([{ element: 'text', value: 'hi' }], /\uE000\uE001(\d+)\uE003/gu, []) // [{ element: 'text', value: 'hi' }]
3032
+ * ```
3033
+ */
3034
+ function restoreMarkdownInlines(nodes, pattern, fills, depth = 0) {
3035
+ if (depth >= MAX_DEPTH) return nodes;
3036
+ const inlineFills = fills.some((fill) => /[\r\n]/u.test(fill)) ? fills.map((fill) => normalizeTemplateMarkdownText(fill)) : fills;
3037
+ return nodes.map((node) => {
3038
+ switch (node.element) {
3039
+ case "text": return {
3040
+ element: "text",
3041
+ value: restoreMarkdownText(node.value, pattern, inlineFills)
3042
+ };
3043
+ case "codeSpan": return {
3044
+ element: "codeSpan",
3045
+ value: normalizeTemplateMarkdownText(restoreMarkdownText(node.value, pattern, inlineFills))
3046
+ };
3047
+ case "break": return node;
3048
+ case "emphasis": return {
3049
+ element: "emphasis",
3050
+ strong: node.strong,
3051
+ children: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1)
3052
+ };
3053
+ case "link": return {
3054
+ element: "link",
3055
+ href: restoreMarkdownText(node.href, pattern, inlineFills),
3056
+ children: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1)
3057
+ };
3058
+ case "image": return {
3059
+ element: "image",
3060
+ src: restoreMarkdownText(node.src, pattern, inlineFills),
3061
+ children: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1)
3062
+ };
3063
+ }
3064
+ });
3065
+ }
3066
+ /**
3067
+ * Restores sentinel slots inside a parsed block markdown node, keeping
3068
+ * verbatim line breaks only inside `CodeBlockNode.code` and sanitizing
3069
+ * `CodeBlockNode.lang` to a single token.
3070
+ *
3071
+ * @param node - Block node parsed from sentinel-substituted markdown
3072
+ * @param pattern - RegExp matching sentinel slots
3073
+ * @param fills - Indexed dynamic fill strings
3074
+ * @param depth - Current recursion depth. Default: `0`
3075
+ * @returns The block node with dynamic fills restored as literal leaves
3076
+ *
3077
+ * @example
3078
+ * ```ts
3079
+ * import { restoreMarkdownBlock } from '@orkestrel/template'
3080
+ *
3081
+ * restoreMarkdownBlock({ element: 'thematicBreak' }, /\uE000\uE001(\d+)\uE003/gu, []) // { element: 'thematicBreak' }
3082
+ * ```
3083
+ */
3084
+ function restoreMarkdownBlock(node, pattern, fills, depth = 0) {
3085
+ if (depth >= MAX_DEPTH) return node;
3086
+ switch (node.element) {
3087
+ case "thematicBreak": return node;
3088
+ case "heading": return {
3089
+ element: "heading",
3090
+ level: node.level,
3091
+ children: restoreMarkdownInlines(node.children, pattern, fills, depth + 1)
3092
+ };
3093
+ case "paragraph": return {
3094
+ element: "paragraph",
3095
+ children: restoreMarkdownInlines(node.children, pattern, fills, depth + 1)
3096
+ };
3097
+ case "codeBlock": {
3098
+ const lang = node.lang !== void 0 ? sanitizeTemplateMarkdownLanguage(restoreMarkdownText(node.lang, pattern, fills)) : void 0;
3099
+ return {
3100
+ element: "codeBlock",
3101
+ ...lang !== void 0 ? { lang } : {},
3102
+ code: restoreMarkdownText(node.code, pattern, fills)
3103
+ };
3104
+ }
3105
+ case "blockquote": return {
3106
+ element: "blockquote",
3107
+ children: node.children.map((child) => restoreMarkdownBlock(child, pattern, fills, depth + 1))
3108
+ };
3109
+ case "list": return {
3110
+ element: "list",
3111
+ ordered: node.ordered,
3112
+ start: node.start,
3113
+ items: node.items.map((item) => ({
3114
+ element: "listItem",
3115
+ children: item.children.map((child) => restoreMarkdownBlock(child, pattern, fills, depth + 1))
3116
+ }))
3117
+ };
3118
+ case "table": return {
3119
+ element: "table",
3120
+ header: node.header.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1)),
3121
+ rows: node.rows.map((row) => row.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1))),
3122
+ align: node.align
3123
+ };
3124
+ }
3125
+ }
3126
+ /**
3127
+ * Builds sanitized markdown blocks from a contiguous run of template-authored
3128
+ * literal text (`true`) and dynamic scalar fill strings (`false`), keeping
3129
+ * dynamic scalars strictly literal leaf text.
3130
+ *
3131
+ * @param run - Ordered `[literal, text]` entries in the run
3132
+ * @param options - Optional HTML sanitization allowlist settings
3133
+ * @returns The sanitized block nodes produced from the run
3134
+ *
3135
+ * @example
3136
+ * ```ts
3137
+ * import { buildTemplateMarkdownBlocks } from '@orkestrel/template'
3138
+ *
3139
+ * buildTemplateMarkdownBlocks([[true, '# '], [false, 'Ada']])[0]?.element // 'heading'
3140
+ * ```
3141
+ */
3142
+ function buildTemplateMarkdownBlocks(run, options) {
3143
+ if (!run.some(([literal, text]) => !literal && text.length > 0)) {
3144
+ const clean = sanitizeTemplateMarkdown(parseMarkdown(run.map(([, text]) => text).join("")), options);
3145
+ return clean !== void 0 && clean.element === "document" ? clean.children : [];
3146
+ }
3147
+ const prefix = resolveMarkdownMarker(run.map(([, text]) => text).join(""));
3148
+ const fills = [];
3149
+ const markedParts = [];
3150
+ for (const [literal, text] of run) {
3151
+ if (literal || text.length === 0) {
3152
+ markedParts.push(text);
3153
+ continue;
3154
+ }
3155
+ const slot = `${prefix}${fills.length}\uE003`;
3156
+ fills.push(text);
3157
+ markedParts.push(slot);
3158
+ }
3159
+ const parsed = parseMarkdown(markedParts.join(""));
3160
+ const pattern = new RegExp(`${prefix}(\\d+)\uE003`, "gu");
3161
+ const clean = sanitizeTemplateMarkdown({
3162
+ element: "document",
3163
+ children: parsed.children.map((block) => restoreMarkdownBlock(block, pattern, fills))
3164
+ }, options);
3165
+ return clean !== void 0 && clean.element === "document" ? clean.children : [];
3166
+ }
3167
+ // src/core/compilers.ts
3168
+ /**
3169
+ * Compiles a Jinja template source string into a {@link TemplateDocument} AST
3170
+ * alongside its original-source {@link TemplateSpan} map.
3171
+ *
3172
+ * @param source - The template's Jinja source string
3173
+ * @returns The compiled document and its node-to-span map
3174
+ *
3175
+ * @example
3176
+ * ```ts
3177
+ * import { compileTemplateProvenance } from '@orkestrel/template'
3178
+ *
3179
+ * const [document, spans] = compileTemplateProvenance('Hi {{ name }}')
3180
+ * spans.get(document) // { start: 0, end: 13 }
3181
+ * ```
3182
+ */
3183
+ function compileTemplateProvenance(source) {
3184
+ if (typeof source !== "string") throw new TemplateError("INVALID", "A template compiles from a string of Jinja source.");
3185
+ const tokens = scanTemplateTokens(source);
3186
+ const spans = /* @__PURE__ */ new Map();
3187
+ const [children] = compileTemplateStatements(tokens, 0, 0, [], false, spans);
3188
+ const document = {
3189
+ syntax: "document",
3190
+ children
3191
+ };
3192
+ spans.set(document, {
3193
+ start: 0,
3194
+ end: source.length
3195
+ });
3196
+ return [document, spans];
3197
+ }
3198
+ /**
3199
+ * Compiles a Jinja template source string into a {@link TemplateDocument} AST.
3200
+ *
3201
+ * @param source - The template's Jinja source string
3202
+ * @returns The compiled document AST
3203
+ *
3204
+ * @example
3205
+ * ```ts
3206
+ * import { compileTemplate } from '@orkestrel/template'
3207
+ *
3208
+ * compileTemplate('{{ bos_token }}').children[0] // { syntax: 'output', value: { term: 'name', name: 'bos_token' } }
3209
+ * ```
3210
+ */
3211
+ function compileTemplate(source) {
3212
+ return compileTemplateProvenance(source)[0];
3213
+ }
3214
+ /**
3215
+ * Compiles a plain `{{name}}` placeholder template into a {@link TemplateDocument}
3216
+ * AST of `text` and `placeholder` nodes alongside original-source UTF-16 spans.
3217
+ *
3218
+ * @param source - The plain placeholder template content
3219
+ * @returns The compiled document and its node-to-span map
3220
+ *
3221
+ * @example
3222
+ * ```ts
3223
+ * import { compilePlainTemplate } from '@orkestrel/template'
3224
+ *
3225
+ * const [document] = compilePlainTemplate('Hi {{name}}')
3226
+ * document.children[1] // { syntax: 'placeholder', name: 'name', raw: '{{name}}' }
3227
+ * ```
3228
+ */
3229
+ function compilePlainTemplate(source) {
3230
+ if (typeof source !== "string") throw new TemplateError("INVALID", "A plain template compiles from a string.");
3231
+ const children = [];
3232
+ const spans = /* @__PURE__ */ new Map();
3233
+ const pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags);
3234
+ const matches = Array.from(source.matchAll(pattern));
3235
+ let cursor = 0;
3236
+ let pendingText = "";
3237
+ let pendingStart = 0;
3238
+ for (let index = 0; index < matches.length; index += 1) {
3239
+ const match = matches[index];
3240
+ if (match === void 0) break;
3241
+ const matchStart = match.index;
3242
+ const matchText = match[0];
3243
+ const matchEnd = matchStart + matchText.length;
3244
+ const rawToken = match[1];
3245
+ if (matchStart > cursor) {
3246
+ if (pendingText === "") pendingStart = cursor;
3247
+ pendingText += source.slice(cursor, matchStart);
3248
+ }
3249
+ if (rawToken === void 0) {
3250
+ if (pendingText === "") pendingStart = matchStart;
3251
+ pendingText += "{{";
3252
+ cursor = matchEnd;
3253
+ continue;
3254
+ }
3255
+ if (pendingText.length > 0) {
3256
+ const textNode = {
3257
+ syntax: "text",
3258
+ value: pendingText
3259
+ };
3260
+ children.push(textNode);
3261
+ spans.set(textNode, {
3262
+ start: pendingStart,
3263
+ end: matchStart
3264
+ });
3265
+ pendingText = "";
3266
+ }
3267
+ const placeholderNode = {
3268
+ syntax: "placeholder",
3269
+ name: rawToken.trim(),
3270
+ raw: matchText
3271
+ };
3272
+ children.push(placeholderNode);
3273
+ spans.set(placeholderNode, {
3274
+ start: matchStart,
3275
+ end: matchEnd
3276
+ });
3277
+ cursor = matchEnd;
3278
+ }
3279
+ const finalText = cursor < source.length ? pendingText + source.slice(cursor) : pendingText;
3280
+ const finalStart = pendingText === "" ? cursor : pendingStart;
3281
+ if (finalText.length > 0) {
3282
+ const textNode = {
3283
+ syntax: "text",
3284
+ value: finalText
3285
+ };
3286
+ children.push(textNode);
3287
+ spans.set(textNode, {
3288
+ start: finalStart,
3289
+ end: source.length
3290
+ });
3291
+ }
3292
+ const document = {
3293
+ syntax: "document",
3294
+ children
3295
+ };
3296
+ spans.set(document, {
3297
+ start: 0,
3298
+ end: source.length
3299
+ });
3300
+ return [document, spans];
3301
+ }
3302
+ /**
3303
+ * Compiles a run of Jinja template statements up to end-of-source or one of the
3304
+ * closing block tag names in `ends`.
3305
+ *
3306
+ * @param tokens - The scanned token stream
3307
+ * @param start - The starting token index
3308
+ * @param depth - Current statement nesting depth
3309
+ * @param ends - Block tag names that terminate this statement run
3310
+ * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them
3311
+ * @param spans - Optional operation-owned span recorder
3312
+ * @returns The compiled statements, stopping token index, and maximum subtree height
3313
+ *
3314
+ * @example
3315
+ * ```ts
3316
+ * import { compileTemplateStatements, scanTemplateTokens } from '@orkestrel/template'
3317
+ *
3318
+ * compileTemplateStatements(scanTemplateTokens('Hi{% endif %}'), 0, 0, ['endif'], false)[1] // 1
3319
+ * ```
3320
+ */
3321
+ function compileTemplateStatements(tokens, start, depth, ends, loop, spans) {
3322
+ checkTemplateDepth(depth, readTemplateToken(tokens, start));
3323
+ const statements = [];
3324
+ const heights = [];
3325
+ let index = start;
3326
+ for (let step = 0; step < tokens.length; step += 1) {
3327
+ const token = readTemplateToken(tokens, index);
3328
+ if (token.token === "end") {
3329
+ if (ends.length === 0) break;
3330
+ throw buildTemplateFormatError(token, `ends before a ${ends.map((name) => `{% ${name} %}`).join(" or ")} tag closes the block`);
3331
+ }
3332
+ if (token.token === "text") {
3333
+ const node = {
3334
+ syntax: "text",
3335
+ value: token.text
3336
+ };
3337
+ statements.push(node);
3338
+ spans?.set(node, {
3339
+ start: token.start,
3340
+ end: token.end
3341
+ });
3342
+ heights.push(0);
3343
+ index += 1;
3344
+ continue;
3345
+ }
3346
+ if (token.token === "comment") {
3347
+ const node = {
3348
+ syntax: "comment",
3349
+ value: token.text
3350
+ };
3351
+ statements.push(node);
3352
+ spans?.set(node, {
3353
+ start: token.start,
3354
+ end: token.end
3355
+ });
3356
+ heights.push(0);
3357
+ index += 1;
3358
+ continue;
3359
+ }
3360
+ if (token.token === "variable") {
3361
+ const [value, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true);
3362
+ checkTemplateDepth(height + 1, token);
3363
+ const after = checkTemplateClose(tokens, next, false);
3364
+ const closeToken = readTemplateToken(tokens, after - 1);
3365
+ const node = {
3366
+ syntax: "output",
3367
+ value
3368
+ };
3369
+ statements.push(node);
3370
+ spans?.set(node, {
3371
+ start: token.start,
3372
+ end: closeToken.end
3373
+ });
3374
+ heights.push(height + 1);
3375
+ index = after;
3376
+ continue;
3377
+ }
3378
+ if (token.token !== "block") throw buildTemplateFormatError(token, `holds ${renderTemplateToken(token)} outside a tag`);
3379
+ const name = readTemplateToken(tokens, index + 1);
3380
+ if (name.token === "name" && ends.includes(name.text)) break;
3381
+ const [statement, next, height] = compileTemplateBlock(tokens, index + 1, depth, loop, spans);
3382
+ const closeToken = readTemplateToken(tokens, next - 1);
3383
+ spans?.set(statement, {
3384
+ start: token.start,
3385
+ end: closeToken.end
3386
+ });
3387
+ statements.push(statement);
3388
+ heights.push(height);
3389
+ index = next;
3390
+ }
3391
+ return [
3392
+ statements,
3393
+ index,
3394
+ heights.reduce((top, height) => Math.max(top, height), 0)
3395
+ ];
3396
+ }
3397
+ /**
3398
+ * Compiles one Jinja block tag (`if`, `for`, `set`, `macro`, `break`, or `continue`).
3399
+ *
3400
+ * @param tokens - The scanned token stream
3401
+ * @param index - The index of the tag name token
3402
+ * @param depth - Current statement nesting depth
3403
+ * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them
3404
+ * @param spans - Optional operation-owned span recorder
3405
+ * @returns The compiled node, token index after closing delimiter, and subtree height
3406
+ *
3407
+ * @example
3408
+ * ```ts
3409
+ * import { compileTemplateBlock, scanTemplateTokens } from '@orkestrel/template'
3410
+ *
3411
+ * compileTemplateBlock(scanTemplateTokens('{% set turn = 1 %}'), 1, 0, false)[0].syntax // 'set'
3412
+ * ```
3413
+ */
3414
+ function compileTemplateBlock(tokens, index, depth, loop, spans) {
3415
+ const name = readTemplateToken(tokens, index);
3416
+ checkTemplateDepth(depth, name);
3417
+ if (name.token !== "name") throw buildTemplateFormatError(name, `expects a tag name and finds ${renderTemplateToken(name)}`);
3418
+ switch (name.text) {
3419
+ case "if": return compileTemplateIf(tokens, index + 1, depth, loop, spans);
3420
+ case "for": return compileTemplateFor(tokens, index + 1, depth, spans);
3421
+ case "macro": return compileTemplateMacro(tokens, index + 1, depth, spans);
3422
+ case "set": {
3423
+ const target = readTemplateToken(tokens, index + 1);
3424
+ checkTemplateTarget(target);
3425
+ const after = readTemplateToken(tokens, index + 2);
3426
+ if (matchesTemplateToken(after, "operator", ".")) {
3427
+ const property = readTemplateToken(tokens, index + 3);
3428
+ checkTemplateTarget(property);
3429
+ checkTemplateToken(tokens, index + 4, "operator", "=");
3430
+ const [value, next, height] = compileTemplateExpression(tokens, index + 5, depth + 1, true);
3431
+ checkTemplateDepth(height + 1, name);
3432
+ return [
3433
+ {
3434
+ syntax: "set",
3435
+ target: {
3436
+ scope: "attribute",
3437
+ object: target.text,
3438
+ name: property.text
3439
+ },
3440
+ value
3441
+ },
3442
+ checkTemplateClose(tokens, next, false),
3443
+ height + 1
3444
+ ];
3445
+ }
3446
+ const feature = matchesTemplateToken(after, "operator", ",") ? "tuple target" : matchesTemplateToken(after, "operator", "=") ? target.text === "loop" ? "loop assignment" : void 0 : "set block";
3447
+ if (feature !== void 0) throw buildTemplateFormatError(name, `writes a ${quoteTemplateText(feature)} form of {% set %}, which the subset does not admit`, { feature });
3448
+ const [value, next, height] = compileTemplateExpression(tokens, index + 3, depth + 1, true);
3449
+ checkTemplateDepth(height + 1, name);
3450
+ return [
3451
+ {
3452
+ syntax: "set",
3453
+ target: {
3454
+ scope: "local",
3455
+ name: target.text
3456
+ },
3457
+ value
3458
+ },
3459
+ checkTemplateClose(tokens, next, false),
3460
+ height + 1
3461
+ ];
3462
+ }
3463
+ case "break":
3464
+ case "continue":
3465
+ if (!loop) throw buildTemplateFormatError(name, `writes {% ${name.text} %} outside a for loop`);
3466
+ return [
3467
+ {
3468
+ syntax: "control",
3469
+ action: name.text
3470
+ },
3471
+ checkTemplateClose(tokens, index + 1, false),
3472
+ 0
3473
+ ];
3474
+ case "elif":
3475
+ case "else":
3476
+ case "endif":
3477
+ case "endfor":
3478
+ case "endmacro": throw buildTemplateFormatError(name, `writes {% ${name.text} %}, which closes no open block`);
3479
+ default: throw buildTemplateFormatError(name, `uses the tag ${quoteTemplateText(name.text)}, which the subset does not admit`, { feature: name.text });
3480
+ }
3481
+ }
3482
+ /**
3483
+ * Compiles a Jinja `if` / `elif` / `else` / `endif` conditional block.
3484
+ *
3485
+ * @param tokens - The scanned token stream
3486
+ * @param index - The token index after `if` or `elif`
3487
+ * @param depth - Current statement nesting depth
3488
+ * @param loop - If `true`, inside a `for` loop; if `false`, outside
3489
+ * @param spans - Optional operation-owned span recorder
3490
+ * @returns The compiled `if` node, token index after `{% endif %}`, and subtree height
3491
+ *
3492
+ * @example
3493
+ * ```ts
3494
+ * import { compileTemplateIf, scanTemplateTokens } from '@orkestrel/template'
3495
+ *
3496
+ * compileTemplateIf(scanTemplateTokens('{% if x %}A{% endif %}'), 2, 0, false)[0].syntax // 'if'
3497
+ * ```
3498
+ */
3499
+ function compileTemplateIf(tokens, index, depth, loop, spans) {
3500
+ const start = readTemplateToken(tokens, index);
3501
+ checkTemplateDepth(depth, start);
3502
+ const [condition, next, conditionHeight] = compileTemplateExpression(tokens, index, depth + 1, false);
3503
+ const [body, end, bodyHeight] = compileTemplateStatements(tokens, checkTemplateClose(tokens, next, true), depth + 1, [
3504
+ "elif",
3505
+ "else",
3506
+ "endif"
3507
+ ], loop, spans);
3508
+ const branchOpen = readTemplateToken(tokens, end);
3509
+ const branch = readTemplateToken(tokens, end + 1);
3510
+ if (branch.text === "elif") {
3511
+ const [alternate, after, alternateHeight] = compileTemplateIf(tokens, end + 2, depth + 1, loop, spans);
3512
+ const closeToken = readTemplateToken(tokens, after - 1);
3513
+ spans?.set(alternate, {
3514
+ start: branchOpen.start,
3515
+ end: closeToken.end
3516
+ });
3517
+ const height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight);
3518
+ checkTemplateDepth(height, start);
3519
+ return [
3520
+ {
3521
+ syntax: "if",
3522
+ condition,
3523
+ body,
3524
+ alternate: [alternate]
3525
+ },
3526
+ after,
3527
+ height
3528
+ ];
3529
+ }
3530
+ if (branch.text === "else") {
3531
+ const [alternate, close, alternateHeight] = compileTemplateStatements(tokens, checkTemplateClose(tokens, end + 2, true), depth + 1, ["endif"], loop, spans);
3532
+ const height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight);
3533
+ checkTemplateDepth(height, start);
3534
+ return [
3535
+ {
3536
+ syntax: "if",
3537
+ condition,
3538
+ body,
3539
+ alternate
3540
+ },
3541
+ checkTemplateClose(tokens, close + 2, false),
3542
+ height
3543
+ ];
3544
+ }
3545
+ const height = 1 + Math.max(conditionHeight, bodyHeight);
3546
+ checkTemplateDepth(height, start);
3547
+ return [
3548
+ {
3549
+ syntax: "if",
3550
+ condition,
3551
+ body
3552
+ },
3553
+ checkTemplateClose(tokens, end + 2, false),
3554
+ height
3555
+ ];
3556
+ }
3557
+ /**
3558
+ * Compiles a Jinja `for` loop supporting single targets and multi-target tuple
3559
+ * unpacking through `{% endfor %}`.
3560
+ *
3561
+ * @param tokens - The scanned token stream
3562
+ * @param index - The token index after `for`
3563
+ * @param depth - Current statement nesting depth
3564
+ * @param spans - Optional operation-owned span recorder
3565
+ * @returns The compiled `for` node, token index after `{% endfor %}`, and subtree height
3566
+ *
3567
+ * @example
3568
+ * ```ts
3569
+ * import { compileTemplateFor, scanTemplateTokens } from '@orkestrel/template'
3570
+ *
3571
+ * compileTemplateFor(scanTemplateTokens('{% for k, v in d|items %}{% endfor %}'), 2, 0)[0]
3572
+ * ```
3573
+ */
3574
+ function compileTemplateFor(tokens, index, depth, spans) {
3575
+ const firstTarget = readTemplateToken(tokens, index);
3576
+ checkTemplateDepth(depth, firstTarget);
3577
+ const targets = [];
3578
+ let position = index;
3579
+ for (let step = 0; step < tokens.length; step += 1) {
3580
+ const target = readTemplateToken(tokens, position);
3581
+ checkTemplateTarget(target);
3582
+ if (target.text === "loop") throw buildTemplateFormatError(target, "names \"loop\" as a for loop's target, which Jinja refuses");
3583
+ if (targets.includes(target.text)) throw buildTemplateFormatError(target, `duplicates the for loop target ${quoteTemplateText(target.text)}`);
3584
+ targets.push(target.text);
3585
+ position += 1;
3586
+ if (!matchesTemplateToken(readTemplateToken(tokens, position), "operator", ",")) break;
3587
+ position += 1;
3588
+ }
3589
+ checkTemplateToken(tokens, position, "name", "in");
3590
+ const [sequence, next, sequenceHeight] = compileTemplateExpression(tokens, position + 1, depth + 1, false);
3591
+ const following = readTemplateToken(tokens, next);
3592
+ const feature = matchesTemplateToken(following, "name", "if") ? "loop filter" : matchesTemplateToken(following, "name", "recursive") ? "recursive loop" : void 0;
3593
+ if (feature !== void 0) throw buildTemplateFormatError(following, `writes a ${feature}, which the subset does not admit`, { feature });
3594
+ const [body, end, bodyHeight] = compileTemplateStatements(tokens, checkTemplateClose(tokens, next, true), depth + 1, ["endfor", "else"], true, spans);
3595
+ const branch = readTemplateToken(tokens, end + 1);
3596
+ if (branch.text === "else") throw buildTemplateFormatError(branch, "writes {% else %} on a for loop, which the subset does not admit", { feature: "for else" });
3597
+ const height = 1 + Math.max(sequenceHeight, bodyHeight);
3598
+ checkTemplateDepth(height, firstTarget);
3599
+ return [
3600
+ {
3601
+ syntax: "for",
3602
+ targets,
3603
+ sequence,
3604
+ body
3605
+ },
3606
+ checkTemplateClose(tokens, end + 2, false),
3607
+ height
3608
+ ];
3609
+ }
3610
+ /**
3611
+ * Compiles a Jinja `{% macro name(a, b=default) %} ... {% endmacro %}` block.
3612
+ *
3613
+ * @param tokens - The scanned token stream
3614
+ * @param index - The token index after `macro`
3615
+ * @param depth - Current statement nesting depth
3616
+ * @param spans - Optional operation-owned span recorder
3617
+ * @returns The compiled `macro` node, token index after `{% endmacro %}`, and subtree height
3618
+ *
3619
+ * @example
3620
+ * ```ts
3621
+ * import { compileTemplateMacro, scanTemplateTokens } from '@orkestrel/template'
3622
+ *
3623
+ * compileTemplateMacro(scanTemplateTokens('{% macro greet(name="Ada") %}{{ name }}{% endmacro %}'), 2, 0)[0].syntax // 'macro'
3624
+ * ```
3625
+ */
3626
+ function compileTemplateMacro(tokens, index, depth, spans) {
3627
+ const macroName = readTemplateToken(tokens, index);
3628
+ checkTemplateDepth(depth, macroName);
3629
+ checkTemplateTarget(macroName);
3630
+ if (macroName.text === "loop") throw buildTemplateFormatError(macroName, "names \"loop\" as a macro, which Jinja refuses");
3631
+ checkTemplateToken(tokens, index + 1, "operator", "(");
3632
+ const parameters = [];
3633
+ const heights = [];
3634
+ let position = index + 2;
3635
+ let seenDefault = false;
3636
+ for (let step = 0; step < tokens.length; step += 1) {
3637
+ if (matchesTemplateToken(readTemplateToken(tokens, position), "operator", ")")) break;
3638
+ const later = parameters.length > 0;
3639
+ if (later) {
3640
+ checkTemplateToken(tokens, position, "operator", ",");
3641
+ position += 1;
3642
+ }
3643
+ const head = readTemplateToken(tokens, position);
3644
+ if (later && matchesTemplateToken(head, "operator", ")")) break;
3645
+ if (matchesTemplateToken(head, "operator", "*") || matchesTemplateToken(head, "operator", "**")) throw buildTemplateFormatError(head, "writes parameter unpacking in a macro, which the subset does not admit", { feature: "argument unpacking" });
3646
+ checkTemplateTarget(head);
3647
+ if (parameters.some((parameter) => parameter.name === head.text)) throw buildTemplateFormatError(head, `duplicates the macro parameter ${quoteTemplateText(head.text)}`);
3648
+ if (matchesTemplateToken(readTemplateToken(tokens, position + 1), "operator", "=")) {
3649
+ seenDefault = true;
3650
+ const [fallback, next, fallbackHeight] = compileTemplateExpression(tokens, position + 2, depth + 1, true);
3651
+ parameters.push({
3652
+ name: head.text,
3653
+ fallback
3654
+ });
3655
+ heights.push(fallbackHeight);
3656
+ position = next;
3657
+ } else {
3658
+ if (seenDefault) throw buildTemplateFormatError(head, `places non-default parameter ${quoteTemplateText(head.text)} after a default parameter`);
3659
+ parameters.push({ name: head.text });
3660
+ position += 1;
3661
+ }
3662
+ }
3663
+ checkTemplateToken(tokens, position, "operator", ")");
3664
+ const [body, end, bodyHeight] = compileTemplateStatements(tokens, checkTemplateClose(tokens, position + 1, true), depth + 1, ["endmacro"], false, spans);
3665
+ const height = 1 + Math.max(bodyHeight, heights.reduce((top, value) => Math.max(top, value), 0));
3666
+ checkTemplateDepth(height, macroName);
3667
+ return [
3668
+ {
3669
+ syntax: "macro",
3670
+ name: macroName.text,
3671
+ parameters,
3672
+ body
3673
+ },
3674
+ checkTemplateClose(tokens, end + 2, false),
3675
+ height
3676
+ ];
3677
+ }
3678
+ /**
3679
+ * Compiles one Jinja expression (`or` / `and` / `not` / comparisons / tests /
3680
+ * arithmetic / postfix / filters), plus inline `if ... else ...` when admitted.
3681
+ *
3682
+ * @param tokens - The scanned token stream
3683
+ * @param index - Starting token index
3684
+ * @param depth - Current expression depth
3685
+ * @param conditional - If `true`, admits inline `x if c else y`; if `false`, stops before `if`
3686
+ * @returns The compiled expression, next token index, and expression height
3687
+ *
3688
+ * @example
3689
+ * ```ts
3690
+ * import { compileTemplateExpression, scanTemplateTokens } from '@orkestrel/template'
3691
+ *
3692
+ * compileTemplateExpression(scanTemplateTokens("{{ 'a' if x else 'b' }}"), 1, 1, true)[0].term // 'conditional'
3693
+ * ```
3694
+ */
3695
+ function compileTemplateExpression(tokens, index, depth, conditional) {
3696
+ const start = readTemplateToken(tokens, index);
3697
+ checkTemplateDepth(depth, start);
3698
+ const [value, next, height] = compileTemplateChain(tokens, index, depth, ["or"], (inner, at, level) => compileTemplateChain(inner, at, level, ["and"], compileTemplateNegation));
3699
+ const branch = readTemplateToken(tokens, next);
3700
+ if (!conditional || !matchesTemplateToken(branch, "name", "if")) return [
3701
+ value,
3702
+ next,
3703
+ height
3704
+ ];
3705
+ const [condition, after, conditionHeight] = compileTemplateChain(tokens, next + 1, depth + 1, ["or"], (inner, at, level) => compileTemplateChain(inner, at, level, ["and"], compileTemplateNegation));
3706
+ if (!matchesTemplateToken(readTemplateToken(tokens, after), "name", "else")) throw buildTemplateFormatError(branch, "writes an inline if without else, which the subset does not admit", { feature: "conditional without else" });
3707
+ const [alternate, end, alternateHeight] = compileTemplateExpression(tokens, after + 1, depth + 1, true);
3708
+ const total = 1 + Math.max(height, conditionHeight, alternateHeight);
3709
+ checkTemplateDepth(total, start);
3710
+ return [
3711
+ {
3712
+ term: "conditional",
3713
+ condition,
3714
+ consequent: value,
3715
+ alternate
3716
+ },
3717
+ end,
3718
+ total
3719
+ ];
3720
+ }
3721
+ /**
3722
+ * Compiles a left-associative binary operator chain at one precedence level.
3723
+ *
3724
+ * @param tokens - The scanned token stream
3725
+ * @param index - Starting token index
3726
+ * @param depth - Current expression depth
3727
+ * @param operators - Operators admitted at this precedence level
3728
+ * @param operand - Compiler for the next tighter precedence level
3729
+ * @returns The compiled expression, next token index, and expression height
3730
+ *
3731
+ * @example
3732
+ * ```ts
3733
+ * import { compileTemplateChain, compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'
3734
+ *
3735
+ * compileTemplateChain(scanTemplateTokens("{{ 'a' ~ 'b' }}"), 1, 1, ['~'], compileTemplateUnary)[0].term // 'binary'
3736
+ * ```
3737
+ */
3738
+ function compileTemplateChain(tokens, index, depth, operators, operand) {
3739
+ const start = readTemplateToken(tokens, index);
3740
+ checkTemplateDepth(depth, start);
3741
+ const [first, after, firstHeight] = operand(tokens, index, depth);
3742
+ let expression = first;
3743
+ let height = firstHeight;
3744
+ let position = after;
3745
+ for (let step = 0; step < tokens.length; step += 1) {
3746
+ const token = readTemplateToken(tokens, position);
3747
+ const operator = operators.find((candidate) => (token.token === "name" || token.token === "operator") && token.text === candidate);
3748
+ if (operator === void 0) break;
3749
+ const [right, next, rightHeight] = operand(tokens, position + 1, depth + 1);
3750
+ expression = {
3751
+ term: "binary",
3752
+ operator,
3753
+ left: expression,
3754
+ right
3755
+ };
3756
+ height = 1 + Math.max(height, rightHeight);
3757
+ checkTemplateDepth(height, start);
3758
+ position = next;
3759
+ }
3760
+ return [
3761
+ expression,
3762
+ position,
3763
+ height
3764
+ ];
3765
+ }
69
3766
  /**
70
- * Narrows an unknown caught value to a {@link TemplateError}.
3767
+ * Compiles logical `not` negation over comparisons.
71
3768
  *
72
- * @remarks
73
- * Recognizes self-branded errors from other package copies and subclasses, and
74
- * refuses transparent proxies and unbranded look-alikes.
3769
+ * @param tokens - The scanned token stream
3770
+ * @param index - Starting token index
3771
+ * @param depth - Current expression depth
3772
+ * @returns The compiled expression, next token index, and expression height
75
3773
  *
76
- * @param value - The value to test (typically a `catch` binding)
77
- * @returns True if `value` is a {@link TemplateError}; false otherwise
3774
+ * @example
3775
+ * ```ts
3776
+ * import { compileTemplateNegation, scanTemplateTokens } from '@orkestrel/template'
3777
+ *
3778
+ * compileTemplateNegation(scanTemplateTokens('{{ not x }}'), 1, 1)[0].term // 'unary'
3779
+ * ```
3780
+ */
3781
+ function compileTemplateNegation(tokens, index, depth) {
3782
+ const token = readTemplateToken(tokens, index);
3783
+ checkTemplateDepth(depth, token);
3784
+ if (!matchesTemplateToken(token, "name", "not")) return compileTemplateComparison(tokens, index, depth);
3785
+ const [value, next, height] = compileTemplateNegation(tokens, index + 1, depth + 1);
3786
+ checkTemplateDepth(height + 1, token);
3787
+ return [
3788
+ {
3789
+ term: "unary",
3790
+ operator: "not",
3791
+ value
3792
+ },
3793
+ next,
3794
+ height + 1
3795
+ ];
3796
+ }
3797
+ /**
3798
+ * Compiles chained Python-style comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`,
3799
+ * `in`, `not in`) over test expressions.
3800
+ *
3801
+ * @param tokens - The scanned token stream
3802
+ * @param index - Starting token index
3803
+ * @param depth - Current expression depth
3804
+ * @returns The compiled expression, next token index, and expression height
78
3805
  *
79
3806
  * @example
80
3807
  * ```ts
81
- * import { isTemplateError } from '@src/core'
3808
+ * import { compileTemplateComparison, scanTemplateTokens } from '@orkestrel/template'
82
3809
  *
83
- * try {
84
- * manager.fill('missing')
85
- * } catch (error) {
86
- * if (isTemplateError(error) && error.code === 'NOTFOUND') return
87
- * }
3810
+ * compileTemplateComparison(scanTemplateTokens("{{ role not in 'system' }}"), 1, 1)[0].term // 'binary'
88
3811
  * ```
89
3812
  */
90
- function isTemplateError(value) {
91
- return holds(() => {
92
- if (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false;
93
- if (INTRINSICS.describe(value, Symbol.for("@orkestrel/template.TemplateError"))?.value !== value) return false;
94
- const code = INTRINSICS.reflect.read(value, "code");
95
- const context = INTRINSICS.reflect.read(value, "context");
96
- return (code === "MISSING" || code === "NOTFOUND" || code === "INVALID" || code === "CONFLICT") && (context === void 0 || isObject(context) || isFunction(context));
3813
+ function compileTemplateComparison(tokens, index, depth) {
3814
+ const start = readTemplateToken(tokens, index);
3815
+ checkTemplateDepth(depth, start);
3816
+ const [first, after, firstHeight] = compileTemplateTest(tokens, index, depth);
3817
+ const links = [];
3818
+ let position = after;
3819
+ for (let step = 0; step < tokens.length; step += 1) {
3820
+ const token = readTemplateToken(tokens, position);
3821
+ const negated = matchesTemplateToken(token, "name", "not") && matchesTemplateToken(readTemplateToken(tokens, position + 1), "name", "in");
3822
+ const operator = token.token === "operator" && isTemplateComparison(token.text) ? token.text : matchesTemplateToken(token, "name", "in") ? "in" : negated ? "not in" : void 0;
3823
+ if (operator === void 0) break;
3824
+ const [operand, next, height] = compileTemplateTest(tokens, position + (negated ? 2 : 1), depth + 1);
3825
+ links.push([
3826
+ operator,
3827
+ operand,
3828
+ height
3829
+ ]);
3830
+ position = next;
3831
+ }
3832
+ const pairs = links.map(([operator, operand, height], link) => {
3833
+ const left = links[link - 1];
3834
+ return [{
3835
+ term: "binary",
3836
+ operator,
3837
+ left: left?.[1] ?? first,
3838
+ right: operand
3839
+ }, 1 + Math.max(left?.[2] ?? firstHeight, height)];
97
3840
  });
3841
+ const [joined, joinedHeight] = pairs.slice(1).reduce((left, right) => [{
3842
+ term: "binary",
3843
+ operator: "and",
3844
+ left: left[0],
3845
+ right: right[0]
3846
+ }, 1 + Math.max(left[1], right[1])], pairs[0] ?? [first, firstHeight]);
3847
+ checkTemplateDepth(joinedHeight, start);
3848
+ return [
3849
+ joined,
3850
+ position,
3851
+ joinedHeight
3852
+ ];
98
3853
  }
99
- // src/core/helpers.ts
100
3854
  /**
101
- * Formats a resolved fill value for substitution into a template's `content`.
3855
+ * Compiles an additive expression optionally followed by a Jinja `is` or
3856
+ * `is not` test (`defined`, `undefined`, `none`, `string`, `mapping`,
3857
+ * `iterable`, `sequence`, `true`, `false`).
102
3858
  *
103
- * @remarks
104
- * A finite number renders with the given locale's thousand grouping (through
105
- * `toLocaleString`); every other value — including `null` — String-coerces.
106
- * `null` therefore renders as the literal string `'null'`, matching
107
- * `String(value)` exactly, so a resolved `null` is visible in the output
108
- * rather than silently empty. An
109
- * invalid BCP-47 `locale` tag throws a `RangeError` from the underlying
110
- * `toLocaleString` call when `value` is a finite number — this is a caller
111
- * error (an invalid locale argument), by design, and is not caught here.
112
- *
113
- * @param value - The resolved value to format
114
- * @param locale - The locale used for finite-number formatting
115
- * @returns The formatted string
3859
+ * @param tokens - The scanned token stream
3860
+ * @param index - Starting token index
3861
+ * @param depth - Current expression depth
3862
+ * @returns The compiled expression, next token index, and expression height
116
3863
  *
117
3864
  * @example
118
3865
  * ```ts
119
- * import { formatValue } from '@src/core'
3866
+ * import { compileTemplateTest, scanTemplateTokens } from '@orkestrel/template'
120
3867
  *
121
- * formatValue(5010, 'en-US') // '5,010'
122
- * formatValue(null, 'en-US') // 'null'
3868
+ * compileTemplateTest(scanTemplateTokens('{{ x is not mapping }}'), 1, 1)[0].term // 'test'
123
3869
  * ```
124
3870
  */
125
- function formatValue(value, locale) {
126
- if (isFiniteNumber(value)) return value.toLocaleString(locale);
127
- return String(value);
3871
+ function compileTemplateTest(tokens, index, depth) {
3872
+ const start = readTemplateToken(tokens, index);
3873
+ checkTemplateDepth(depth, start);
3874
+ const [value, next, valueHeight] = compileTemplateSum(tokens, index, depth);
3875
+ if (!matchesTemplateToken(readTemplateToken(tokens, next), "name", "is")) return [
3876
+ value,
3877
+ next,
3878
+ valueHeight
3879
+ ];
3880
+ const negated = matchesTemplateToken(readTemplateToken(tokens, next + 1), "name", "not");
3881
+ const at = next + (negated ? 2 : 1);
3882
+ const name = readTemplateToken(tokens, at);
3883
+ if (name.token !== "name") throw buildTemplateFormatError(name, `expects a test name and finds ${renderTemplateToken(name)}`);
3884
+ const dotted = matchesTemplateToken(readTemplateToken(tokens, at + 1), "operator", ".");
3885
+ if (dotted || !TEMPLATE_TESTS.some((admitted) => admitted === name.text)) {
3886
+ const spelled = dotted ? `${name.text}.${readTemplateToken(tokens, at + 2).text}` : name.text;
3887
+ throw buildTemplateFormatError(name, `uses the test ${quoteTemplateText(spelled)}, which the subset does not admit`, { feature: spelled });
3888
+ }
3889
+ const following = readTemplateToken(tokens, at + 1);
3890
+ const empty = matchesTemplateToken(following, "operator", "(") && matchesTemplateToken(readTemplateToken(tokens, at + 2), "operator", ")");
3891
+ const argued = !empty && (matchesTemplateToken(following, "operator", "(") || matchesTemplateToken(following, "operator", "[") || matchesTemplateToken(following, "operator", "{") || [
3892
+ "string",
3893
+ "integer",
3894
+ "float"
3895
+ ].includes(following.token) || following.token === "name" && ![
3896
+ "else",
3897
+ "or",
3898
+ "and",
3899
+ "in",
3900
+ "not"
3901
+ ].includes(following.text));
3902
+ if (matchesTemplateToken(following, "name", "is")) throw buildTemplateFormatError(following, "chains two tests with \"is\", which Jinja refuses");
3903
+ if (argued) throw buildTemplateFormatError(following, "passes test arguments, which the subset does not admit", { feature: "test arguments" });
3904
+ const cursor = at + (empty ? 3 : 1);
3905
+ if (matchesTemplateToken(readTemplateToken(tokens, cursor), "name", "is")) throw buildTemplateFormatError(readTemplateToken(tokens, cursor), "chains two tests with \"is\", which Jinja refuses");
3906
+ const height = valueHeight + 1;
3907
+ checkTemplateDepth(height, start);
3908
+ return [
3909
+ {
3910
+ term: "test",
3911
+ name: name.text,
3912
+ value,
3913
+ negated
3914
+ },
3915
+ cursor,
3916
+ height
3917
+ ];
128
3918
  }
129
3919
  /**
130
- * Resolves a field path against a fill-values record, refusing any path that
131
- * touches a prototype-pollution-unsafe segment.
3920
+ * Compiles a left-associative `+` / `-` chain over `~` concatenations.
132
3921
  *
133
- * @remarks
134
- * A prototype-pollution guard shared by `fillTemplate` and `Template#validate`
135
- * so the two stay in lockstep: `path` normalizes to a segment array (a bare
136
- * string `path` becomes a single-segment array); if any segment appears in
137
- * `UNSAFE_FIELD_SEGMENTS` (`'__proto__'`, `'constructor'`, `'prototype'`), the
138
- * lookup is refused and `undefined` is returned without ever calling
139
- * `resolveField` — a path like `['__proto__', 'polluted']` can never reach
140
- * the record's actual prototype chain through this function. Every other
141
- * path resolves through `@orkestrel/contract`'s `resolveField`.
3922
+ * @param tokens - The scanned token stream
3923
+ * @param index - Starting token index
3924
+ * @param depth - Current expression depth
3925
+ * @returns The compiled expression, next token index, and expression height
142
3926
  *
143
- * @param record - The fill-values record to resolve against
144
- * @param path - The field path — a single segment or a segment array
145
- * @returns The resolved value, or `undefined` when unresolved or the path is unsafe
3927
+ * @example
3928
+ * ```ts
3929
+ * import { compileTemplateSum, scanTemplateTokens } from '@orkestrel/template'
3930
+ *
3931
+ * compileTemplateSum(scanTemplateTokens('{{ n - 1 }}'), 1, 1)[0].term // 'binary'
3932
+ * ```
3933
+ */
3934
+ function compileTemplateSum(tokens, index, depth) {
3935
+ return compileTemplateChain(tokens, index, depth, ["+", "-"], (inner, at, level) => compileTemplateChain(inner, at, level, ["~"], compileTemplateUnary));
3936
+ }
3937
+ /**
3938
+ * Compiles unary `-`/`+`, primaries, member reads, sequence slices, function
3939
+ * and string method calls, and `|` filter chains.
3940
+ *
3941
+ * @param tokens - The scanned token stream
3942
+ * @param index - Starting token index
3943
+ * @param depth - Current expression depth
3944
+ * @returns The compiled expression, next token index, and expression height
146
3945
  *
147
3946
  * @example
148
3947
  * ```ts
149
- * import { resolveSafeField } from '@src/core'
3948
+ * import { compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'
150
3949
  *
151
- * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1
152
- * resolveSafeField({}, ['__proto__', 'polluted']) // undefined
3950
+ * compileTemplateUnary(scanTemplateTokens('{{ messages[::-1] }}'), 1, 1)[0].term // 'slice'
153
3951
  * ```
154
3952
  */
155
- function resolveSafeField(record, path) {
156
- if ((isArray(path) ? path : [path]).some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return void 0;
157
- return resolveField(record, path);
3953
+ function compileTemplateUnary(tokens, index, depth) {
3954
+ const start = readTemplateToken(tokens, index);
3955
+ checkTemplateDepth(depth, start);
3956
+ if (matchesTemplateToken(start, "operator", "-") || matchesTemplateToken(start, "operator", "+")) {
3957
+ const operator = start.text === "-" ? "-" : "+";
3958
+ const [value, next, height] = compileTemplateUnary(tokens, index + 1, depth + 1);
3959
+ checkTemplateDepth(height + 1, start);
3960
+ return [
3961
+ {
3962
+ term: "unary",
3963
+ operator,
3964
+ value
3965
+ },
3966
+ next,
3967
+ height + 1
3968
+ ];
3969
+ }
3970
+ const [primary, after, primaryHeight] = compileTemplatePrimary(tokens, index, depth);
3971
+ let expression = primary;
3972
+ let height = primaryHeight;
3973
+ let position = after;
3974
+ for (let step = 0; step < tokens.length; step += 1) {
3975
+ const token = readTemplateToken(tokens, position);
3976
+ if (matchesTemplateToken(token, "operator", ".")) {
3977
+ const name = readTemplateToken(tokens, position + 1);
3978
+ if (name.token !== "name" && name.token !== "integer") throw buildTemplateFormatError(name, `expects a name or an integer after "." and finds ${renderTemplateToken(name)}`);
3979
+ const key = {
3980
+ term: "literal",
3981
+ value: name.token === "name" ? name.text : decodeTemplateNumber(name)
3982
+ };
3983
+ checkTemplateLoopMember(expression, key, name);
3984
+ expression = {
3985
+ term: "member",
3986
+ object: expression,
3987
+ key
3988
+ };
3989
+ height = 1 + Math.max(height, 0);
3990
+ position += 2;
3991
+ } else if (matchesTemplateToken(token, "operator", "[")) {
3992
+ const [subscripted, next, subscriptHeight] = compileTemplateSubscript(tokens, position, depth + 1, expression);
3993
+ expression = subscripted;
3994
+ height = 1 + Math.max(height, subscriptHeight);
3995
+ position = next;
3996
+ } else if (matchesTemplateToken(token, "operator", "(")) {
3997
+ if (expression.term !== "name" && expression.term !== "member") throw buildTemplateFormatError(token, "writes a call, which the subset does not admit", { feature: "call" });
3998
+ const [values, keywords, next, valuesHeight] = compileTemplateArguments(tokens, position, depth + 1);
3999
+ expression = {
4000
+ term: "call",
4001
+ callee: expression,
4002
+ values,
4003
+ keywords
4004
+ };
4005
+ height = 1 + Math.max(height, valuesHeight);
4006
+ position = next;
4007
+ } else break;
4008
+ checkTemplateDepth(height, start);
4009
+ }
4010
+ let filtered = expression;
4011
+ let filteredHeight = height;
4012
+ let cursor = position;
4013
+ for (let step = 0; step < tokens.length; step += 1) {
4014
+ const token = readTemplateToken(tokens, cursor);
4015
+ if (!matchesTemplateToken(token, "operator", "|")) {
4016
+ if (matchesTemplateToken(token, "operator", "(")) throw buildTemplateFormatError(token, "calls a filter, which the subset does not admit", { feature: "call" });
4017
+ break;
4018
+ }
4019
+ const name = readTemplateToken(tokens, cursor + 1);
4020
+ if (name.token !== "name") throw buildTemplateFormatError(name, `expects a filter name and finds ${renderTemplateToken(name)}`);
4021
+ const dotted = matchesTemplateToken(readTemplateToken(tokens, cursor + 2), "operator", ".");
4022
+ if (dotted || !TEMPLATE_FILTERS.some((admitted) => admitted === name.text)) {
4023
+ const spelled = dotted ? `${name.text}.${readTemplateToken(tokens, cursor + 3).text}` : name.text;
4024
+ throw buildTemplateFormatError(name, `uses the filter ${quoteTemplateText(spelled)}, which the subset does not admit`, { feature: spelled });
4025
+ }
4026
+ const following = readTemplateToken(tokens, cursor + 2);
4027
+ const empty = matchesTemplateToken(following, "operator", "(") && matchesTemplateToken(readTemplateToken(tokens, cursor + 3), "operator", ")");
4028
+ if (!empty && matchesTemplateToken(following, "operator", "(")) throw buildTemplateFormatError(following, "passes filter arguments, which the subset does not admit", { feature: "filter arguments" });
4029
+ filtered = {
4030
+ term: "filter",
4031
+ name: name.text,
4032
+ value: filtered
4033
+ };
4034
+ filteredHeight += 1;
4035
+ cursor = cursor + (empty ? 4 : 2);
4036
+ checkTemplateDepth(filteredHeight, start);
4037
+ }
4038
+ const following = readTemplateToken(tokens, cursor);
4039
+ const arithmetic = following.token === "operator" && keyOf(TEMPLATE_OPERATOR_FEATURES)(following.text) ? TEMPLATE_OPERATOR_FEATURES[following.text] : void 0;
4040
+ if (arithmetic !== void 0) throw buildTemplateFormatError(following, `writes ${arithmetic}, which the subset does not admit`, { feature: arithmetic });
4041
+ return [
4042
+ filtered,
4043
+ cursor,
4044
+ filteredHeight
4045
+ ];
158
4046
  }
159
4047
  /**
160
- * Resolves one `{{name}}` token against the declared placeholders and the
161
- * fill-values record.
4048
+ * Compiles one primary template expression: a literal, name, adjacent string
4049
+ * concatenation, or parenthesized sub-expression.
162
4050
  *
163
- * @remarks
164
- * The single implementation of the token rule `fillTemplate` and
165
- * `Template#validate` both apply, so the two can never drift: the declared
166
- * {@link TemplatePlaceholder} sharing the token's `name` (exact match)
167
- * supplies its `path`, falling back to the token split on `.`; the value
168
- * resolves through `resolveSafeField`, so any segment in
169
- * `UNSAFE_FIELD_SEGMENTS` yields `undefined` without ever calling
170
- * `resolveField`; `required` is `true` for an undeclared token and for a
171
- * declared placeholder whose `required` is not `false`. The token is passed
172
- * already trimmed. `fallback` is not applied here — it is read from
173
- * `declared` by each caller, because `fill` substitutes it and `validate`
174
- * only counts it.
4051
+ * @param tokens - The scanned token stream
4052
+ * @param index - Token index of the primary
4053
+ * @param depth - Current expression depth
4054
+ * @returns The compiled expression, next token index, and expression height
175
4055
  *
176
- * @param record - The fill-values record the token resolves against
177
- * @param placeholders - The declared placeholders the token matches by name
178
- * @param token - The trimmed token text, without its `{{` / `}}` delimiters
179
- * @returns The {@link TemplateTokenResolution} for the token
4056
+ * @example
4057
+ * ```ts
4058
+ * import { compileTemplatePrimary, scanTemplateTokens } from '@orkestrel/template'
4059
+ *
4060
+ * compileTemplatePrimary(scanTemplateTokens("{{ 'a' 'b' }}"), 1, 1)[0] // { term: 'literal', value: 'ab' }
4061
+ * ```
4062
+ */
4063
+ function compileTemplatePrimary(tokens, index, depth) {
4064
+ const token = readTemplateToken(tokens, index);
4065
+ checkTemplateDepth(depth, token);
4066
+ switch (token.token) {
4067
+ case "name":
4068
+ if (keyOf(TEMPLATE_LITERALS)(token.text)) return [
4069
+ {
4070
+ term: "literal",
4071
+ value: TEMPLATE_LITERALS[token.text]
4072
+ },
4073
+ index + 1,
4074
+ 0
4075
+ ];
4076
+ if (!((token.text === "raise_exception" || token.text === "namespace") && matchesTemplateToken(readTemplateToken(tokens, index + 1), "operator", "(")) && TEMPLATE_FUNCTIONS.some((name) => name === token.text)) throw buildTemplateFormatError(token, `uses the function ${quoteTemplateText(token.text)}, which the subset does not admit`, { feature: token.text });
4077
+ return [
4078
+ {
4079
+ term: "name",
4080
+ name: token.text
4081
+ },
4082
+ index + 1,
4083
+ 0
4084
+ ];
4085
+ case "string": {
4086
+ const parts = [];
4087
+ let position = index;
4088
+ for (let step = 0; step < tokens.length; step += 1) {
4089
+ const part = readTemplateToken(tokens, position);
4090
+ if (part.token !== "string") break;
4091
+ parts.push(decodeTemplateString(part));
4092
+ position += 1;
4093
+ }
4094
+ return [
4095
+ {
4096
+ term: "literal",
4097
+ value: parts.join("")
4098
+ },
4099
+ position,
4100
+ 0
4101
+ ];
4102
+ }
4103
+ case "integer":
4104
+ case "float": return [
4105
+ {
4106
+ term: "literal",
4107
+ value: decodeTemplateNumber(token)
4108
+ },
4109
+ index + 1,
4110
+ 0
4111
+ ];
4112
+ case "operator":
4113
+ if (token.text === "(") {
4114
+ if (matchesTemplateToken(readTemplateToken(tokens, index + 1), "operator", ")")) throw buildTemplateFormatError(token, "writes an empty tuple, which the subset does not admit", { feature: "tuple" });
4115
+ const [inner, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true);
4116
+ if (matchesTemplateToken(readTemplateToken(tokens, next), "operator", ",")) throw buildTemplateFormatError(token, "writes a tuple, which the subset does not admit", { feature: "tuple" });
4117
+ checkTemplateToken(tokens, next, "operator", ")");
4118
+ return [
4119
+ inner,
4120
+ next + 1,
4121
+ height
4122
+ ];
4123
+ }
4124
+ if (token.text === "[" || token.text === "{") {
4125
+ const feature = token.text === "[" ? "list literal" : "dict literal";
4126
+ throw buildTemplateFormatError(token, `writes a ${feature}, which the subset does not admit`, { feature });
4127
+ }
4128
+ throw buildTemplateFormatError(token, `expects a value and finds ${renderTemplateToken(token)}`);
4129
+ default: throw buildTemplateFormatError(token, `expects a value and finds ${renderTemplateToken(token)}`);
4130
+ }
4131
+ }
4132
+ /**
4133
+ * Compiles positional and named keyword arguments of a call from `(` through `)`.
4134
+ *
4135
+ * @param tokens - The scanned token stream
4136
+ * @param index - Token index of the opening `(`
4137
+ * @param depth - Current expression depth
4138
+ * @returns Positional arguments, keyword arguments, next token index, and max height
180
4139
  *
181
4140
  * @example
182
4141
  * ```ts
183
- * import { resolveToken } from '@src/core'
4142
+ * import { compileTemplateArguments, scanTemplateTokens } from '@orkestrel/template'
184
4143
  *
185
- * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'
186
- * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false
4144
+ * compileTemplateArguments(scanTemplateTokens('{{ namespace(value=0) }}'), 2, 1)[1][0]?.name // 'value'
187
4145
  * ```
188
4146
  */
189
- function resolveToken(record, placeholders, token) {
190
- const declared = placeholders.find((placeholder) => placeholder.name === token);
191
- return {
192
- value: resolveSafeField(record, declared?.path ?? token.split(".")),
193
- declared,
194
- required: declared === void 0 || declared.required !== false
195
- };
4147
+ function compileTemplateArguments(tokens, index, depth) {
4148
+ checkTemplateDepth(depth, readTemplateToken(tokens, index));
4149
+ checkTemplateToken(tokens, index, "operator", "(");
4150
+ const values = [];
4151
+ const keywords = [];
4152
+ const heights = [];
4153
+ let position = index + 1;
4154
+ for (let step = 0; step < tokens.length; step += 1) {
4155
+ if (matchesTemplateToken(readTemplateToken(tokens, position), "operator", ")")) break;
4156
+ const later = position > index + 1;
4157
+ if (later) checkTemplateToken(tokens, position, "operator", ",");
4158
+ const at = later ? position + 1 : position;
4159
+ const head = readTemplateToken(tokens, at);
4160
+ if (later && matchesTemplateToken(head, "operator", ")")) {
4161
+ position = at;
4162
+ break;
4163
+ }
4164
+ if (matchesTemplateToken(head, "operator", "*") || matchesTemplateToken(head, "operator", "**")) throw buildTemplateFormatError(head, "passes argument unpacking, which the subset does not admit", { feature: "argument unpacking" });
4165
+ if (head.token === "name" && matchesTemplateToken(readTemplateToken(tokens, at + 1), "operator", "=")) {
4166
+ if (keywords.some((keyword) => keyword.name === head.text)) throw buildTemplateFormatError(head, `duplicates the keyword argument ${quoteTemplateText(head.text)}`);
4167
+ const [value, next, height] = compileTemplateExpression(tokens, at + 2, depth + 1, true);
4168
+ keywords.push({
4169
+ name: head.text,
4170
+ value
4171
+ });
4172
+ heights.push(height);
4173
+ position = next;
4174
+ continue;
4175
+ }
4176
+ if (keywords.length > 0) throw buildTemplateFormatError(head, "places a positional argument after a keyword argument");
4177
+ const [value, next, height] = compileTemplateExpression(tokens, at, depth + 1, true);
4178
+ values.push(value);
4179
+ heights.push(height);
4180
+ position = next;
4181
+ }
4182
+ checkTemplateToken(tokens, position, "operator", ")");
4183
+ return [
4184
+ values,
4185
+ keywords,
4186
+ position + 1,
4187
+ heights.reduce((top, height) => Math.max(top, height), 0)
4188
+ ];
196
4189
  }
197
4190
  /**
198
- * Substitutes every `{{name}}` token in `content` in a single pass.
4191
+ * Compiles one `[key]` member lookup or `[start:stop:step]` slice subscript
4192
+ * starting at `[` and ending after `]`.
199
4193
  *
200
- * @remarks
201
- * Uses a fresh `RegExp` clone of `FILL_PATTERN` per call (never sharing its
202
- * `lastIndex`) and a single `String#replace` scan — substituted output is
203
- * never re-scanned. Each token resolves through `resolveToken`, the one rule
204
- * `Template#validate` also applies: the matching declared
205
- * {@link TemplatePlaceholder} (exact `name`) supplies its `path` (falling
206
- * back to the token split on `.`); any path segment in `UNSAFE_FIELD_SEGMENTS`
207
- * makes the token unresolved without ever calling `resolveField` (a
208
- * prototype-pollution guard). A resolved value formats through `formatValue`; an
209
- * unresolved value falls back to the placeholder's `fallback` when declared;
210
- * otherwise `options.missing` governs — `'literal'` re-emits the original
211
- * `{{name}}` text, `'empty'` emits `''`, and `'error'` emits `''` for every
212
- * token but collects every unresolved required token (an undeclared token, or
213
- * a declared token with `required !== false`) and throws one
214
- * {@link TemplateError} coded `MISSING` listing them all, in first-appearance
215
- * order, once the scan completes. An escaped `\{{` emits a literal `{{`.
216
- *
217
- * Called with no declared `placeholders` and `{ missing: 'empty' }`, this is a
218
- * bare interpolation over `content` — every token resolves by dotted path
219
- * against the values record and every unresolved token emits `''`.
220
- * `FILL_PATTERN`'s token class (`[^{}]`) excludes `{`, so a token containing
221
- * `{` never matches and the surrounding `{{` stays literal.
4194
+ * @param tokens - The scanned token stream
4195
+ * @param index - Token index of the opening `[`
4196
+ * @param depth - Current expression depth
4197
+ * @param object - The target expression being indexed or sliced
4198
+ * @returns The compiled member or slice expression, next token index, and argument height
222
4199
  *
223
- * @param content - The template content carrying `{{name}}` tokens
224
- * @param values - The values tokens resolve against
225
- * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and the declared `placeholders` (default none) tokens resolve against
226
- * @returns The substituted content
4200
+ * @example
4201
+ * ```ts
4202
+ * import { compileTemplateSubscript, scanTemplateTokens } from '@orkestrel/template'
4203
+ *
4204
+ * compileTemplateSubscript(scanTemplateTokens('{{ a[::-1] }}'), 2, 1, { term: 'name', name: 'a' })[0].term // 'slice'
4205
+ * ```
4206
+ */
4207
+ function compileTemplateSubscript(tokens, index, depth, object) {
4208
+ checkTemplateDepth(depth, readTemplateToken(tokens, index));
4209
+ const first = readTemplateToken(tokens, index + 1);
4210
+ if (matchesTemplateToken(first, "operator", "]")) throw buildTemplateFormatError(first, "writes an empty subscript");
4211
+ const [sliceStart, afterStart, startHeight] = matchesTemplateToken(first, "operator", ":") ? [
4212
+ void 0,
4213
+ index + 1,
4214
+ 0
4215
+ ] : compileTemplateExpression(tokens, index + 1, depth, true);
4216
+ const separator = readTemplateToken(tokens, afterStart);
4217
+ if (matchesTemplateToken(separator, "operator", ",")) throw buildTemplateFormatError(separator, "writes a tuple subscript, which the subset does not admit", { feature: "tuple" });
4218
+ if (!matchesTemplateToken(separator, "operator", ":")) {
4219
+ checkTemplateToken(tokens, afterStart, "operator", "]");
4220
+ if (sliceStart === void 0) throw buildTemplateFormatError(first, "writes an empty subscript");
4221
+ checkTemplateLoopMember(object, sliceStart, first);
4222
+ return [
4223
+ {
4224
+ term: "member",
4225
+ object,
4226
+ key: sliceStart
4227
+ },
4228
+ afterStart + 1,
4229
+ startHeight
4230
+ ];
4231
+ }
4232
+ const stopToken = readTemplateToken(tokens, afterStart + 1);
4233
+ const [sliceStop, afterStop, stopHeight] = matchesTemplateToken(stopToken, "operator", ":") || matchesTemplateToken(stopToken, "operator", "]") ? [
4234
+ void 0,
4235
+ afterStart + 1,
4236
+ 0
4237
+ ] : compileTemplateExpression(tokens, afterStart + 1, depth, true);
4238
+ const hasStepColon = matchesTemplateToken(readTemplateToken(tokens, afterStop), "operator", ":");
4239
+ const stepToken = hasStepColon ? readTemplateToken(tokens, afterStop + 1) : void 0;
4240
+ const [sliceStep, afterStep, stepHeight] = !hasStepColon || stepToken !== void 0 && matchesTemplateToken(stepToken, "operator", "]") ? [
4241
+ void 0,
4242
+ hasStepColon ? afterStop + 1 : afterStop,
4243
+ 0
4244
+ ] : compileTemplateExpression(tokens, afterStop + 1, depth, true);
4245
+ checkTemplateToken(tokens, afterStep, "operator", "]");
4246
+ return [
4247
+ {
4248
+ term: "slice",
4249
+ object,
4250
+ ...sliceStart !== void 0 ? { start: sliceStart } : {},
4251
+ ...sliceStop !== void 0 ? { stop: sliceStop } : {},
4252
+ ...sliceStep !== void 0 ? { step: sliceStep } : {}
4253
+ },
4254
+ afterStep + 1,
4255
+ Math.max(startHeight, stopHeight, stepHeight)
4256
+ ];
4257
+ }
4258
+ // src/core/parsers.ts
4259
+ /**
4260
+ * Parses an unknown input into a {@link TemplateDocument}, returning `undefined`
4261
+ * on malformed syntax, unadmitted constructs, exceeded depth, or off-shape input
4262
+ * without throwing.
4263
+ *
4264
+ * @param source - A Jinja template string or an already-built {@link TemplateDocument}
4265
+ * @returns A validated {@link TemplateDocument}, or `undefined` when invalid
227
4266
  *
228
4267
  * @example
229
4268
  * ```ts
230
- * import { fillTemplate } from '@src/core'
4269
+ * import { parseTemplate } from '@orkestrel/template'
231
4270
  *
232
- * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'
233
- * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'
4271
+ * parseTemplate('Hi {{ name }}')?.syntax // 'document'
4272
+ * parseTemplate('{% if unclosed %}') // undefined
234
4273
  * ```
235
4274
  */
236
- function fillTemplate(content, values, options) {
237
- const placeholders = options?.placeholders ?? [];
238
- const missing = options?.missing ?? "error";
239
- const locale = options?.locale ?? "en-US";
240
- const record = values ?? {};
241
- const missingNames = [];
242
- const pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags);
243
- const result = content.replace(pattern, (matchText, rawToken) => {
244
- if (rawToken === void 0) return "{{";
245
- const token = rawToken.trim();
246
- const { value, declared, required } = resolveToken(record, placeholders, token);
247
- if (value !== void 0) return formatValue(value, locale);
248
- if (declared?.fallback !== void 0) return formatValue(declared.fallback, locale);
249
- if (missing === "literal") return matchText;
250
- if (missing === "empty") return "";
251
- if (required && !missingNames.includes(token)) missingNames.push(token);
252
- return "";
253
- });
254
- if (missing === "error" && missingNames.length > 0) throw new TemplateError("MISSING", `Missing required placeholder(s): ${missingNames.join(", ")}`, { missing: missingNames });
255
- return result;
4275
+ function parseTemplate(source) {
4276
+ if (isTemplateDocument(source)) return source;
4277
+ if (!isString(source)) return void 0;
4278
+ const outcome = attempt(() => compileTemplate(source));
4279
+ return outcome.success ? outcome.value : void 0;
256
4280
  }
257
4281
  // src/core/shapers.ts
258
4282
  /**
@@ -269,7 +4293,7 @@ function fillTemplate(content, values, options) {
269
4293
  *
270
4294
  * @example
271
4295
  * ```ts
272
- * import { placeholderShape } from '@src/core'
4296
+ * import { placeholderShape } from '@orkestrel/template'
273
4297
  * import { createContract } from '@orkestrel/contract'
274
4298
  *
275
4299
  * const contract = createContract(placeholderShape([{ name: 'city' }]))
@@ -284,6 +4308,312 @@ function placeholderShape(placeholders) {
284
4308
  }
285
4309
  return objectShape(properties);
286
4310
  }
4311
+ /**
4312
+ * Normalizes an `@orkestrel/html` node into a document and enforces
4313
+ * `@orkestrel/html`'s unlowerable sanitize floor, failing closed to an empty
4314
+ * document on off-shape input.
4315
+ *
4316
+ * @param node - The HTML document or node to sanitize
4317
+ * @param options - Optional allowlist overrides (cannot lower `@orkestrel/html`'s security floor)
4318
+ * @returns The sanitized {@link HTMLDocument}
4319
+ *
4320
+ * @example
4321
+ * ```ts
4322
+ * import { sanitizeTemplateHTML } from '@orkestrel/template'
4323
+ *
4324
+ * sanitizeTemplateHTML({ category: 'element', name: 'script', attributes: [], children: [] }).children // []
4325
+ * ```
4326
+ */
4327
+ function sanitizeTemplateHTML(node, options) {
4328
+ const document = node.category === "document" ? node : {
4329
+ category: "document",
4330
+ children: [node]
4331
+ };
4332
+ if (!isHTMLDocument(document)) return {
4333
+ category: "document",
4334
+ children: []
4335
+ };
4336
+ return new HTML(document).sanitize(options).document;
4337
+ }
4338
+ /**
4339
+ * Projects a compiled template document or Jinja source into a sanitized
4340
+ * {@link HTMLDocument}.
4341
+ *
4342
+ * @remarks
4343
+ * Plain string template text and interpolated scalar values always become safe
4344
+ * `TextNode` leaves rather than raw HTML markup, eliminating XSS from fill
4345
+ * strings. Embedded `HTMLNode` leaves and fill values pass through
4346
+ * `sanitizeTemplateHTML`, and embedded `MarkdownNode` leaves and fill values
4347
+ * project through `markdownToHTML` then `sanitizeTemplateHTML`.
4348
+ *
4349
+ * @param source - A compiled {@link TemplateDocument} or Jinja source string
4350
+ * @param values - Optional runtime values record
4351
+ * @param options - Optional evaluation and HTML sanitization settings
4352
+ * @returns A sanitized {@link HTMLDocument}
4353
+ *
4354
+ * @example
4355
+ * ```ts
4356
+ * import { templateToHTML } from '@orkestrel/template'
4357
+ *
4358
+ * templateToHTML('Hi {{ name }}', { name: '<b>Ada</b>' }).children
4359
+ * // [{ category: 'text', value: 'Hi <b>Ada</b>' }]
4360
+ * ```
4361
+ */
4362
+ function templateToHTML(source, values, options) {
4363
+ const document = isString(source) ? compileTemplate(source) : source;
4364
+ if (!isTemplateDocument(document)) throw new TemplateError("INVALID", "templateToHTML requires a valid TemplateDocument or source string.");
4365
+ const parts = evaluateTemplateParts(document, values, options);
4366
+ const children = [];
4367
+ for (const part of parts) {
4368
+ if (typeof part === "string") {
4369
+ if (part.length > 0) children.push({
4370
+ category: "text",
4371
+ value: part
4372
+ });
4373
+ continue;
4374
+ }
4375
+ if (isHTMLNode(part)) {
4376
+ const clean = sanitizeTemplateHTML(part, options?.sanitize);
4377
+ for (const child of clean.children) children.push(child);
4378
+ continue;
4379
+ }
4380
+ const clean = sanitizeTemplateHTML(markdownToHTML(part), options?.sanitize);
4381
+ for (const child of clean.children) children.push(child);
4382
+ }
4383
+ return {
4384
+ category: "document",
4385
+ children: mergeText(children)
4386
+ };
4387
+ }
4388
+ /**
4389
+ * Projects a compiled template document or Jinja source into a canonical
4390
+ * {@link MarkdownDocument}.
4391
+ *
4392
+ * @remarks
4393
+ * Template-authored literal text parses through `parseMarkdown`, while dynamic
4394
+ * scalar fill values stay literal leaves and are never parsed as Markdown
4395
+ * syntax. Inline dynamic fills and `CodeSpanNode` values collapse line breaks
4396
+ * (`\r\n`, `\r`, `\n`) to single spaces so round-tripping through
4397
+ * `renderMarkdown` and `parseMarkdown` never splits headings, table rows,
4398
+ * code spans, or paragraphs; `CodeBlockNode.lang` sanitizes to a single token
4399
+ * free of whitespace, backticks, and tildes; and `CodeBlockNode.code` preserves
4400
+ * line breaks verbatim inside dynamically sized fences. Embedded `HTMLNode`
4401
+ * values sanitize through `sanitizeTemplateHTML`, project through
4402
+ * `htmlToMarkdown`, and sanitize URL schemes; embedded `MarkdownNode` values
4403
+ * sanitize URL schemes by unwrapping unsafe `LinkNode` elements and dropping
4404
+ * unsafe `ImageNode` elements. `@orkestrel/markdown` has no raw-HTML AST node
4405
+ * and emits `TextRun` text verbatim in `renderMarkdown`, so callers targeting a
4406
+ * third-party raw-HTML Markdown renderer must use `templateToHTML` or sanitize
4407
+ * at that HTML boundary.
4408
+ *
4409
+ * @param source - A compiled {@link TemplateDocument} or Jinja source string
4410
+ * @param values - Optional runtime values record
4411
+ * @param options - Optional evaluation and HTML sanitization settings
4412
+ * @returns A {@link MarkdownDocument}
4413
+ *
4414
+ * @example
4415
+ * ```ts
4416
+ * import { templateToMarkdown } from '@orkestrel/template'
4417
+ *
4418
+ * templateToMarkdown('# Hello {{ name }}', { name: 'Ada' }).children[0]?.element // 'heading'
4419
+ * ```
4420
+ */
4421
+ function templateToMarkdown(source, values, options) {
4422
+ const document = isString(source) ? compileTemplate(source) : source;
4423
+ if (!isTemplateDocument(document)) throw new TemplateError("INVALID", "templateToMarkdown requires a valid TemplateDocument or source string.");
4424
+ const grouped = evaluateTaggedTemplateParts(document, values, options).reduce((runs, [literal, part]) => {
4425
+ if (typeof part !== "string") return [...runs, part];
4426
+ const previous = runs.at(-1);
4427
+ if (isArray(previous)) {
4428
+ const entry = [literal, part];
4429
+ return [...runs.slice(0, -1), [...previous, entry]];
4430
+ }
4431
+ return [...runs, [[literal, part]]];
4432
+ }, []);
4433
+ const blocks = [];
4434
+ for (const part of grouped) {
4435
+ if (isArray(part)) {
4436
+ for (const block of buildTemplateMarkdownBlocks(part, options?.sanitize)) blocks.push(block);
4437
+ continue;
4438
+ }
4439
+ if (isHTMLNode(part)) {
4440
+ const clean = sanitizeTemplateHTML(part, options?.sanitize);
4441
+ const sanitized = sanitizeTemplateMarkdown(htmlToMarkdown(clean), options?.sanitize);
4442
+ if (sanitized !== void 0 && sanitized.element === "document") for (const block of sanitized.children) blocks.push(block);
4443
+ continue;
4444
+ }
4445
+ const sanitized = sanitizeTemplateMarkdown(part, options?.sanitize);
4446
+ if (sanitized === void 0) continue;
4447
+ if (sanitized.element === "document" || sanitized.element === "listItem") for (const block of sanitized.children) blocks.push(block);
4448
+ else if (isBlockNode(sanitized)) blocks.push(sanitized);
4449
+ else if (isInlineNode(sanitized)) blocks.push({
4450
+ element: "paragraph",
4451
+ children: [sanitized]
4452
+ });
4453
+ }
4454
+ return {
4455
+ element: "document",
4456
+ children: blocks
4457
+ };
4458
+ }
4459
+ // src/core/templates/TemplateTree.ts
4460
+ /**
4461
+ * Wraps a compiled {@link TemplateDocument} AST as an immutable handle
4462
+ * exposing provenance lookup, depth-first traversal, queries, copy-on-write
4463
+ * rewrites, total folds, shallow streaming, evaluation, and canonical source
4464
+ * rendering.
4465
+ *
4466
+ * @remarks
4467
+ * Construct with `{ source }` to compile Jinja source with original UTF-16
4468
+ * provenance spans, or `{ document, spans? }` to adopt an existing validated
4469
+ * {@link TemplateDocument}. Every query and rewrite preserves immutability.
4470
+ *
4471
+ * @example
4472
+ * ```ts
4473
+ * import { TemplateTree } from '@orkestrel/template'
4474
+ *
4475
+ * const tree = new TemplateTree({ source: 'Hi {{ name }}' })
4476
+ * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'
4477
+ * ```
4478
+ */
4479
+ var TemplateTree = class TemplateTree {
4480
+ #document;
4481
+ #spans;
4482
+ constructor(options) {
4483
+ const given = options;
4484
+ if (!isObject(given)) throw new TemplateError("INVALID", "TemplateTree requires an options object.");
4485
+ if ("source" in given) {
4486
+ const source = Reflect.get(given, "source");
4487
+ if (!isString(source)) throw new TemplateError("INVALID", "TemplateTree source must be a string.");
4488
+ const [document, spans] = compileTemplateProvenance(source);
4489
+ this.#document = document;
4490
+ this.#spans = new Map(spans);
4491
+ return;
4492
+ }
4493
+ const document = Reflect.get(given, "document");
4494
+ if (!isTemplateDocument(document)) throw new TemplateError("INVALID", "TemplateTree document must be a valid TemplateDocument.");
4495
+ const spans = Reflect.get(given, "spans");
4496
+ if (spans !== void 0 && !isMap(spans)) throw new TemplateError("INVALID", "TemplateTree spans must be a Map when provided.");
4497
+ this.#document = document;
4498
+ const copied = /* @__PURE__ */ new Map();
4499
+ if (spans !== void 0) {
4500
+ for (const [node, span] of spans.entries()) if (isTemplateNode(node) && isTemplateSpan(span)) copied.set(node, {
4501
+ start: span.start,
4502
+ end: span.end
4503
+ });
4504
+ }
4505
+ this.#spans = copied;
4506
+ }
4507
+ /** Exposes the stored {@link TemplateDocument} AST root. */
4508
+ get document() {
4509
+ return this.#document;
4510
+ }
4511
+ /**
4512
+ * Returns the half-open original-source region for a node, or `undefined`
4513
+ * when this handle holds no provenance for that node.
4514
+ *
4515
+ * @param node - The node whose provenance to read
4516
+ * @returns A fresh {@link TemplateSpan}, or `undefined`
4517
+ */
4518
+ span(node) {
4519
+ const span = this.#spans.get(node);
4520
+ return span === void 0 ? void 0 : {
4521
+ start: span.start,
4522
+ end: span.end
4523
+ };
4524
+ }
4525
+ /**
4526
+ * Walks every node in the document depth-first in pre-order, root first.
4527
+ *
4528
+ * @returns A lazy generator over every node in the document
4529
+ */
4530
+ *walk() {
4531
+ yield* walkTemplateNodes(this.#document);
4532
+ }
4533
+ find(predicate) {
4534
+ for (const node of this.walk()) if (predicate(node)) return node;
4535
+ }
4536
+ filter(predicate) {
4537
+ return this.walk().filter((node) => predicate(node)).toArray();
4538
+ }
4539
+ /**
4540
+ * Rewrites the document bottom-up with copy-on-write provenance preservation
4541
+ * and returns a derived {@link TemplateTreeInterface}.
4542
+ *
4543
+ * @param rewrite - The bottom-up node rewrite callback
4544
+ * @returns A derived handle over the rewritten document
4545
+ */
4546
+ map(rewrite) {
4547
+ const [document, derivations] = mapTemplateDocument(this.#document, rewrite);
4548
+ return this.#derive(document, derivations);
4549
+ }
4550
+ /**
4551
+ * Reduces the document depth-first in pre-order into one accumulated value.
4552
+ *
4553
+ * @param callback - The reducer step combining value and node
4554
+ * @param initial - The initial accumulated value
4555
+ * @returns The final accumulated value
4556
+ */
4557
+ reduce(callback, initial) {
4558
+ return this.walk().reduce((value, node) => callback(value, node), initial);
4559
+ }
4560
+ /**
4561
+ * Folds the document bottom-up through a total handler table covering every
4562
+ * syntax variant.
4563
+ *
4564
+ * @param handlers - Total handler map keyed by `syntax`
4565
+ * @returns The folded value of the document root
4566
+ */
4567
+ fold(handlers) {
4568
+ return foldTemplateDocument(this.#document, handlers);
4569
+ }
4570
+ /**
4571
+ * Returns a fresh, pull-based stream over the document's top-level children
4572
+ * in source order.
4573
+ *
4574
+ * @returns A pull-based {@link ReadableStream} over top-level nodes
4575
+ */
4576
+ stream() {
4577
+ return streamTemplateNodes(this.#document);
4578
+ }
4579
+ /**
4580
+ * Evaluates the template document against runtime values and returns rendered
4581
+ * text.
4582
+ *
4583
+ * @param values - Optional runtime values record
4584
+ * @param options - Optional evaluation, placeholder, and sanitize settings
4585
+ * @returns The rendered text
4586
+ */
4587
+ evaluate(values, options) {
4588
+ return evaluateTemplate(this.#document, values, options);
4589
+ }
4590
+ /**
4591
+ * Renders the template document back to canonical template source text.
4592
+ *
4593
+ * @returns The canonical template source string
4594
+ */
4595
+ render() {
4596
+ return renderTemplate(this.#document);
4597
+ }
4598
+ #derive(document, derivations) {
4599
+ const spans = /* @__PURE__ */ new Map();
4600
+ for (const node of walkTemplateNodes(document)) {
4601
+ const own = this.#spans.get(node);
4602
+ if (own !== void 0) {
4603
+ spans.set(node, own);
4604
+ continue;
4605
+ }
4606
+ const source = derivations.get(node);
4607
+ if (source === void 0) continue;
4608
+ const span = this.#spans.get(source);
4609
+ if (span !== void 0) spans.set(node, span);
4610
+ }
4611
+ return new TemplateTree({
4612
+ document,
4613
+ spans
4614
+ });
4615
+ }
4616
+ };
287
4617
  // src/core/templates/Template.ts
288
4618
  /**
289
4619
  * Represents a named, versionable template — `{{name}}` tokens in `content`,
@@ -443,6 +4773,25 @@ var Template = class {
443
4773
  parameters() {
444
4774
  return schemaToParameters(this.#contract.schema);
445
4775
  }
4776
+ /**
4777
+ * Returns an immutable compiled tree handle over this template's plain
4778
+ * placeholder content.
4779
+ *
4780
+ * @returns A {@link TemplateTreeInterface} parsed by `compilePlainTemplate`
4781
+ *
4782
+ * @example
4783
+ * ```ts
4784
+ * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })
4785
+ * instance.tree().document.children.length // 2
4786
+ * ```
4787
+ */
4788
+ tree() {
4789
+ const [document, spans] = compilePlainTemplate(this.content);
4790
+ return new TemplateTree({
4791
+ document,
4792
+ spans
4793
+ });
4794
+ }
446
4795
  };
447
4796
  // src/core/templates/TemplateManager.ts
448
4797
  /**
@@ -723,6 +5072,24 @@ function createTemplate(options) {
723
5072
  function createTemplateManager(options) {
724
5073
  return new TemplateManager(options);
725
5074
  }
726
- export { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN, Template, TemplateError, TemplateManager, UNSAFE_FIELD_SEGMENTS, createTemplate, createTemplateManager, fillTemplate, formatValue, isTemplateError, placeholderShape, resolveSafeField, resolveToken };
5075
+ /**
5076
+ * Creates a working {@link TemplateTreeInterface} from Jinja `source` text or
5077
+ * an existing {@link TemplateDocument}, backed by the `TemplateTree` class.
5078
+ *
5079
+ * @param options - Either `{ source }` to compile or `{ document, spans? }` to adopt
5080
+ * @returns A working {@link TemplateTreeInterface}
5081
+ *
5082
+ * @example
5083
+ * ```ts
5084
+ * import { createTemplateTree } from '@orkestrel/template'
5085
+ *
5086
+ * const tree = createTemplateTree({ source: 'Hi {{ name }}' })
5087
+ * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'
5088
+ * ```
5089
+ */
5090
+ function createTemplateTree(options) {
5091
+ return new TemplateTree(options);
5092
+ }
5093
+ export { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN, TEMPLATE_COMPARISONS, TEMPLATE_ERROR_CODES, TEMPLATE_ESCAPES, TEMPLATE_FILTERS, TEMPLATE_FUNCTIONS, TEMPLATE_LITERALS, TEMPLATE_LOOP_REFUSALS, TEMPLATE_METHODS, TEMPLATE_OPERATOR_FEATURES, TEMPLATE_SEGMENT_PATTERN, TEMPLATE_SPACE, TEMPLATE_STRING_METHODS, TEMPLATE_TESTS, TEMPLATE_TOKEN_PATTERN, Template, TemplateError, TemplateManager, TemplateTree, UNSAFE_FIELD_SEGMENTS, addTemplateValues, applyTemplateFilter, applyTemplateTest, bindTemplateName, buildTemplateEvaluationError, buildTemplateFormatError, buildTemplateMarkdownBlocks, callTemplateExpression, callTemplateMethod, checkTemplateClose, checkTemplateDepth, checkTemplateLoopMember, checkTemplateTarget, checkTemplateToken, collectTemplateItems, compareTemplateValues, compilePlainTemplate, compileTemplate, compileTemplateArguments, compileTemplateBlock, compileTemplateChain, compileTemplateComparison, compileTemplateExpression, compileTemplateFor, compileTemplateIf, compileTemplateMacro, compileTemplateNegation, compileTemplatePrimary, compileTemplateProvenance, compileTemplateStatements, compileTemplateSubscript, compileTemplateSum, compileTemplateTest, compileTemplateUnary, createTemplate, createTemplateManager, createTemplateTree, decodeTemplateNumber, decodeTemplateString, evaluateTaggedTemplateParts, evaluateTemplate, evaluateTemplateExpression, evaluateTemplateParts, executeTemplateNodes, fillTemplate, filterTemplateNodes, findTemplateName, findTemplateNode, foldTemplateDocument, formatValue, isTemplateComparison, isTemplateDocument, isTemplateError, isTemplateErrorCode, isTemplateExpression, isTemplateLoop, isTemplateMacro, isTemplateNamespace, isTemplateNode, isTemplateSpan, isTemplateTarget, locateTemplateOffset, mapTemplateDocument, mapTemplateOffsets, matchesTemplateEqual, matchesTemplateIndent, matchesTemplateMember, matchesTemplateToken, matchesTemplateTruth, negateTemplateValue, normalizeTemplateMarkdownText, normalizeTemplateSource, normalizeTemplateValue, parseTemplate, placeholderShape, quoteTemplateText, readTemplateMember, readTemplateToken, reduceTemplateDocument, renderTemplate, renderTemplateExpression, renderTemplateNodes, renderTemplateNumber, renderTemplatePart, renderTemplateToken, renderTemplateType, renderTemplateValue, resolveMarkdownMarker, resolveSafeField, resolveToken, restoreMarkdownBlock, restoreMarkdownInlines, restoreMarkdownText, rewriteTemplateNode, runTemplateNodes, sanitizeTemplateHTML, sanitizeTemplateMarkdown, sanitizeTemplateMarkdownBlocks, sanitizeTemplateMarkdownInlines, sanitizeTemplateMarkdownLanguage, scanTemplateTag, scanTemplateTokens, serializeTemplateJSON, sliceTemplateSequence, streamTemplateNodes, subtractTemplateValues, templateToHTML, templateToMarkdown, trimTemplateText, walkTemplateNodes };
727
5094
 
728
5095
  //# sourceMappingURL=index.js.map