@orkestrel/template 0.0.17 → 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,8 +1,628 @@
1
+ import type { BlockNode } from '@orkestrel/markdown';
1
2
  import type { ContractShape } from '@orkestrel/contract';
2
3
  import type { EmitterErrorHandler } from '@orkestrel/emitter';
3
4
  import type { EmitterHooks } from '@orkestrel/emitter';
4
5
  import type { EmitterInterface } from '@orkestrel/emitter';
5
6
  import type { FieldPath } from '@orkestrel/contract';
7
+ import type { HTMLDocument } from '@orkestrel/html';
8
+ import type { HTMLNode } from '@orkestrel/html';
9
+ import type { HTMLSanitizeOptions } from '@orkestrel/html';
10
+ import type { InlineNode } from '@orkestrel/markdown';
11
+ import type { MarkdownDocument } from '@orkestrel/markdown';
12
+ import type { MarkdownNode } from '@orkestrel/markdown';
13
+
14
+ /**
15
+ * Adds two runtime template values under Python `+` rules for strings, numbers, and lists.
16
+ *
17
+ * @param left - The first operand
18
+ * @param right - The second operand
19
+ * @returns The sum or concatenation
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { addTemplateValues } from '@orkestrel/template'
24
+ *
25
+ * addTemplateValues('<|im_start|>', 'user') // '<|im_start|>user'
26
+ * ```
27
+ */
28
+ export declare function addTemplateValues(left: TemplateRuntimeValue, right: TemplateRuntimeValue): TemplateRuntimeValue;
29
+
30
+ /**
31
+ * Applies one of the admitted Jinja `|` filters (`trim`, `length`, `tojson`,
32
+ * `items`, `safe`, `string`) to a runtime value.
33
+ *
34
+ * @param name - The filter name
35
+ * @param value - The value to transform
36
+ * @returns The filtered runtime value
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import { applyTemplateFilter } from '@orkestrel/template'
41
+ *
42
+ * applyTemplateFilter('trim', ' Hi\n') // 'Hi'
43
+ * applyTemplateFilter('length', 'héllo') // 5
44
+ * ```
45
+ */
46
+ export declare function applyTemplateFilter(name: string, value: TemplateRuntimeValue): TemplateRuntimeValue;
47
+
48
+ /**
49
+ * Applies one of the admitted Jinja `is` tests (`defined`, `undefined`, `none`,
50
+ * `string`, `mapping`, `iterable`, `sequence`, `true`, `false`) to a runtime value.
51
+ *
52
+ * @param name - The test name
53
+ * @param value - The value to inspect
54
+ * @returns True if `value` satisfies the test; false otherwise
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { applyTemplateTest } from '@orkestrel/template'
59
+ *
60
+ * applyTemplateTest('true', true) // true
61
+ * applyTemplateTest('true', 1) // false
62
+ * ```
63
+ */
64
+ export declare function applyTemplateTest(name: string, value: TemplateRuntimeValue): boolean;
65
+
66
+ /**
67
+ * Binds a variable name in a copy of the innermost scope frame without mutating
68
+ * the input frames.
69
+ *
70
+ * @param frames - The scope stack, outermost first
71
+ * @param name - The variable name to bind
72
+ * @param value - The runtime value to bind
73
+ * @returns A fresh scope stack carrying the updated innermost frame
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * import { bindTemplateName, findTemplateName } from '@orkestrel/template'
78
+ *
79
+ * findTemplateName(bindTemplateName([new Map()], 'turn', 2), 'turn') // 2
80
+ * ```
81
+ */
82
+ export declare function bindTemplateName(frames: TemplateScope, name: string, value: TemplateRuntimeValue): TemplateScope;
83
+
84
+ /**
85
+ * Builds an `EVALUATION`-coded {@link TemplateError} for runtime evaluation refusals.
86
+ *
87
+ * @param message - The diagnostic clause after "The template"
88
+ * @param context - Additional context members describing the failure
89
+ * @returns The constructed {@link TemplateError}
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * import { buildTemplateEvaluationError } from '@orkestrel/template'
94
+ *
95
+ * buildTemplateEvaluationError('adds a string to an integer').code // 'EVALUATION'
96
+ * ```
97
+ */
98
+ export declare function buildTemplateEvaluationError(message: string, context?: Readonly<Record<string, unknown>>): TemplateError;
99
+
100
+ /**
101
+ * Builds a `FORMAT`-coded {@link TemplateError} anchored at a token's source location.
102
+ *
103
+ * @param token - The token locating the syntax or subset refusal
104
+ * @param message - The diagnostic clause after "the template"
105
+ * @param context - Additional context members carried beside `line`, `column`, `start`, and `end`
106
+ * @returns The constructed {@link TemplateError}
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { buildTemplateFormatError, scanTemplateTokens } from '@orkestrel/template'
111
+ *
112
+ * const [token] = scanTemplateTokens('{{ x }}')
113
+ * buildTemplateFormatError(token, 'uses an unknown filter', { feature: 'unknown' }).code // 'FORMAT'
114
+ * ```
115
+ */
116
+ export declare function buildTemplateFormatError(token: TemplateToken, message: string, context?: Readonly<Record<string, unknown>>): TemplateError;
117
+
118
+ /**
119
+ * Builds sanitized markdown blocks from a contiguous run of template-authored
120
+ * literal text (`true`) and dynamic scalar fill strings (`false`), keeping
121
+ * dynamic scalars strictly literal leaf text.
122
+ *
123
+ * @param run - Ordered `[literal, text]` entries in the run
124
+ * @param options - Optional HTML sanitization allowlist settings
125
+ * @returns The sanitized block nodes produced from the run
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * import { buildTemplateMarkdownBlocks } from '@orkestrel/template'
130
+ *
131
+ * buildTemplateMarkdownBlocks([[true, '# '], [false, 'Ada']])[0]?.element // 'heading'
132
+ * ```
133
+ */
134
+ export declare function buildTemplateMarkdownBlocks(run: ReadonlyArray<readonly [literal: boolean, text: string]>, options?: HTMLSanitizeOptions): readonly BlockNode[];
135
+
136
+ /**
137
+ * Evaluates a template call expression — dispatching built-in `raise_exception`
138
+ * and `namespace`, string method calls, and user-defined `TemplateMacro` calls.
139
+ *
140
+ * @param callee - The callee expression
141
+ * @param positionalExpressions - Positional argument expressions
142
+ * @param keywordExpressions - Named keyword argument expressions
143
+ * @param frames - Active lexical scope frames
144
+ * @param namespaces - Evaluation-owned mutable namespace registry
145
+ * @param options - Optional evaluation settings
146
+ * @param callDepth - Current macro call depth
147
+ * @returns The call result
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * import { callTemplateExpression } from '@orkestrel/template'
152
+ *
153
+ * callTemplateExpression({ term: 'name', name: 'namespace' }, [], [{ name: 'n', value: { term: 'literal', value: 1 } }], [new Map()], new Map(), undefined, 0)
154
+ * ```
155
+ */
156
+ export declare function callTemplateExpression(callee: TemplateExpression, positionalExpressions: readonly TemplateExpression[], keywordExpressions: readonly TemplateKeyword[], frames: TemplateScope, namespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>, options: TemplateEvaluateOptions | undefined, callDepth: number): TemplateRuntimeValue;
157
+
158
+ /**
159
+ * Invokes one of the admitted Python `str` methods (`startswith`, `endswith`,
160
+ * `split`, `strip`, `rstrip`, `lstrip`) on a string receiver with exact Python
161
+ * character-set and splitting semantics.
162
+ *
163
+ * @param receiver - The string receiver
164
+ * @param method - The string method name
165
+ * @param positional - Positional arguments
166
+ * @param keywords - Named keyword arguments
167
+ * @returns The method's return value
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * import { callTemplateMethod } from '@orkestrel/template'
172
+ *
173
+ * callTemplateMethod('hello\n\n', 'rstrip', ['\n'], []) // 'hello'
174
+ * callTemplateMethod('a</think>b', 'split', ['</think>'], []) // ['a', 'b']
175
+ * ```
176
+ */
177
+ export declare function callTemplateMethod(receiver: string, method: string, positional: readonly TemplateRuntimeValue[], keywords: ReadonlyArray<readonly [name: string, value: TemplateRuntimeValue]>): TemplateRuntimeValue;
178
+
179
+ /**
180
+ * Consumes an optional trailing colon (where admitted) and closing tag delimiter.
181
+ *
182
+ * @param tokens - The token stream
183
+ * @param index - The position after the tag's expression
184
+ * @param colon - If `true`, admits one trailing colon before the closer; if `false`, requires the closer immediately
185
+ * @returns The index after the closing delimiter
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { checkTemplateClose, scanTemplateTokens } from '@orkestrel/template'
190
+ *
191
+ * checkTemplateClose(scanTemplateTokens('{% else: %}'), 2, true) // 4
192
+ * ```
193
+ */
194
+ export declare function checkTemplateClose(tokens: readonly TemplateToken[], index: number, colon: boolean): number;
195
+
196
+ /**
197
+ * Refuses template nesting deeper than `MAX_DEPTH` (`64`) with a `FORMAT`-coded
198
+ * {@link TemplateError}.
199
+ *
200
+ * @param depth - The nesting level reached
201
+ * @param token - The token locating the refusal
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * import { checkTemplateDepth, scanTemplateTokens } from '@orkestrel/template'
206
+ *
207
+ * checkTemplateDepth(4, scanTemplateTokens('{{ x }}')[0])
208
+ * ```
209
+ */
210
+ export declare function checkTemplateDepth(depth: number, token: TemplateToken): void;
211
+
212
+ /**
213
+ * Refuses a compile-time read of a `loop` member listed in `TEMPLATE_LOOP_REFUSALS`.
214
+ *
215
+ * @param object - The target expression being indexed
216
+ * @param key - The member key expression
217
+ * @param token - The token locating the refusal
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * import { checkTemplateLoopMember, scanTemplateTokens } from '@orkestrel/template'
222
+ *
223
+ * checkTemplateLoopMember(
224
+ * { term: 'name', name: 'loop' },
225
+ * { term: 'literal', value: 'previtem' },
226
+ * scanTemplateTokens('{{ loop.previtem }}')[1],
227
+ * )
228
+ * ```
229
+ */
230
+ export declare function checkTemplateLoopMember(object: TemplateExpression, key: TemplateExpression, token: TemplateToken): void;
231
+
232
+ /**
233
+ * Refuses an invalid assignment target name such as a literal, reserved global
234
+ * function, or private `__`-prefixed identifier.
235
+ *
236
+ * @param token - The target token to validate
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * import { checkTemplateTarget, scanTemplateTokens } from '@orkestrel/template'
241
+ *
242
+ * checkTemplateTarget(scanTemplateTokens('{% set count = 1 %}')[2])
243
+ * ```
244
+ */
245
+ export declare function checkTemplateTarget(token: TemplateToken): void;
246
+
247
+ /**
248
+ * Refuses a token that does not match an expected form and optional text with a
249
+ * `FORMAT`-coded {@link TemplateError}.
250
+ *
251
+ * @param tokens - The token stream
252
+ * @param index - The index to validate
253
+ * @param form - The required token form
254
+ * @param text - Optional exact text to require
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * import { checkTemplateToken, scanTemplateTokens } from '@orkestrel/template'
259
+ *
260
+ * checkTemplateToken(scanTemplateTokens('{{ x }}'), 1, 'name', 'x')
261
+ * ```
262
+ */
263
+ export declare function checkTemplateToken(tokens: readonly TemplateToken[], index: number, form: TemplateTokenForm, text?: string): void;
264
+
265
+ /**
266
+ * Collects the iterable elements of a runtime value for a `for` loop.
267
+ *
268
+ * @param value - The value to iterate
269
+ * @returns The elements in iteration order
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * import { collectTemplateItems } from '@orkestrel/template'
274
+ *
275
+ * collectTemplateItems(new Map([['role', 'user']])) // ['role']
276
+ * ```
277
+ */
278
+ export declare function collectTemplateItems(value: TemplateRuntimeValue): readonly TemplateRuntimeValue[];
279
+
280
+ /**
281
+ * Compares two runtime template values for ordering under Python `<` rules.
282
+ *
283
+ * @param left - The first value
284
+ * @param right - The second value
285
+ * @returns Negative when `left < right`, positive when `left > right`, and `0` when equal
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * import { compareTemplateValues } from '@orkestrel/template'
290
+ *
291
+ * compareTemplateValues(1, 2) < 0 // true
292
+ * ```
293
+ */
294
+ export declare function compareTemplateValues(left: TemplateRuntimeValue, right: TemplateRuntimeValue): number;
295
+
296
+ /**
297
+ * Compiles a plain `{{name}}` placeholder template into a {@link TemplateDocument}
298
+ * AST of `text` and `placeholder` nodes alongside original-source UTF-16 spans.
299
+ *
300
+ * @param source - The plain placeholder template content
301
+ * @returns The compiled document and its node-to-span map
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * import { compilePlainTemplate } from '@orkestrel/template'
306
+ *
307
+ * const [document] = compilePlainTemplate('Hi {{name}}')
308
+ * document.children[1] // { syntax: 'placeholder', name: 'name', raw: '{{name}}' }
309
+ * ```
310
+ */
311
+ export declare function compilePlainTemplate(source: string): TemplateParseResult;
312
+
313
+ /**
314
+ * Compiles a Jinja template source string into a {@link TemplateDocument} AST.
315
+ *
316
+ * @param source - The template's Jinja source string
317
+ * @returns The compiled document AST
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * import { compileTemplate } from '@orkestrel/template'
322
+ *
323
+ * compileTemplate('{{ bos_token }}').children[0] // { syntax: 'output', value: { term: 'name', name: 'bos_token' } }
324
+ * ```
325
+ */
326
+ export declare function compileTemplate(source: string): TemplateDocument;
327
+
328
+ /**
329
+ * Compiles positional and named keyword arguments of a call from `(` through `)`.
330
+ *
331
+ * @param tokens - The scanned token stream
332
+ * @param index - Token index of the opening `(`
333
+ * @param depth - Current expression depth
334
+ * @returns Positional arguments, keyword arguments, next token index, and max height
335
+ *
336
+ * @example
337
+ * ```ts
338
+ * import { compileTemplateArguments, scanTemplateTokens } from '@orkestrel/template'
339
+ *
340
+ * compileTemplateArguments(scanTemplateTokens('{{ namespace(value=0) }}'), 2, 1)[1][0]?.name // 'value'
341
+ * ```
342
+ */
343
+ export declare function compileTemplateArguments(tokens: readonly TemplateToken[], index: number, depth: number): readonly [
344
+ values: readonly TemplateExpression[],
345
+ keywords: readonly TemplateKeyword[],
346
+ end: number,
347
+ height: number
348
+ ];
349
+
350
+ /**
351
+ * Compiles one Jinja block tag (`if`, `for`, `set`, `macro`, `break`, or `continue`).
352
+ *
353
+ * @param tokens - The scanned token stream
354
+ * @param index - The index of the tag name token
355
+ * @param depth - Current statement nesting depth
356
+ * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them
357
+ * @param spans - Optional operation-owned span recorder
358
+ * @returns The compiled node, token index after closing delimiter, and subtree height
359
+ *
360
+ * @example
361
+ * ```ts
362
+ * import { compileTemplateBlock, scanTemplateTokens } from '@orkestrel/template'
363
+ *
364
+ * compileTemplateBlock(scanTemplateTokens('{% set turn = 1 %}'), 1, 0, false)[0].syntax // 'set'
365
+ * ```
366
+ */
367
+ export declare function compileTemplateBlock(tokens: readonly TemplateToken[], index: number, depth: number, loop: boolean, spans?: Map<TemplateNode, TemplateSpan>): readonly [statement: TemplateNode, end: number, height: number];
368
+
369
+ /**
370
+ * Compiles a left-associative binary operator chain at one precedence level.
371
+ *
372
+ * @param tokens - The scanned token stream
373
+ * @param index - Starting token index
374
+ * @param depth - Current expression depth
375
+ * @param operators - Operators admitted at this precedence level
376
+ * @param operand - Compiler for the next tighter precedence level
377
+ * @returns The compiled expression, next token index, and expression height
378
+ *
379
+ * @example
380
+ * ```ts
381
+ * import { compileTemplateChain, compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'
382
+ *
383
+ * compileTemplateChain(scanTemplateTokens("{{ 'a' ~ 'b' }}"), 1, 1, ['~'], compileTemplateUnary)[0].term // 'binary'
384
+ * ```
385
+ */
386
+ export declare function compileTemplateChain(tokens: readonly TemplateToken[], index: number, depth: number, operators: readonly TemplateOperator[], operand: (tokens: readonly TemplateToken[], index: number, depth: number) => readonly [expression: TemplateExpression, end: number, height: number]): readonly [expression: TemplateExpression, end: number, height: number];
387
+
388
+ /**
389
+ * Compiles chained Python-style comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`,
390
+ * `in`, `not in`) over test expressions.
391
+ *
392
+ * @param tokens - The scanned token stream
393
+ * @param index - Starting token index
394
+ * @param depth - Current expression depth
395
+ * @returns The compiled expression, next token index, and expression height
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * import { compileTemplateComparison, scanTemplateTokens } from '@orkestrel/template'
400
+ *
401
+ * compileTemplateComparison(scanTemplateTokens("{{ role not in 'system' }}"), 1, 1)[0].term // 'binary'
402
+ * ```
403
+ */
404
+ export declare function compileTemplateComparison(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
405
+
406
+ /**
407
+ * Compiles one Jinja expression (`or` / `and` / `not` / comparisons / tests /
408
+ * arithmetic / postfix / filters), plus inline `if ... else ...` when admitted.
409
+ *
410
+ * @param tokens - The scanned token stream
411
+ * @param index - Starting token index
412
+ * @param depth - Current expression depth
413
+ * @param conditional - If `true`, admits inline `x if c else y`; if `false`, stops before `if`
414
+ * @returns The compiled expression, next token index, and expression height
415
+ *
416
+ * @example
417
+ * ```ts
418
+ * import { compileTemplateExpression, scanTemplateTokens } from '@orkestrel/template'
419
+ *
420
+ * compileTemplateExpression(scanTemplateTokens("{{ 'a' if x else 'b' }}"), 1, 1, true)[0].term // 'conditional'
421
+ * ```
422
+ */
423
+ export declare function compileTemplateExpression(tokens: readonly TemplateToken[], index: number, depth: number, conditional: boolean): readonly [expression: TemplateExpression, end: number, height: number];
424
+
425
+ /**
426
+ * Compiles a Jinja `for` loop supporting single targets and multi-target tuple
427
+ * unpacking through `{% endfor %}`.
428
+ *
429
+ * @param tokens - The scanned token stream
430
+ * @param index - The token index after `for`
431
+ * @param depth - Current statement nesting depth
432
+ * @param spans - Optional operation-owned span recorder
433
+ * @returns The compiled `for` node, token index after `{% endfor %}`, and subtree height
434
+ *
435
+ * @example
436
+ * ```ts
437
+ * import { compileTemplateFor, scanTemplateTokens } from '@orkestrel/template'
438
+ *
439
+ * compileTemplateFor(scanTemplateTokens('{% for k, v in d|items %}{% endfor %}'), 2, 0)[0]
440
+ * ```
441
+ */
442
+ export declare function compileTemplateFor(tokens: readonly TemplateToken[], index: number, depth: number, spans?: Map<TemplateNode, TemplateSpan>): readonly [statement: TemplateNode, end: number, height: number];
443
+
444
+ /**
445
+ * Compiles a Jinja `if` / `elif` / `else` / `endif` conditional block.
446
+ *
447
+ * @param tokens - The scanned token stream
448
+ * @param index - The token index after `if` or `elif`
449
+ * @param depth - Current statement nesting depth
450
+ * @param loop - If `true`, inside a `for` loop; if `false`, outside
451
+ * @param spans - Optional operation-owned span recorder
452
+ * @returns The compiled `if` node, token index after `{% endif %}`, and subtree height
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * import { compileTemplateIf, scanTemplateTokens } from '@orkestrel/template'
457
+ *
458
+ * compileTemplateIf(scanTemplateTokens('{% if x %}A{% endif %}'), 2, 0, false)[0].syntax // 'if'
459
+ * ```
460
+ */
461
+ export declare function compileTemplateIf(tokens: readonly TemplateToken[], index: number, depth: number, loop: boolean, spans?: Map<TemplateNode, TemplateSpan>): readonly [statement: TemplateNode, end: number, height: number];
462
+
463
+ /**
464
+ * Compiles a Jinja `{% macro name(a, b=default) %} ... {% endmacro %}` block.
465
+ *
466
+ * @param tokens - The scanned token stream
467
+ * @param index - The token index after `macro`
468
+ * @param depth - Current statement nesting depth
469
+ * @param spans - Optional operation-owned span recorder
470
+ * @returns The compiled `macro` node, token index after `{% endmacro %}`, and subtree height
471
+ *
472
+ * @example
473
+ * ```ts
474
+ * import { compileTemplateMacro, scanTemplateTokens } from '@orkestrel/template'
475
+ *
476
+ * compileTemplateMacro(scanTemplateTokens('{% macro greet(name="Ada") %}{{ name }}{% endmacro %}'), 2, 0)[0].syntax // 'macro'
477
+ * ```
478
+ */
479
+ export declare function compileTemplateMacro(tokens: readonly TemplateToken[], index: number, depth: number, spans?: Map<TemplateNode, TemplateSpan>): readonly [statement: TemplateNode, end: number, height: number];
480
+
481
+ /**
482
+ * Compiles logical `not` negation over comparisons.
483
+ *
484
+ * @param tokens - The scanned token stream
485
+ * @param index - Starting token index
486
+ * @param depth - Current expression depth
487
+ * @returns The compiled expression, next token index, and expression height
488
+ *
489
+ * @example
490
+ * ```ts
491
+ * import { compileTemplateNegation, scanTemplateTokens } from '@orkestrel/template'
492
+ *
493
+ * compileTemplateNegation(scanTemplateTokens('{{ not x }}'), 1, 1)[0].term // 'unary'
494
+ * ```
495
+ */
496
+ export declare function compileTemplateNegation(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
497
+
498
+ /**
499
+ * Compiles one primary template expression: a literal, name, adjacent string
500
+ * concatenation, or parenthesized sub-expression.
501
+ *
502
+ * @param tokens - The scanned token stream
503
+ * @param index - Token index of the primary
504
+ * @param depth - Current expression depth
505
+ * @returns The compiled expression, next token index, and expression height
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * import { compileTemplatePrimary, scanTemplateTokens } from '@orkestrel/template'
510
+ *
511
+ * compileTemplatePrimary(scanTemplateTokens("{{ 'a' 'b' }}"), 1, 1)[0] // { term: 'literal', value: 'ab' }
512
+ * ```
513
+ */
514
+ export declare function compileTemplatePrimary(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
515
+
516
+ /**
517
+ * Compiles a Jinja template source string into a {@link TemplateDocument} AST
518
+ * alongside its original-source {@link TemplateSpan} map.
519
+ *
520
+ * @param source - The template's Jinja source string
521
+ * @returns The compiled document and its node-to-span map
522
+ *
523
+ * @example
524
+ * ```ts
525
+ * import { compileTemplateProvenance } from '@orkestrel/template'
526
+ *
527
+ * const [document, spans] = compileTemplateProvenance('Hi {{ name }}')
528
+ * spans.get(document) // { start: 0, end: 13 }
529
+ * ```
530
+ */
531
+ export declare function compileTemplateProvenance(source: string): TemplateParseResult;
532
+
533
+ /**
534
+ * Compiles a run of Jinja template statements up to end-of-source or one of the
535
+ * closing block tag names in `ends`.
536
+ *
537
+ * @param tokens - The scanned token stream
538
+ * @param start - The starting token index
539
+ * @param depth - Current statement nesting depth
540
+ * @param ends - Block tag names that terminate this statement run
541
+ * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them
542
+ * @param spans - Optional operation-owned span recorder
543
+ * @returns The compiled statements, stopping token index, and maximum subtree height
544
+ *
545
+ * @example
546
+ * ```ts
547
+ * import { compileTemplateStatements, scanTemplateTokens } from '@orkestrel/template'
548
+ *
549
+ * compileTemplateStatements(scanTemplateTokens('Hi{% endif %}'), 0, 0, ['endif'], false)[1] // 1
550
+ * ```
551
+ */
552
+ export declare function compileTemplateStatements(tokens: readonly TemplateToken[], start: number, depth: number, ends: readonly string[], loop: boolean, spans?: Map<TemplateNode, TemplateSpan>): readonly [statements: readonly TemplateNode[], end: number, height: number];
553
+
554
+ /**
555
+ * Compiles one `[key]` member lookup or `[start:stop:step]` slice subscript
556
+ * starting at `[` and ending after `]`.
557
+ *
558
+ * @param tokens - The scanned token stream
559
+ * @param index - Token index of the opening `[`
560
+ * @param depth - Current expression depth
561
+ * @param object - The target expression being indexed or sliced
562
+ * @returns The compiled member or slice expression, next token index, and argument height
563
+ *
564
+ * @example
565
+ * ```ts
566
+ * import { compileTemplateSubscript, scanTemplateTokens } from '@orkestrel/template'
567
+ *
568
+ * compileTemplateSubscript(scanTemplateTokens('{{ a[::-1] }}'), 2, 1, { term: 'name', name: 'a' })[0].term // 'slice'
569
+ * ```
570
+ */
571
+ export declare function compileTemplateSubscript(tokens: readonly TemplateToken[], index: number, depth: number, object: TemplateExpression): readonly [expression: TemplateExpression, end: number, height: number];
572
+
573
+ /**
574
+ * Compiles a left-associative `+` / `-` chain over `~` concatenations.
575
+ *
576
+ * @param tokens - The scanned token stream
577
+ * @param index - Starting token index
578
+ * @param depth - Current expression depth
579
+ * @returns The compiled expression, next token index, and expression height
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * import { compileTemplateSum, scanTemplateTokens } from '@orkestrel/template'
584
+ *
585
+ * compileTemplateSum(scanTemplateTokens('{{ n - 1 }}'), 1, 1)[0].term // 'binary'
586
+ * ```
587
+ */
588
+ export declare function compileTemplateSum(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
589
+
590
+ /**
591
+ * Compiles an additive expression optionally followed by a Jinja `is` or
592
+ * `is not` test (`defined`, `undefined`, `none`, `string`, `mapping`,
593
+ * `iterable`, `sequence`, `true`, `false`).
594
+ *
595
+ * @param tokens - The scanned token stream
596
+ * @param index - Starting token index
597
+ * @param depth - Current expression depth
598
+ * @returns The compiled expression, next token index, and expression height
599
+ *
600
+ * @example
601
+ * ```ts
602
+ * import { compileTemplateTest, scanTemplateTokens } from '@orkestrel/template'
603
+ *
604
+ * compileTemplateTest(scanTemplateTokens('{{ x is not mapping }}'), 1, 1)[0].term // 'test'
605
+ * ```
606
+ */
607
+ export declare function compileTemplateTest(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
608
+
609
+ /**
610
+ * Compiles unary `-`/`+`, primaries, member reads, sequence slices, function
611
+ * and string method calls, and `|` filter chains.
612
+ *
613
+ * @param tokens - The scanned token stream
614
+ * @param index - Starting token index
615
+ * @param depth - Current expression depth
616
+ * @returns The compiled expression, next token index, and expression height
617
+ *
618
+ * @example
619
+ * ```ts
620
+ * import { compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'
621
+ *
622
+ * compileTemplateUnary(scanTemplateTokens('{{ messages[::-1] }}'), 1, 1)[0].term // 'slice'
623
+ * ```
624
+ */
625
+ export declare function compileTemplateUnary(tokens: readonly TemplateToken[], index: number, depth: number): readonly [expression: TemplateExpression, end: number, height: number];
6
626
 
7
627
  /**
8
628
  * Creates a working {@link TemplateInterface} from a {@link TemplateOptions}
@@ -58,6 +678,53 @@ import type { FieldPath } from '@orkestrel/contract';
58
678
  */
59
679
  export declare function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface;
60
680
 
681
+ /**
682
+ * Creates a working {@link TemplateTreeInterface} from Jinja `source` text or
683
+ * an existing {@link TemplateDocument}, backed by the `TemplateTree` class.
684
+ *
685
+ * @param options - Either `{ source }` to compile or `{ document, spans? }` to adopt
686
+ * @returns A working {@link TemplateTreeInterface}
687
+ *
688
+ * @example
689
+ * ```ts
690
+ * import { createTemplateTree } from '@orkestrel/template'
691
+ *
692
+ * const tree = createTemplateTree({ source: 'Hi {{ name }}' })
693
+ * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'
694
+ * ```
695
+ */
696
+ export declare function createTemplateTree(options: TemplateTreeOptions): TemplateTreeInterface;
697
+
698
+ /**
699
+ * Decodes an `integer` or `float` token as Jinja reads numeric literals.
700
+ *
701
+ * @param token - The numeric literal token
702
+ * @returns The decoded finite number
703
+ *
704
+ * @example
705
+ * ```ts
706
+ * import { decodeTemplateNumber, scanTemplateTokens } from '@orkestrel/template'
707
+ *
708
+ * decodeTemplateNumber(scanTemplateTokens('{{ 0x1F }}')[1]) // 31
709
+ * ```
710
+ */
711
+ export declare function decodeTemplateNumber(token: TemplateToken): number;
712
+
713
+ /**
714
+ * Decodes a quoted Jinja string token using Python `unicode-escape` rules.
715
+ *
716
+ * @param token - The string literal token including quotes
717
+ * @returns The decoded string value
718
+ *
719
+ * @example
720
+ * ```ts
721
+ * import { decodeTemplateString, scanTemplateTokens } from '@orkestrel/template'
722
+ *
723
+ * decodeTemplateString(scanTemplateTokens("{{ 'a\\nb' }}")[1]) // 'a\nb'
724
+ * ```
725
+ */
726
+ export declare function decodeTemplateString(token: TemplateToken): string;
727
+
61
728
  /**
62
729
  * Holds `'en-US'`, the default `locale` for `Template#fill` /
63
730
  * `TemplateManager#fill` when unspecified.
@@ -70,62 +737,130 @@ import type { FieldPath } from '@orkestrel/contract';
70
737
  */
71
738
  export declare const DEFAULT_MISSING_POLICY: MissingPolicy;
72
739
 
740
+ /**
741
+ * Evaluates a compiled {@link TemplateDocument} into tagged parts distinguishing
742
+ * template-authored literal text (`true`) from dynamic fill output (`false`).
743
+ *
744
+ * @param document - The compiled template document
745
+ * @param values - Optional runtime values record
746
+ * @param options - Optional evaluation, placeholder, and sanitize settings
747
+ * @returns The ordered list of tagged evaluated parts
748
+ *
749
+ * @example
750
+ * ```ts
751
+ * import { compileTemplate, evaluateTaggedTemplateParts } from '@orkestrel/template'
752
+ *
753
+ * evaluateTaggedTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' })
754
+ * // [[true, 'Hi '], [false, 'Ada']]
755
+ * ```
756
+ */
757
+ export declare function evaluateTaggedTemplateParts(document: TemplateDocument, values?: TemplateFillValues, options?: TemplateEvaluateOptions): ReadonlyArray<readonly [literal: boolean, part: TemplatePart]>;
758
+
759
+ /**
760
+ * Evaluates a compiled {@link TemplateDocument} against runtime values and
761
+ * joins every emitted part into a rendered string.
762
+ *
763
+ * @param document - The compiled template document
764
+ * @param values - Optional runtime values record
765
+ * @param options - Optional evaluation, placeholder, and sanitize settings
766
+ * @returns The rendered output string
767
+ *
768
+ * @example
769
+ * ```ts
770
+ * import { compileTemplate, evaluateTemplate } from '@orkestrel/template'
771
+ *
772
+ * evaluateTemplate(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // 'Hi Ada'
773
+ * ```
774
+ */
775
+ export declare function evaluateTemplate(document: TemplateDocument, values?: TemplateFillValues, options?: TemplateEvaluateOptions): string;
776
+
777
+ /**
778
+ * Evaluates a single {@link TemplateExpression} against runtime scope frames and
779
+ * namespace bindings.
780
+ *
781
+ * @param expression - The compiled expression to evaluate
782
+ * @param frames - The lexical scope frames, outermost first
783
+ * @param namespaces - Evaluation-owned map from `TemplateNamespace` to its mutable backing `Map`
784
+ * @param options - Optional evaluation settings
785
+ * @param callDepth - Current macro call depth. Default: `0`
786
+ * @returns The evaluated runtime value
787
+ *
788
+ * @example
789
+ * ```ts
790
+ * import { evaluateTemplateExpression } from '@orkestrel/template'
791
+ *
792
+ * evaluateTemplateExpression({ term: 'literal', value: 42 }, [new Map()], new Map()) // 42
793
+ * ```
794
+ */
795
+ export declare function evaluateTemplateExpression(expression: TemplateExpression, frames: TemplateScope, namespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>, options?: TemplateEvaluateOptions, callDepth?: number): TemplateRuntimeValue;
796
+
797
+ /**
798
+ * Evaluates a compiled {@link TemplateDocument} into an ordered list of
799
+ * tree-valued {@link TemplatePart}s (`string`, sanitized `HTMLNode`, or `MarkdownNode`).
800
+ *
801
+ * @param document - The compiled template document
802
+ * @param values - Optional runtime values record
803
+ * @param options - Optional evaluation, placeholder, and sanitize settings
804
+ * @returns The ordered list of evaluated parts
805
+ *
806
+ * @example
807
+ * ```ts
808
+ * import { compileTemplate, evaluateTemplateParts } from '@orkestrel/template'
809
+ *
810
+ * evaluateTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // ['Hi ', 'Ada']
811
+ * ```
812
+ */
813
+ export declare function evaluateTemplateParts(document: TemplateDocument, values?: TemplateFillValues, options?: TemplateEvaluateOptions): readonly TemplatePart[];
814
+
815
+ /**
816
+ * Executes a sequence of compiled {@link TemplateNode}s in order, threading
817
+ * lexical `set` and `macro` bindings into subsequent siblings until a loop
818
+ * control (`break` or `continue`) terminates the run.
819
+ *
820
+ * @param nodes - The nodes to execute in order
821
+ * @param frames - Active lexical scope frames
822
+ * @param namespaces - Evaluation-owned mutable namespace registry
823
+ * @param options - Optional evaluation settings
824
+ * @param callDepth - Current macro call depth. Default: `0`
825
+ * @returns The emitted parts, updated scope frames, and optional loop control signal
826
+ *
827
+ * @example
828
+ * ```ts
829
+ * import { executeTemplateNodes } from '@orkestrel/template'
830
+ *
831
+ * executeTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // ['Hi']
832
+ * ```
833
+ */
834
+ export declare function executeTemplateNodes(nodes: readonly TemplateNode[], frames: TemplateScope, namespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>, options?: TemplateEvaluateOptions, callDepth?: number): readonly [
835
+ parts: readonly TemplatePart[],
836
+ frames: TemplateScope,
837
+ control: 'break' | 'continue' | undefined
838
+ ];
839
+
73
840
  /**
74
841
  * Holds the single-pass `{{name}}` substitution pattern shared by
75
842
  * `Template#fill` and `Template#validate`.
76
843
  *
77
844
  * @remarks
78
845
  * Global-flagged, two-alternative pattern: a match of the first alternative
79
- * (`\{{` — a literal backslash followed by `{{`) means "emit a literal
80
- * `{{`" — the escape hatch for content that must show `{{` without
81
- * triggering substitution. A match that instead populates capture group 1
82
- * (`\{{([^{}]+?)\}\}`) means "substitute the named token" — group 1 is the
83
- * untrimmed token text between the braces; every call site trims it
84
- * (`token.trim()`) before using it as a lookup name, so `'{{ name }}'` still
85
- * resolves `'name'`. The pattern deliberately does not wrap the token in
86
- * `\s*` — an unclosed `'{{' + ' '.repeat(n)` with no closing `}}` would
87
- * otherwise force the regex engine into catastrophic backtracking over the
88
- * whitespace run (O(n^2)); trimming after the match keeps the same
89
- * whitespace tolerance without the backtracking hazard. Every call site
90
- * builds a fresh `RegExp` from `.source` / `.flags` rather than sharing this
91
- * instance's mutable `lastIndex` across scans.
846
+ * (`\{{` — a literal backslash followed by `{{`) emits a literal `{{`. A match
847
+ * populating capture group 1 (`\{\{([^{}]+?)\}\}`) resolves the trimmed token
848
+ * name without backtracking on unclosed whitespace runs. Every call site builds
849
+ * a fresh `RegExp` from `.source` and `.flags`.
92
850
  */
93
851
  export declare const FILL_PATTERN: RegExp;
94
852
 
95
853
  /**
96
854
  * Substitutes every `{{name}}` token in `content` in a single pass.
97
855
  *
98
- * @remarks
99
- * Uses a fresh `RegExp` clone of `FILL_PATTERN` per call (never sharing its
100
- * `lastIndex`) and a single `String#replace` scan — substituted output is
101
- * never re-scanned. Each token resolves through `resolveToken`, the one rule
102
- * `Template#validate` also applies: the matching declared
103
- * {@link TemplatePlaceholder} (exact `name`) supplies its `path` (falling
104
- * back to the token split on `.`); any path segment in `UNSAFE_FIELD_SEGMENTS`
105
- * makes the token unresolved without ever calling `resolveField` (a
106
- * prototype-pollution guard). A resolved value formats through `formatValue`; an
107
- * unresolved value falls back to the placeholder's `fallback` when declared;
108
- * otherwise `options.missing` governs — `'literal'` re-emits the original
109
- * `{{name}}` text, `'empty'` emits `''`, and `'error'` emits `''` for every
110
- * token but collects every unresolved required token (an undeclared token, or
111
- * a declared token with `required !== false`) and throws one
112
- * {@link TemplateError} coded `MISSING` listing them all, in first-appearance
113
- * order, once the scan completes. An escaped `\{{` emits a literal `{{`.
114
- *
115
- * Called with no declared `placeholders` and `{ missing: 'empty' }`, this is a
116
- * bare interpolation over `content` — every token resolves by dotted path
117
- * against the values record and every unresolved token emits `''`.
118
- * `FILL_PATTERN`'s token class (`[^{}]`) excludes `{`, so a token containing
119
- * `{` never matches and the surrounding `{{` stays literal.
120
- *
121
856
  * @param content - The template content carrying `{{name}}` tokens
122
857
  * @param values - The values tokens resolve against
123
- * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and the declared `placeholders` (default none) tokens resolve against
858
+ * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and declared `placeholders`
124
859
  * @returns The substituted content
125
860
  *
126
861
  * @example
127
862
  * ```ts
128
- * import { fillTemplate } from '@src/core'
863
+ * import { fillTemplate } from '@orkestrel/template'
129
864
  *
130
865
  * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'
131
866
  * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'
@@ -134,36 +869,152 @@ import type { FieldPath } from '@orkestrel/contract';
134
869
  export declare function fillTemplate(content: string, values?: TemplateFillValues, options?: TemplateFillContext): string;
135
870
 
136
871
  /**
137
- * Formats a resolved fill value for substitution into a template's `content`.
138
- *
139
- * @remarks
140
- * A finite number renders with the given locale's thousand grouping (through
141
- * `toLocaleString`); every other value — including `null` — String-coerces.
142
- * `null` therefore renders as the literal string `'null'`, matching
143
- * `String(value)` exactly, so a resolved `null` is visible in the output
144
- * rather than silently empty. An
145
- * invalid BCP-47 `locale` tag throws a `RangeError` from the underlying
146
- * `toLocaleString` call when `value` is a finite number — this is a caller
147
- * error (an invalid locale argument), by design, and is not caught here.
872
+ * Collects every {@link TemplateNode} in depth-first pre-order matching a
873
+ * guard or predicate.
148
874
  *
149
- * @param value - The resolved value to format
150
- * @param locale - The locale used for finite-number formatting
151
- * @returns The formatted string
875
+ * @param root - The root node to search
876
+ * @param predicate - The guard or predicate to test each node
877
+ * @returns The matching nodes in walk order
152
878
  *
153
879
  * @example
154
880
  * ```ts
155
- * import { formatValue } from '@src/core'
881
+ * import { compileTemplate, filterTemplateNodes } from '@orkestrel/template'
156
882
  *
157
- * formatValue(5010, 'en-US') // '5,010'
158
- * formatValue(null, 'en-US') // 'null'
883
+ * filterTemplateNodes(compileTemplate('{{ a }}{{ b }}'), (node) => node.syntax === 'output').length // 2
159
884
  * ```
160
885
  */
161
- export declare function formatValue(value: unknown, locale: string): string;
886
+ export declare function filterTemplateNodes<T extends TemplateNode>(root: TemplateNode, guard: (node: TemplateNode) => node is T): readonly T[];
887
+
888
+ export declare function filterTemplateNodes(root: TemplateNode, predicate: (node: TemplateNode) => boolean): readonly TemplateNode[];
162
889
 
163
890
  /**
164
- * Narrows an unknown caught value to a {@link TemplateError}.
891
+ * Finds the binding for a variable name across lexical scope frames from innermost
892
+ * to outermost.
165
893
  *
166
- * @remarks
894
+ * @param frames - The scope stack, outermost first
895
+ * @param name - The variable name to resolve
896
+ * @returns The bound runtime value, or `undefined` when unbound
897
+ *
898
+ * @example
899
+ * ```ts
900
+ * import { findTemplateName } from '@orkestrel/template'
901
+ *
902
+ * findTemplateName([new Map([['bos_token', '<s>']])], 'bos_token') // '<s>'
903
+ * ```
904
+ */
905
+ export declare function findTemplateName(frames: TemplateScope, name: string): TemplateRuntimeValue;
906
+
907
+ /**
908
+ * Finds the first {@link TemplateNode} in depth-first pre-order matching a
909
+ * guard or predicate.
910
+ *
911
+ * @param root - The root node to search
912
+ * @param predicate - The guard or predicate to test each node
913
+ * @returns The first matching node, or `undefined`
914
+ *
915
+ * @example
916
+ * ```ts
917
+ * import { compileTemplate, findTemplateNode } from '@orkestrel/template'
918
+ *
919
+ * findTemplateNode(compileTemplate('Hi {{ name }}'), (node) => node.syntax === 'output')?.syntax // 'output'
920
+ * ```
921
+ */
922
+ export declare function findTemplateNode<T extends TemplateNode>(root: TemplateNode, guard: (node: TemplateNode) => node is T): T | undefined;
923
+
924
+ export declare function findTemplateNode(root: TemplateNode, predicate: (node: TemplateNode) => boolean): TemplateNode | undefined;
925
+
926
+ /**
927
+ * Folds a {@link TemplateNode} bottom-up through a total {@link TemplateHandlerMap}
928
+ * covering every syntax variant, capped at `MAX_DEPTH`.
929
+ *
930
+ * @param node - The node to fold
931
+ * @param handlers - Total handler map keyed by `syntax`
932
+ * @param depth - Current recursion depth. Default: `0`
933
+ * @returns The folded result
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * import { compileTemplate, foldTemplateDocument } from '@orkestrel/template'
938
+ *
939
+ * const doc = compileTemplate('Hi')
940
+ * foldTemplateDocument(doc, {
941
+ * document: (_, children) => children.reduce((a, b) => a + b, 1),
942
+ * text: () => 1,
943
+ * placeholder: () => 1,
944
+ * output: () => 1,
945
+ * if: (_, children) => children.reduce((a, b) => a + b, 1),
946
+ * for: (_, children) => children.reduce((a, b) => a + b, 1),
947
+ * set: () => 1,
948
+ * macro: (_, children) => children.reduce((a, b) => a + b, 1),
949
+ * control: () => 1,
950
+ * comment: () => 1,
951
+ * html: () => 1,
952
+ * markdown: () => 1,
953
+ * }) // 2
954
+ * ```
955
+ */
956
+ export declare function foldTemplateDocument<T>(node: TemplateNode, handlers: TemplateHandlerMap<T>, depth?: number): T;
957
+
958
+ /**
959
+ * Formats a resolved fill value for substitution into a template's `content`.
960
+ *
961
+ * @remarks
962
+ * A finite number renders with the given locale's thousand grouping through
963
+ * `toLocaleString`. An `@orkestrel/html` node passes through `@orkestrel/html`'s
964
+ * sanitize floor before rendering with `renderHTML`, and an `@orkestrel/markdown`
965
+ * node renders with `renderMarkdown`. Every other value — including `null` —
966
+ * String-coerces.
967
+ *
968
+ * @param value - The resolved value to format
969
+ * @param locale - The locale used for finite-number formatting
970
+ * @returns The formatted string
971
+ *
972
+ * @example
973
+ * ```ts
974
+ * import { formatValue } from '@orkestrel/template'
975
+ *
976
+ * formatValue(5010, 'en-US') // '5,010'
977
+ * formatValue(null, 'en-US') // 'null'
978
+ * ```
979
+ */
980
+ export declare function formatValue(value: unknown, locale: string): string;
981
+
982
+ /**
983
+ * Checks whether a string token is one of the single-token {@link TemplateComparison} operators.
984
+ *
985
+ * @param value - The value to test
986
+ * @returns True if `value` is in `TEMPLATE_COMPARISONS`; false otherwise
987
+ *
988
+ * @example
989
+ * ```ts
990
+ * import { isTemplateComparison } from '@orkestrel/template'
991
+ *
992
+ * isTemplateComparison('==') // true
993
+ * isTemplateComparison('in') // false
994
+ * ```
995
+ */
996
+ export declare function isTemplateComparison(value: unknown): value is TemplateComparison;
997
+
998
+ /**
999
+ * Checks whether an unknown value is a structurally valid root {@link TemplateDocument}.
1000
+ *
1001
+ * @param value - The value to test
1002
+ * @returns True if `value` is a complete, cycle-free document within `MAX_DEPTH`; false otherwise
1003
+ *
1004
+ * @example
1005
+ * ```ts
1006
+ * import { isTemplateDocument } from '@orkestrel/template'
1007
+ *
1008
+ * isTemplateDocument({ syntax: 'document', children: [] }) // true
1009
+ * isTemplateDocument({ syntax: 'text', value: 'Hi' }) // false
1010
+ * ```
1011
+ */
1012
+ export declare function isTemplateDocument(value: unknown): value is TemplateDocument;
1013
+
1014
+ /**
1015
+ * Narrows an unknown caught value to a {@link TemplateError}.
1016
+ *
1017
+ * @remarks
167
1018
  * Recognizes self-branded errors from other package copies and subclasses, and
168
1019
  * refuses transparent proxies and unbranded look-alikes.
169
1020
  *
@@ -172,109 +1023,956 @@ import type { FieldPath } from '@orkestrel/contract';
172
1023
  *
173
1024
  * @example
174
1025
  * ```ts
175
- * import { isTemplateError } from '@src/core'
1026
+ * import { isTemplateError, TemplateError } from '@orkestrel/template'
1027
+ *
1028
+ * try {
1029
+ * throw new TemplateError('NOTFOUND', 'Unknown template id: missing', { id: 'missing' })
1030
+ * } catch (error) {
1031
+ * if (isTemplateError(error) && error.code === 'NOTFOUND') return
1032
+ * }
1033
+ * ```
1034
+ */
1035
+ export declare function isTemplateError(value: unknown): value is TemplateError;
1036
+
1037
+ /**
1038
+ * Checks whether an unknown value is a declared {@link TemplateErrorCode}.
1039
+ *
1040
+ * @param value - The value to test
1041
+ * @returns True if `value` is one of `TEMPLATE_ERROR_CODES`; false otherwise
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * import { isTemplateErrorCode } from '@orkestrel/template'
1046
+ *
1047
+ * isTemplateErrorCode('FORMAT') // true
1048
+ * isTemplateErrorCode('OTHER') // false
1049
+ * ```
1050
+ */
1051
+ export declare function isTemplateErrorCode(value: unknown): value is TemplateErrorCode;
1052
+
1053
+ /**
1054
+ * Checks whether an unknown value is a valid {@link TemplateExpression} within `MAX_DEPTH` and free of cycles.
1055
+ *
1056
+ * @param value - The value to test
1057
+ * @param depth - Current recursion depth. Default: `0`
1058
+ * @param ancestors - Ancestor set used to refuse reference cycles
1059
+ * @returns True if `value` is a well-formed expression; false otherwise
1060
+ *
1061
+ * @example
1062
+ * ```ts
1063
+ * import { isTemplateExpression } from '@orkestrel/template'
1064
+ *
1065
+ * isTemplateExpression({ term: 'literal', value: 'Hi' }) // true
1066
+ * isTemplateExpression({ term: 'unknown' }) // false
1067
+ * ```
1068
+ */
1069
+ export declare function isTemplateExpression(value: unknown, depth?: number, ancestors?: WeakSet<object>): value is TemplateExpression;
1070
+
1071
+ /**
1072
+ * Checks whether a runtime value is a `for` {@link TemplateLoop} state record.
1073
+ *
1074
+ * @param value - The runtime value to inspect
1075
+ * @returns True if `value` is a loop state record; false otherwise
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * import { isTemplateLoop } from '@orkestrel/template'
1080
+ *
1081
+ * isTemplateLoop({ index0: 0, length: 1, previtem: undefined, nextitem: undefined }) // true
1082
+ * ```
1083
+ */
1084
+ export declare function isTemplateLoop(value: unknown): value is TemplateLoop;
1085
+
1086
+ /**
1087
+ * Checks whether a runtime value is a compiled {@link TemplateMacro} closure.
1088
+ *
1089
+ * @param value - The runtime value to inspect
1090
+ * @returns True if `value` is a macro closure; false otherwise
1091
+ *
1092
+ * @example
1093
+ * ```ts
1094
+ * import { isTemplateMacro } from '@orkestrel/template'
1095
+ *
1096
+ * isTemplateMacro('text') // false
1097
+ * ```
1098
+ */
1099
+ export declare function isTemplateMacro(value: unknown): value is TemplateMacro;
1100
+
1101
+ /**
1102
+ * Checks whether an unknown value is a runtime {@link TemplateNamespace} container.
1103
+ *
1104
+ * @param value - The value to test
1105
+ * @returns True if `value` is a namespace container with a `Map` of bindings; false otherwise
1106
+ *
1107
+ * @example
1108
+ * ```ts
1109
+ * import { isTemplateNamespace } from '@orkestrel/template'
1110
+ *
1111
+ * isTemplateNamespace({ namespace: true, values: new Map() }) // true
1112
+ * isTemplateNamespace(new Map()) // false
1113
+ * ```
1114
+ */
1115
+ export declare function isTemplateNamespace(value: unknown): value is TemplateNamespace;
1116
+
1117
+ /**
1118
+ * Checks whether an unknown value is a valid {@link TemplateNode} within `MAX_DEPTH` and free of cycles.
1119
+ *
1120
+ * @param value - The value to test
1121
+ * @param depth - Current recursion depth. Default: `0`
1122
+ * @param ancestors - Ancestor set used to refuse reference cycles
1123
+ * @returns True if `value` is a structurally valid template AST node; false otherwise
1124
+ *
1125
+ * @example
1126
+ * ```ts
1127
+ * import { isTemplateNode } from '@orkestrel/template'
1128
+ *
1129
+ * isTemplateNode({ syntax: 'text', value: 'Hello' }) // true
1130
+ * isTemplateNode({ syntax: 'unknown' }) // false
1131
+ * ```
1132
+ */
1133
+ export declare function isTemplateNode(value: unknown, depth?: number, ancestors?: WeakSet<object>): value is TemplateNode;
1134
+
1135
+ /**
1136
+ * Checks whether an unknown value is a valid half-open {@link TemplateSpan}.
1137
+ *
1138
+ * @param value - The value to test
1139
+ * @returns True if `value` carries non-negative integer `start <= end`; false otherwise
1140
+ *
1141
+ * @example
1142
+ * ```ts
1143
+ * import { isTemplateSpan } from '@orkestrel/template'
1144
+ *
1145
+ * isTemplateSpan({ start: 0, end: 5 }) // true
1146
+ * isTemplateSpan({ start: 5, end: 2 }) // false
1147
+ * ```
1148
+ */
1149
+ export declare function isTemplateSpan(value: unknown): value is TemplateSpan;
1150
+
1151
+ /**
1152
+ * Checks whether an unknown value is a valid {@link TemplateTarget} (`local` or `attribute`).
1153
+ *
1154
+ * @param value - The value to test
1155
+ * @returns True if `value` is a well-formed assignment target; false otherwise
1156
+ *
1157
+ * @example
1158
+ * ```ts
1159
+ * import { isTemplateTarget } from '@orkestrel/template'
1160
+ *
1161
+ * isTemplateTarget({ scope: 'local', name: 'x' }) // true
1162
+ * isTemplateTarget({ scope: 'attribute', object: 'ns', name: 'count' }) // true
1163
+ * ```
1164
+ */
1165
+ export declare function isTemplateTarget(value: unknown): value is TemplateTarget;
1166
+
1167
+ /**
1168
+ * Locates a UTF-16 offset in a template source as a 1-based `[line, column]` pair.
1169
+ *
1170
+ * @param starts - The starting offset of each line in ascending order
1171
+ * @param offset - The offset to locate
1172
+ * @returns The 1-based line and column
1173
+ *
1174
+ * @example
1175
+ * ```ts
1176
+ * import { locateTemplateOffset } from '@orkestrel/template'
1177
+ *
1178
+ * locateTemplateOffset([0, 4], 5) // [2, 2]
1179
+ * ```
1180
+ */
1181
+ export declare function locateTemplateOffset(starts: readonly number[], offset: number): readonly [line: number, column: number];
1182
+
1183
+ /**
1184
+ * Rewrites a {@link TemplateDocument} bottom-up (copy-on-write) and returns the
1185
+ * rewritten document alongside its output-to-input derivation map.
1186
+ *
1187
+ * @param document - The document to rewrite
1188
+ * @param rewrite - The bottom-up node rewrite callback
1189
+ * @returns The rewritten document and its provenance derivations
1190
+ *
1191
+ * @example
1192
+ * ```ts
1193
+ * import { compileTemplate, mapTemplateDocument } from '@orkestrel/template'
1194
+ *
1195
+ * const [rewritten] = mapTemplateDocument(compileTemplate('hi'), (node) =>
1196
+ * node.syntax === 'text' ? { syntax: 'text', value: node.value.toUpperCase() } : node,
1197
+ * )
1198
+ * rewritten.children[0] // { syntax: 'text', value: 'HI' }
1199
+ * ```
1200
+ */
1201
+ export declare function mapTemplateDocument(document: TemplateDocument, rewrite: TemplateRewriteHandler): TemplateDerivation<TemplateDocument>;
1202
+
1203
+ /**
1204
+ * Maps each character position of `normalizeTemplateSource(source)` back to its
1205
+ * UTF-16 offset in the original unnormalized source.
1206
+ *
1207
+ * @param source - The original unnormalized template source
1208
+ * @returns The normalized text and its boundary-to-original offset array
1209
+ *
1210
+ * @example
1211
+ * ```ts
1212
+ * import { mapTemplateOffsets } from '@orkestrel/template'
1213
+ *
1214
+ * mapTemplateOffsets('a\r\nb')[1] // [0, 1, 3, 4]
1215
+ * ```
1216
+ */
1217
+ export declare function mapTemplateOffsets(source: string): readonly [normalized: string, offsets: readonly number[]];
1218
+
1219
+ /**
1220
+ * Checks whether two runtime template values are equal under Python `==` rules.
1221
+ *
1222
+ * @param left - The first value
1223
+ * @param right - The second value
1224
+ * @returns True if equal; false otherwise
1225
+ *
1226
+ * @example
1227
+ * ```ts
1228
+ * import { matchesTemplateEqual } from '@orkestrel/template'
1229
+ *
1230
+ * matchesTemplateEqual(true, 1) // true
1231
+ * matchesTemplateEqual('1', 1) // false
1232
+ * ```
1233
+ */
1234
+ export declare function matchesTemplateEqual(left: TemplateRuntimeValue, right: TemplateRuntimeValue): boolean;
1235
+
1236
+ /**
1237
+ * Checks whether a trailing text node ends with a whitespace-only line that
1238
+ * Jinja's `lstrip_blocks` would strip before a following block or comment tag.
1239
+ *
1240
+ * @param node - The preceding sibling node, if any
1241
+ * @param atLineStart - Whether the text node itself opened at a line start
1242
+ * @returns True if a `+` marker is needed to keep the whitespace verbatim; false otherwise
1243
+ *
1244
+ * @example
1245
+ * ```ts
1246
+ * import { matchesTemplateIndent } from '@orkestrel/template'
1247
+ *
1248
+ * matchesTemplateIndent({ syntax: 'text', value: ' ' }, true) // true
1249
+ * ```
1250
+ */
1251
+ export declare function matchesTemplateIndent(node: TemplateNode | undefined, atLineStart: boolean): boolean;
1252
+
1253
+ /**
1254
+ * Checks whether a container holds a value under Python `in` rules.
1255
+ *
1256
+ * @param value - The value to look for
1257
+ * @param container - The container to inspect
1258
+ * @returns True if `container` contains `value`; false otherwise
1259
+ *
1260
+ * @example
1261
+ * ```ts
1262
+ * import { matchesTemplateMember } from '@orkestrel/template'
1263
+ *
1264
+ * matchesTemplateMember('tool', 'tool_calls') // true
1265
+ * ```
1266
+ */
1267
+ export declare function matchesTemplateMember(value: TemplateRuntimeValue, container: TemplateRuntimeValue): boolean;
1268
+
1269
+ /**
1270
+ * Checks whether a scanned token matches an expected form and optional text.
1271
+ *
1272
+ * @param token - The token to inspect
1273
+ * @param form - The required token form
1274
+ * @param text - Optional exact text to match
1275
+ * @returns True if `token` matches; false otherwise
1276
+ *
1277
+ * @example
1278
+ * ```ts
1279
+ * import { matchesTemplateToken } from '@orkestrel/template'
1280
+ *
1281
+ * matchesTemplateToken({ token: 'name', text: 'in', line: 1, column: 1, start: 0, end: 2 }, 'name', 'in') // true
1282
+ * ```
1283
+ */
1284
+ export declare function matchesTemplateToken(token: TemplateToken, form: TemplateTokenForm, text?: string): boolean;
1285
+
1286
+ /**
1287
+ * Checks whether a runtime template value is truthy under Python `bool` rules.
1288
+ *
1289
+ * @param value - The value to test
1290
+ * @returns True if truthy; false otherwise
1291
+ *
1292
+ * @example
1293
+ * ```ts
1294
+ * import { matchesTemplateTruth } from '@orkestrel/template'
1295
+ *
1296
+ * matchesTemplateTruth('') // false
1297
+ * matchesTemplateTruth([0]) // true
1298
+ * ```
1299
+ */
1300
+ export declare function matchesTemplateTruth(value: TemplateRuntimeValue): boolean;
1301
+
1302
+ /**
1303
+ * Names how {@link TemplateInterface#fill} handles an unresolved required
1304
+ * placeholder.
1305
+ *
1306
+ * @remarks
1307
+ * `error` — throws a {@link TemplateError} coded `MISSING`. `empty` —
1308
+ * substitutes an empty string. `literal` — substitutes the placeholder's own
1309
+ * `{{name}}` token back into the output, unchanged.
1310
+ */
1311
+ export declare type MissingPolicy = 'error' | 'empty' | 'literal';
1312
+
1313
+ /**
1314
+ * Applies unary `-` or `+` to a numeric runtime template value.
1315
+ *
1316
+ * @param operator - `'-'` for negation or `'+'` for numeric identity
1317
+ * @param value - The numeric operand
1318
+ * @returns The resulting number
1319
+ *
1320
+ * @example
1321
+ * ```ts
1322
+ * import { negateTemplateValue } from '@orkestrel/template'
1323
+ *
1324
+ * negateTemplateValue('-', 1) // -1
1325
+ * ```
1326
+ */
1327
+ export declare function negateTemplateValue(operator: '-' | '+', value: TemplateRuntimeValue): number;
1328
+
1329
+ /**
1330
+ * Collapses line breaks inside inline markdown text to single spaces so inline
1331
+ * spans stay on one line through round-trip parsing.
1332
+ *
1333
+ * @param value - The inline text string to normalize
1334
+ * @returns The single-line string with `\r\n`, `\r`, and `\n` replaced by `' '`
1335
+ *
1336
+ * @example
1337
+ * ```ts
1338
+ * import { normalizeTemplateMarkdownText } from '@orkestrel/template'
1339
+ *
1340
+ * normalizeTemplateMarkdownText('a\n\nb') // 'a b'
1341
+ * ```
1342
+ */
1343
+ export declare function normalizeTemplateMarkdownText(value: string): string;
1344
+
1345
+ /**
1346
+ * Normalizes a Jinja template source by converting every line ending to `\n`
1347
+ * and dropping one trailing line ending when present.
1348
+ *
1349
+ * @param source - The raw template source
1350
+ * @returns The normalized source text
1351
+ *
1352
+ * @example
1353
+ * ```ts
1354
+ * import { normalizeTemplateSource } from '@orkestrel/template'
1355
+ *
1356
+ * normalizeTemplateSource('Hi\r\n\r\n') // 'Hi\n'
1357
+ * ```
1358
+ */
1359
+ export declare function normalizeTemplateSource(source: string): string;
1360
+
1361
+ /**
1362
+ * Normalizes a caller-supplied value into a runtime {@link TemplateRuntimeValue},
1363
+ * converting plain objects to string-keyed `Map`s while preserving `HTMLNode`,
1364
+ * `MarkdownNode`, and `TemplateNamespace` instances and capping depth at `MAX_DEPTH`.
1365
+ *
1366
+ * @param value - The value to normalize
1367
+ * @param depth - Current recursion depth. Default: `0`
1368
+ * @param ancestors - Ancestor set used to guard against cycles
1369
+ * @returns The normalized runtime value
1370
+ *
1371
+ * @example
1372
+ * ```ts
1373
+ * import { normalizeTemplateValue } from '@orkestrel/template'
1374
+ *
1375
+ * normalizeTemplateValue({ role: 'user' }) // Map { 'role' => 'user' }
1376
+ * ```
1377
+ */
1378
+ export declare function normalizeTemplateValue(value: unknown, depth?: number, ancestors?: WeakSet<object>): TemplateRuntimeValue;
1379
+
1380
+ /**
1381
+ * Parses an unknown input into a {@link TemplateDocument}, returning `undefined`
1382
+ * on malformed syntax, unadmitted constructs, exceeded depth, or off-shape input
1383
+ * without throwing.
1384
+ *
1385
+ * @param source - A Jinja template string or an already-built {@link TemplateDocument}
1386
+ * @returns A validated {@link TemplateDocument}, or `undefined` when invalid
1387
+ *
1388
+ * @example
1389
+ * ```ts
1390
+ * import { parseTemplate } from '@orkestrel/template'
1391
+ *
1392
+ * parseTemplate('Hi {{ name }}')?.syntax // 'document'
1393
+ * parseTemplate('{% if unclosed %}') // undefined
1394
+ * ```
1395
+ */
1396
+ export declare function parseTemplate(source: unknown): TemplateDocument | undefined;
1397
+
1398
+ /**
1399
+ * Builds the `@orkestrel/contract` object shape describing a template's
1400
+ * declared placeholders.
1401
+ *
1402
+ * @remarks
1403
+ * Each placeholder becomes a `stringShape` carrying its `description`;
1404
+ * `required === false` wraps it in `optionalShape`. Used by `Template` to
1405
+ * compile its `parameters()` contract once per instance.
1406
+ *
1407
+ * @param placeholders - The declared placeholders to shape
1408
+ * @returns The contract shape for `createContract`
1409
+ *
1410
+ * @example
1411
+ * ```ts
1412
+ * import { placeholderShape } from '@orkestrel/template'
1413
+ * import { createContract } from '@orkestrel/contract'
1414
+ *
1415
+ * const contract = createContract(placeholderShape([{ name: 'city' }]))
1416
+ * ```
1417
+ */
1418
+ export declare function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape;
1419
+
1420
+ /**
1421
+ * Quotes untrusted text for a template error message as a length-capped JSON
1422
+ * string literal.
1423
+ *
1424
+ * @param value - The raw text to quote
1425
+ * @returns The quoted diagnostic text
1426
+ *
1427
+ * @example
1428
+ * ```ts
1429
+ * import { quoteTemplateText } from '@orkestrel/template'
1430
+ *
1431
+ * quoteTemplateText('tojson') // '"tojson"'
1432
+ * ```
1433
+ */
1434
+ export declare function quoteTemplateText(value: string): string;
1435
+
1436
+ /**
1437
+ * Reads a member or index of a runtime template value under sandboxed Jinja rules,
1438
+ * supporting negative sequence indexing, `TemplateNamespace` properties, and
1439
+ * `loop.previtem` / `loop.nextitem`.
1440
+ *
1441
+ * @param object - The object or sequence to read from
1442
+ * @param key - The member name or integer index
1443
+ * @returns The resolved member value, or `undefined` when absent
1444
+ *
1445
+ * @example
1446
+ * ```ts
1447
+ * import { readTemplateMember } from '@orkestrel/template'
1448
+ *
1449
+ * readTemplateMember(['a', 'b'], -1) // 'b'
1450
+ * ```
1451
+ */
1452
+ export declare function readTemplateMember(object: TemplateRuntimeValue, key: TemplateRuntimeValue): TemplateRuntimeValue;
1453
+
1454
+ /**
1455
+ * Reads the token at an index of a token stream, throwing on `fault` tokens or
1456
+ * an empty stream.
1457
+ *
1458
+ * @param tokens - The token stream
1459
+ * @param index - The index to read
1460
+ * @returns The resolved token
1461
+ *
1462
+ * @example
1463
+ * ```ts
1464
+ * import { readTemplateToken, scanTemplateTokens } from '@orkestrel/template'
1465
+ *
1466
+ * readTemplateToken(scanTemplateTokens('{{ x }}'), 1).text // 'x'
1467
+ * ```
1468
+ */
1469
+ export declare function readTemplateToken(tokens: readonly TemplateToken[], index: number): TemplateToken;
1470
+
1471
+ /**
1472
+ * Reduces a {@link TemplateNode} depth-first in pre-order into one accumulated value.
1473
+ *
1474
+ * @param root - The root node to reduce
1475
+ * @param callback - The step combining the accumulated value and each visited node
1476
+ * @param initial - The initial accumulated value
1477
+ * @returns The final accumulated value
1478
+ *
1479
+ * @example
1480
+ * ```ts
1481
+ * import { compileTemplate, reduceTemplateDocument } from '@orkestrel/template'
1482
+ *
1483
+ * reduceTemplateDocument(compileTemplate('Hi {{ name }}'), (count) => count + 1, 0) // 3
1484
+ * ```
1485
+ */
1486
+ export declare function reduceTemplateDocument<T>(root: TemplateNode, callback: (value: T, node: TemplateNode) => T, initial: T): T;
1487
+
1488
+ /**
1489
+ * Renders a {@link TemplateNode} back to canonical template source text.
1490
+ *
1491
+ * @remarks
1492
+ * For every compiled pure-Jinja {@link TemplateDocument}, `compileTemplate(renderTemplate(doc))`
1493
+ * produces a structurally equal document and `renderTemplate(compileTemplate(renderTemplate(doc)))`
1494
+ * equals `renderTemplate(doc)`.
1495
+ *
1496
+ * @param node - The node or document to render
1497
+ * @returns The canonical template source text
1498
+ *
1499
+ * @example
1500
+ * ```ts
1501
+ * import { compileTemplate, renderTemplate } from '@orkestrel/template'
1502
+ *
1503
+ * renderTemplate(compileTemplate('Hi {{ name }}')) // 'Hi {{ name }}'
1504
+ * ```
1505
+ */
1506
+ export declare function renderTemplate(node: TemplateNode): string;
1507
+
1508
+ /**
1509
+ * Renders a {@link TemplateExpression} back to canonical Jinja expression syntax
1510
+ * that compiles back to an equivalent AST.
1511
+ *
1512
+ * @param expression - The expression to render
1513
+ * @returns Canonical Jinja expression text
1514
+ *
1515
+ * @example
1516
+ * ```ts
1517
+ * import { renderTemplateExpression } from '@orkestrel/template'
1518
+ *
1519
+ * renderTemplateExpression({ term: 'name', name: 'messages' }) // 'messages'
1520
+ * ```
1521
+ */
1522
+ export declare function renderTemplateExpression(expression: TemplateExpression): string;
1523
+
1524
+ /**
1525
+ * Renders an ordered list of sibling {@link TemplateNode}s into canonical source
1526
+ * text, preserving leading whitespace and trailing newlines against Jinja's
1527
+ * `lstrip_blocks` and `trim_blocks` rules with `+` markers where needed.
1528
+ *
1529
+ * @param nodes - The sibling nodes to render
1530
+ * @param precedingNewline - Whether the list opens at a line boundary
1531
+ * @returns The canonical template source for the node list
1532
+ *
1533
+ * @example
1534
+ * ```ts
1535
+ * import { renderTemplateNodes } from '@orkestrel/template'
1536
+ *
1537
+ * renderTemplateNodes([{ syntax: 'text', value: 'Hi' }], true) // 'Hi'
1538
+ * ```
1539
+ */
1540
+ export declare function renderTemplateNodes(nodes: readonly TemplateNode[], precedingNewline: boolean): string;
1541
+
1542
+ /**
1543
+ * Renders a finite or special number using Python `str` formatting.
1544
+ *
1545
+ * @param value - The number to format
1546
+ * @returns The Python-formatted numeric text
1547
+ *
1548
+ * @example
1549
+ * ```ts
1550
+ * import { renderTemplateNumber } from '@orkestrel/template'
1551
+ *
1552
+ * renderTemplateNumber(0.00001) // '1e-05'
1553
+ * ```
1554
+ */
1555
+ export declare function renderTemplateNumber(value: number): string;
1556
+
1557
+ /**
1558
+ * Renders one emitted {@link TemplatePart} to string text, sanitizing `HTMLNode`s
1559
+ * through `@orkestrel/html` and rendering `MarkdownNode`s through `@orkestrel/markdown`.
1560
+ *
1561
+ * @param part - The emitted template part
1562
+ * @param options - Optional evaluation and sanitize settings
1563
+ * @returns The rendered string
1564
+ *
1565
+ * @example
1566
+ * ```ts
1567
+ * import { renderTemplatePart } from '@orkestrel/template'
1568
+ *
1569
+ * renderTemplatePart({ category: 'text', value: 'a & b' }) // 'a &amp; b'
1570
+ * ```
1571
+ */
1572
+ export declare function renderTemplatePart(part: TemplatePart, options?: TemplateEvaluateOptions): string;
1573
+
1574
+ /**
1575
+ * Renders a scanned token into a readable label for syntax diagnostics.
1576
+ *
1577
+ * @param token - The token to describe
1578
+ * @returns The human-readable token description
1579
+ *
1580
+ * @example
1581
+ * ```ts
1582
+ * import { renderTemplateToken } from '@orkestrel/template'
1583
+ *
1584
+ * renderTemplateToken({ token: 'end', text: '', line: 1, column: 1, start: 0, end: 0 }) // 'the end of the template'
1585
+ * ```
1586
+ */
1587
+ export declare function renderTemplateToken(token: TemplateToken): string;
1588
+
1589
+ /**
1590
+ * Renders the Python-equivalent type label of a runtime value for diagnostics.
1591
+ *
1592
+ * @param value - The runtime value to describe
1593
+ * @returns The type description
1594
+ *
1595
+ * @example
1596
+ * ```ts
1597
+ * import { renderTemplateType } from '@orkestrel/template'
1598
+ *
1599
+ * renderTemplateType(new Map()) // 'a mapping'
1600
+ * ```
1601
+ */
1602
+ export declare function renderTemplateType(value: TemplateRuntimeValue): string;
1603
+
1604
+ /**
1605
+ * Renders a runtime template value as string output using Python/Jinja rules,
1606
+ * sanitizing `HTMLNode`s through `@orkestrel/html` and rendering `MarkdownNode`s
1607
+ * through `@orkestrel/markdown`.
1608
+ *
1609
+ * @param value - The runtime value to render
1610
+ * @returns The rendered text
1611
+ *
1612
+ * @example
1613
+ * ```ts
1614
+ * import { renderTemplateValue } from '@orkestrel/template'
1615
+ *
1616
+ * renderTemplateValue(true) // 'True'
1617
+ * renderTemplateValue(null) // 'None'
1618
+ * ```
1619
+ */
1620
+ export declare function renderTemplateValue(value: TemplateRuntimeValue): string;
1621
+
1622
+ /**
1623
+ * Resolves a Private Use Area sentinel prefix guaranteed absent from `combined`.
1624
+ *
1625
+ * @param combined - Concatenated template text and fill values in one markdown run
1626
+ * @returns The collision-free sentinel prefix
1627
+ *
1628
+ * @example
1629
+ * ```ts
1630
+ * import { resolveMarkdownMarker } from '@orkestrel/template'
1631
+ *
1632
+ * resolveMarkdownMarker('plain text') // '\uE000\uE001'
1633
+ * ```
1634
+ */
1635
+ export declare function resolveMarkdownMarker(combined: string): string;
1636
+
1637
+ /**
1638
+ * Resolves a field path against a fill-values record, refusing any path that
1639
+ * touches a prototype-pollution-unsafe segment.
1640
+ *
1641
+ * @param record - The fill-values record to resolve against
1642
+ * @param path - The field path — a single segment or a segment array
1643
+ * @returns The resolved value, or `undefined` when unresolved or the path is unsafe
1644
+ *
1645
+ * @example
1646
+ * ```ts
1647
+ * import { resolveSafeField } from '@orkestrel/template'
1648
+ *
1649
+ * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1
1650
+ * resolveSafeField({}, ['__proto__', 'polluted']) // undefined
1651
+ * ```
1652
+ */
1653
+ export declare function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown;
1654
+
1655
+ /**
1656
+ * Resolves one `{{name}}` token against the declared placeholders and the
1657
+ * fill-values record.
1658
+ *
1659
+ * @param record - The fill-values record the token resolves against
1660
+ * @param placeholders - The declared placeholders the token matches by name
1661
+ * @param token - The trimmed token text, without its `{{` / `}}` delimiters
1662
+ * @returns The {@link TemplateTokenResolution} for the token
1663
+ *
1664
+ * @example
1665
+ * ```ts
1666
+ * import { resolveToken } from '@orkestrel/template'
1667
+ *
1668
+ * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'
1669
+ * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false
1670
+ * ```
1671
+ */
1672
+ export declare function resolveToken(record: TemplateFillValues, placeholders: readonly TemplatePlaceholder[], token: string): TemplateTokenResolution;
1673
+
1674
+ /**
1675
+ * Restores sentinel slots inside a parsed block markdown node, keeping
1676
+ * verbatim line breaks only inside `CodeBlockNode.code` and sanitizing
1677
+ * `CodeBlockNode.lang` to a single token.
1678
+ *
1679
+ * @param node - Block node parsed from sentinel-substituted markdown
1680
+ * @param pattern - RegExp matching sentinel slots
1681
+ * @param fills - Indexed dynamic fill strings
1682
+ * @param depth - Current recursion depth. Default: `0`
1683
+ * @returns The block node with dynamic fills restored as literal leaves
1684
+ *
1685
+ * @example
1686
+ * ```ts
1687
+ * import { restoreMarkdownBlock } from '@orkestrel/template'
1688
+ *
1689
+ * restoreMarkdownBlock({ element: 'thematicBreak' }, /\uE000\uE001(\d+)\uE003/gu, []) // { element: 'thematicBreak' }
1690
+ * ```
1691
+ */
1692
+ export declare function restoreMarkdownBlock(node: BlockNode, pattern: RegExp, fills: readonly string[], depth?: number): BlockNode;
1693
+
1694
+ /**
1695
+ * Restores sentinel slots inside a list of parsed inline markdown nodes,
1696
+ * collapsing line breaks inside substituted dynamic fills and `CodeSpanNode`
1697
+ * values so inline content stays single-line across round-trips.
1698
+ *
1699
+ * @param nodes - Inline nodes parsed from sentinel-substituted markdown
1700
+ * @param pattern - RegExp matching sentinel slots
1701
+ * @param fills - Indexed dynamic fill strings
1702
+ * @param depth - Current recursion depth. Default: `0`
1703
+ * @returns The inline nodes with dynamic fills restored as literal leaves
1704
+ *
1705
+ * @example
1706
+ * ```ts
1707
+ * import { restoreMarkdownInlines } from '@orkestrel/template'
1708
+ *
1709
+ * restoreMarkdownInlines([{ element: 'text', value: 'hi' }], /\uE000\uE001(\d+)\uE003/gu, []) // [{ element: 'text', value: 'hi' }]
1710
+ * ```
1711
+ */
1712
+ export declare function restoreMarkdownInlines(nodes: readonly InlineNode[], pattern: RegExp, fills: readonly string[], depth?: number): readonly InlineNode[];
1713
+
1714
+ /**
1715
+ * Replaces every sentinel slot in a parsed markdown leaf string with its
1716
+ * literal dynamic fill string in a single pass.
1717
+ *
1718
+ * @param text - Parsed leaf string possibly holding sentinel slots
1719
+ * @param pattern - RegExp matching sentinel slots for this run
1720
+ * @param fills - Indexed dynamic fill strings
1721
+ * @returns The restored literal string
1722
+ *
1723
+ * @example
1724
+ * ```ts
1725
+ * import { restoreMarkdownText } from '@orkestrel/template'
1726
+ *
1727
+ * restoreMarkdownText('\uE000\uE0010\uE003', /\uE000\uE001(\d+)\uE003/gu, ['Ada']) // 'Ada'
1728
+ * ```
1729
+ */
1730
+ export declare function restoreMarkdownText(text: string, pattern: RegExp, fills: readonly string[]): string;
1731
+
1732
+ /**
1733
+ * Rewrites one {@link TemplateNode} bottom-up with copy-on-write identity
1734
+ * preservation, recording each rebuilt node's direct source in `derivations`.
1735
+ *
1736
+ * @param node - The node to rewrite
1737
+ * @param rewrite - The bottom-up rewrite callback
1738
+ * @param derivations - Operation-owned derivation map
1739
+ * @param depth - Current recursion depth
1740
+ * @returns The rewritten node
1741
+ *
1742
+ * @example
1743
+ * ```ts
1744
+ * import { rewriteTemplateNode } from '@orkestrel/template'
1745
+ *
1746
+ * rewriteTemplateNode({ syntax: 'text', value: 'hi' }, (node) => node, new Map(), 0)
1747
+ * ```
1748
+ */
1749
+ export declare function rewriteTemplateNode(node: TemplateNode, rewrite: TemplateRewriteHandler, derivations: Map<TemplateNode, TemplateNode | undefined>, depth: number): TemplateNode;
1750
+
1751
+ /**
1752
+ * Executes a sequence of compiled {@link TemplateNode}s in order, tagging each
1753
+ * emitted part with whether it came from literal template text (`true`) or a
1754
+ * dynamic expression/placeholder (`false`).
1755
+ *
1756
+ * @param nodes - The nodes to execute in order
1757
+ * @param frames - Active lexical scope frames
1758
+ * @param namespaces - Evaluation-owned mutable namespace registry
1759
+ * @param options - Optional evaluation settings
1760
+ * @param callDepth - Current macro call depth. Default: `0`
1761
+ * @returns The tagged emitted parts, updated scope frames, and optional loop control signal
1762
+ *
1763
+ * @example
1764
+ * ```ts
1765
+ * import { runTemplateNodes } from '@orkestrel/template'
1766
+ *
1767
+ * runTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // [[true, 'Hi']]
1768
+ * ```
1769
+ */
1770
+ export declare function runTemplateNodes(nodes: readonly TemplateNode[], frames: TemplateScope, namespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>, options?: TemplateEvaluateOptions, callDepth?: number): readonly [
1771
+ parts: ReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,
1772
+ frames: TemplateScope,
1773
+ control: 'break' | 'continue' | undefined
1774
+ ];
1775
+
1776
+ /**
1777
+ * Normalizes an `@orkestrel/html` node into a document and enforces
1778
+ * `@orkestrel/html`'s unlowerable sanitize floor, failing closed to an empty
1779
+ * document on off-shape input.
1780
+ *
1781
+ * @param node - The HTML document or node to sanitize
1782
+ * @param options - Optional allowlist overrides (cannot lower `@orkestrel/html`'s security floor)
1783
+ * @returns The sanitized {@link HTMLDocument}
1784
+ *
1785
+ * @example
1786
+ * ```ts
1787
+ * import { sanitizeTemplateHTML } from '@orkestrel/template'
1788
+ *
1789
+ * sanitizeTemplateHTML({ category: 'element', name: 'script', attributes: [], children: [] }).children // []
1790
+ * ```
1791
+ */
1792
+ export declare function sanitizeTemplateHTML(node: HTMLNode, options?: HTMLSanitizeOptions): HTMLDocument;
1793
+
1794
+ /**
1795
+ * Sanitizes a `@orkestrel/markdown` node recursively by unwrapping any
1796
+ * `LinkNode` whose `href` fails `sanitizeURL`, dropping any `ImageNode` whose
1797
+ * `src` fails `sanitizeURL`, collapsing `CodeSpanNode` line breaks, and
1798
+ * sanitizing `CodeBlockNode` fence languages.
1799
+ *
1800
+ * @param node - The markdown AST node to sanitize
1801
+ * @param options - Optional HTML sanitization allowlist settings
1802
+ * @param depth - Current recursion depth. Default: `0`
1803
+ * @returns The sanitized node, or `undefined` when dropped
1804
+ *
1805
+ * @example
1806
+ * ```ts
1807
+ * import { parseMarkdown } from '@orkestrel/markdown'
1808
+ * import { sanitizeTemplateMarkdown } from '@orkestrel/template'
1809
+ *
1810
+ * sanitizeTemplateMarkdown(parseMarkdown('![x](javascript:alert(1))')) // { element: 'document', children: [{ element: 'paragraph', children: [] }] }
1811
+ * ```
1812
+ */
1813
+ export declare function sanitizeTemplateMarkdown(node: MarkdownNode, options?: HTMLSanitizeOptions, depth?: number): MarkdownNode | undefined;
1814
+
1815
+ /**
1816
+ * Sanitizes block `@orkestrel/markdown` nodes recursively through
1817
+ * `sanitizeTemplateMarkdown`, dropping any node that sanitizes to `undefined`.
1818
+ *
1819
+ * @param nodes - The block nodes to sanitize
1820
+ * @param options - Optional HTML sanitization allowlist settings
1821
+ * @param depth - Current recursion depth. Default: `0`
1822
+ * @returns The sanitized block nodes
1823
+ *
1824
+ * @example
1825
+ * ```ts
1826
+ * import { parseMarkdown } from '@orkestrel/markdown'
1827
+ * import { sanitizeTemplateMarkdownBlocks } from '@orkestrel/template'
1828
+ *
1829
+ * sanitizeTemplateMarkdownBlocks(parseMarkdown('Hi').children).length // 1
1830
+ * ```
1831
+ */
1832
+ export declare function sanitizeTemplateMarkdownBlocks(nodes: readonly BlockNode[], options?: HTMLSanitizeOptions, depth?: number): readonly BlockNode[];
1833
+
1834
+ /**
1835
+ * Sanitizes inline `@orkestrel/markdown` nodes recursively by unwrapping unsafe
1836
+ * `LinkNode` elements, dropping unsafe `ImageNode` elements, and collapsing
1837
+ * line breaks inside `CodeSpanNode` values.
1838
+ *
1839
+ * @param nodes - The inline nodes to sanitize
1840
+ * @param options - Optional HTML sanitization allowlist settings
1841
+ * @param depth - Current recursion depth. Default: `0`
1842
+ * @returns The sanitized inline nodes
1843
+ *
1844
+ * @example
1845
+ * ```ts
1846
+ * import { parseInline } from '@orkestrel/markdown'
1847
+ * import { sanitizeTemplateMarkdownInlines } from '@orkestrel/template'
1848
+ *
1849
+ * sanitizeTemplateMarkdownInlines(parseInline('[x](javascript:alert(1))')) // [{ element: 'text', value: 'x' }]
1850
+ * ```
1851
+ */
1852
+ export declare function sanitizeTemplateMarkdownInlines(nodes: readonly InlineNode[], options?: HTMLSanitizeOptions, depth?: number): readonly InlineNode[];
1853
+
1854
+ /**
1855
+ * Sanitizes a fenced code block language info string to a single token free of
1856
+ * whitespace, line breaks, backticks, and tildes.
1857
+ *
1858
+ * @param lang - The raw fence info-string language value
1859
+ * @returns The sanitized single-token language tag, or `undefined` when empty
1860
+ *
1861
+ * @example
1862
+ * ```ts
1863
+ * import { sanitizeTemplateMarkdownLanguage } from '@orkestrel/template'
1864
+ *
1865
+ * sanitizeTemplateMarkdownLanguage('ts\n```\n[x](javascript:alert(1))') // 'ts'
1866
+ * sanitizeTemplateMarkdownLanguage(' ') // undefined
1867
+ * ```
1868
+ */
1869
+ export declare function sanitizeTemplateMarkdownLanguage(lang: string): string | undefined;
1870
+
1871
+ /**
1872
+ * Scans the interior of one Jinja tag into lexical tokens with original UTF-16
1873
+ * offsets and 1-based line and column positions.
1874
+ *
1875
+ * @param text - The tag interior between delimiters
1876
+ * @param offset - The normalized-source offset of the tag interior's start
1877
+ * @param starts - Line-start offsets in the normalized source
1878
+ * @param offsets - Boundary map from normalized offsets to original UTF-16 offsets
1879
+ * @returns The scanned tokens inside the tag
1880
+ *
1881
+ * @example
1882
+ * ```ts
1883
+ * import { scanTemplateTag } from '@orkestrel/template'
1884
+ *
1885
+ * scanTemplateTag(' loop.first ', 2, [0]).map((token) => token.text) // ['loop', '.', 'first']
1886
+ * ```
1887
+ */
1888
+ export declare function scanTemplateTag(text: string, offset: number, starts: readonly number[], offsets?: readonly number[]): readonly TemplateToken[];
1889
+
1890
+ /**
1891
+ * Scans a raw Jinja template source into its token stream, including trimmed
1892
+ * text, comments, tag delimiters, inner tokens, and a closing `end` token.
1893
+ *
1894
+ * @param source - The template source
1895
+ * @returns The scanned tokens, ending with an `end` token
1896
+ *
1897
+ * @example
1898
+ * ```ts
1899
+ * import { scanTemplateTokens } from '@orkestrel/template'
176
1900
  *
177
- * try {
178
- * manager.fill('missing')
179
- * } catch (error) {
180
- * if (isTemplateError(error) && error.code === 'NOTFOUND') return
181
- * }
1901
+ * scanTemplateTokens('Hi {{ name }}').map((token) => token.token)
1902
+ * // ['text', 'variable', 'name', 'close', 'end']
182
1903
  * ```
183
1904
  */
184
- export declare function isTemplateError(value: unknown): value is TemplateError;
1905
+ export declare function scanTemplateTokens(source: string): readonly TemplateToken[];
185
1906
 
186
1907
  /**
187
- * Names how {@link TemplateInterface#fill} handles an unresolved required
188
- * placeholder.
1908
+ * Serializes a runtime template value to deterministic JSON matching `minja`
1909
+ * and Python `json.dumps` (`", "` and `": "` separators, insertion key order,
1910
+ * unescaped non-ASCII Unicode).
189
1911
  *
190
- * @remarks
191
- * `error` — throws a {@link TemplateError} coded `MISSING`. `empty` —
192
- * substitutes an empty string. `literal` — substitutes the placeholder's own
193
- * `{{name}}` token back into the output, unchanged.
1912
+ * @param value - The runtime value to serialize
1913
+ * @param depth - Current recursion depth. Default: `0`
1914
+ * @param ancestors - Ancestor set used to guard against cycles
1915
+ * @returns The serialized JSON string
1916
+ *
1917
+ * @example
1918
+ * ```ts
1919
+ * import { serializeTemplateJSON } from '@orkestrel/template'
1920
+ *
1921
+ * serializeTemplateJSON(new Map([['b', true], ['a', [1, 2]]])) // '{"b": true, "a": [1, 2]}'
1922
+ * ```
194
1923
  */
195
- export declare type MissingPolicy = 'error' | 'empty' | 'literal';
1924
+ export declare function serializeTemplateJSON(value: TemplateRuntimeValue, depth?: number, ancestors?: WeakSet<object>): string;
196
1925
 
197
1926
  /**
198
- * Builds the `@orkestrel/contract` object shape describing a template's
199
- * declared placeholders.
200
- *
201
- * @remarks
202
- * Each placeholder becomes a `stringShape` carrying its `description`;
203
- * `required === false` wraps it in `optionalShape`. Used by `Template` to
204
- * compile its `parameters()` contract once per instance.
1927
+ * Slices a string (by Unicode code points) or list under Python
1928
+ * `seq[start:stop:step]` semantics, including negative bounds and `[::-1]`.
205
1929
  *
206
- * @param placeholders - The declared placeholders to shape
207
- * @returns The contract shape for `createContract`
1930
+ * @param object - The string or list to slice
1931
+ * @param start - Optional inclusive start index (`undefined` or `null` for default)
1932
+ * @param stop - Optional exclusive stop index (`undefined` or `null` for default)
1933
+ * @param step - Optional non-zero stride (`undefined` or `null` for `1`)
1934
+ * @returns The sliced string or list
208
1935
  *
209
1936
  * @example
210
1937
  * ```ts
211
- * import { placeholderShape } from '@src/core'
212
- * import { createContract } from '@orkestrel/contract'
1938
+ * import { sliceTemplateSequence } from '@orkestrel/template'
213
1939
  *
214
- * const contract = createContract(placeholderShape([{ name: 'city' }]))
1940
+ * sliceTemplateSequence(['a', 'b', 'c'], undefined, undefined, -1) // ['c', 'b', 'a']
215
1941
  * ```
216
1942
  */
217
- export declare function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape;
1943
+ export declare function sliceTemplateSequence(object: TemplateRuntimeValue, start: TemplateRuntimeValue, stop: TemplateRuntimeValue, step: TemplateRuntimeValue): TemplateRuntimeValue;
218
1944
 
219
1945
  /**
220
- * Resolves a field path against a fill-values record, refusing any path that
221
- * touches a prototype-pollution-unsafe segment.
1946
+ * Creates a fresh, pull-based `ReadableStream` over a {@link TemplateDocument}'s
1947
+ * direct top-level children in source order.
222
1948
  *
223
- * @remarks
224
- * A prototype-pollution guard shared by `fillTemplate` and `Template#validate`
225
- * so the two stay in lockstep: `path` normalizes to a segment array (a bare
226
- * string `path` becomes a single-segment array); if any segment appears in
227
- * `UNSAFE_FIELD_SEGMENTS` (`'__proto__'`, `'constructor'`, `'prototype'`), the
228
- * lookup is refused and `undefined` is returned without ever calling
229
- * `resolveField` — a path like `['__proto__', 'polluted']` can never reach
230
- * the record's actual prototype chain through this function. Every other
231
- * path resolves through `@orkestrel/contract`'s `resolveField`.
232
- *
233
- * @param record - The fill-values record to resolve against
234
- * @param path - The field path — a single segment or a segment array
235
- * @returns The resolved value, or `undefined` when unresolved or the path is unsafe
1949
+ * @param document - The document whose top-level children to stream
1950
+ * @returns A pull-based stream yielding one top-level node per pull
236
1951
  *
237
1952
  * @example
238
1953
  * ```ts
239
- * import { resolveSafeField } from '@src/core'
1954
+ * import { compileTemplate, streamTemplateNodes } from '@orkestrel/template'
240
1955
  *
241
- * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1
242
- * resolveSafeField({}, ['__proto__', 'polluted']) // undefined
1956
+ * const reader = streamTemplateNodes(compileTemplate('Hi {{ name }}')).getReader()
243
1957
  * ```
244
1958
  */
245
- export declare function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown;
1959
+ export declare function streamTemplateNodes(document: TemplateDocument): ReadableStream<TemplateNode>;
246
1960
 
247
1961
  /**
248
- * Resolves one `{{name}}` token against the declared placeholders and the
249
- * fill-values record.
250
- *
251
- * @remarks
252
- * The single implementation of the token rule `fillTemplate` and
253
- * `Template#validate` both apply, so the two can never drift: the declared
254
- * {@link TemplatePlaceholder} sharing the token's `name` (exact match)
255
- * supplies its `path`, falling back to the token split on `.`; the value
256
- * resolves through `resolveSafeField`, so any segment in
257
- * `UNSAFE_FIELD_SEGMENTS` yields `undefined` without ever calling
258
- * `resolveField`; `required` is `true` for an undeclared token and for a
259
- * declared placeholder whose `required` is not `false`. The token is passed
260
- * already trimmed. `fallback` is not applied here — it is read from
261
- * `declared` by each caller, because `fill` substitutes it and `validate`
262
- * only counts it.
1962
+ * Subtracts two numeric runtime template values under Python `-` rules.
263
1963
  *
264
- * @param record - The fill-values record the token resolves against
265
- * @param placeholders - The declared placeholders the token matches by name
266
- * @param token - The trimmed token text, without its `{{` / `}}` delimiters
267
- * @returns The {@link TemplateTokenResolution} for the token
1964
+ * @param left - The left numeric operand
1965
+ * @param right - The right numeric operand
1966
+ * @returns The numeric difference
268
1967
  *
269
1968
  * @example
270
1969
  * ```ts
271
- * import { resolveToken } from '@src/core'
1970
+ * import { subtractTemplateValues } from '@orkestrel/template'
272
1971
  *
273
- * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'
274
- * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false
1972
+ * subtractTemplateValues(5, 1) // 4
275
1973
  * ```
276
1974
  */
277
- export declare function resolveToken(record: TemplateFillValues, placeholders: readonly TemplatePlaceholder[], token: string): TemplateTokenResolution;
1975
+ export declare function subtractTemplateValues(left: TemplateRuntimeValue, right: TemplateRuntimeValue): number;
278
1976
 
279
1977
  /**
280
1978
  * Represents a named, versionable template — `{{name}}` tokens in `content`,
@@ -380,6 +2078,144 @@ import type { FieldPath } from '@orkestrel/contract';
380
2078
  * ```
381
2079
  */
382
2080
  parameters(): Readonly<Record<string, unknown>> | undefined;
2081
+ /**
2082
+ * Returns an immutable compiled tree handle over this template's plain
2083
+ * placeholder content.
2084
+ *
2085
+ * @returns A {@link TemplateTreeInterface} parsed by `compilePlainTemplate`
2086
+ *
2087
+ * @example
2088
+ * ```ts
2089
+ * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })
2090
+ * instance.tree().document.children.length // 2
2091
+ * ```
2092
+ */
2093
+ tree(): TemplateTreeInterface;
2094
+ }
2095
+
2096
+ /**
2097
+ * Lists the single-token comparison operators admitted in template expressions.
2098
+ */
2099
+ export declare const TEMPLATE_COMPARISONS: readonly ["==", "!=", "<", ">", "<=", ">="];
2100
+
2101
+ /**
2102
+ * Lists every machine-readable error code admitted on a {@link TemplateError}.
2103
+ */
2104
+ export declare const TEMPLATE_ERROR_CODES: readonly TemplateErrorCode[];
2105
+
2106
+ /**
2107
+ * Maps each single-character Python `unicode-escape` sequence after `\` to its
2108
+ * decoded character.
2109
+ */
2110
+ export declare const TEMPLATE_ESCAPES: Readonly<{
2111
+ readonly '\\': '\\';
2112
+ readonly "'": "'";
2113
+ readonly '"': '"';
2114
+ readonly a: '\u0007';
2115
+ readonly b: '\b';
2116
+ readonly f: '\f';
2117
+ readonly n: '\n';
2118
+ readonly r: '\r';
2119
+ readonly t: '\t';
2120
+ readonly v: '\v';
2121
+ }>;
2122
+
2123
+ /**
2124
+ * Lists the Jinja `|` filters admitted by the template compiler and evaluator.
2125
+ */
2126
+ export declare const TEMPLATE_FILTERS: readonly ["trim", "length", "tojson", "items", "safe", "string"];
2127
+
2128
+ /**
2129
+ * Lists the global Jinja and Hugging Face chat-template function names
2130
+ * recognized by the compiler, of which `raise_exception` and `namespace` are
2131
+ * admitted as calls.
2132
+ */
2133
+ export declare const TEMPLATE_FUNCTIONS: readonly ["raise_exception", "namespace", "strftime_now", "dict", "range", "lipsum", "cycler", "joiner"];
2134
+
2135
+ /**
2136
+ * Maps each Jinja built-in constant spelling to its runtime literal value.
2137
+ */
2138
+ export declare const TEMPLATE_LITERALS: Readonly<{
2139
+ readonly true: true;
2140
+ readonly false: false;
2141
+ readonly none: null;
2142
+ readonly True: true;
2143
+ readonly False: false;
2144
+ readonly None: null;
2145
+ }>;
2146
+
2147
+ /**
2148
+ * Lists the Jinja `loop` members refused by the template subset; `index`,
2149
+ * `index0`, `first`, `last`, `length`, `previtem`, and `nextitem` are admitted.
2150
+ */
2151
+ export declare const TEMPLATE_LOOP_REFUSALS: readonly ["revindex", "revindex0", "depth", "depth0", "cycle", "changed"];
2152
+
2153
+ /**
2154
+ * Lists Python attribute and method names on strings, lists, and mappings that
2155
+ * refuse bare property reads rather than returning unbound method objects.
2156
+ */
2157
+ export declare const TEMPLATE_METHODS: Readonly<{
2158
+ string: readonly string[];
2159
+ list: readonly string[];
2160
+ mapping: readonly string[];
2161
+ }>;
2162
+
2163
+ /**
2164
+ * Maps each arithmetic operator outside the admitted template subset to the
2165
+ * feature label carried in its refusal context.
2166
+ */
2167
+ export declare const TEMPLATE_OPERATOR_FEATURES: Readonly<{
2168
+ readonly '*': 'multiplication';
2169
+ readonly '/': 'division';
2170
+ readonly '//': 'floor division';
2171
+ readonly '%': 'modulo';
2172
+ readonly '**': 'power';
2173
+ }>;
2174
+
2175
+ /**
2176
+ * Matches one root-level segment of a Jinja template source: a run of literal
2177
+ * text and the tag, comment, or unclosed delimiter that follows it.
2178
+ */
2179
+ export declare const TEMPLATE_SEGMENT_PATTERN: RegExp;
2180
+
2181
+ /**
2182
+ * Holds the regular-expression character class Python's `str.isspace` reports
2183
+ * as whitespace for Jinja whitespace markers, `lstrip_blocks`, `trim`, `rstrip`,
2184
+ * `lstrip`, and default `split`.
2185
+ */
2186
+ export declare const TEMPLATE_SPACE = "[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
2187
+
2188
+ /**
2189
+ * Lists the Python `str` methods admitted on string receivers in template
2190
+ * expressions.
2191
+ */
2192
+ export declare const TEMPLATE_STRING_METHODS: readonly ["startswith", "endswith", "split", "strip", "rstrip", "lstrip"];
2193
+
2194
+ /**
2195
+ * Lists the Jinja `is` / `is not` tests admitted by the template compiler and
2196
+ * evaluator.
2197
+ */
2198
+ export declare const TEMPLATE_TESTS: readonly ["defined", "undefined", "none", "string", "mapping", "iterable", "sequence", "true", "false"];
2199
+
2200
+ /**
2201
+ * Matches one lexical token inside a Jinja template tag in lexer precedence
2202
+ * order: whitespace, float, integer, name, string literal, operator, or fault.
2203
+ */
2204
+ export declare const TEMPLATE_TOKEN_PATTERN: RegExp;
2205
+
2206
+ /** Represents one Jinja `{# comment #}` node preserved for canonical round-trip fidelity. */
2207
+ export declare interface TemplateCommentNode {
2208
+ readonly syntax: 'comment';
2209
+ readonly value: string;
2210
+ }
2211
+
2212
+ /** Names the single-token comparison operators admitted in template expressions. */
2213
+ export declare type TemplateComparison = '==' | '!=' | '<' | '>' | '<=' | '>=';
2214
+
2215
+ /** Represents one Jinja `{% break %}` or `{% continue %}` loop-control node. */
2216
+ export declare interface TemplateControlNode {
2217
+ readonly syntax: 'control';
2218
+ readonly action: 'break' | 'continue';
383
2219
  }
384
2220
 
385
2221
  /**
@@ -404,17 +2240,33 @@ import type { FieldPath } from '@orkestrel/contract';
404
2240
  readonly tags?: readonly string[];
405
2241
  }
406
2242
 
2243
+ /**
2244
+ * Carries a rewritten value alongside the map linking each rebuilt node back to
2245
+ * its direct source node.
2246
+ */
2247
+ export declare type TemplateDerivation<T> = readonly [
2248
+ value: T,
2249
+ derivations: ReadonlyMap<TemplateNode, TemplateNode | undefined>
2250
+ ];
2251
+
2252
+ /** Represents the root document node of a compiled template AST. */
2253
+ export declare interface TemplateDocument {
2254
+ readonly syntax: 'document';
2255
+ readonly children: readonly TemplateNode[];
2256
+ }
2257
+
407
2258
  /**
408
2259
  * Represents an error thrown by the template layer — a machine-readable
409
2260
  * {@link TemplateErrorCode} and an optional `context` record naming the
410
- * offending id or placeholder name.
2261
+ * offending id, placeholder name, source position, or feature.
411
2262
  *
412
2263
  * @remarks
413
- * Thrown for: a required placeholder staying unresolved under the `error`
414
- * {@link MissingPolicy} (`MISSING`), an unknown template id
415
- * (`NOTFOUND`), `createTemplate` handed invalid data (`INVALID`), and
416
- * `TemplateManagerInterface#register` handed an id already present without
417
- * `options.replace` (`CONFLICT`).
2264
+ * Thrown for: an unresolved required placeholder under `'error'` (`MISSING`),
2265
+ * an unknown registry id (`NOTFOUND`), invalid construction or AST input
2266
+ * (`INVALID`), a duplicate registration id without `options.replace`
2267
+ * (`CONFLICT`), malformed or unadmitted template syntax or exceeded nesting
2268
+ * depth (`FORMAT`), a runtime operation error (`EVALUATION`), and a
2269
+ * template-authored `raise_exception(message)` call (`RAISE`).
418
2270
  */
419
2271
  export declare class TemplateError extends Error {
420
2272
  readonly code: TemplateErrorCode;
@@ -423,17 +2275,72 @@ import type { FieldPath } from '@orkestrel/contract';
423
2275
  }
424
2276
 
425
2277
  /**
426
- * Names the coded misuse / failure conditions thrown as a {@link TemplateError}.
2278
+ * Names the coded misuse and failure conditions thrown as a {@link TemplateError}.
427
2279
  *
428
2280
  * @remarks
429
2281
  * `MISSING` — a required placeholder stayed unresolved under the `error`
430
2282
  * {@link MissingPolicy}. `NOTFOUND` — `TemplateManagerInterface#fill`,
431
- * `#validate`, or `#parameters` was handed an unknown id.
432
- * `INVALID` — `createTemplate` was handed data that fails validation.
433
- * `CONFLICT` — `register` was handed an id already present without
434
- * `options.replace`.
2283
+ * `#validate`, or `#parameters` received an unknown id. `INVALID` — invalid
2284
+ * construction or AST data. `CONFLICT` — duplicate registration id without
2285
+ * `options.replace`. `FORMAT` — malformed template syntax, unadmitted
2286
+ * feature, or depth exceeding `MAX_DEPTH`. `EVALUATION` — runtime operation
2287
+ * failure. `RAISE` — template-authored `raise_exception(message)`.
2288
+ */
2289
+ export declare type TemplateErrorCode = 'MISSING' | 'NOTFOUND' | 'INVALID' | 'CONFLICT' | 'FORMAT' | 'EVALUATION' | 'RAISE';
2290
+
2291
+ /** Carries optional evaluation settings for `evaluateTemplate`, `evaluateTemplateParts`, and `TemplateTree#evaluate`. */
2292
+ export declare interface TemplateEvaluateOptions extends TemplateFillContext {
2293
+ readonly sanitize?: HTMLSanitizeOptions;
2294
+ }
2295
+
2296
+ /**
2297
+ * Represents one compiled template expression node, discriminated by `term`.
435
2298
  */
436
- export declare type TemplateErrorCode = 'MISSING' | 'NOTFOUND' | 'INVALID' | 'CONFLICT';
2299
+ export declare type TemplateExpression = {
2300
+ readonly term: 'literal';
2301
+ readonly value: string | number | boolean | null;
2302
+ } | {
2303
+ readonly term: 'name';
2304
+ readonly name: string;
2305
+ } | {
2306
+ readonly term: 'member';
2307
+ readonly object: TemplateExpression;
2308
+ readonly key: TemplateExpression;
2309
+ } | {
2310
+ readonly term: 'slice';
2311
+ readonly object: TemplateExpression;
2312
+ readonly start?: TemplateExpression;
2313
+ readonly stop?: TemplateExpression;
2314
+ readonly step?: TemplateExpression;
2315
+ } | {
2316
+ readonly term: 'call';
2317
+ readonly callee: TemplateExpression;
2318
+ readonly values: readonly TemplateExpression[];
2319
+ readonly keywords: readonly TemplateKeyword[];
2320
+ } | {
2321
+ readonly term: 'filter';
2322
+ readonly name: string;
2323
+ readonly value: TemplateExpression;
2324
+ } | {
2325
+ readonly term: 'test';
2326
+ readonly name: string;
2327
+ readonly value: TemplateExpression;
2328
+ readonly negated: boolean;
2329
+ } | {
2330
+ readonly term: 'unary';
2331
+ readonly operator: TemplateUnaryOperator;
2332
+ readonly value: TemplateExpression;
2333
+ } | {
2334
+ readonly term: 'binary';
2335
+ readonly operator: TemplateOperator;
2336
+ readonly left: TemplateExpression;
2337
+ readonly right: TemplateExpression;
2338
+ } | {
2339
+ readonly term: 'conditional';
2340
+ readonly condition: TemplateExpression;
2341
+ readonly consequent: TemplateExpression;
2342
+ readonly alternate: TemplateExpression;
2343
+ };
437
2344
 
438
2345
  /**
439
2346
  * Carries the full option bag `fillTemplate` takes — the per-call
@@ -458,10 +2365,57 @@ import type { FieldPath } from '@orkestrel/contract';
458
2365
  /** Represents the values a {@link TemplateInterface#fill} / `#validate` call resolves placeholders against. */
459
2366
  export declare type TemplateFillValues = Readonly<Record<string, unknown>>;
460
2367
 
2368
+ /** Represents one Jinja `{% for %}` loop node in a compiled template AST. */
2369
+ export declare interface TemplateForNode {
2370
+ readonly syntax: 'for';
2371
+ readonly targets: readonly string[];
2372
+ readonly sequence: TemplateExpression;
2373
+ readonly body: readonly TemplateNode[];
2374
+ }
2375
+
2376
+ /** Represents a bottom-up fold handler for one template AST syntax variant. */
2377
+ export declare type TemplateHandler<TNode, T> = (node: TNode, children: readonly T[]) => T;
2378
+
2379
+ /**
2380
+ * Declares the total catamorphism handler table for `foldTemplateDocument` and
2381
+ * `TemplateTreeInterface#fold`, keyed by every `TemplateNode` `syntax` variant.
2382
+ */
2383
+ export declare interface TemplateHandlerMap<T> {
2384
+ readonly document: TemplateHandler<TemplateDocument, T>;
2385
+ readonly text: TemplateHandler<TemplateTextNode, T>;
2386
+ readonly placeholder: TemplateHandler<TemplatePlaceholderNode, T>;
2387
+ readonly output: TemplateHandler<TemplateOutputNode, T>;
2388
+ readonly if: TemplateHandler<TemplateIfNode, T>;
2389
+ readonly for: TemplateHandler<TemplateForNode, T>;
2390
+ readonly set: TemplateHandler<TemplateSetNode, T>;
2391
+ readonly macro: TemplateHandler<TemplateMacroNode, T>;
2392
+ readonly control: TemplateHandler<TemplateControlNode, T>;
2393
+ readonly comment: TemplateHandler<TemplateCommentNode, T>;
2394
+ readonly html: TemplateHandler<TemplateHTMLNode, T>;
2395
+ readonly markdown: TemplateHandler<TemplateMarkdownNode, T>;
2396
+ }
2397
+
2398
+ /** Represents an embedded `@orkestrel/html` document leaf inside a template AST. */
2399
+ export declare interface TemplateHTMLNode {
2400
+ readonly syntax: 'html';
2401
+ readonly document: HTMLDocument;
2402
+ }
2403
+
2404
+ /** Carries optional evaluation and HTML sanitization settings for `templateToHTML`. */
2405
+ export declare type TemplateHTMLOptions = TemplateEvaluateOptions;
2406
+
2407
+ /** Represents one Jinja `{% if %}` branch node in a compiled template AST. */
2408
+ export declare interface TemplateIfNode {
2409
+ readonly syntax: 'if';
2410
+ readonly condition: TemplateExpression;
2411
+ readonly body: readonly TemplateNode[];
2412
+ readonly alternate?: readonly TemplateNode[];
2413
+ }
2414
+
461
2415
  /**
462
2416
  * Declares the template contract a consumer holds — the readonly template
463
- * record and the `definition`, `fill`, `validate`, and `parameters` calls
464
- * over it.
2417
+ * record and the `definition`, `fill`, `validate`, `parameters`, and `tree`
2418
+ * calls over it.
465
2419
  *
466
2420
  * @remarks
467
2421
  * `Template` implements this contract exactly, so the class exposes these
@@ -504,6 +2458,41 @@ import type { FieldPath } from '@orkestrel/contract';
504
2458
  * `@orkestrel/contract`.
505
2459
  */
506
2460
  parameters(): Readonly<Record<string, unknown>> | undefined;
2461
+ /** Returns an immutable compiled tree handle over this template's plain placeholder content. */
2462
+ tree(): TemplateTreeInterface;
2463
+ }
2464
+
2465
+ /**
2466
+ * Describes one named keyword argument in a template call expression.
2467
+ */
2468
+ export declare interface TemplateKeyword {
2469
+ readonly name: string;
2470
+ readonly value: TemplateExpression;
2471
+ }
2472
+
2473
+ /** Describes the Jinja `loop` state exposed inside each iteration of a `for` loop. */
2474
+ export declare interface TemplateLoop {
2475
+ readonly index0: number;
2476
+ readonly length: number;
2477
+ readonly previtem: TemplateRuntimeValue;
2478
+ readonly nextitem: TemplateRuntimeValue;
2479
+ }
2480
+
2481
+ /** Represents a compiled Jinja macro closure bound at runtime. */
2482
+ export declare interface TemplateMacro {
2483
+ readonly macro: true;
2484
+ readonly name: string;
2485
+ readonly parameters: readonly TemplateParameter[];
2486
+ readonly body: readonly TemplateNode[];
2487
+ readonly closure: TemplateScope;
2488
+ }
2489
+
2490
+ /** Represents one Jinja `{% macro %}` definition node in a compiled template AST. */
2491
+ export declare interface TemplateMacroNode {
2492
+ readonly syntax: 'macro';
2493
+ readonly name: string;
2494
+ readonly parameters: readonly TemplateParameter[];
2495
+ readonly body: readonly TemplateNode[];
507
2496
  }
508
2497
 
509
2498
  /**
@@ -748,6 +2737,29 @@ import type { FieldPath } from '@orkestrel/contract';
748
2737
  readonly error?: EmitterErrorHandler;
749
2738
  }
750
2739
 
2740
+ /** Represents an embedded `@orkestrel/markdown` document leaf inside a template AST. */
2741
+ export declare interface TemplateMarkdownNode {
2742
+ readonly syntax: 'markdown';
2743
+ readonly document: MarkdownDocument;
2744
+ }
2745
+
2746
+ /**
2747
+ * Represents a mutable Jinja `namespace(...)` container whose properties
2748
+ * persist across `for` loop and `macro` boundaries.
2749
+ */
2750
+ export declare interface TemplateNamespace {
2751
+ readonly namespace: true;
2752
+ readonly values: ReadonlyMap<string, TemplateRuntimeValue>;
2753
+ }
2754
+
2755
+ /**
2756
+ * Represents any node in a compiled template AST, discriminated by `syntax`.
2757
+ */
2758
+ export declare type TemplateNode = TemplateDocument | TemplateTextNode | TemplatePlaceholderNode | TemplateOutputNode | TemplateIfNode | TemplateForNode | TemplateSetNode | TemplateMacroNode | TemplateControlNode | TemplateCommentNode | TemplateHTMLNode | TemplateMarkdownNode;
2759
+
2760
+ /** Names the binary operators admitted in template expressions. */
2761
+ export declare type TemplateOperator = '+' | '-' | '~' | TemplateComparison | 'in' | 'not in' | 'and' | 'or';
2762
+
751
2763
  /**
752
2764
  * Carries the options for `createTemplate` / the `Template` constructor.
753
2765
  *
@@ -769,6 +2781,33 @@ import type { FieldPath } from '@orkestrel/contract';
769
2781
  readonly locale?: string;
770
2782
  }
771
2783
 
2784
+ /** Represents one Jinja `{{ expression }}` output tag in a compiled template AST. */
2785
+ export declare interface TemplateOutputNode {
2786
+ readonly syntax: 'output';
2787
+ readonly value: TemplateExpression;
2788
+ }
2789
+
2790
+ /**
2791
+ * Describes one formal parameter of a {@link TemplateMacroNode}, carrying its
2792
+ * name and optional default expression.
2793
+ */
2794
+ export declare interface TemplateParameter {
2795
+ readonly name: string;
2796
+ readonly fallback?: TemplateExpression;
2797
+ }
2798
+
2799
+ /**
2800
+ * Carries a compiled {@link TemplateDocument} alongside its original-source
2801
+ * {@link TemplateSpan} map.
2802
+ */
2803
+ export declare type TemplateParseResult = readonly [
2804
+ document: TemplateDocument,
2805
+ spans: ReadonlyMap<TemplateNode, TemplateSpan>
2806
+ ];
2807
+
2808
+ /** Represents one emitted part of a tree-valued template evaluation. */
2809
+ export declare type TemplatePart = string | HTMLNode | MarkdownNode;
2810
+
772
2811
  /**
773
2812
  * Represents one placeholder a {@link TemplateDefinition}'s `content`
774
2813
  * declares — its lookup name, an optional field path into the values record,
@@ -791,6 +2830,13 @@ import type { FieldPath } from '@orkestrel/contract';
791
2830
  readonly description?: string;
792
2831
  }
793
2832
 
2833
+ /** Represents one plain `{{name}}` placeholder token in a compiled plain template AST. */
2834
+ export declare interface TemplatePlaceholderNode {
2835
+ readonly syntax: 'placeholder';
2836
+ readonly name: string;
2837
+ readonly raw: string;
2838
+ }
2839
+
794
2840
  /** Represents a query for `TemplateManagerInterface#find` — every supplied field must match. */
795
2841
  export declare interface TemplateQuery {
796
2842
  readonly name?: string;
@@ -809,6 +2855,90 @@ import type { FieldPath } from '@orkestrel/contract';
809
2855
  readonly replace?: boolean;
810
2856
  }
811
2857
 
2858
+ /** Represents a bottom-up copy-on-write rewrite callback for `mapTemplateDocument` and `TemplateTreeInterface#map`. */
2859
+ export declare type TemplateRewriteHandler = (node: TemplateNode) => TemplateNode;
2860
+
2861
+ /** Represents any value handled during template expression evaluation. */
2862
+ export declare type TemplateRuntimeValue = undefined | null | boolean | number | string | HTMLNode | MarkdownNode | TemplateLoop | TemplateNamespace | TemplateMacro | readonly TemplateRuntimeValue[] | ReadonlyMap<string, TemplateRuntimeValue>;
2863
+
2864
+ /** Represents one lexical scope stack of runtime variable frames, outermost first. */
2865
+ export declare type TemplateScope = ReadonlyArray<ReadonlyMap<string, TemplateRuntimeValue>>;
2866
+
2867
+ /** Represents one Jinja `{% set %}` assignment node in a compiled template AST. */
2868
+ export declare interface TemplateSetNode {
2869
+ readonly syntax: 'set';
2870
+ readonly target: TemplateTarget;
2871
+ readonly value: TemplateExpression;
2872
+ }
2873
+
2874
+ /**
2875
+ * Represents a half-open region of the original template source in UTF-16 code
2876
+ * units, with `start` inclusive and `end` exclusive.
2877
+ */
2878
+ export declare interface TemplateSpan {
2879
+ readonly start: number;
2880
+ readonly end: number;
2881
+ }
2882
+
2883
+ /**
2884
+ * Names a compiled template assignment target, discriminated by `scope`:
2885
+ * `'local'` binds a frame variable and `'attribute'` updates a
2886
+ * {@link TemplateNamespace} property.
2887
+ */
2888
+ export declare type TemplateTarget = {
2889
+ readonly scope: 'local';
2890
+ readonly name: string;
2891
+ } | {
2892
+ readonly scope: 'attribute';
2893
+ readonly object: string;
2894
+ readonly name: string;
2895
+ };
2896
+
2897
+ /** Represents literal character text in a compiled template AST. */
2898
+ export declare interface TemplateTextNode {
2899
+ readonly syntax: 'text';
2900
+ readonly value: string;
2901
+ }
2902
+
2903
+ /**
2904
+ * Projects a compiled template document or Jinja source into a sanitized
2905
+ * {@link HTMLDocument}.
2906
+ *
2907
+ * @remarks
2908
+ * Plain string template text and interpolated scalar values always become safe
2909
+ * `TextNode` leaves rather than raw HTML markup, eliminating XSS from fill
2910
+ * strings. Embedded `HTMLNode` leaves and fill values pass through
2911
+ * `sanitizeTemplateHTML`, and embedded `MarkdownNode` leaves and fill values
2912
+ * project through `markdownToHTML` then `sanitizeTemplateHTML`.
2913
+ *
2914
+ * @param source - A compiled {@link TemplateDocument} or Jinja source string
2915
+ * @param values - Optional runtime values record
2916
+ * @param options - Optional evaluation and HTML sanitization settings
2917
+ * @returns A sanitized {@link HTMLDocument}
2918
+ *
2919
+ * @example
2920
+ * ```ts
2921
+ * import { templateToHTML } from '@orkestrel/template'
2922
+ *
2923
+ * templateToHTML('Hi {{ name }}', { name: '<b>Ada</b>' }).children
2924
+ * // [{ category: 'text', value: 'Hi <b>Ada</b>' }]
2925
+ * ```
2926
+ */
2927
+ export declare function templateToHTML(source: TemplateDocument | string, values?: TemplateFillValues, options?: TemplateHTMLOptions): HTMLDocument;
2928
+
2929
+ /** Describes one scanned template token with its 1-based line/column and UTF-16 source offsets. */
2930
+ export declare interface TemplateToken {
2931
+ readonly token: TemplateTokenForm;
2932
+ readonly text: string;
2933
+ readonly line: number;
2934
+ readonly column: number;
2935
+ readonly start: number;
2936
+ readonly end: number;
2937
+ }
2938
+
2939
+ /** Names the lexical token categories produced while scanning template tags. */
2940
+ export declare type TemplateTokenForm = 'text' | 'comment' | 'block' | 'variable' | 'close' | 'name' | 'string' | 'integer' | 'float' | 'operator' | 'fault' | 'end';
2941
+
812
2942
  /**
813
2943
  * Represents one `{{name}}` token's resolution — the single token rule
814
2944
  * `fillTemplate` and `TemplateInterface#validate` share.
@@ -828,6 +2958,177 @@ import type { FieldPath } from '@orkestrel/contract';
828
2958
  readonly required: boolean;
829
2959
  }
830
2960
 
2961
+ /**
2962
+ * Projects a compiled template document or Jinja source into a canonical
2963
+ * {@link MarkdownDocument}.
2964
+ *
2965
+ * @remarks
2966
+ * Template-authored literal text parses through `parseMarkdown`, while dynamic
2967
+ * scalar fill values stay literal leaves and are never parsed as Markdown
2968
+ * syntax. Inline dynamic fills and `CodeSpanNode` values collapse line breaks
2969
+ * (`\r\n`, `\r`, `\n`) to single spaces so round-tripping through
2970
+ * `renderMarkdown` and `parseMarkdown` never splits headings, table rows,
2971
+ * code spans, or paragraphs; `CodeBlockNode.lang` sanitizes to a single token
2972
+ * free of whitespace, backticks, and tildes; and `CodeBlockNode.code` preserves
2973
+ * line breaks verbatim inside dynamically sized fences. Embedded `HTMLNode`
2974
+ * values sanitize through `sanitizeTemplateHTML`, project through
2975
+ * `htmlToMarkdown`, and sanitize URL schemes; embedded `MarkdownNode` values
2976
+ * sanitize URL schemes by unwrapping unsafe `LinkNode` elements and dropping
2977
+ * unsafe `ImageNode` elements. `@orkestrel/markdown` has no raw-HTML AST node
2978
+ * and emits `TextRun` text verbatim in `renderMarkdown`, so callers targeting a
2979
+ * third-party raw-HTML Markdown renderer must use `templateToHTML` or sanitize
2980
+ * at that HTML boundary.
2981
+ *
2982
+ * @param source - A compiled {@link TemplateDocument} or Jinja source string
2983
+ * @param values - Optional runtime values record
2984
+ * @param options - Optional evaluation and HTML sanitization settings
2985
+ * @returns A {@link MarkdownDocument}
2986
+ *
2987
+ * @example
2988
+ * ```ts
2989
+ * import { templateToMarkdown } from '@orkestrel/template'
2990
+ *
2991
+ * templateToMarkdown('# Hello {{ name }}', { name: 'Ada' }).children[0]?.element // 'heading'
2992
+ * ```
2993
+ */
2994
+ export declare function templateToMarkdown(source: TemplateDocument | string, values?: TemplateFillValues, options?: TemplateEvaluateOptions): MarkdownDocument;
2995
+
2996
+ /**
2997
+ * Wraps a compiled {@link TemplateDocument} AST as an immutable handle
2998
+ * exposing provenance lookup, depth-first traversal, queries, copy-on-write
2999
+ * rewrites, total folds, shallow streaming, evaluation, and canonical source
3000
+ * rendering.
3001
+ *
3002
+ * @remarks
3003
+ * Construct with `{ source }` to compile Jinja source with original UTF-16
3004
+ * provenance spans, or `{ document, spans? }` to adopt an existing validated
3005
+ * {@link TemplateDocument}. Every query and rewrite preserves immutability.
3006
+ *
3007
+ * @example
3008
+ * ```ts
3009
+ * import { TemplateTree } from '@orkestrel/template'
3010
+ *
3011
+ * const tree = new TemplateTree({ source: 'Hi {{ name }}' })
3012
+ * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'
3013
+ * ```
3014
+ */
3015
+ export declare class TemplateTree implements TemplateTreeInterface {
3016
+ #private;
3017
+ constructor(options: TemplateTreeOptions);
3018
+ /** Exposes the stored {@link TemplateDocument} AST root. */
3019
+ get document(): TemplateDocument;
3020
+ /**
3021
+ * Returns the half-open original-source region for a node, or `undefined`
3022
+ * when this handle holds no provenance for that node.
3023
+ *
3024
+ * @param node - The node whose provenance to read
3025
+ * @returns A fresh {@link TemplateSpan}, or `undefined`
3026
+ */
3027
+ span(node: TemplateNode): TemplateSpan | undefined;
3028
+ /**
3029
+ * Walks every node in the document depth-first in pre-order, root first.
3030
+ *
3031
+ * @returns A lazy generator over every node in the document
3032
+ */
3033
+ walk(): Generator<TemplateNode>;
3034
+ find<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): T | undefined;
3035
+ find(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined;
3036
+ filter<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): readonly T[];
3037
+ filter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[];
3038
+ /**
3039
+ * Rewrites the document bottom-up with copy-on-write provenance preservation
3040
+ * and returns a derived {@link TemplateTreeInterface}.
3041
+ *
3042
+ * @param rewrite - The bottom-up node rewrite callback
3043
+ * @returns A derived handle over the rewritten document
3044
+ */
3045
+ map(rewrite: TemplateRewriteHandler): TemplateTreeInterface;
3046
+ /**
3047
+ * Reduces the document depth-first in pre-order into one accumulated value.
3048
+ *
3049
+ * @param callback - The reducer step combining value and node
3050
+ * @param initial - The initial accumulated value
3051
+ * @returns The final accumulated value
3052
+ */
3053
+ reduce<T>(callback: (value: T, node: TemplateNode) => T, initial: T): T;
3054
+ /**
3055
+ * Folds the document bottom-up through a total handler table covering every
3056
+ * syntax variant.
3057
+ *
3058
+ * @param handlers - Total handler map keyed by `syntax`
3059
+ * @returns The folded value of the document root
3060
+ */
3061
+ fold<T>(handlers: TemplateHandlerMap<T>): T;
3062
+ /**
3063
+ * Returns a fresh, pull-based stream over the document's top-level children
3064
+ * in source order.
3065
+ *
3066
+ * @returns A pull-based {@link ReadableStream} over top-level nodes
3067
+ */
3068
+ stream(): ReadableStream<TemplateNode>;
3069
+ /**
3070
+ * Evaluates the template document against runtime values and returns rendered
3071
+ * text.
3072
+ *
3073
+ * @param values - Optional runtime values record
3074
+ * @param options - Optional evaluation, placeholder, and sanitize settings
3075
+ * @returns The rendered text
3076
+ */
3077
+ evaluate(values?: TemplateFillValues, options?: TemplateEvaluateOptions): string;
3078
+ /**
3079
+ * Renders the template document back to canonical template source text.
3080
+ *
3081
+ * @returns The canonical template source string
3082
+ */
3083
+ render(): string;
3084
+ }
3085
+
3086
+ /**
3087
+ * Declares the immutable AST handle contract over a compiled template document
3088
+ * — exposing provenance lookup, traversal, queries, copy-on-write rewrites,
3089
+ * total folds, shallow streaming, evaluation, and canonical source rendering.
3090
+ */
3091
+ export declare interface TemplateTreeInterface {
3092
+ readonly document: TemplateDocument;
3093
+ /** Returns the half-open original-source region for a node, or `undefined` when none is recorded. */
3094
+ span(node: TemplateNode): TemplateSpan | undefined;
3095
+ /** Walks every node in the document depth-first in pre-order, root first. */
3096
+ walk(): Generator<TemplateNode>;
3097
+ /** Finds the first node matching a type guard or predicate in walk order. */
3098
+ find<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): T | undefined;
3099
+ find(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined;
3100
+ /** Collects every node matching a type guard or predicate in walk order. */
3101
+ filter<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): readonly T[];
3102
+ filter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[];
3103
+ /** Rewrites the document bottom-up with copy-on-write provenance preservation and returns a derived handle. */
3104
+ map(rewrite: TemplateRewriteHandler): TemplateTreeInterface;
3105
+ /** Reduces the document depth-first in pre-order into one accumulated value. */
3106
+ reduce<T>(callback: (value: T, node: TemplateNode) => T, initial: T): T;
3107
+ /** Folds the document bottom-up through a total handler table covering every syntax variant. */
3108
+ fold<T>(handlers: TemplateHandlerMap<T>): T;
3109
+ /** Returns a fresh, pull-based stream over the document's top-level children in source order. */
3110
+ stream(): ReadableStream<TemplateNode>;
3111
+ /** Evaluates the template document against runtime values and returns rendered text. */
3112
+ evaluate(values?: TemplateFillValues, options?: TemplateEvaluateOptions): string;
3113
+ /** Renders the template document back to canonical template source text. */
3114
+ render(): string;
3115
+ }
3116
+
3117
+ /**
3118
+ * Carries the constructor options for `TemplateTree` and `createTemplateTree`:
3119
+ * either raw Jinja `source` text to compile or an already-built `document`
3120
+ * with optional provenance `spans`.
3121
+ */
3122
+ export declare type TemplateTreeOptions = {
3123
+ readonly source: string;
3124
+ } | {
3125
+ readonly document: TemplateDocument;
3126
+ readonly spans?: ReadonlyMap<TemplateNode, TemplateSpan>;
3127
+ };
3128
+
3129
+ /** Names the unary operators admitted in template expressions. */
3130
+ export declare type TemplateUnaryOperator = 'not' | '-' | '+';
3131
+
831
3132
  /** Reports the outcome of `TemplateInterface#validate` — which required placeholders are unresolved, and which supplied values are unused. */
832
3133
  export declare interface TemplateValidationResult {
833
3134
  readonly valid: boolean;
@@ -835,6 +3136,25 @@ import type { FieldPath } from '@orkestrel/contract';
835
3136
  readonly extra: readonly string[];
836
3137
  }
837
3138
 
3139
+ /**
3140
+ * Trims literal template text between adjacent Jinja tags under `trim_blocks`
3141
+ * and `lstrip_blocks`, honoring `-` and `+` delimiter markers.
3142
+ *
3143
+ * @param text - The text between the two tags
3144
+ * @param closer - The closing delimiter of the preceding tag, or `''` at start
3145
+ * @param opener - The opening delimiter of the following tag, or `''` at end
3146
+ * @returns The trimmed text
3147
+ *
3148
+ * @example
3149
+ * ```ts
3150
+ * import { trimTemplateText } from '@orkestrel/template'
3151
+ *
3152
+ * trimTemplateText('\n ', '%}', '{%') // ''
3153
+ * trimTemplateText('Hi \n', '}}', '{{-') // 'Hi'
3154
+ * ```
3155
+ */
3156
+ export declare function trimTemplateText(text: string, closer: string, opener: string): string;
3157
+
838
3158
  /**
839
3159
  * Lists the prototype-pollution-unsafe field-path segments `'__proto__'`,
840
3160
  * `'constructor'`, and `'prototype'` — a fill lookup refuses to resolve a path
@@ -842,4 +3162,22 @@ import type { FieldPath } from '@orkestrel/contract';
842
3162
  */
843
3163
  export declare const UNSAFE_FIELD_SEGMENTS: readonly string[];
844
3164
 
3165
+ /**
3166
+ * Walks a {@link TemplateNode} depth-first in pre-order, yielding the root
3167
+ * first and capping descent at `MAX_DEPTH`.
3168
+ *
3169
+ * @param root - The root node to traverse
3170
+ * @param depth - Current traversal depth. Default: `0`
3171
+ * @returns A lazy generator over every visited node
3172
+ *
3173
+ * @example
3174
+ * ```ts
3175
+ * import { compileTemplate, walkTemplateNodes } from '@orkestrel/template'
3176
+ *
3177
+ * Array.from(walkTemplateNodes(compileTemplate('Hi {{ name }}'))).map((node) => node.syntax)
3178
+ * // ['document', 'text', 'output']
3179
+ * ```
3180
+ */
3181
+ export declare function walkTemplateNodes(root: TemplateNode, depth?: number): Generator<TemplateNode>;
3182
+
845
3183
  export { }