@orkestrel/template 0.0.18 → 0.0.19
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/compilers.ts","../../../src/core/parsers.ts","../../../src/core/shapers.ts","../../../src/core/templates/TemplateTree.ts","../../../src/core/templates/Template.ts","../../../src/core/templates/TemplateManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MissingPolicy, TemplateErrorCode } from './types.js'\n\n// Frozen default data and Jinja grammar tables for the template module —\n// constants are UPPER_SNAKE_CASE data, the sole home for module-scope literal\n// defaults. `MAX_DEPTH` is imported directly from `@orkestrel/html` wherever\n// depth bounds are enforced and is never redeclared here.\n\n/**\n * Holds the single-pass `{{name}}` substitution pattern shared by\n * `Template#fill` and `Template#validate`.\n *\n * @remarks\n * Global-flagged, two-alternative pattern: a match of the first alternative\n * (`\\{{` — a literal backslash followed by `{{`) emits a literal `{{`. A match\n * populating capture group 1 (`\\{\\{([^{}]+?)\\}\\}`) resolves the trimmed token\n * name without backtracking on unclosed whitespace runs. Every call site builds\n * a fresh `RegExp` from `.source` and `.flags`.\n */\nexport const FILL_PATTERN = /\\\\\\{\\{|\\{\\{([^{}]+?)\\}\\}/g\n\n/**\n * Holds `'error'`, the default `missing` policy for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_MISSING_POLICY: MissingPolicy = 'error'\n\n/**\n * Holds `'en-US'`, the default `locale` for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_LOCALE = 'en-US'\n\n/**\n * Lists the prototype-pollution-unsafe field-path segments `'__proto__'`,\n * `'constructor'`, and `'prototype'` — a fill lookup refuses to resolve a path\n * containing one of them, treating the placeholder as unresolved.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'constructor',\n\t'prototype',\n])\n\n/**\n * Lists every machine-readable error code admitted on a {@link TemplateError}.\n */\nexport const TEMPLATE_ERROR_CODES: readonly TemplateErrorCode[] = Object.freeze([\n\t'MISSING',\n\t'NOTFOUND',\n\t'INVALID',\n\t'CONFLICT',\n\t'FORMAT',\n\t'EVALUATION',\n\t'RAISE',\n])\n\n/**\n * Holds the regular-expression character class Python's `str.isspace` reports\n * as whitespace for Jinja whitespace markers, `lstrip_blocks`, `trim`, `rstrip`,\n * `lstrip`, and default `split`.\n */\nexport const TEMPLATE_SPACE =\n\t'[\\\\t-\\\\r\\\\x1c-\\\\x20\\\\x85\\\\xa0\\\\u1680\\\\u2000-\\\\u200a\\\\u2028\\\\u2029\\\\u202f\\\\u205f\\\\u3000]'\n\n/**\n * Matches one root-level segment of a Jinja template source: a run of literal\n * text and the tag, comment, or unclosed delimiter that follows it.\n */\nexport const TEMPLATE_SEGMENT_PATTERN =\n\t/((?:[^{]|\\{(?![{%#]))*)(?:(\\{%[-+]?)((?:'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"|[^'\"])*?)([-+]?%\\})|(\\{\\{[-+]?)((?:'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"|[^'\"])*?)(-?\\}\\})|(\\{#[-+]?)([^]*?)([-+]?#\\})|(\\{[{%#])[^]*|$)/gy\n\n/**\n * Matches one lexical token inside a Jinja template tag in lexer precedence\n * order: whitespace, float, integer, name, string literal, operator, or fault.\n */\nexport const TEMPLATE_TOKEN_PATTERN = new RegExp(\n\t`(${TEMPLATE_SPACE}+)|((?<!\\\\.)(?:\\\\d+_)*\\\\d+(?:(?:\\\\.(?:\\\\d+_)*\\\\d+)?[eE][-+]?(?:\\\\d+_)*\\\\d+|\\\\.(?:\\\\d+_)*\\\\d+))|(0[bB](?:_?[01])+|0[oO](?:_?[0-7])+|0[xX](?:_?[\\\\da-fA-F])+|[1-9](?:_?\\\\d)*|0(?:_?0)*)|([\\\\p{XID_Start}_]\\\\p{XID_Continue}*)|('(?:[^'\\\\\\\\]|\\\\\\\\[^])*'|\"(?:[^\"\\\\\\\\]|\\\\\\\\[^])*\")|(\\\\/\\\\/|\\\\*\\\\*|==|!=|>=|<=|[-+/*%~[\\\\](){}<>=.:|,;])|([^])`,\n\t'gyu',\n)\n\n/**\n * Maps each Jinja built-in constant spelling to its runtime literal value.\n */\nexport const TEMPLATE_LITERALS = Object.freeze({\n\ttrue: true,\n\tfalse: false,\n\tnone: null,\n\tTrue: true,\n\tFalse: false,\n\tNone: null,\n} as const)\n\n/**\n * Lists the single-token comparison operators admitted in template expressions.\n */\nexport const TEMPLATE_COMPARISONS = Object.freeze(['==', '!=', '<', '>', '<=', '>='] as const)\n\n/**\n * Maps each single-character Python `unicode-escape` sequence after `\\` to its\n * decoded character.\n */\nexport const TEMPLATE_ESCAPES = Object.freeze({\n\t'\\\\': '\\\\',\n\t\"'\": \"'\",\n\t'\"': '\"',\n\ta: '\\x07',\n\tb: '\\b',\n\tf: '\\f',\n\tn: '\\n',\n\tr: '\\r',\n\tt: '\\t',\n\tv: '\\v',\n} as const)\n\n/**\n * Lists the global Jinja and Hugging Face chat-template function names\n * recognized by the compiler, of which `raise_exception` and `namespace` are\n * admitted as calls.\n */\nexport const TEMPLATE_FUNCTIONS = Object.freeze([\n\t'raise_exception',\n\t'namespace',\n\t'strftime_now',\n\t'dict',\n\t'range',\n\t'lipsum',\n\t'cycler',\n\t'joiner',\n] as const)\n\n/**\n * Lists the Jinja `|` filters admitted by the template compiler and evaluator.\n */\nexport const TEMPLATE_FILTERS = Object.freeze([\n\t'trim',\n\t'length',\n\t'tojson',\n\t'items',\n\t'safe',\n\t'string',\n] as const)\n\n/**\n * Lists the Jinja `is` / `is not` tests admitted by the template compiler and\n * evaluator.\n */\nexport const TEMPLATE_TESTS = Object.freeze([\n\t'defined',\n\t'undefined',\n\t'none',\n\t'string',\n\t'mapping',\n\t'iterable',\n\t'sequence',\n\t'true',\n\t'false',\n] as const)\n\n/**\n * Lists the Python `str` methods admitted on string receivers in template\n * expressions.\n */\nexport const TEMPLATE_STRING_METHODS = Object.freeze([\n\t'startswith',\n\t'endswith',\n\t'split',\n\t'strip',\n\t'rstrip',\n\t'lstrip',\n] as const)\n\n/**\n * Lists Python attribute and method names on strings, lists, and mappings that\n * refuse bare property reads rather than returning unbound method objects.\n */\nexport const TEMPLATE_METHODS = Object.freeze({\n\tstring: Object.freeze([\n\t\t'capitalize',\n\t\t'casefold',\n\t\t'center',\n\t\t'count',\n\t\t'encode',\n\t\t'endswith',\n\t\t'expandtabs',\n\t\t'find',\n\t\t'format',\n\t\t'format_map',\n\t\t'index',\n\t\t'isalnum',\n\t\t'isalpha',\n\t\t'isascii',\n\t\t'isdecimal',\n\t\t'isdigit',\n\t\t'isidentifier',\n\t\t'islower',\n\t\t'isnumeric',\n\t\t'isprintable',\n\t\t'isspace',\n\t\t'istitle',\n\t\t'isupper',\n\t\t'join',\n\t\t'ljust',\n\t\t'lower',\n\t\t'lstrip',\n\t\t'maketrans',\n\t\t'partition',\n\t\t'removeprefix',\n\t\t'removesuffix',\n\t\t'replace',\n\t\t'rfind',\n\t\t'rindex',\n\t\t'rjust',\n\t\t'rpartition',\n\t\t'rsplit',\n\t\t'rstrip',\n\t\t'split',\n\t\t'splitlines',\n\t\t'startswith',\n\t\t'strip',\n\t\t'swapcase',\n\t\t'title',\n\t\t'translate',\n\t\t'upper',\n\t\t'zfill',\n\t]),\n\tlist: Object.freeze([\n\t\t'append',\n\t\t'clear',\n\t\t'copy',\n\t\t'count',\n\t\t'extend',\n\t\t'index',\n\t\t'insert',\n\t\t'pop',\n\t\t'remove',\n\t\t'reverse',\n\t\t'sort',\n\t]),\n\tmapping: Object.freeze([\n\t\t'clear',\n\t\t'copy',\n\t\t'fromkeys',\n\t\t'get',\n\t\t'items',\n\t\t'keys',\n\t\t'pop',\n\t\t'popitem',\n\t\t'setdefault',\n\t\t'update',\n\t\t'values',\n\t]),\n})\n\n/**\n * Lists the Jinja `loop` members refused by the template subset; `index`,\n * `index0`, `first`, `last`, `length`, `previtem`, and `nextitem` are admitted.\n */\nexport const TEMPLATE_LOOP_REFUSALS = Object.freeze([\n\t'revindex',\n\t'revindex0',\n\t'depth',\n\t'depth0',\n\t'cycle',\n\t'changed',\n] as const)\n\n/**\n * Maps each arithmetic operator outside the admitted template subset to the\n * feature label carried in its refusal context.\n */\nexport const TEMPLATE_OPERATOR_FEATURES = Object.freeze({\n\t'*': 'multiplication',\n\t'/': 'division',\n\t'//': 'floor division',\n\t'%': 'modulo',\n\t'**': 'power',\n} as const)\n","import type { TemplateErrorCode } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\nimport { TEMPLATE_ERROR_CODES } from './constants.js'\n\n// Misuse and compilation/evaluation failures in the template layer throw a\n// self-branded `TemplateError` carrying a machine-readable `code`, so callers\n// narrow safely through `isTemplateError` and branch on `error.code`.\n\n/**\n * Represents an error thrown by the template layer — a machine-readable\n * {@link TemplateErrorCode} and an optional `context` record naming the\n * offending id, placeholder name, source position, or feature.\n *\n * @remarks\n * Thrown for: an unresolved required placeholder under `'error'` (`MISSING`),\n * an unknown registry id (`NOTFOUND`), invalid construction or AST input\n * (`INVALID`), a duplicate registration id without `options.replace`\n * (`CONFLICT`), malformed or unadmitted template syntax or exceeded nesting\n * depth (`FORMAT`), a runtime operation error (`EVALUATION`), and a\n * template-authored `raise_exception(message)` call (`RAISE`).\n */\nexport class TemplateError extends Error {\n\treadonly code: TemplateErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: TemplateErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/template.TemplateError'), { value: this })\n\t\tthis.name = 'TemplateError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link TemplateError}.\n *\n * @remarks\n * Recognizes self-branded errors from other package copies and subclasses, and\n * refuses transparent proxies and unbranded look-alikes.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link TemplateError}; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateError, TemplateError } from '@orkestrel/template'\n *\n * try {\n * \tthrow new TemplateError('NOTFOUND', 'Unknown template id: missing', { id: 'missing' })\n * } catch (error) {\n * \tif (isTemplateError(error) && error.code === 'NOTFOUND') return\n * }\n * ```\n */\nexport function isTemplateError(value: unknown): value is TemplateError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (\n\t\t\tINTRINSICS.describe(value, Symbol.for('@orkestrel/template.TemplateError'))?.value !== value\n\t\t)\n\t\t\treturn false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\tTEMPLATE_ERROR_CODES.some((admitted) => admitted === code) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n","import type {\n\tTemplateComparison,\n\tTemplateDocument,\n\tTemplateErrorCode,\n\tTemplateExpression,\n\tTemplateNamespace,\n\tTemplateNode,\n\tTemplateOperator,\n\tTemplateSpan,\n\tTemplateTarget,\n\tTemplateUnaryOperator,\n} from './types.js'\nimport {\n\tholds,\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisMap,\n\tisNonNegativeInteger,\n\tisObject,\n\tisRecord,\n\tisString,\n} from '@orkestrel/contract'\nimport { isHTMLDocument, MAX_DEPTH } from '@orkestrel/html'\nimport { isMarkdownDocument } from '@orkestrel/markdown'\nimport { TEMPLATE_COMPARISONS, TEMPLATE_ERROR_CODES } from './constants.js'\n\n// Total, class-free runtime guards for the template AST, expressions, spans,\n// namespaces, and error codes. Every recursive guard tracks ancestors with a\n// `WeakSet` and caps descent at `MAX_DEPTH` imported from `@orkestrel/html`.\n\n/**\n * Checks whether an unknown value is a declared {@link TemplateErrorCode}.\n *\n * @param value - The value to test\n * @returns True if `value` is one of `TEMPLATE_ERROR_CODES`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateErrorCode } from '@orkestrel/template'\n *\n * isTemplateErrorCode('FORMAT') // true\n * isTemplateErrorCode('OTHER') // false\n * ```\n */\nexport function isTemplateErrorCode(value: unknown): value is TemplateErrorCode {\n\treturn holds(() => isString(value) && TEMPLATE_ERROR_CODES.some((code) => code === value))\n}\n\n/**\n * Checks whether an unknown value is a valid half-open {@link TemplateSpan}.\n *\n * @param value - The value to test\n * @returns True if `value` carries non-negative integer `start <= end`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateSpan } from '@orkestrel/template'\n *\n * isTemplateSpan({ start: 0, end: 5 }) // true\n * isTemplateSpan({ start: 5, end: 2 }) // false\n * ```\n */\nexport function isTemplateSpan(value: unknown): value is TemplateSpan {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Object.keys(value)\n\t\tif (keys.length !== 2) return false\n\t\tconst start: unknown = value.start\n\t\tconst end: unknown = value.end\n\t\treturn isNonNegativeInteger(start) && isNonNegativeInteger(end) && start <= end\n\t})\n}\n\n/**\n * Checks whether a string token is one of the single-token {@link TemplateComparison} operators.\n *\n * @param value - The value to test\n * @returns True if `value` is in `TEMPLATE_COMPARISONS`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateComparison } from '@orkestrel/template'\n *\n * isTemplateComparison('==') // true\n * isTemplateComparison('in') // false\n * ```\n */\nexport function isTemplateComparison(value: unknown): value is TemplateComparison {\n\treturn holds(() => isString(value) && TEMPLATE_COMPARISONS.some((operator) => operator === value))\n}\n\n/**\n * Checks whether an unknown value is a runtime {@link TemplateNamespace} container.\n *\n * @param value - The value to test\n * @returns True if `value` is a namespace container with a `Map` of bindings; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateNamespace } from '@orkestrel/template'\n *\n * isTemplateNamespace({ namespace: true, values: new Map() }) // true\n * isTemplateNamespace(new Map()) // false\n * ```\n */\nexport function isTemplateNamespace(value: unknown): value is TemplateNamespace {\n\treturn holds(() => {\n\t\tif (!isObject(value) || isArray(value) || isMap(value)) return false\n\t\treturn Reflect.get(value, 'namespace') === true && isMap(Reflect.get(value, 'values'))\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateTarget} (`local` or `attribute`).\n *\n * @param value - The value to test\n * @returns True if `value` is a well-formed assignment target; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateTarget } from '@orkestrel/template'\n *\n * isTemplateTarget({ scope: 'local', name: 'x' }) // true\n * isTemplateTarget({ scope: 'attribute', object: 'ns', name: 'count' }) // true\n * ```\n */\nexport function isTemplateTarget(value: unknown): value is TemplateTarget {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst scope: unknown = value.scope\n\t\tif (scope === 'local') {\n\t\t\treturn Object.keys(value).length === 2 && isString(value.name) && value.name.length > 0\n\t\t}\n\t\tif (scope === 'attribute') {\n\t\t\treturn (\n\t\t\t\tObject.keys(value).length === 3 &&\n\t\t\t\tisString(value.object) &&\n\t\t\t\tvalue.object.length > 0 &&\n\t\t\t\tisString(value.name) &&\n\t\t\t\tvalue.name.length > 0\n\t\t\t)\n\t\t}\n\t\treturn false\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateExpression} within `MAX_DEPTH` and free of cycles.\n *\n * @param value - The value to test\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to refuse reference cycles\n * @returns True if `value` is a well-formed expression; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateExpression } from '@orkestrel/template'\n *\n * isTemplateExpression({ term: 'literal', value: 'Hi' }) // true\n * isTemplateExpression({ term: 'unknown' }) // false\n * ```\n */\nexport function isTemplateExpression(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): value is TemplateExpression {\n\treturn holds(() => {\n\t\tif (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false\n\t\tconst term: unknown = value.term\n\t\tif (!isString(term)) return false\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst keys = Object.keys(value)\n\t\t\tconst next = depth + 1\n\t\t\tswitch (term) {\n\t\t\t\tcase 'literal': {\n\t\t\t\t\tconst literal: unknown = value.value\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 2 &&\n\t\t\t\t\t\t(literal === null || isString(literal) || isBoolean(literal) || isFiniteNumber(literal))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'name':\n\t\t\t\t\treturn keys.length === 2 && isString(value.name) && value.name.length > 0\n\t\t\t\tcase 'member':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisTemplateExpression(value.object, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.key, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'slice': {\n\t\t\t\t\tconst allowed = keys.every(\n\t\t\t\t\t\t(key) =>\n\t\t\t\t\t\t\tkey === 'term' ||\n\t\t\t\t\t\t\tkey === 'object' ||\n\t\t\t\t\t\t\tkey === 'start' ||\n\t\t\t\t\t\t\tkey === 'stop' ||\n\t\t\t\t\t\t\tkey === 'step',\n\t\t\t\t\t)\n\t\t\t\t\treturn (\n\t\t\t\t\t\tallowed &&\n\t\t\t\t\t\tisTemplateExpression(value.object, next, ancestors) &&\n\t\t\t\t\t\t(value.start === undefined || isTemplateExpression(value.start, next, ancestors)) &&\n\t\t\t\t\t\t(value.stop === undefined || isTemplateExpression(value.stop, next, ancestors)) &&\n\t\t\t\t\t\t(value.step === undefined || isTemplateExpression(value.step, next, ancestors))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'call': {\n\t\t\t\t\tconst rawValues: unknown = value.values\n\t\t\t\t\tconst rawKeywords: unknown = value.keywords\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisTemplateExpression(value.callee, next, ancestors) &&\n\t\t\t\t\t\tisArray(rawValues) &&\n\t\t\t\t\t\trawValues.every((item) => isTemplateExpression(item, next, ancestors)) &&\n\t\t\t\t\t\tisArray(rawKeywords) &&\n\t\t\t\t\t\trawKeywords.every(\n\t\t\t\t\t\t\t(keyword) =>\n\t\t\t\t\t\t\t\tisRecord(keyword) &&\n\t\t\t\t\t\t\t\tObject.keys(keyword).length === 2 &&\n\t\t\t\t\t\t\t\tisString(keyword.name) &&\n\t\t\t\t\t\t\t\tkeyword.name.length > 0 &&\n\t\t\t\t\t\t\t\tisTemplateExpression(keyword.value, next, ancestors),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'filter':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'test':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisBoolean(value.negated) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'unary': {\n\t\t\t\t\tconst operator: unknown = value.operator\n\t\t\t\t\tconst admittedUnary: readonly TemplateUnaryOperator[] = ['not', '-', '+']\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisString(operator) &&\n\t\t\t\t\t\tadmittedUnary.some((candidate) => candidate === operator) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'binary': {\n\t\t\t\t\tconst operator: unknown = value.operator\n\t\t\t\t\tconst admittedBinary: readonly TemplateOperator[] = [\n\t\t\t\t\t\t'+',\n\t\t\t\t\t\t'-',\n\t\t\t\t\t\t'~',\n\t\t\t\t\t\t'==',\n\t\t\t\t\t\t'!=',\n\t\t\t\t\t\t'<',\n\t\t\t\t\t\t'>',\n\t\t\t\t\t\t'<=',\n\t\t\t\t\t\t'>=',\n\t\t\t\t\t\t'in',\n\t\t\t\t\t\t'not in',\n\t\t\t\t\t\t'and',\n\t\t\t\t\t\t'or',\n\t\t\t\t\t]\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(operator) &&\n\t\t\t\t\t\tadmittedBinary.some((candidate) => candidate === operator) &&\n\t\t\t\t\t\tisTemplateExpression(value.left, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.right, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'conditional':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisTemplateExpression(value.condition, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.consequent, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.alternate, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tdefault:\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateNode} within `MAX_DEPTH` and free of cycles.\n *\n * @param value - The value to test\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to refuse reference cycles\n * @returns True if `value` is a structurally valid template AST node; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateNode } from '@orkestrel/template'\n *\n * isTemplateNode({ syntax: 'text', value: 'Hello' }) // true\n * isTemplateNode({ syntax: 'unknown' }) // false\n * ```\n */\nexport function isTemplateNode(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): value is TemplateNode {\n\treturn holds(() => {\n\t\tif (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false\n\t\tconst syntax: unknown = value.syntax\n\t\tif (!isString(syntax)) return false\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst keys = Object.keys(value)\n\t\t\tconst next = depth + 1\n\t\t\tswitch (syntax) {\n\t\t\t\tcase 'document': {\n\t\t\t\t\tconst children: unknown = value.children\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 2 &&\n\t\t\t\t\t\tisArray(children) &&\n\t\t\t\t\t\tchildren.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'text':\n\t\t\t\t\treturn keys.length === 2 && isString(value.value)\n\t\t\t\tcase 'placeholder':\n\t\t\t\t\treturn keys.length === 3 && isString(value.name) && isString(value.raw)\n\t\t\t\tcase 'output':\n\t\t\t\t\treturn keys.length === 2 && isTemplateExpression(value.value, next, ancestors)\n\t\t\t\tcase 'if': {\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\tconst alternate: unknown = value.alternate\n\t\t\t\t\tconst allowed = keys.every(\n\t\t\t\t\t\t(key) =>\n\t\t\t\t\t\t\tkey === 'syntax' || key === 'condition' || key === 'body' || key === 'alternate',\n\t\t\t\t\t)\n\t\t\t\t\treturn (\n\t\t\t\t\t\tallowed &&\n\t\t\t\t\t\tisTemplateExpression(value.condition, next, ancestors) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\t(alternate === undefined ||\n\t\t\t\t\t\t\t(isArray(alternate) &&\n\t\t\t\t\t\t\t\talternate.every(\n\t\t\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t\t\t)))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'for': {\n\t\t\t\t\tconst targets: unknown = value.targets\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisArray(targets) &&\n\t\t\t\t\t\ttargets.length > 0 &&\n\t\t\t\t\t\ttargets.every((target) => isString(target) && target.length > 0) &&\n\t\t\t\t\t\tisTemplateExpression(value.sequence, next, ancestors) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'set':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisTemplateTarget(value.target) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'macro': {\n\t\t\t\t\tconst parameters: unknown = value.parameters\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisArray(parameters) &&\n\t\t\t\t\t\tparameters.every(\n\t\t\t\t\t\t\t(parameter) =>\n\t\t\t\t\t\t\t\tisRecord(parameter) &&\n\t\t\t\t\t\t\t\tObject.keys(parameter).every((key) => key === 'name' || key === 'fallback') &&\n\t\t\t\t\t\t\t\tisString(parameter.name) &&\n\t\t\t\t\t\t\t\tparameter.name.length > 0 &&\n\t\t\t\t\t\t\t\t(parameter.fallback === undefined ||\n\t\t\t\t\t\t\t\t\tisTemplateExpression(parameter.fallback, next, ancestors)),\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'control':\n\t\t\t\t\treturn keys.length === 2 && (value.action === 'break' || value.action === 'continue')\n\t\t\t\tcase 'comment':\n\t\t\t\t\treturn keys.length === 2 && isString(value.value)\n\t\t\t\tcase 'html':\n\t\t\t\t\treturn keys.length === 2 && isHTMLDocument(value.document)\n\t\t\t\tcase 'markdown':\n\t\t\t\t\treturn keys.length === 2 && isMarkdownDocument(value.document)\n\t\t\t\tdefault:\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t})\n}\n\n/**\n * Checks whether an unknown value is a structurally valid root {@link TemplateDocument}.\n *\n * @param value - The value to test\n * @returns True if `value` is a complete, cycle-free document within `MAX_DEPTH`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateDocument } from '@orkestrel/template'\n *\n * isTemplateDocument({ syntax: 'document', children: [] }) // true\n * isTemplateDocument({ syntax: 'text', value: 'Hi' }) // false\n * ```\n */\nexport function isTemplateDocument(value: unknown): value is TemplateDocument {\n\treturn isTemplateNode(value) && value.syntax === 'document'\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { HTMLDocument, HTMLSanitizeOptions } from '@orkestrel/html'\nimport type {\n\tBlockNode,\n\tInlineNode,\n\tListItemNode,\n\tMarkdownDocument,\n\tMarkdownNode,\n} from '@orkestrel/markdown'\nimport type {\n\tTemplateDerivation,\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateExpression,\n\tTemplateFillContext,\n\tTemplateFillValues,\n\tTemplateHandlerMap,\n\tTemplateKeyword,\n\tTemplateLoop,\n\tTemplateMacro,\n\tTemplateNamespace,\n\tTemplateNode,\n\tTemplatePart,\n\tTemplatePlaceholder,\n\tTemplateRewriteHandler,\n\tTemplateRuntimeValue,\n\tTemplateScope,\n\tTemplateToken,\n\tTemplateTokenForm,\n\tTemplateTokenResolution,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisMap,\n\tisObject,\n\tisRecord,\n\tisString,\n\tkeyOf,\n\tresolveField,\n} from '@orkestrel/contract'\nimport {\n\tcreateHTML,\n\tisHTMLNode,\n\tMAX_DEPTH,\n\trenderHTML,\n\tSAFE_URL_SCHEMES,\n\tsanitizeURL,\n} from '@orkestrel/html'\nimport {\n\tcoalesceText,\n\tflattenText,\n\tisBlockNode,\n\tisMarkdownNode,\n\tparseMarkdown,\n\trenderMarkdown,\n} from '@orkestrel/markdown'\nimport {\n\tDEFAULT_LOCALE,\n\tDEFAULT_MISSING_POLICY,\n\tFILL_PATTERN,\n\tTEMPLATE_ESCAPES,\n\tTEMPLATE_FILTERS,\n\tTEMPLATE_FUNCTIONS,\n\tTEMPLATE_LITERALS,\n\tTEMPLATE_LOOP_REFUSALS,\n\tTEMPLATE_METHODS,\n\tTEMPLATE_SEGMENT_PATTERN,\n\tTEMPLATE_SPACE,\n\tTEMPLATE_STRING_METHODS,\n\tTEMPLATE_TESTS,\n\tTEMPLATE_TOKEN_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\nimport { isTemplateDocument, isTemplateNamespace } from './validators.js'\n\n// Pure, class-free leaves for plain template filling, Jinja lexing and\n// evaluation, AST traversal/fold/rewrite, and canonical source rendering.\n// HTML sanitization on tree-valued fills routes through `@orkestrel/html`'s\n// `createHTML` factory so no local class is imported here.\n\n// === Plain placeholder leaves (0.0.17 contract + tree-valued fill)\n\n/**\n * Formats a resolved fill value for substitution into a template's `content`.\n *\n * @remarks\n * A finite number renders with the given locale's thousand grouping through\n * `toLocaleString`. An `@orkestrel/html` node passes through `@orkestrel/html`'s\n * sanitize floor before rendering with `renderHTML`, and an `@orkestrel/markdown`\n * node renders with `renderMarkdown`. Every other value — including `null` —\n * String-coerces.\n *\n * @param value - The resolved value to format\n * @param locale - The locale used for finite-number formatting\n * @returns The formatted string\n *\n * @example\n * ```ts\n * import { formatValue } from '@orkestrel/template'\n *\n * formatValue(5010, 'en-US') // '5,010'\n * formatValue(null, 'en-US') // 'null'\n * ```\n */\nexport function formatValue(value: unknown, locale: string): string {\n\tif (isFiniteNumber(value)) return value.toLocaleString(locale)\n\tif (isHTMLNode(value)) {\n\t\tconst document: HTMLDocument =\n\t\t\tvalue.category === 'document' ? value : { category: 'document', children: [value] }\n\t\treturn renderHTML(createHTML(document).sanitize().document)\n\t}\n\tif (isMarkdownNode(value)) return renderMarkdown(value)\n\treturn String(value)\n}\n\n/**\n * Resolves a field path against a fill-values record, refusing any path that\n * touches a prototype-pollution-unsafe segment.\n *\n * @param record - The fill-values record to resolve against\n * @param path - The field path — a single segment or a segment array\n * @returns The resolved value, or `undefined` when unresolved or the path is unsafe\n *\n * @example\n * ```ts\n * import { resolveSafeField } from '@orkestrel/template'\n *\n * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1\n * resolveSafeField({}, ['__proto__', 'polluted']) // undefined\n * ```\n */\nexport function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown {\n\tconst segments = isArray(path) ? path : [path]\n\tif (segments.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return undefined\n\treturn resolveField(record, path)\n}\n\n/**\n * Resolves one `{{name}}` token against the declared placeholders and the\n * fill-values record.\n *\n * @param record - The fill-values record the token resolves against\n * @param placeholders - The declared placeholders the token matches by name\n * @param token - The trimmed token text, without its `{{` / `}}` delimiters\n * @returns The {@link TemplateTokenResolution} for the token\n *\n * @example\n * ```ts\n * import { resolveToken } from '@orkestrel/template'\n *\n * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'\n * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false\n * ```\n */\nexport function resolveToken(\n\trecord: TemplateFillValues,\n\tplaceholders: readonly TemplatePlaceholder[],\n\ttoken: string,\n): TemplateTokenResolution {\n\tconst declared = placeholders.find((placeholder) => placeholder.name === token)\n\tconst path = declared?.path ?? token.split('.')\n\treturn {\n\t\tvalue: resolveSafeField(record, path),\n\t\tdeclared,\n\t\trequired: declared === undefined || declared.required !== false,\n\t}\n}\n\n/**\n * Substitutes every `{{name}}` token in `content` in a single pass.\n *\n * @param content - The template content carrying `{{name}}` tokens\n * @param values - The values tokens resolve against\n * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and declared `placeholders`\n * @returns The substituted content\n *\n * @example\n * ```ts\n * import { fillTemplate } from '@orkestrel/template'\n *\n * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'\n * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'\n * ```\n */\nexport function fillTemplate(\n\tcontent: string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateFillContext,\n): string {\n\tconst placeholders = options?.placeholders ?? []\n\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\tconst record = values ?? {}\n\n\tconst missingNames: string[] = []\n\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst result = content.replace(pattern, (matchText: string, rawToken: string | undefined) => {\n\t\tif (rawToken === undefined) return '{{'\n\t\tconst token = rawToken.trim()\n\n\t\tconst { value, declared, required } = resolveToken(record, placeholders, token)\n\n\t\tif (value !== undefined) return formatValue(value, locale)\n\t\tif (declared?.fallback !== undefined) return formatValue(declared.fallback, locale)\n\n\t\tif (missing === 'literal') return matchText\n\t\tif (missing === 'empty') return ''\n\n\t\tif (required && !missingNames.includes(token)) {\n\t\t\tmissingNames.push(token)\n\t\t}\n\t\treturn ''\n\t})\n\n\tif (missing === 'error' && missingNames.length > 0) {\n\t\tthrow new TemplateError(\n\t\t\t'MISSING',\n\t\t\t`Missing required placeholder(s): ${missingNames.join(', ')}`,\n\t\t\t{ missing: missingNames },\n\t\t)\n\t}\n\n\treturn result\n}\n\n// === Lexing, source normalization, and compiler diagnostics\n\n/**\n * Quotes untrusted text for a template error message as a length-capped JSON\n * string literal.\n *\n * @param value - The raw text to quote\n * @returns The quoted diagnostic text\n *\n * @example\n * ```ts\n * import { quoteTemplateText } from '@orkestrel/template'\n *\n * quoteTemplateText('tojson') // '\"tojson\"'\n * ```\n */\nexport function quoteTemplateText(value: string): string {\n\tconst clipped = value.length > 120 ? `${value.slice(0, 120)}...` : value\n\treturn JSON.stringify(clipped)\n}\n\n/**\n * Normalizes a Jinja template source by converting every line ending to `\\n`\n * and dropping one trailing line ending when present.\n *\n * @param source - The raw template source\n * @returns The normalized source text\n *\n * @example\n * ```ts\n * import { normalizeTemplateSource } from '@orkestrel/template'\n *\n * normalizeTemplateSource('Hi\\r\\n\\r\\n') // 'Hi\\n'\n * ```\n */\nexport function normalizeTemplateSource(source: string): string {\n\tconst lines = source.split(/\\r\\n|\\r|\\n/)\n\treturn (lines.at(-1) === '' ? lines.slice(0, -1) : lines).join('\\n')\n}\n\n/**\n * Trims literal template text between adjacent Jinja tags under `trim_blocks`\n * and `lstrip_blocks`, honoring `-` and `+` delimiter markers.\n *\n * @param text - The text between the two tags\n * @param closer - The closing delimiter of the preceding tag, or `''` at start\n * @param opener - The opening delimiter of the following tag, or `''` at end\n * @returns The trimmed text\n *\n * @example\n * ```ts\n * import { trimTemplateText } from '@orkestrel/template'\n *\n * trimTemplateText('\\n ', '%}', '{%') // ''\n * trimTemplateText('Hi \\n', '}}', '{{-') // 'Hi'\n * ```\n */\nexport function trimTemplateText(text: string, closer: string, opener: string): string {\n\tconst kept = closer.startsWith('-')\n\t\t? text.replace(new RegExp(`^${TEMPLATE_SPACE}+`, 'u'), '')\n\t\t: (closer === '%}' || closer === '#}') && text.startsWith('\\n')\n\t\t\t? text.slice(1)\n\t\t\t: text\n\tif (opener.endsWith('-')) return kept.replace(new RegExp(`${TEMPLATE_SPACE}+$`, 'u'), '')\n\tif (opener !== '{%' && opener !== '{#') return kept\n\tconst start = kept.lastIndexOf('\\n') + 1\n\tconst starting = closer === '' || text.slice(0, text.length - kept.length).endsWith('\\n')\n\treturn (start > 0 || starting) && new RegExp(`^${TEMPLATE_SPACE}+$`, 'u').test(kept.slice(start))\n\t\t? kept.slice(0, start)\n\t\t: kept\n}\n\n/**\n * Locates a UTF-16 offset in a template source as a 1-based `[line, column]` pair.\n *\n * @param starts - The starting offset of each line in ascending order\n * @param offset - The offset to locate\n * @returns The 1-based line and column\n *\n * @example\n * ```ts\n * import { locateTemplateOffset } from '@orkestrel/template'\n *\n * locateTemplateOffset([0, 4], 5) // [2, 2]\n * ```\n */\nexport function locateTemplateOffset(\n\tstarts: readonly number[],\n\toffset: number,\n): readonly [line: number, column: number] {\n\tconst line = Math.max(\n\t\t0,\n\t\tstarts.findLastIndex((start) => start <= offset),\n\t)\n\treturn [line + 1, offset - (starts[line] ?? 0) + 1]\n}\n\n/**\n * Maps each character position of `normalizeTemplateSource(source)` back to its\n * UTF-16 offset in the original unnormalized source.\n *\n * @param source - The original unnormalized template source\n * @returns The normalized text and its boundary-to-original offset array\n *\n * @example\n * ```ts\n * import { mapTemplateOffsets } from '@orkestrel/template'\n *\n * mapTemplateOffsets('a\\r\\nb')[1] // [0, 1, 3, 4]\n * ```\n */\nexport function mapTemplateOffsets(\n\tsource: string,\n): readonly [normalized: string, offsets: readonly number[]] {\n\tconst chars: string[] = []\n\tconst offsets: number[] = []\n\tfor (let index = 0; index < source.length; index += 1) {\n\t\tconst code = source.charCodeAt(index)\n\t\tif (code === 10 && source.charCodeAt(index - 1) === 13) continue\n\t\toffsets.push(index)\n\t\tchars.push(code === 13 ? '\\n' : (source[index] ?? ''))\n\t}\n\tconst trailing = chars.at(-1) === '\\n'\n\tconst keptChars = trailing ? chars.slice(0, -1) : chars\n\tconst keptOffsets = trailing ? offsets.slice(0, -1) : offsets\n\tconst finalOffset = trailing ? (offsets.at(-1) ?? source.length) : source.length\n\treturn [keptChars.join(''), [...keptOffsets, finalOffset]]\n}\n\n/**\n * Scans the interior of one Jinja tag into lexical tokens with original UTF-16\n * offsets and 1-based line and column positions.\n *\n * @param text - The tag interior between delimiters\n * @param offset - The normalized-source offset of the tag interior's start\n * @param starts - Line-start offsets in the normalized source\n * @param offsets - Boundary map from normalized offsets to original UTF-16 offsets\n * @returns The scanned tokens inside the tag\n *\n * @example\n * ```ts\n * import { scanTemplateTag } from '@orkestrel/template'\n *\n * scanTemplateTag(' loop.first ', 2, [0]).map((token) => token.text) // ['loop', '.', 'first']\n * ```\n */\nexport function scanTemplateTag(\n\ttext: string,\n\toffset: number,\n\tstarts: readonly number[],\n\toffsets?: readonly number[],\n): readonly TemplateToken[] {\n\tconst pattern = new RegExp(TEMPLATE_TOKEN_PATTERN.source, TEMPLATE_TOKEN_PATTERN.flags)\n\treturn Array.from(text.matchAll(pattern)).flatMap((match): readonly TemplateToken[] => {\n\t\tconst normalizedStart = offset + match.index\n\t\tconst normalizedEnd = normalizedStart + match[0].length\n\t\tconst [line, column] = locateTemplateOffset(starts, normalizedStart)\n\t\tconst start = offsets?.[normalizedStart] ?? normalizedStart\n\t\tconst end = offsets?.[normalizedEnd] ?? normalizedEnd\n\t\tif (match[1] !== undefined) return []\n\t\tif (match[7] !== undefined) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttoken: 'fault',\n\t\t\t\t\ttext: `holds the character ${quoteTemplateText(match[0])}, which starts no token`,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t\tstart,\n\t\t\t\t\tend,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tconst token: TemplateTokenForm =\n\t\t\tmatch[2] !== undefined\n\t\t\t\t? 'float'\n\t\t\t\t: match[3] !== undefined\n\t\t\t\t\t? 'integer'\n\t\t\t\t\t: match[4] !== undefined\n\t\t\t\t\t\t? 'name'\n\t\t\t\t\t\t: match[5] !== undefined\n\t\t\t\t\t\t\t? 'string'\n\t\t\t\t\t\t\t: 'operator'\n\t\treturn [{ token, text: match[0], line, column, start, end }]\n\t})\n}\n\n/**\n * Scans a raw Jinja template source into its token stream, including trimmed\n * text, comments, tag delimiters, inner tokens, and a closing `end` token.\n *\n * @param source - The template source\n * @returns The scanned tokens, ending with an `end` token\n *\n * @example\n * ```ts\n * import { scanTemplateTokens } from '@orkestrel/template'\n *\n * scanTemplateTokens('Hi {{ name }}').map((token) => token.token)\n * // ['text', 'variable', 'name', 'close', 'end']\n * ```\n */\nexport function scanTemplateTokens(source: string): readonly TemplateToken[] {\n\tconst [normalized, offsets] = mapTemplateOffsets(source)\n\tconst starts = [0, ...Array.from(normalized.matchAll(/\\n/g), (match) => match.index + 1)]\n\tconst pattern = new RegExp(TEMPLATE_SEGMENT_PATTERN.source, TEMPLATE_SEGMENT_PATTERN.flags)\n\tconst segments = Array.from(normalized.matchAll(pattern))\n\tconst tokens = segments.flatMap((segment, index): readonly TemplateToken[] => {\n\t\tconst previous = segments[index - 1]\n\t\tconst text = segment[1] ?? ''\n\t\tconst opener = segment[2] ?? segment[5] ?? segment[8] ?? segment[11] ?? ''\n\t\tconst kept = trimTemplateText(\n\t\t\ttext,\n\t\t\tprevious?.[4] ?? previous?.[7] ?? previous?.[10] ?? '',\n\t\t\topener,\n\t\t)\n\t\tconst [line, column] = locateTemplateOffset(starts, segment.index)\n\t\tconst textStart = offsets[segment.index] ?? segment.index\n\t\tconst textEnd = offsets[segment.index + text.length] ?? segment.index + text.length\n\t\tconst leading: readonly TemplateToken[] =\n\t\t\tkept === ''\n\t\t\t\t? []\n\t\t\t\t: [{ token: 'text', text: kept, line, column, start: textStart, end: textEnd }]\n\t\tconst tag = segment.index + text.length\n\t\tconst [tagLine, tagColumn] = locateTemplateOffset(starts, tag)\n\t\tconst tagStart = offsets[tag] ?? tag\n\t\tif (segment[11] !== undefined) {\n\t\t\tconst subject = segment[11] === '{#' ? 'comment' : 'tag'\n\t\t\treturn [\n\t\t\t\t...leading,\n\t\t\t\t{\n\t\t\t\t\ttoken: 'fault',\n\t\t\t\t\ttext: `opens a ${subject} that never closes`,\n\t\t\t\t\tline: tagLine,\n\t\t\t\t\tcolumn: tagColumn,\n\t\t\t\t\tstart: tagStart,\n\t\t\t\t\tend: source.length,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (segment[8] !== undefined && segment[9] !== undefined && segment[10] !== undefined) {\n\t\t\tconst commentEnd = tag + segment[8].length + segment[9].length + segment[10].length\n\t\t\treturn [\n\t\t\t\t...leading,\n\t\t\t\t{\n\t\t\t\t\ttoken: 'comment',\n\t\t\t\t\ttext: segment[9],\n\t\t\t\t\tline: tagLine,\n\t\t\t\t\tcolumn: tagColumn,\n\t\t\t\t\tstart: tagStart,\n\t\t\t\t\tend: offsets[commentEnd] ?? commentEnd,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tconst inside = segment[3] ?? segment[6]\n\t\tconst closer = segment[4] ?? segment[7]\n\t\tif (inside === undefined || closer === undefined) return leading\n\t\tconst closeOffset = tag + opener.length + inside.length\n\t\tconst [closeLine, closeColumn] = locateTemplateOffset(starts, closeOffset)\n\t\tconst openEnd = offsets[tag + opener.length] ?? tag + opener.length\n\t\tconst closeStart = offsets[closeOffset] ?? closeOffset\n\t\tconst closeEnd = offsets[closeOffset + closer.length] ?? closeOffset + closer.length\n\t\treturn [\n\t\t\t...leading,\n\t\t\t{\n\t\t\t\ttoken: segment[2] === undefined ? 'variable' : 'block',\n\t\t\t\ttext: opener,\n\t\t\t\tline: tagLine,\n\t\t\t\tcolumn: tagColumn,\n\t\t\t\tstart: tagStart,\n\t\t\t\tend: openEnd,\n\t\t\t},\n\t\t\t...scanTemplateTag(inside, tag + opener.length, starts, offsets),\n\t\t\t{\n\t\t\t\ttoken: 'close',\n\t\t\t\ttext: closer,\n\t\t\t\tline: closeLine,\n\t\t\t\tcolumn: closeColumn,\n\t\t\t\tstart: closeStart,\n\t\t\t\tend: closeEnd,\n\t\t\t},\n\t\t]\n\t})\n\tconst [line, column] = locateTemplateOffset(starts, normalized.length)\n\treturn [\n\t\t...tokens,\n\t\t{ token: 'end', text: '', line, column, start: source.length, end: source.length },\n\t]\n}\n\n/**\n * Builds a `FORMAT`-coded {@link TemplateError} anchored at a token's source location.\n *\n * @param token - The token locating the syntax or subset refusal\n * @param message - The diagnostic clause after \"the template\"\n * @param context - Additional context members carried beside `line`, `column`, `start`, and `end`\n * @returns The constructed {@link TemplateError}\n *\n * @example\n * ```ts\n * import { buildTemplateFormatError, scanTemplateTokens } from '@orkestrel/template'\n *\n * const [token] = scanTemplateTokens('{{ x }}')\n * buildTemplateFormatError(token, 'uses an unknown filter', { feature: 'unknown' }).code // 'FORMAT'\n * ```\n */\nexport function buildTemplateFormatError(\n\ttoken: TemplateToken,\n\tmessage: string,\n\tcontext?: Readonly<Record<string, unknown>>,\n): TemplateError {\n\treturn new TemplateError(\n\t\t'FORMAT',\n\t\t`At line ${token.line}, column ${token.column}, the template ${message}.`,\n\t\t{\n\t\t\t...context,\n\t\t\tline: token.line,\n\t\t\tcolumn: token.column,\n\t\t\tstart: token.start,\n\t\t\tend: token.end,\n\t\t},\n\t)\n}\n\n/**\n * Builds an `EVALUATION`-coded {@link TemplateError} for runtime evaluation refusals.\n *\n * @param message - The diagnostic clause after \"The template\"\n * @param context - Additional context members describing the failure\n * @returns The constructed {@link TemplateError}\n *\n * @example\n * ```ts\n * import { buildTemplateEvaluationError } from '@orkestrel/template'\n *\n * buildTemplateEvaluationError('adds a string to an integer').code // 'EVALUATION'\n * ```\n */\nexport function buildTemplateEvaluationError(\n\tmessage: string,\n\tcontext?: Readonly<Record<string, unknown>>,\n): TemplateError {\n\treturn new TemplateError('EVALUATION', `The template ${message}.`, context)\n}\n\n/**\n * Renders a scanned token into a readable label for syntax diagnostics.\n *\n * @param token - The token to describe\n * @returns The human-readable token description\n *\n * @example\n * ```ts\n * import { renderTemplateToken } from '@orkestrel/template'\n *\n * renderTemplateToken({ token: 'end', text: '', line: 1, column: 1, start: 0, end: 0 }) // 'the end of the template'\n * ```\n */\nexport function renderTemplateToken(token: TemplateToken): string {\n\tif (token.token === 'end') return 'the end of the template'\n\tif (token.token === 'text') return 'template text'\n\tif (token.token === 'comment') return 'a comment'\n\treturn quoteTemplateText(token.text)\n}\n\n/**\n * Checks whether a scanned token matches an expected form and optional text.\n *\n * @param token - The token to inspect\n * @param form - The required token form\n * @param text - Optional exact text to match\n * @returns True if `token` matches; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateToken } from '@orkestrel/template'\n *\n * matchesTemplateToken({ token: 'name', text: 'in', line: 1, column: 1, start: 0, end: 2 }, 'name', 'in') // true\n * ```\n */\nexport function matchesTemplateToken(\n\ttoken: TemplateToken,\n\tform: TemplateTokenForm,\n\ttext?: string,\n): boolean {\n\treturn token.token === form && (text === undefined || token.text === text)\n}\n\n/**\n * Reads the token at an index of a token stream, throwing on `fault` tokens or\n * an empty stream.\n *\n * @param tokens - The token stream\n * @param index - The index to read\n * @returns The resolved token\n *\n * @example\n * ```ts\n * import { readTemplateToken, scanTemplateTokens } from '@orkestrel/template'\n *\n * readTemplateToken(scanTemplateTokens('{{ x }}'), 1).text // 'x'\n * ```\n */\nexport function readTemplateToken(tokens: readonly TemplateToken[], index: number): TemplateToken {\n\tconst token = tokens[index] ?? tokens.at(-1)\n\tif (token === undefined) {\n\t\tthrow new TemplateError('INVALID', 'A template compiles from at least its end token.')\n\t}\n\tif (token.token === 'fault') throw buildTemplateFormatError(token, token.text)\n\treturn token\n}\n\n/**\n * Refuses a token that does not match an expected form and optional text with a\n * `FORMAT`-coded {@link TemplateError}.\n *\n * @param tokens - The token stream\n * @param index - The index to validate\n * @param form - The required token form\n * @param text - Optional exact text to require\n *\n * @example\n * ```ts\n * import { checkTemplateToken, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateToken(scanTemplateTokens('{{ x }}'), 1, 'name', 'x')\n * ```\n */\nexport function checkTemplateToken(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tform: TemplateTokenForm,\n\ttext?: string,\n): void {\n\tconst token = readTemplateToken(tokens, index)\n\tif (matchesTemplateToken(token, form, text)) return\n\tconst expected =\n\t\tform === 'close'\n\t\t\t? 'the tag to close'\n\t\t\t: text === undefined\n\t\t\t\t? `a ${form}`\n\t\t\t\t: quoteTemplateText(text)\n\tthrow buildTemplateFormatError(\n\t\ttoken,\n\t\t`expects ${expected} and finds ${renderTemplateToken(token)}`,\n\t)\n}\n\n/**\n * Consumes an optional trailing colon (where admitted) and closing tag delimiter.\n *\n * @param tokens - The token stream\n * @param index - The position after the tag's expression\n * @param colon - If `true`, admits one trailing colon before the closer; if `false`, requires the closer immediately\n * @returns The index after the closing delimiter\n *\n * @example\n * ```ts\n * import { checkTemplateClose, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateClose(scanTemplateTokens('{% else: %}'), 2, true) // 4\n * ```\n */\nexport function checkTemplateClose(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tcolon: boolean,\n): number {\n\tconst token = readTemplateToken(tokens, index)\n\tif (matchesTemplateToken(token, 'operator', ',')) {\n\t\tthrow buildTemplateFormatError(token, 'writes a tuple, which the subset does not admit', {\n\t\t\tfeature: 'tuple',\n\t\t})\n\t}\n\tconst start = colon && matchesTemplateToken(token, 'operator', ':') ? index + 1 : index\n\tcheckTemplateToken(tokens, start, 'close')\n\treturn start + 1\n}\n\n/**\n * Refuses template nesting deeper than `MAX_DEPTH` (`64`) with a `FORMAT`-coded\n * {@link TemplateError}.\n *\n * @param depth - The nesting level reached\n * @param token - The token locating the refusal\n *\n * @example\n * ```ts\n * import { checkTemplateDepth, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateDepth(4, scanTemplateTokens('{{ x }}')[0])\n * ```\n */\nexport function checkTemplateDepth(depth: number, token: TemplateToken): void {\n\tif (depth <= MAX_DEPTH) return\n\tthrow buildTemplateFormatError(token, `nests deeper than ${MAX_DEPTH} levels`, {\n\t\tlimit: MAX_DEPTH,\n\t})\n}\n\n/**\n * Refuses an invalid assignment target name such as a literal, reserved global\n * function, or private `__`-prefixed identifier.\n *\n * @param token - The target token to validate\n *\n * @example\n * ```ts\n * import { checkTemplateTarget, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateTarget(scanTemplateTokens('{% set count = 1 %}')[2])\n * ```\n */\nexport function checkTemplateTarget(token: TemplateToken): void {\n\tif (token.token !== 'name' || keyOf(TEMPLATE_LITERALS)(token.text)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to ${renderTemplateToken(token)}, which is not a name`,\n\t\t)\n\t}\n\tif (token.text.startsWith('__')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to the private name ${quoteTemplateText(token.text)}`,\n\t\t\t{ feature: 'private' },\n\t\t)\n\t}\n\tif (TEMPLATE_FUNCTIONS.some((name) => name === token.text)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to the function ${quoteTemplateText(token.text)}, which the subset does not admit`,\n\t\t\t{ feature: token.text },\n\t\t)\n\t}\n}\n\n/**\n * Refuses a compile-time read of a `loop` member listed in `TEMPLATE_LOOP_REFUSALS`.\n *\n * @param object - The target expression being indexed\n * @param key - The member key expression\n * @param token - The token locating the refusal\n *\n * @example\n * ```ts\n * import { checkTemplateLoopMember, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateLoopMember(\n * { term: 'name', name: 'loop' },\n * { term: 'literal', value: 'previtem' },\n * scanTemplateTokens('{{ loop.previtem }}')[1],\n * )\n * ```\n */\nexport function checkTemplateLoopMember(\n\tobject: TemplateExpression,\n\tkey: TemplateExpression,\n\ttoken: TemplateToken,\n): void {\n\tif (object.term !== 'name' || object.name !== 'loop' || key.term !== 'literal') return\n\tconst name = key.value\n\tif (!TEMPLATE_LOOP_REFUSALS.some((member) => member === name)) return\n\tthrow buildTemplateFormatError(\n\t\ttoken,\n\t\t`reads ${quoteTemplateText(`loop.${String(name)}`)}, which the subset does not admit`,\n\t\t{ feature: `loop.${String(name)}` },\n\t)\n}\n\n/**\n * Decodes a quoted Jinja string token using Python `unicode-escape` rules.\n *\n * @param token - The string literal token including quotes\n * @returns The decoded string value\n *\n * @example\n * ```ts\n * import { decodeTemplateString, scanTemplateTokens } from '@orkestrel/template'\n *\n * decodeTemplateString(scanTemplateTokens(\"{{ 'a\\\\nb' }}\")[1]) // 'a\\nb'\n * ```\n */\nexport function decodeTemplateString(token: TemplateToken): string {\n\treturn token.text\n\t\t.slice(1, -1)\n\t\t.replace(\n\t\t\t/\\\\(x[\\da-fA-F]{2}|u[\\da-fA-F]{4}|U[\\da-fA-F]{8}|[0-7]{1,3}|N\\{[^}]*\\}|[^])/gu,\n\t\t\t(escape: string, body: string) => {\n\t\t\t\tconst lead = body[0] ?? ''\n\t\t\t\tif (body.length > 1 && lead === 'N') {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t`writes the named escape ${quoteTemplateText(escape)}, which the subset does not admit`,\n\t\t\t\t\t\t{ feature: 'named escape' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (body.length > 1 && (lead === 'x' || lead === 'u' || lead === 'U')) {\n\t\t\t\t\tconst point = Number.parseInt(body.slice(1), 16)\n\t\t\t\t\tif (point > 0x10ffff) {\n\t\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t\t`writes the escape ${quoteTemplateText(escape)}, past U+10FFFF`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\treturn String.fromCodePoint(point)\n\t\t\t\t}\n\t\t\t\tif (/^[0-7]/u.test(body)) return String.fromCodePoint(Number.parseInt(body, 8))\n\t\t\t\tif (body === 'x' || body === 'u' || body === 'U' || body === 'N') {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t`writes the truncated escape ${quoteTemplateText(escape)}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (body === '\\n') return ''\n\t\t\t\tif (keyOf(TEMPLATE_ESCAPES)(body)) return TEMPLATE_ESCAPES[body]\n\t\t\t\tconst point = body.codePointAt(0) ?? 0\n\t\t\t\tif (point < 0x80) return escape\n\t\t\t\tconst hex = point.toString(16)\n\t\t\t\treturn point < 0x100\n\t\t\t\t\t? `\\\\x${hex.padStart(2, '0')}`\n\t\t\t\t\t: point < 0x10000\n\t\t\t\t\t\t? `\\\\u${hex.padStart(4, '0')}`\n\t\t\t\t\t\t: `\\\\U${hex.padStart(8, '0')}`\n\t\t\t},\n\t\t)\n}\n\n/**\n * Decodes an `integer` or `float` token as Jinja reads numeric literals.\n *\n * @param token - The numeric literal token\n * @returns The decoded finite number\n *\n * @example\n * ```ts\n * import { decodeTemplateNumber, scanTemplateTokens } from '@orkestrel/template'\n *\n * decodeTemplateNumber(scanTemplateTokens('{{ 0x1F }}')[1]) // 31\n * ```\n */\nexport function decodeTemplateNumber(token: TemplateToken): number {\n\tconst value = Number(token.text.replaceAll('_', ''))\n\tif (token.token === 'integer' && !Number.isSafeInteger(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`writes the integer ${quoteTemplateText(token.text)}, past the integers JavaScript holds exactly`,\n\t\t\t{ feature: 'big integer' },\n\t\t)\n\t}\n\tif (token.token === 'float' && Number.isInteger(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`writes the float ${quoteTemplateText(token.text)}, whose whole value the subset holds as an integer`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tif (Number.isNaN(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`expects a number and finds ${renderTemplateToken(token)}`,\n\t\t)\n\t}\n\treturn value\n}\n\n// === Runtime value normalization, operators, filters, tests, and methods\n\n/**\n * Normalizes a caller-supplied value into a runtime {@link TemplateRuntimeValue},\n * converting plain objects to string-keyed `Map`s while preserving `HTMLNode`,\n * `MarkdownNode`, and `TemplateNamespace` instances and capping depth at `MAX_DEPTH`.\n *\n * @param value - The value to normalize\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to guard against cycles\n * @returns The normalized runtime value\n *\n * @example\n * ```ts\n * import { normalizeTemplateValue } from '@orkestrel/template'\n *\n * normalizeTemplateValue({ role: 'user' }) // Map { 'role' => 'user' }\n * ```\n */\nexport function normalizeTemplateValue(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): TemplateRuntimeValue {\n\tif (\n\t\tvalue === undefined ||\n\t\tvalue === null ||\n\t\tisBoolean(value) ||\n\t\ttypeof value === 'number' ||\n\t\tisString(value)\n\t) {\n\t\treturn value\n\t}\n\tif (isHTMLNode(value) || isMarkdownNode(value) || isTemplateNamespace(value)) return value\n\tif (depth > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`nests runtime values deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (isArray(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic list in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\treturn value.map((item) => normalizeTemplateValue(item, depth + 1, ancestors))\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isMap(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic mapping in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\t\tfor (const [entryKey, entryValue] of value.entries()) {\n\t\t\t\tif (isString(entryKey) && entryValue !== undefined) {\n\t\t\t\t\tentries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)])\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Map(entries)\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isRecord(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic record in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\t\tfor (const [entryKey, entryValue] of Object.entries(value)) {\n\t\t\t\tif (entryValue !== undefined) {\n\t\t\t\t\tentries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)])\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Map(entries)\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\treturn String(value)\n}\n\n/**\n * Checks whether a runtime value is a compiled {@link TemplateMacro} closure.\n *\n * @param value - The runtime value to inspect\n * @returns True if `value` is a macro closure; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateMacro } from '@orkestrel/template'\n *\n * isTemplateMacro('text') // false\n * ```\n */\nexport function isTemplateMacro(value: unknown): value is TemplateMacro {\n\treturn (\n\t\tisObject(value) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\tReflect.get(value, 'macro') === true &&\n\t\tisString(Reflect.get(value, 'name'))\n\t)\n}\n\n/**\n * Checks whether a runtime value is a `for` {@link TemplateLoop} state record.\n *\n * @param value - The runtime value to inspect\n * @returns True if `value` is a loop state record; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateLoop } from '@orkestrel/template'\n *\n * isTemplateLoop({ index0: 0, length: 1, previtem: undefined, nextitem: undefined }) // true\n * ```\n */\nexport function isTemplateLoop(value: unknown): value is TemplateLoop {\n\treturn (\n\t\tisObject(value) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\t!isTemplateNamespace(value) &&\n\t\t!isTemplateMacro(value) &&\n\t\t!isHTMLNode(value) &&\n\t\t!isMarkdownNode(value) &&\n\t\ttypeof Reflect.get(value, 'index0') === 'number' &&\n\t\ttypeof Reflect.get(value, 'length') === 'number'\n\t)\n}\n\n/**\n * Renders the Python-equivalent type label of a runtime value for diagnostics.\n *\n * @param value - The runtime value to describe\n * @returns The type description\n *\n * @example\n * ```ts\n * import { renderTemplateType } from '@orkestrel/template'\n *\n * renderTemplateType(new Map()) // 'a mapping'\n * ```\n */\nexport function renderTemplateType(value: TemplateRuntimeValue): string {\n\tif (value === undefined) return 'an undefined value'\n\tif (value === null) return 'none'\n\tif (typeof value === 'boolean') return 'a boolean'\n\tif (typeof value === 'number') return Number.isInteger(value) ? 'an integer' : 'a float'\n\tif (typeof value === 'string') return 'a string'\n\tif (isHTMLNode(value)) return 'an HTML node'\n\tif (isMarkdownNode(value)) return 'a Markdown node'\n\tif (isArray(value)) return 'a list'\n\tif (isMap(value)) return 'a mapping'\n\tif (isTemplateNamespace(value)) return 'a namespace'\n\tif (isTemplateMacro(value)) return 'a macro'\n\treturn 'a loop'\n}\n\n/**\n * Renders a finite or special number using Python `str` formatting.\n *\n * @param value - The number to format\n * @returns The Python-formatted numeric text\n *\n * @example\n * ```ts\n * import { renderTemplateNumber } from '@orkestrel/template'\n *\n * renderTemplateNumber(0.00001) // '1e-05'\n * ```\n */\nexport function renderTemplateNumber(value: number): string {\n\tif (Number.isNaN(value)) return 'nan'\n\tif (value === Infinity) return 'inf'\n\tif (value === -Infinity) return '-inf'\n\tif (Number.isInteger(value)) return Object.is(value, -0) ? '0' : String(value)\n\tconst [digits = '', power = '0'] = value.toExponential().split('e')\n\tconst exponent = Number(power)\n\tif (exponent >= -4 && exponent < 16) return String(value)\n\treturn `${digits}e${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`\n}\n\n/**\n * Renders a runtime template value as string output using Python/Jinja rules,\n * sanitizing `HTMLNode`s through `@orkestrel/html` and rendering `MarkdownNode`s\n * through `@orkestrel/markdown`.\n *\n * @param value - The runtime value to render\n * @returns The rendered text\n *\n * @example\n * ```ts\n * import { renderTemplateValue } from '@orkestrel/template'\n *\n * renderTemplateValue(true) // 'True'\n * renderTemplateValue(null) // 'None'\n * ```\n */\nexport function renderTemplateValue(value: TemplateRuntimeValue): string {\n\tif (typeof value === 'string') return value\n\tif (value === undefined) return ''\n\tif (value === null) return 'None'\n\tif (typeof value === 'boolean') return value ? 'True' : 'False'\n\tif (typeof value === 'number') return renderTemplateNumber(value)\n\tif (isHTMLNode(value)) {\n\t\tconst document: HTMLDocument =\n\t\t\tvalue.category === 'document' ? value : { category: 'document', children: [value] }\n\t\treturn renderHTML(createHTML(document).sanitize().document)\n\t}\n\tif (isMarkdownNode(value)) return renderMarkdown(value)\n\tthrow buildTemplateEvaluationError(\n\t\t`prints ${renderTemplateType(value)}, which Python prints as its repr and the subset does not`,\n\t\t{ feature: 'repr' },\n\t)\n}\n\n/**\n * Serializes a runtime template value to deterministic JSON matching `minja`\n * and Python `json.dumps` (`\", \"` and `\": \"` separators, insertion key order,\n * unescaped non-ASCII Unicode).\n *\n * @param value - The runtime value to serialize\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to guard against cycles\n * @returns The serialized JSON string\n *\n * @example\n * ```ts\n * import { serializeTemplateJSON } from '@orkestrel/template'\n *\n * serializeTemplateJSON(new Map([['b', true], ['a', [1, 2]]])) // '{\"b\": true, \"a\": [1, 2]}'\n * ```\n */\nexport function serializeTemplateJSON(\n\tvalue: TemplateRuntimeValue,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): string {\n\tif (depth > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`serializes JSON deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (value === null || value === undefined) return 'null'\n\tif (typeof value === 'boolean') return value ? 'true' : 'false'\n\tif (typeof value === 'number') {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a non-finite number to JSON', {\n\t\t\t\tfeature: 'tojson',\n\t\t\t})\n\t\t}\n\t\treturn Object.is(value, -0) ? '0' : String(value)\n\t}\n\tif (typeof value === 'string') return JSON.stringify(value)\n\tif (isArray(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a cyclic list to JSON', { feature: 'tojson' })\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst items = value.map((item) => serializeTemplateJSON(item, depth + 1, ancestors))\n\t\t\treturn `[${items.join(', ')}]`\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isMap(value) || isTemplateNamespace(value)) {\n\t\tconst map = isTemplateNamespace(value) ? value.values : value\n\t\tif (ancestors.has(map)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a cyclic mapping to JSON', {\n\t\t\t\tfeature: 'tojson',\n\t\t\t})\n\t\t}\n\t\tancestors.add(map)\n\t\ttry {\n\t\t\tconst pairs = Array.from(map.entries()).map(\n\t\t\t\t([entryKey, entryValue]) =>\n\t\t\t\t\t`${JSON.stringify(entryKey)}: ${serializeTemplateJSON(entryValue, depth + 1, ancestors)}`,\n\t\t\t)\n\t\t\treturn `{${pairs.join(', ')}}`\n\t\t} finally {\n\t\t\tancestors.delete(map)\n\t\t}\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`serializes ${renderTemplateType(value)} to JSON, which is not JSON-serializable`,\n\t\t{ feature: 'tojson' },\n\t)\n}\n\n/**\n * Checks whether a runtime template value is truthy under Python `bool` rules.\n *\n * @param value - The value to test\n * @returns True if truthy; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateTruth } from '@orkestrel/template'\n *\n * matchesTemplateTruth('') // false\n * matchesTemplateTruth([0]) // true\n * ```\n */\nexport function matchesTemplateTruth(value: TemplateRuntimeValue): boolean {\n\tif (value === undefined || value === null) return false\n\tif (typeof value === 'boolean') return value\n\tif (typeof value === 'number') return value !== 0\n\tif (typeof value === 'string') return value.length > 0\n\tif (isHTMLNode(value) || isMarkdownNode(value) || isTemplateMacro(value)) return true\n\tif (isArray(value)) return value.length > 0\n\tif (isMap(value)) return value.size > 0\n\tif (isTemplateNamespace(value)) return value.values.size > 0\n\treturn value.length > 0\n}\n\n/**\n * Checks whether two runtime template values are equal under Python `==` rules.\n *\n * @param left - The first value\n * @param right - The second value\n * @returns True if equal; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateEqual } from '@orkestrel/template'\n *\n * matchesTemplateEqual(true, 1) // true\n * matchesTemplateEqual('1', 1) // false\n * ```\n */\nexport function matchesTemplateEqual(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): boolean {\n\tif (\n\t\t(typeof left === 'number' || typeof left === 'boolean') &&\n\t\t(typeof right === 'number' || typeof right === 'boolean')\n\t) {\n\t\treturn Number(left) === Number(right)\n\t}\n\tif (isArray(left)) {\n\t\treturn (\n\t\t\tisArray(right) &&\n\t\t\tleft.length === right.length &&\n\t\t\tleft.every((item, index) => matchesTemplateEqual(item, right[index]))\n\t\t)\n\t}\n\tif (isMap(left)) {\n\t\treturn (\n\t\t\tisMap(right) &&\n\t\t\tleft.size === right.size &&\n\t\t\tArray.from(left).every(\n\t\t\t\t([key, item]) => right.has(key) && matchesTemplateEqual(item, right.get(key)),\n\t\t\t)\n\t\t)\n\t}\n\treturn left === right\n}\n\n/**\n * Compares two runtime template values for ordering under Python `<` rules.\n *\n * @param left - The first value\n * @param right - The second value\n * @returns Negative when `left < right`, positive when `left > right`, and `0` when equal\n *\n * @example\n * ```ts\n * import { compareTemplateValues } from '@orkestrel/template'\n *\n * compareTemplateValues(1, 2) < 0 // true\n * ```\n */\nexport function compareTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): number {\n\tif (\n\t\t(typeof left === 'number' || typeof left === 'boolean') &&\n\t\t(typeof right === 'number' || typeof right === 'boolean')\n\t) {\n\t\treturn Number(left) < Number(right) ? -1 : Number(left) > Number(right) ? 1 : 0\n\t}\n\tif (typeof left === 'string' && typeof right === 'string') {\n\t\tconst one = Array.from(left, (character) => character.codePointAt(0) ?? 0)\n\t\tconst two = Array.from(right, (character) => character.codePointAt(0) ?? 0)\n\t\tconst index = one.findIndex((point, position) => point !== two[position])\n\t\tif (index === -1) return one.length - two.length\n\t\treturn (one[index] ?? 0) - (two[index] ?? -1)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`orders ${renderTemplateType(left)} against ${renderTemplateType(right)}, which the subset does not admit`,\n\t\t{ feature: 'ordering' },\n\t)\n}\n\n/**\n * Checks whether a container holds a value under Python `in` rules.\n *\n * @param value - The value to look for\n * @param container - The container to inspect\n * @returns True if `container` contains `value`; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateMember } from '@orkestrel/template'\n *\n * matchesTemplateMember('tool', 'tool_calls') // true\n * ```\n */\nexport function matchesTemplateMember(\n\tvalue: TemplateRuntimeValue,\n\tcontainer: TemplateRuntimeValue,\n): boolean {\n\tif (container === undefined) return false\n\tif (typeof container === 'string' && typeof value === 'string') {\n\t\tif (value.isWellFormed()) return container.includes(value)\n\t\treturn `,${Array.from(container, (character) => character.codePointAt(0)).join(',')},`.includes(\n\t\t\t`,${Array.from(value, (character) => character.codePointAt(0)).join(',')},`,\n\t\t)\n\t}\n\tif (isArray(container)) return container.some((item) => matchesTemplateEqual(value, item))\n\tif (isMap(container) && !isArray(value) && !isMap(value) && !isTemplateNamespace(value)) {\n\t\treturn typeof value === 'string' && container.has(value)\n\t}\n\tif (\n\t\tisTemplateNamespace(container) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\t!isTemplateNamespace(value)\n\t) {\n\t\treturn typeof value === 'string' && container.values.has(value)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`looks for ${renderTemplateType(value)} in ${renderTemplateType(container)}, which the subset does not admit`,\n\t\t{ feature: 'membership' },\n\t)\n}\n\n/**\n * Adds two runtime template values under Python `+` rules for strings, numbers, and lists.\n *\n * @param left - The first operand\n * @param right - The second operand\n * @returns The sum or concatenation\n *\n * @example\n * ```ts\n * import { addTemplateValues } from '@orkestrel/template'\n *\n * addTemplateValues('<|im_start|>', 'user') // '<|im_start|>user'\n * ```\n */\nexport function addTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (typeof left === 'string' && typeof right === 'string') return left + right\n\tif (isArray(left) && isArray(right)) return [...left, ...right]\n\tif (typeof left === 'number' && typeof right === 'number') {\n\t\tconst sum = left + right\n\t\tif (Number.isInteger(left) && Number.isInteger(right)) {\n\t\t\tif (Number.isSafeInteger(sum)) return sum\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t'adds integers past the integers JavaScript holds exactly',\n\t\t\t\t{ feature: 'big integer' },\n\t\t\t)\n\t\t}\n\t\tif (!Number.isInteger(sum)) return sum\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`adds floats to the whole value ${String(sum)}, which Python prints as a float`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`adds ${renderTemplateType(right)} to ${renderTemplateType(left)}, which the subset does not admit`,\n\t\t{ feature: 'addition' },\n\t)\n}\n\n/**\n * Subtracts two numeric runtime template values under Python `-` rules.\n *\n * @param left - The left numeric operand\n * @param right - The right numeric operand\n * @returns The numeric difference\n *\n * @example\n * ```ts\n * import { subtractTemplateValues } from '@orkestrel/template'\n *\n * subtractTemplateValues(5, 1) // 4\n * ```\n */\nexport function subtractTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): number {\n\tif (typeof left === 'number' && typeof right === 'number') {\n\t\tconst difference = left - right\n\t\tif (Number.isInteger(left) && Number.isInteger(right)) {\n\t\t\tif (Number.isSafeInteger(difference)) return Object.is(difference, -0) ? 0 : difference\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t'subtracts integers past the integers JavaScript holds exactly',\n\t\t\t\t{ feature: 'big integer' },\n\t\t\t)\n\t\t}\n\t\tif (!Number.isInteger(difference)) return difference\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`subtracts floats to the whole value ${String(difference)}, which Python prints as a float`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`subtracts ${renderTemplateType(right)} from ${renderTemplateType(left)}, which the subset does not admit`,\n\t\t{ feature: 'subtraction' },\n\t)\n}\n\n/**\n * Applies unary `-` or `+` to a numeric runtime template value.\n *\n * @param operator - `'-'` for negation or `'+'` for numeric identity\n * @param value - The numeric operand\n * @returns The resulting number\n *\n * @example\n * ```ts\n * import { negateTemplateValue } from '@orkestrel/template'\n *\n * negateTemplateValue('-', 1) // -1\n * ```\n */\nexport function negateTemplateValue(operator: '-' | '+', value: TemplateRuntimeValue): number {\n\tif (typeof value !== 'number') {\n\t\tconst feature = operator === '-' ? 'unary minus' : 'unary plus'\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies ${feature} to ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t\t{ feature },\n\t\t)\n\t}\n\tif (operator === '+') return value\n\tconst negated = -value\n\tif (Number.isInteger(value) && !Number.isSafeInteger(negated)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t'negates an integer past the integers JavaScript holds exactly',\n\t\t\t{ feature: 'big integer' },\n\t\t)\n\t}\n\treturn Object.is(negated, -0) ? 0 : negated\n}\n\n/**\n * Reads a member or index of a runtime template value under sandboxed Jinja rules,\n * supporting negative sequence indexing, `TemplateNamespace` properties, and\n * `loop.previtem` / `loop.nextitem`.\n *\n * @param object - The object or sequence to read from\n * @param key - The member name or integer index\n * @returns The resolved member value, or `undefined` when absent\n *\n * @example\n * ```ts\n * import { readTemplateMember } from '@orkestrel/template'\n *\n * readTemplateMember(['a', 'b'], -1) // 'b'\n * ```\n */\nexport function readTemplateMember(\n\tobject: TemplateRuntimeValue,\n\tkey: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (object === undefined) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the member ${typeof key === 'string' ? quoteTemplateText(key) : renderTemplateType(key)} of an undefined value, which Jinja refuses`,\n\t\t\t{ feature: 'undefined' },\n\t\t)\n\t}\n\tif (typeof key === 'string' && key.startsWith('__')) {\n\t\tthrow buildTemplateEvaluationError(`reads the private member ${quoteTemplateText(key)}`, {\n\t\t\tfeature: 'private',\n\t\t})\n\t}\n\tif (object === null) return undefined\n\tif (typeof object === 'number' || typeof object === 'boolean') {\n\t\tif (typeof key !== 'string') return undefined\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the attribute ${quoteTemplateText(key)} of ${renderTemplateType(object)}`,\n\t\t\t{ feature: 'attribute' },\n\t\t)\n\t}\n\tif (isTemplateNamespace(object)) {\n\t\treturn typeof key === 'string' ? object.values.get(key) : undefined\n\t}\n\tconst methods =\n\t\ttypeof object === 'string'\n\t\t\t? TEMPLATE_METHODS.string\n\t\t\t: isArray(object)\n\t\t\t\t? TEMPLATE_METHODS.list\n\t\t\t\t: isMap(object)\n\t\t\t\t\t? TEMPLATE_METHODS.mapping\n\t\t\t\t\t: []\n\tif (typeof key === 'string' && methods.includes(key)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the method ${quoteTemplateText(key)} of ${renderTemplateType(object)}, which the subset does not admit`,\n\t\t\t{ feature: 'method' },\n\t\t)\n\t}\n\tif (isMap(object)) return typeof key === 'string' ? object.get(key) : undefined\n\tif (typeof object === 'string' || isArray(object)) {\n\t\tconst index = typeof key === 'boolean' ? Number(key) : key\n\t\tif (typeof index !== 'number' || !Number.isInteger(index)) return undefined\n\t\tconst items = typeof object === 'string' ? Array.from(object) : object\n\t\tconst resolved = index < 0 ? items.length + index : index\n\t\treturn resolved >= 0 && resolved < items.length ? items[resolved] : undefined\n\t}\n\tif (!isTemplateLoop(object) || typeof key !== 'string') return undefined\n\tif (TEMPLATE_LOOP_REFUSALS.some((member) => member === key)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads ${quoteTemplateText(`loop.${key}`)}, which the subset does not admit`,\n\t\t\t{ feature: `loop.${key}` },\n\t\t)\n\t}\n\tswitch (key) {\n\t\tcase 'index':\n\t\t\treturn object.index0 + 1\n\t\tcase 'index0':\n\t\t\treturn object.index0\n\t\tcase 'first':\n\t\t\treturn object.index0 === 0\n\t\tcase 'last':\n\t\t\treturn object.index0 === object.length - 1\n\t\tcase 'length':\n\t\t\treturn object.length\n\t\tcase 'previtem':\n\t\t\treturn object.previtem\n\t\tcase 'nextitem':\n\t\t\treturn object.nextitem\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/**\n * Slices a string (by Unicode code points) or list under Python\n * `seq[start:stop:step]` semantics, including negative bounds and `[::-1]`.\n *\n * @param object - The string or list to slice\n * @param start - Optional inclusive start index (`undefined` or `null` for default)\n * @param stop - Optional exclusive stop index (`undefined` or `null` for default)\n * @param step - Optional non-zero stride (`undefined` or `null` for `1`)\n * @returns The sliced string or list\n *\n * @example\n * ```ts\n * import { sliceTemplateSequence } from '@orkestrel/template'\n *\n * sliceTemplateSequence(['a', 'b', 'c'], undefined, undefined, -1) // ['c', 'b', 'a']\n * ```\n */\nexport function sliceTemplateSequence(\n\tobject: TemplateRuntimeValue,\n\tstart: TemplateRuntimeValue,\n\tstop: TemplateRuntimeValue,\n\tstep: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (typeof object !== 'string' && !isArray(object)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`slices ${renderTemplateType(object)}, which is not a sequence`,\n\t\t\t{ feature: 'slice' },\n\t\t)\n\t}\n\tconst rawStep =\n\t\tstep === undefined || step === null ? 1 : typeof step === 'boolean' ? Number(step) : step\n\tif (typeof rawStep !== 'number' || !Number.isInteger(rawStep)) {\n\t\tthrow buildTemplateEvaluationError('slices with a non-integer step', { feature: 'slice' })\n\t}\n\tif (rawStep === 0) {\n\t\tthrow buildTemplateEvaluationError('slices with a step of 0', { feature: 'slice' })\n\t}\n\tconst rawStart =\n\t\tstart === undefined || start === null\n\t\t\t? undefined\n\t\t\t: typeof start === 'boolean'\n\t\t\t\t? Number(start)\n\t\t\t\t: start\n\tconst rawStop =\n\t\tstop === undefined || stop === null\n\t\t\t? undefined\n\t\t\t: typeof stop === 'boolean'\n\t\t\t\t? Number(stop)\n\t\t\t\t: stop\n\tif (\n\t\t(rawStart !== undefined && (typeof rawStart !== 'number' || !Number.isInteger(rawStart))) ||\n\t\t(rawStop !== undefined && (typeof rawStop !== 'number' || !Number.isInteger(rawStop)))\n\t) {\n\t\tthrow buildTemplateEvaluationError('slices with a non-integer bound', { feature: 'slice' })\n\t}\n\tconst items = typeof object === 'string' ? Array.from(object) : object\n\tconst length = items.length\n\tconst from =\n\t\trawStep > 0\n\t\t\t? rawStart === undefined\n\t\t\t\t? 0\n\t\t\t\t: rawStart < 0\n\t\t\t\t\t? Math.max(0, length + rawStart)\n\t\t\t\t\t: Math.min(length, rawStart)\n\t\t\t: rawStart === undefined\n\t\t\t\t? length - 1\n\t\t\t\t: rawStart < 0\n\t\t\t\t\t? Math.max(-1, length + rawStart)\n\t\t\t\t\t: Math.min(length - 1, rawStart)\n\tconst to =\n\t\trawStep > 0\n\t\t\t? rawStop === undefined\n\t\t\t\t? length\n\t\t\t\t: rawStop < 0\n\t\t\t\t\t? Math.max(0, length + rawStop)\n\t\t\t\t\t: Math.min(length, rawStop)\n\t\t\t: rawStop === undefined\n\t\t\t\t? -1\n\t\t\t\t: rawStop < 0\n\t\t\t\t\t? Math.max(-1, length + rawStop)\n\t\t\t\t\t: Math.min(length - 1, rawStop)\n\tconst picked: TemplateRuntimeValue[] = []\n\tif (rawStep > 0) {\n\t\tfor (let index = from; index < to; index += rawStep) {\n\t\t\tpicked.push(items[index])\n\t\t}\n\t} else {\n\t\tfor (let index = from; index > to; index += rawStep) {\n\t\t\tpicked.push(items[index])\n\t\t}\n\t}\n\treturn typeof object === 'string' ? picked.join('') : picked\n}\n\n/**\n * Collects the iterable elements of a runtime value for a `for` loop.\n *\n * @param value - The value to iterate\n * @returns The elements in iteration order\n *\n * @example\n * ```ts\n * import { collectTemplateItems } from '@orkestrel/template'\n *\n * collectTemplateItems(new Map([['role', 'user']])) // ['role']\n * ```\n */\nexport function collectTemplateItems(value: TemplateRuntimeValue): readonly TemplateRuntimeValue[] {\n\tif (value === undefined) return []\n\tif (typeof value === 'string') return Array.from(value)\n\tif (isArray(value)) return value\n\tif (isMap(value)) return Array.from(value.keys())\n\tif (isTemplateNamespace(value)) return Array.from(value.values.keys())\n\tthrow buildTemplateEvaluationError(\n\t\t`iterates ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t{ feature: 'iteration' },\n\t)\n}\n\n/**\n * Applies one of the admitted Jinja `|` filters (`trim`, `length`, `tojson`,\n * `items`, `safe`, `string`) to a runtime value.\n *\n * @param name - The filter name\n * @param value - The value to transform\n * @returns The filtered runtime value\n *\n * @example\n * ```ts\n * import { applyTemplateFilter } from '@orkestrel/template'\n *\n * applyTemplateFilter('trim', ' Hi\\n') // 'Hi'\n * applyTemplateFilter('length', 'héllo') // 5\n * ```\n */\nexport function applyTemplateFilter(\n\tname: string,\n\tvalue: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (!TEMPLATE_FILTERS.some((filter) => filter === name)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t{ feature: name },\n\t\t)\n\t}\n\tswitch (name) {\n\t\tcase 'trim':\n\t\t\treturn renderTemplateValue(value).replace(\n\t\t\t\tnew RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, 'gu'),\n\t\t\t\t'',\n\t\t\t)\n\t\tcase 'length': {\n\t\t\tif (value === undefined) return 0\n\t\t\tif (typeof value === 'string') return Array.from(value).length\n\t\t\tif (isArray(value)) return value.length\n\t\t\tif (isMap(value)) return value.size\n\t\t\tif (isTemplateNamespace(value)) return value.values.size\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`measures the length of ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t\t\t{ feature: 'length' },\n\t\t\t)\n\t\t}\n\t\tcase 'tojson':\n\t\t\treturn serializeTemplateJSON(value)\n\t\tcase 'items': {\n\t\t\tif (value === undefined) return []\n\t\t\tif (isMap(value))\n\t\t\t\treturn Array.from(value.entries(), ([entryKey, entryValue]) => [entryKey, entryValue])\n\t\t\tif (isTemplateNamespace(value)) {\n\t\t\t\treturn Array.from(value.values.entries(), ([entryKey, entryValue]) => [\n\t\t\t\t\tentryKey,\n\t\t\t\t\tentryValue,\n\t\t\t\t])\n\t\t\t}\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`reads items of ${renderTemplateType(value)}, which is not a mapping`,\n\t\t\t\t{ feature: 'items' },\n\t\t\t)\n\t\t}\n\t\tcase 'safe':\n\t\t\treturn value\n\t\tcase 'string':\n\t\t\treturn renderTemplateValue(value)\n\t\tdefault:\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t\t{ feature: name },\n\t\t\t)\n\t}\n}\n\n/**\n * Applies one of the admitted Jinja `is` tests (`defined`, `undefined`, `none`,\n * `string`, `mapping`, `iterable`, `sequence`, `true`, `false`) to a runtime value.\n *\n * @param name - The test name\n * @param value - The value to inspect\n * @returns True if `value` satisfies the test; false otherwise\n *\n * @example\n * ```ts\n * import { applyTemplateTest } from '@orkestrel/template'\n *\n * applyTemplateTest('true', true) // true\n * applyTemplateTest('true', 1) // false\n * ```\n */\nexport function applyTemplateTest(name: string, value: TemplateRuntimeValue): boolean {\n\tif (!TEMPLATE_TESTS.some((test) => test === name)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies the test ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t{ feature: name },\n\t\t)\n\t}\n\tswitch (name) {\n\t\tcase 'defined':\n\t\t\treturn value !== undefined\n\t\tcase 'undefined':\n\t\t\treturn value === undefined\n\t\tcase 'none':\n\t\t\treturn value === null\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string'\n\t\tcase 'mapping':\n\t\t\treturn isMap(value) || isTemplateNamespace(value)\n\t\tcase 'iterable':\n\t\t\treturn (\n\t\t\t\ttypeof value === 'string' || isArray(value) || isMap(value) || isTemplateNamespace(value)\n\t\t\t)\n\t\tcase 'sequence':\n\t\t\treturn typeof value === 'string' || isArray(value)\n\t\tcase 'true':\n\t\t\treturn value === true\n\t\tcase 'false':\n\t\t\treturn value === false\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\n/**\n * Invokes one of the admitted Python `str` methods (`startswith`, `endswith`,\n * `split`, `strip`, `rstrip`, `lstrip`) on a string receiver with exact Python\n * character-set and splitting semantics.\n *\n * @param receiver - The string receiver\n * @param method - The string method name\n * @param positional - Positional arguments\n * @param keywords - Named keyword arguments\n * @returns The method's return value\n *\n * @example\n * ```ts\n * import { callTemplateMethod } from '@orkestrel/template'\n *\n * callTemplateMethod('hello\\n\\n', 'rstrip', ['\\n'], []) // 'hello'\n * callTemplateMethod('a</think>b', 'split', ['</think>'], []) // ['a', 'b']\n * ```\n */\nexport function callTemplateMethod(\n\treceiver: string,\n\tmethod: string,\n\tpositional: readonly TemplateRuntimeValue[],\n\tkeywords: ReadonlyArray<readonly [name: string, value: TemplateRuntimeValue]>,\n): TemplateRuntimeValue {\n\tif (!TEMPLATE_STRING_METHODS.some((admitted) => admitted === method)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`,\n\t\t\t{ feature: method },\n\t\t)\n\t}\n\tswitch (method) {\n\t\tcase 'startswith':\n\t\tcase 'endswith': {\n\t\t\tif (keywords.length > 0 || positional.length < 1 || positional.length > 3) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with invalid arguments`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [needle, start, end] = positional\n\t\t\tconst target =\n\t\t\t\tstart === undefined && end === undefined\n\t\t\t\t\t? receiver\n\t\t\t\t\t: String(sliceTemplateSequence(receiver, start, end, 1))\n\t\t\tconst candidates = isArray(needle) ? needle : [needle]\n\t\t\tif (!candidates.every((candidate) => typeof candidate === 'string')) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with a non-string prefix or suffix`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn candidates.some((candidate) =>\n\t\t\t\tmethod === 'startswith' ? target.startsWith(candidate) : target.endsWith(candidate),\n\t\t\t)\n\t\t}\n\t\tcase 'strip': {\n\t\t\tconst trimmedLeft = callTemplateMethod(receiver, 'lstrip', positional, keywords)\n\t\t\treturn typeof trimmedLeft === 'string'\n\t\t\t\t? callTemplateMethod(trimmedLeft, 'rstrip', positional, keywords)\n\t\t\t\t: ''\n\t\t}\n\t\tcase 'rstrip':\n\t\tcase 'lstrip': {\n\t\t\tif (keywords.length > 0 || positional.length > 1) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with invalid arguments`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [chars] = positional\n\t\t\tif (chars === undefined || chars === null) {\n\t\t\t\tconst stripPattern =\n\t\t\t\t\tmethod === 'rstrip'\n\t\t\t\t\t\t? new RegExp(`${TEMPLATE_SPACE}+$`, 'u')\n\t\t\t\t\t\t: new RegExp(`^${TEMPLATE_SPACE}+`, 'u')\n\t\t\t\treturn receiver.replace(stripPattern, '')\n\t\t\t}\n\t\t\tif (typeof chars !== 'string') {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with a non-string character set`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst charSet = new Set(Array.from(chars))\n\t\t\tconst points = Array.from(receiver)\n\t\t\tif (method === 'rstrip') {\n\t\t\t\tlet end = points.length\n\t\t\t\tfor (let index = points.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tif (!charSet.has(points[index] ?? '')) break\n\t\t\t\t\tend = index\n\t\t\t\t}\n\t\t\t\treturn points.slice(0, end).join('')\n\t\t\t}\n\t\t\tlet start = 0\n\t\t\tfor (let index = 0; index < points.length; index += 1) {\n\t\t\t\tif (!charSet.has(points[index] ?? '')) break\n\t\t\t\tstart = index + 1\n\t\t\t}\n\t\t\treturn points.slice(start).join('')\n\t\t}\n\t\tcase 'split': {\n\t\t\tconst unknownKeyword = keywords.find(([name]) => name !== 'sep' && name !== 'maxsplit')\n\t\t\tif (unknownKeyword !== undefined || positional.length > 2) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with invalid arguments', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst sepKeyword = keywords.find(([name]) => name === 'sep')\n\t\t\tconst maxsplitKeyword = keywords.find(([name]) => name === 'maxsplit')\n\t\t\tif (\n\t\t\t\t(sepKeyword !== undefined && positional.length >= 1) ||\n\t\t\t\t(maxsplitKeyword !== undefined && positional.length >= 2)\n\t\t\t) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with duplicate arguments', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst sep = sepKeyword !== undefined ? sepKeyword[1] : positional[0]\n\t\t\tconst rawMax = maxsplitKeyword !== undefined ? maxsplitKeyword[1] : positional[1]\n\t\t\tconst maxsplit =\n\t\t\t\trawMax === undefined ? -1 : typeof rawMax === 'boolean' ? Number(rawMax) : rawMax\n\t\t\tif (typeof maxsplit !== 'number' || !Number.isInteger(maxsplit)) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with a non-integer maxsplit', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (sep === undefined || sep === null) {\n\t\t\t\tif (maxsplit < 0) {\n\t\t\t\t\tconst trimmed = receiver.replace(\n\t\t\t\t\t\tnew RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, 'gu'),\n\t\t\t\t\t\t'',\n\t\t\t\t\t)\n\t\t\t\t\treturn trimmed === '' ? [] : trimmed.split(new RegExp(`${TEMPLATE_SPACE}+`, 'gu'))\n\t\t\t\t}\n\t\t\t\tconst leading = receiver.replace(new RegExp(`^${TEMPLATE_SPACE}+`, 'u'), '')\n\t\t\t\tif (leading === '') return []\n\t\t\t\tif (maxsplit === 0) return [leading]\n\t\t\t\tconst gaps = Array.from(leading.matchAll(new RegExp(`${TEMPLATE_SPACE}+`, 'gu')))\n\t\t\t\tconst parts: string[] = []\n\t\t\t\tlet from = 0\n\t\t\t\tfor (let index = 0; index < gaps.length && parts.length < maxsplit; index += 1) {\n\t\t\t\t\tconst gap = gaps[index]\n\t\t\t\t\tif (gap === undefined) break\n\t\t\t\t\tparts.push(leading.slice(from, gap.index))\n\t\t\t\t\tfrom = gap.index + gap[0].length\n\t\t\t\t}\n\t\t\t\tif (from < leading.length) parts.push(leading.slice(from))\n\t\t\t\treturn parts\n\t\t\t}\n\t\t\tif (typeof sep !== 'string') {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with a non-string separator', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (sep.length === 0) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with an empty separator', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (maxsplit < 0) return receiver.split(sep)\n\t\t\tif (maxsplit === 0) return [receiver]\n\t\t\tconst parts: string[] = []\n\t\t\tlet from = 0\n\t\t\tfor (let count = 0; count < maxsplit; count += 1) {\n\t\t\t\tconst found = receiver.indexOf(sep, from)\n\t\t\t\tif (found === -1) break\n\t\t\t\tparts.push(receiver.slice(from, found))\n\t\t\t\tfrom = found + sep.length\n\t\t\t}\n\t\t\tparts.push(receiver.slice(from))\n\t\t\treturn parts\n\t\t}\n\t\tdefault:\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`,\n\t\t\t\t{ feature: method },\n\t\t\t)\n\t}\n}\n\n/**\n * Finds the binding for a variable name across lexical scope frames from innermost\n * to outermost.\n *\n * @param frames - The scope stack, outermost first\n * @param name - The variable name to resolve\n * @returns The bound runtime value, or `undefined` when unbound\n *\n * @example\n * ```ts\n * import { findTemplateName } from '@orkestrel/template'\n *\n * findTemplateName([new Map([['bos_token', '<s>']])], 'bos_token') // '<s>'\n * ```\n */\nexport function findTemplateName(frames: TemplateScope, name: string): TemplateRuntimeValue {\n\treturn frames.findLast((frame) => frame.has(name))?.get(name)\n}\n\n/**\n * Binds a variable name in a copy of the innermost scope frame without mutating\n * the input frames.\n *\n * @param frames - The scope stack, outermost first\n * @param name - The variable name to bind\n * @param value - The runtime value to bind\n * @returns A fresh scope stack carrying the updated innermost frame\n *\n * @example\n * ```ts\n * import { bindTemplateName, findTemplateName } from '@orkestrel/template'\n *\n * findTemplateName(bindTemplateName([new Map()], 'turn', 2), 'turn') // 2\n * ```\n */\nexport function bindTemplateName(\n\tframes: TemplateScope,\n\tname: string,\n\tvalue: TemplateRuntimeValue,\n): TemplateScope {\n\tconst inner = frames.at(-1) ?? new Map<string, TemplateRuntimeValue>()\n\treturn [...frames.slice(0, -1), new Map([...inner, [name, value]])]\n}\n\n// === Tree-valued template evaluator\n\n/**\n * Evaluates a single {@link TemplateExpression} against runtime scope frames and\n * namespace bindings.\n *\n * @param expression - The compiled expression to evaluate\n * @param frames - The lexical scope frames, outermost first\n * @param namespaces - Evaluation-owned map from `TemplateNamespace` to its mutable backing `Map`\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The evaluated runtime value\n *\n * @example\n * ```ts\n * import { evaluateTemplateExpression } from '@orkestrel/template'\n *\n * evaluateTemplateExpression({ term: 'literal', value: 42 }, [new Map()], new Map()) // 42\n * ```\n */\nexport function evaluateTemplateExpression(\n\texpression: TemplateExpression,\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): TemplateRuntimeValue {\n\tswitch (expression.term) {\n\t\tcase 'literal':\n\t\t\treturn expression.value\n\t\tcase 'name':\n\t\t\treturn findTemplateName(frames, expression.name)\n\t\tcase 'member':\n\t\t\treturn readTemplateMember(\n\t\t\t\tevaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth),\n\t\t\t\tevaluateTemplateExpression(expression.key, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'slice':\n\t\t\treturn sliceTemplateSequence(\n\t\t\t\tevaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth),\n\t\t\t\texpression.start === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.start, frames, namespaces, options, callDepth),\n\t\t\t\texpression.stop === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.stop, frames, namespaces, options, callDepth),\n\t\t\t\texpression.step === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.step, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'call':\n\t\t\treturn callTemplateExpression(\n\t\t\t\texpression.callee,\n\t\t\t\texpression.values,\n\t\t\t\texpression.keywords,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\tcase 'filter':\n\t\t\treturn applyTemplateFilter(\n\t\t\t\texpression.name,\n\t\t\t\tevaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'test': {\n\t\t\tconst matched = applyTemplateTest(\n\t\t\t\texpression.name,\n\t\t\t\tevaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\t\treturn expression.negated ? !matched : matched\n\t\t}\n\t\tcase 'unary': {\n\t\t\tconst operand = evaluateTemplateExpression(\n\t\t\t\texpression.value,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tif (expression.operator === 'not') return !matchesTemplateTruth(operand)\n\t\t\treturn negateTemplateValue(expression.operator, operand)\n\t\t}\n\t\tcase 'conditional':\n\t\t\treturn matchesTemplateTruth(\n\t\t\t\tevaluateTemplateExpression(expression.condition, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\t\t\t? evaluateTemplateExpression(expression.consequent, frames, namespaces, options, callDepth)\n\t\t\t\t: evaluateTemplateExpression(expression.alternate, frames, namespaces, options, callDepth)\n\t\tcase 'binary': {\n\t\t\tconst left = evaluateTemplateExpression(\n\t\t\t\texpression.left,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tif (expression.operator === 'and') {\n\t\t\t\treturn matchesTemplateTruth(left)\n\t\t\t\t\t? evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth)\n\t\t\t\t\t: left\n\t\t\t}\n\t\t\tif (expression.operator === 'or') {\n\t\t\t\treturn matchesTemplateTruth(left)\n\t\t\t\t\t? left\n\t\t\t\t\t: evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth)\n\t\t\t}\n\t\t\tconst right = evaluateTemplateExpression(\n\t\t\t\texpression.right,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tswitch (expression.operator) {\n\t\t\t\tcase '+':\n\t\t\t\t\treturn addTemplateValues(left, right)\n\t\t\t\tcase '-':\n\t\t\t\t\treturn subtractTemplateValues(left, right)\n\t\t\t\tcase '~':\n\t\t\t\t\treturn renderTemplateValue(left) + renderTemplateValue(right)\n\t\t\t\tcase '==':\n\t\t\t\t\treturn matchesTemplateEqual(left, right)\n\t\t\t\tcase '!=':\n\t\t\t\t\treturn !matchesTemplateEqual(left, right)\n\t\t\t\tcase '<':\n\t\t\t\t\treturn compareTemplateValues(left, right) < 0\n\t\t\t\tcase '>':\n\t\t\t\t\treturn compareTemplateValues(left, right) > 0\n\t\t\t\tcase '<=':\n\t\t\t\t\treturn compareTemplateValues(left, right) <= 0\n\t\t\t\tcase '>=':\n\t\t\t\t\treturn compareTemplateValues(left, right) >= 0\n\t\t\t\tcase 'in':\n\t\t\t\t\treturn matchesTemplateMember(left, right)\n\t\t\t\tcase 'not in':\n\t\t\t\t\treturn !matchesTemplateMember(left, right)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Evaluates a template call expression — dispatching built-in `raise_exception`\n * and `namespace`, string method calls, and user-defined `TemplateMacro` calls.\n *\n * @param callee - The callee expression\n * @param positionalExpressions - Positional argument expressions\n * @param keywordExpressions - Named keyword argument expressions\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth\n * @returns The call result\n *\n * @example\n * ```ts\n * import { callTemplateExpression } from '@orkestrel/template'\n *\n * callTemplateExpression({ term: 'name', name: 'namespace' }, [], [{ name: 'n', value: { term: 'literal', value: 1 } }], [new Map()], new Map(), undefined, 0)\n * ```\n */\nexport function callTemplateExpression(\n\tcallee: TemplateExpression,\n\tpositionalExpressions: readonly TemplateExpression[],\n\tkeywordExpressions: readonly TemplateKeyword[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions: TemplateEvaluateOptions | undefined,\n\tcallDepth: number,\n): TemplateRuntimeValue {\n\tif (callee.term === 'member') {\n\t\tconst receiver = evaluateTemplateExpression(\n\t\t\tcallee.object,\n\t\t\tframes,\n\t\t\tnamespaces,\n\t\t\toptions,\n\t\t\tcallDepth,\n\t\t)\n\t\tconst key = evaluateTemplateExpression(callee.key, frames, namespaces, options, callDepth)\n\t\tconst positional = positionalExpressions.map((value) =>\n\t\t\tevaluateTemplateExpression(value, frames, namespaces, options, callDepth),\n\t\t)\n\t\tconst keywords = keywordExpressions.map((keyword): readonly [string, TemplateRuntimeValue] => [\n\t\t\tkeyword.name,\n\t\t\tevaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth),\n\t\t])\n\t\tif (typeof receiver === 'string' && typeof key === 'string') {\n\t\t\treturn callTemplateMethod(receiver, key, positional, keywords)\n\t\t}\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls method ${typeof key === 'string' ? quoteTemplateText(key) : renderTemplateType(key)} on ${renderTemplateType(receiver)}, which the subset does not admit`,\n\t\t\t{ feature: 'method call' },\n\t\t)\n\t}\n\tconst positional = positionalExpressions.map((value) =>\n\t\tevaluateTemplateExpression(value, frames, namespaces, options, callDepth),\n\t)\n\tconst keywords = keywordExpressions.map((keyword): readonly [string, TemplateRuntimeValue] => [\n\t\tkeyword.name,\n\t\tevaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth),\n\t])\n\tif (callee.term === 'name' && callee.name === 'raise_exception') {\n\t\tif (positional.length !== 1 || keywords.length > 0) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls raise_exception with ${positional.length} positional and ${keywords.length} keyword arguments; it takes one message`,\n\t\t\t)\n\t\t}\n\t\tconst text = renderTemplateValue(positional[0])\n\t\tthrow new TemplateError(\n\t\t\t'RAISE',\n\t\t\t`The template raised an exception: ${quoteTemplateText(text)}.`,\n\t\t\t{\n\t\t\t\tmessage: text,\n\t\t\t},\n\t\t)\n\t}\n\tif (callee.term === 'name' && callee.name === 'namespace') {\n\t\tif (positional.length > 1) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls namespace with ${positional.length} positional arguments; it takes at most one mapping`,\n\t\t\t\t{ feature: 'namespace' },\n\t\t\t)\n\t\t}\n\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\tconst [initial] = positional\n\t\tif (initial !== undefined) {\n\t\t\tif (isMap(initial)) {\n\t\t\t\tfor (const [entryKey, entryValue] of initial.entries()) {\n\t\t\t\t\tentries.push([entryKey, entryValue])\n\t\t\t\t}\n\t\t\t} else if (isTemplateNamespace(initial)) {\n\t\t\t\tfor (const [entryKey, entryValue] of initial.values.entries()) {\n\t\t\t\t\tentries.push([entryKey, entryValue])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t`calls namespace with ${renderTemplateType(initial)} instead of a mapping`,\n\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tfor (const [entryKey, entryValue] of keywords) {\n\t\t\tentries.push([entryKey, entryValue])\n\t\t}\n\t\tconst backing = new Map<string, TemplateRuntimeValue>(entries)\n\t\tconst container: TemplateNamespace = { namespace: true, values: backing }\n\t\tnamespaces.set(container, backing)\n\t\treturn container\n\t}\n\tconst target = evaluateTemplateExpression(callee, frames, namespaces, options, callDepth)\n\tif (!isTemplateMacro(target)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls ${renderTemplateType(target)}, which is not a function`,\n\t\t\t{ feature: 'call' },\n\t\t)\n\t}\n\tif (callDepth + 1 > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`nests macro calls deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (positional.length > target.parameters.length) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls macro ${quoteTemplateText(target.name)} with ${positional.length} arguments; it accepts at most ${target.parameters.length}`,\n\t\t\t{ feature: 'macro' },\n\t\t)\n\t}\n\tconst bound = new Map<string, TemplateRuntimeValue>()\n\tfor (const [index, value] of positional.entries()) {\n\t\tconst parameter = target.parameters[index]\n\t\tif (parameter !== undefined) bound.set(parameter.name, value)\n\t}\n\tfor (const [keywordName, keywordValue] of keywords) {\n\t\tconst matches = target.parameters.some((parameter) => parameter.name === keywordName)\n\t\tif (!matches) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls macro ${quoteTemplateText(target.name)} with unexpected keyword ${quoteTemplateText(keywordName)}`,\n\t\t\t\t{ feature: 'macro' },\n\t\t\t)\n\t\t}\n\t\tif (bound.has(keywordName)) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls macro ${quoteTemplateText(target.name)} with duplicate argument ${quoteTemplateText(keywordName)}`,\n\t\t\t\t{ feature: 'macro' },\n\t\t\t)\n\t\t}\n\t\tbound.set(keywordName, keywordValue)\n\t}\n\tconst rootFrame = frames[0]\n\tconst baseFrames: TemplateScope =\n\t\trootFrame !== undefined ? [rootFrame, ...target.closure] : target.closure\n\tfor (const parameter of target.parameters) {\n\t\tif (!bound.has(parameter.name)) {\n\t\t\tbound.set(\n\t\t\t\tparameter.name,\n\t\t\t\tparameter.fallback === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(\n\t\t\t\t\t\t\tparameter.fallback,\n\t\t\t\t\t\t\tbaseFrames,\n\t\t\t\t\t\t\tnamespaces,\n\t\t\t\t\t\t\toptions,\n\t\t\t\t\t\t\tcallDepth + 1,\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\tconst [parts] = executeTemplateNodes(\n\t\ttarget.body,\n\t\t[...baseFrames, bound],\n\t\tnamespaces,\n\t\toptions,\n\t\tcallDepth + 1,\n\t)\n\treturn parts.map((part) => renderTemplatePart(part, options)).join('')\n}\n\n/**\n * Executes a sequence of compiled {@link TemplateNode}s in order, tagging each\n * emitted part with whether it came from literal template text (`true`) or a\n * dynamic expression/placeholder (`false`).\n *\n * @param nodes - The nodes to execute in order\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The tagged emitted parts, updated scope frames, and optional loop control signal\n *\n * @example\n * ```ts\n * import { runTemplateNodes } from '@orkestrel/template'\n *\n * runTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // [[true, 'Hi']]\n * ```\n */\nexport function runTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): readonly [\n\tparts: ReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\tframes: TemplateScope,\n\tcontrol: 'break' | 'continue' | undefined,\n] {\n\tconst steps: Array<\n\t\treadonly [\n\t\t\tReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\t\t\tTemplateScope,\n\t\t\t'break' | 'continue' | undefined,\n\t\t]\n\t> = []\n\tfor (const node of nodes) {\n\t\tconst previous = steps.at(-1)\n\t\tif (previous?.[2] !== undefined) break\n\t\tconst active = previous?.[1] ?? frames\n\t\tswitch (node.syntax) {\n\t\t\tcase 'document':\n\t\t\t\tsteps.push(runTemplateNodes(node.children, active, namespaces, options, callDepth))\n\t\t\t\tbreak\n\t\t\tcase 'text':\n\t\t\t\tsteps.push([[[true, node.value]], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'comment':\n\t\t\t\tsteps.push([[], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'html': {\n\t\t\t\tconst sanitized = createHTML(node.document).sanitize(options?.sanitize).document\n\t\t\t\tsteps.push([[[false, sanitized]], active, undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'markdown':\n\t\t\t\tsteps.push([[[false, node.document]], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'placeholder': {\n\t\t\t\tconst rawRecord: Record<string, unknown> = {}\n\t\t\t\tconst root = active[0]\n\t\t\t\tif (root !== undefined) {\n\t\t\t\t\tfor (const [entryKey, entryValue] of root.entries()) {\n\t\t\t\t\t\trawRecord[entryKey] = entryValue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst placeholders = options?.placeholders ?? []\n\t\t\t\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\t\t\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\t\t\t\tconst { value, declared, required } = resolveToken(rawRecord, placeholders, node.name)\n\t\t\t\tconst resolved = value !== undefined ? value : declared?.fallback\n\t\t\t\tif (resolved !== undefined) {\n\t\t\t\t\tif (isHTMLNode(resolved)) {\n\t\t\t\t\t\tconst document: HTMLDocument =\n\t\t\t\t\t\t\tresolved.category === 'document'\n\t\t\t\t\t\t\t\t? resolved\n\t\t\t\t\t\t\t\t: { category: 'document', children: [resolved] }\n\t\t\t\t\t\tsteps.push([\n\t\t\t\t\t\t\t[[false, createHTML(document).sanitize(options?.sanitize).document]],\n\t\t\t\t\t\t\tactive,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t])\n\t\t\t\t\t} else if (isMarkdownNode(resolved)) {\n\t\t\t\t\t\tsteps.push([[[false, resolved]], active, undefined])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsteps.push([[[false, formatValue(resolved, locale)]], active, undefined])\n\t\t\t\t\t}\n\t\t\t\t} else if (missing === 'literal') {\n\t\t\t\t\tsteps.push([[[false, node.raw]], active, undefined])\n\t\t\t\t} else if (missing === 'empty' || !required) {\n\t\t\t\t\tsteps.push([[[false, '']], active, undefined])\n\t\t\t\t} else {\n\t\t\t\t\tthrow new TemplateError('MISSING', `Missing required placeholder(s): ${node.name}`, {\n\t\t\t\t\t\tmissing: [node.name],\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'output': {\n\t\t\t\tconst evaluated = evaluateTemplateExpression(\n\t\t\t\t\tnode.value,\n\t\t\t\t\tactive,\n\t\t\t\t\tnamespaces,\n\t\t\t\t\toptions,\n\t\t\t\t\tcallDepth,\n\t\t\t\t)\n\t\t\t\tif (isHTMLNode(evaluated)) {\n\t\t\t\t\tconst document: HTMLDocument =\n\t\t\t\t\t\tevaluated.category === 'document'\n\t\t\t\t\t\t\t? evaluated\n\t\t\t\t\t\t\t: { category: 'document', children: [evaluated] }\n\t\t\t\t\tsteps.push([\n\t\t\t\t\t\t[[false, createHTML(document).sanitize(options?.sanitize).document]],\n\t\t\t\t\t\tactive,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t])\n\t\t\t\t} else if (isMarkdownNode(evaluated)) {\n\t\t\t\t\tsteps.push([[[false, evaluated]], active, undefined])\n\t\t\t\t} else {\n\t\t\t\t\tsteps.push([[[false, renderTemplateValue(evaluated)]], active, undefined])\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'if': {\n\t\t\t\tconst branch = matchesTemplateTruth(\n\t\t\t\t\tevaluateTemplateExpression(node.condition, active, namespaces, options, callDepth),\n\t\t\t\t)\n\t\t\t\t\t? node.body\n\t\t\t\t\t: (node.alternate ?? [])\n\t\t\t\tsteps.push(runTemplateNodes(branch, active, namespaces, options, callDepth))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'for': {\n\t\t\t\tconst items = collectTemplateItems(\n\t\t\t\t\tevaluateTemplateExpression(node.sequence, active, namespaces, options, callDepth),\n\t\t\t\t)\n\t\t\t\tconst turns: Array<\n\t\t\t\t\treadonly [\n\t\t\t\t\t\tReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\t\t\t\t\t\t'break' | 'continue' | undefined,\n\t\t\t\t\t]\n\t\t\t\t> = []\n\t\t\t\tfor (const [index0, item] of items.entries()) {\n\t\t\t\t\tif (turns.at(-1)?.[1] === 'break') break\n\t\t\t\t\tconst loopFrame = new Map<string, TemplateRuntimeValue>()\n\t\t\t\t\tif (node.targets.length === 1) {\n\t\t\t\t\t\tconst [targetName] = node.targets\n\t\t\t\t\t\tif (targetName !== undefined) loopFrame.set(targetName, item)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst unpacked = collectTemplateItems(item)\n\t\t\t\t\t\tif (unpacked.length !== node.targets.length) {\n\t\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t\t`unpacks ${unpacked.length} values into ${node.targets.length} loop targets`,\n\t\t\t\t\t\t\t\t{ feature: 'unpacking' },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const [position, targetName] of node.targets.entries()) {\n\t\t\t\t\t\t\tloopFrame.set(targetName, unpacked[position])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tloopFrame.set('loop', {\n\t\t\t\t\t\tindex0,\n\t\t\t\t\t\tlength: items.length,\n\t\t\t\t\t\tprevitem: index0 > 0 ? items[index0 - 1] : undefined,\n\t\t\t\t\t\tnextitem: index0 + 1 < items.length ? items[index0 + 1] : undefined,\n\t\t\t\t\t})\n\t\t\t\t\tconst [parts, , control] = runTemplateNodes(\n\t\t\t\t\t\tnode.body,\n\t\t\t\t\t\t[...active, loopFrame],\n\t\t\t\t\t\tnamespaces,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tcallDepth,\n\t\t\t\t\t)\n\t\t\t\t\tturns.push([parts, control])\n\t\t\t\t}\n\t\t\t\tsteps.push([turns.flatMap(([parts]) => parts), active, undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'set': {\n\t\t\t\tconst value = evaluateTemplateExpression(node.value, active, namespaces, options, callDepth)\n\t\t\t\tif (node.target.scope === 'local') {\n\t\t\t\t\tsteps.push([[], bindTemplateName(active, node.target.name, value), undefined])\n\t\t\t\t} else {\n\t\t\t\t\tconst container = findTemplateName(active, node.target.object)\n\t\t\t\t\tif (!isTemplateNamespace(container)) {\n\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t`sets attribute ${quoteTemplateText(node.target.name)} on ${renderTemplateType(container)}, which is not a namespace`,\n\t\t\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst backing = namespaces.get(container)\n\t\t\t\t\tif (backing === undefined) {\n\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t`sets attribute ${quoteTemplateText(node.target.name)} on a readonly namespace`,\n\t\t\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tbacking.set(node.target.name, value)\n\t\t\t\t\tsteps.push([[], active, undefined])\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'macro': {\n\t\t\t\tconst macro: TemplateMacro = {\n\t\t\t\t\tmacro: true,\n\t\t\t\t\tname: node.name,\n\t\t\t\t\tparameters: node.parameters,\n\t\t\t\t\tbody: node.body,\n\t\t\t\t\tclosure: active,\n\t\t\t\t}\n\t\t\t\tsteps.push([[], bindTemplateName(active, node.name, macro), undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'control':\n\t\t\t\tsteps.push([[], active, node.action])\n\t\t\t\tbreak\n\t\t}\n\t}\n\tconst last = steps.at(-1)\n\treturn [steps.flatMap(([parts]) => parts), last?.[1] ?? frames, last?.[2]]\n}\n\n/**\n * Executes a sequence of compiled {@link TemplateNode}s in order, threading\n * lexical `set` and `macro` bindings into subsequent siblings until a loop\n * control (`break` or `continue`) terminates the run.\n *\n * @param nodes - The nodes to execute in order\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The emitted parts, updated scope frames, and optional loop control signal\n *\n * @example\n * ```ts\n * import { executeTemplateNodes } from '@orkestrel/template'\n *\n * executeTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // ['Hi']\n * ```\n */\nexport function executeTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): readonly [\n\tparts: readonly TemplatePart[],\n\tframes: TemplateScope,\n\tcontrol: 'break' | 'continue' | undefined,\n] {\n\tconst [tagged, updated, control] = runTemplateNodes(nodes, frames, namespaces, options, callDepth)\n\treturn [tagged.map(([, part]) => part), updated, control]\n}\n\n/**\n * Renders one emitted {@link TemplatePart} to string text, sanitizing `HTMLNode`s\n * through `@orkestrel/html` and rendering `MarkdownNode`s through `@orkestrel/markdown`.\n *\n * @param part - The emitted template part\n * @param options - Optional evaluation and sanitize settings\n * @returns The rendered string\n *\n * @example\n * ```ts\n * import { renderTemplatePart } from '@orkestrel/template'\n *\n * renderTemplatePart({ category: 'text', value: 'a & b' }) // 'a & b'\n * ```\n */\nexport function renderTemplatePart(part: TemplatePart, options?: TemplateEvaluateOptions): string {\n\tif (typeof part === 'string') return part\n\tif (isHTMLNode(part)) {\n\t\tconst document: HTMLDocument =\n\t\t\tpart.category === 'document' ? part : { category: 'document', children: [part] }\n\t\treturn renderHTML(createHTML(document).sanitize(options?.sanitize).document)\n\t}\n\treturn renderMarkdown(part)\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} into tagged parts distinguishing\n * template-authored literal text (`true`) from dynamic fill output (`false`).\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The ordered list of tagged evaluated parts\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTaggedTemplateParts } from '@orkestrel/template'\n *\n * evaluateTaggedTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' })\n * // [[true, 'Hi '], [false, 'Ada']]\n * ```\n */\nexport function evaluateTaggedTemplateParts(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): ReadonlyArray<readonly [literal: boolean, part: TemplatePart]> {\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError('INVALID', 'A template evaluates a valid TemplateDocument.')\n\t}\n\tconst frame = new Map<string, TemplateRuntimeValue>()\n\tif (values !== undefined) {\n\t\tfor (const [entryKey, entryValue] of Object.entries(values)) {\n\t\t\tif (entryValue !== undefined) {\n\t\t\t\tframe.set(entryKey, normalizeTemplateValue(entryValue))\n\t\t\t}\n\t\t}\n\t}\n\tconst namespaces = new Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>()\n\treturn runTemplateNodes(document.children, [frame], namespaces, options, 0)[0]\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} into an ordered list of\n * tree-valued {@link TemplatePart}s (`string`, sanitized `HTMLNode`, or `MarkdownNode`).\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The ordered list of evaluated parts\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTemplateParts } from '@orkestrel/template'\n *\n * evaluateTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // ['Hi ', 'Ada']\n * ```\n */\nexport function evaluateTemplateParts(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): readonly TemplatePart[] {\n\treturn evaluateTaggedTemplateParts(document, values, options).map(([, part]) => part)\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} against runtime values and\n * joins every emitted part into a rendered string.\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The rendered output string\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTemplate } from '@orkestrel/template'\n *\n * evaluateTemplate(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function evaluateTemplate(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): string {\n\tconst parts = evaluateTemplateParts(document, values, options)\n\treturn parts.map((part) => renderTemplatePart(part, options)).join('')\n}\n\n// === AST traversal, queries, fold, rewrite, streaming, and canonical renderer\n\n/**\n * Walks a {@link TemplateNode} depth-first in pre-order, yielding the root\n * first and capping descent at `MAX_DEPTH`.\n *\n * @param root - The root node to traverse\n * @param depth - Current traversal depth. Default: `0`\n * @returns A lazy generator over every visited node\n *\n * @example\n * ```ts\n * import { compileTemplate, walkTemplateNodes } from '@orkestrel/template'\n *\n * Array.from(walkTemplateNodes(compileTemplate('Hi {{ name }}'))).map((node) => node.syntax)\n * // ['document', 'text', 'output']\n * ```\n */\nexport function* walkTemplateNodes(root: TemplateNode, depth = 0): Generator<TemplateNode> {\n\tyield root\n\tif (depth >= MAX_DEPTH) return\n\tconst next = depth + 1\n\tswitch (root.syntax) {\n\t\tcase 'document':\n\t\t\tfor (const child of root.children) yield* walkTemplateNodes(child, next)\n\t\t\treturn\n\t\tcase 'if':\n\t\t\tfor (const child of root.body) yield* walkTemplateNodes(child, next)\n\t\t\tif (root.alternate !== undefined) {\n\t\t\t\tfor (const child of root.alternate) yield* walkTemplateNodes(child, next)\n\t\t\t}\n\t\t\treturn\n\t\tcase 'for':\n\t\tcase 'macro':\n\t\t\tfor (const child of root.body) yield* walkTemplateNodes(child, next)\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn\n\t}\n}\n\n/**\n * Finds the first {@link TemplateNode} in depth-first pre-order matching a\n * guard or predicate.\n *\n * @param root - The root node to search\n * @param predicate - The guard or predicate to test each node\n * @returns The first matching node, or `undefined`\n *\n * @example\n * ```ts\n * import { compileTemplate, findTemplateNode } from '@orkestrel/template'\n *\n * findTemplateNode(compileTemplate('Hi {{ name }}'), (node) => node.syntax === 'output')?.syntax // 'output'\n * ```\n */\nexport function findTemplateNode<T extends TemplateNode>(\n\troot: TemplateNode,\n\tguard: (node: TemplateNode) => node is T,\n): T | undefined\nexport function findTemplateNode(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): TemplateNode | undefined\nexport function findTemplateNode(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): TemplateNode | undefined {\n\tfor (const node of walkTemplateNodes(root)) {\n\t\tif (predicate(node)) return node\n\t}\n\treturn undefined\n}\n\n/**\n * Collects every {@link TemplateNode} in depth-first pre-order matching a\n * guard or predicate.\n *\n * @param root - The root node to search\n * @param predicate - The guard or predicate to test each node\n * @returns The matching nodes in walk order\n *\n * @example\n * ```ts\n * import { compileTemplate, filterTemplateNodes } from '@orkestrel/template'\n *\n * filterTemplateNodes(compileTemplate('{{ a }}{{ b }}'), (node) => node.syntax === 'output').length // 2\n * ```\n */\nexport function filterTemplateNodes<T extends TemplateNode>(\n\troot: TemplateNode,\n\tguard: (node: TemplateNode) => node is T,\n): readonly T[]\nexport function filterTemplateNodes(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): readonly TemplateNode[]\nexport function filterTemplateNodes(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): readonly TemplateNode[] {\n\treturn walkTemplateNodes(root)\n\t\t.filter((node) => predicate(node))\n\t\t.toArray()\n}\n\n/**\n * Reduces a {@link TemplateNode} depth-first in pre-order into one accumulated value.\n *\n * @param root - The root node to reduce\n * @param callback - The step combining the accumulated value and each visited node\n * @param initial - The initial accumulated value\n * @returns The final accumulated value\n *\n * @example\n * ```ts\n * import { compileTemplate, reduceTemplateDocument } from '@orkestrel/template'\n *\n * reduceTemplateDocument(compileTemplate('Hi {{ name }}'), (count) => count + 1, 0) // 3\n * ```\n */\nexport function reduceTemplateDocument<T>(\n\troot: TemplateNode,\n\tcallback: (value: T, node: TemplateNode) => T,\n\tinitial: T,\n): T {\n\treturn walkTemplateNodes(root).reduce((value, node) => callback(value, node), initial)\n}\n\n/**\n * Folds a {@link TemplateNode} bottom-up through a total {@link TemplateHandlerMap}\n * covering every syntax variant, capped at `MAX_DEPTH`.\n *\n * @param node - The node to fold\n * @param handlers - Total handler map keyed by `syntax`\n * @param depth - Current recursion depth. Default: `0`\n * @returns The folded result\n *\n * @example\n * ```ts\n * import { compileTemplate, foldTemplateDocument } from '@orkestrel/template'\n *\n * const doc = compileTemplate('Hi')\n * foldTemplateDocument(doc, {\n * document: (_, children) => children.reduce((a, b) => a + b, 1),\n * text: () => 1,\n * placeholder: () => 1,\n * output: () => 1,\n * if: (_, children) => children.reduce((a, b) => a + b, 1),\n * for: (_, children) => children.reduce((a, b) => a + b, 1),\n * set: () => 1,\n * macro: (_, children) => children.reduce((a, b) => a + b, 1),\n * control: () => 1,\n * comment: () => 1,\n * html: () => 1,\n * markdown: () => 1,\n * }) // 2\n * ```\n */\nexport function foldTemplateDocument<T>(\n\tnode: TemplateNode,\n\thandlers: TemplateHandlerMap<T>,\n\tdepth = 0,\n): T {\n\tconst next = depth + 1\n\tconst capped = depth >= MAX_DEPTH\n\tswitch (node.syntax) {\n\t\tcase 'document':\n\t\t\treturn handlers.document(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.children.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'text':\n\t\t\treturn handlers.text(node, [])\n\t\tcase 'placeholder':\n\t\t\treturn handlers.placeholder(node, [])\n\t\tcase 'output':\n\t\t\treturn handlers.output(node, [])\n\t\tcase 'if': {\n\t\t\tconst children = capped\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t...node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t\t\t\t...(node.alternate ?? []).map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t\t\t]\n\t\t\treturn handlers.if(node, children)\n\t\t}\n\t\tcase 'for':\n\t\t\treturn handlers.for(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'set':\n\t\t\treturn handlers.set(node, [])\n\t\tcase 'macro':\n\t\t\treturn handlers.macro(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'control':\n\t\t\treturn handlers.control(node, [])\n\t\tcase 'comment':\n\t\t\treturn handlers.comment(node, [])\n\t\tcase 'html':\n\t\t\treturn handlers.html(node, [])\n\t\tcase 'markdown':\n\t\t\treturn handlers.markdown(node, [])\n\t}\n}\n\n/**\n * Rewrites one {@link TemplateNode} bottom-up with copy-on-write identity\n * preservation, recording each rebuilt node's direct source in `derivations`.\n *\n * @param node - The node to rewrite\n * @param rewrite - The bottom-up rewrite callback\n * @param derivations - Operation-owned derivation map\n * @param depth - Current recursion depth\n * @returns The rewritten node\n *\n * @example\n * ```ts\n * import { rewriteTemplateNode } from '@orkestrel/template'\n *\n * rewriteTemplateNode({ syntax: 'text', value: 'hi' }, (node) => node, new Map(), 0)\n * ```\n */\nexport function rewriteTemplateNode(\n\tnode: TemplateNode,\n\trewrite: TemplateRewriteHandler,\n\tderivations: Map<TemplateNode, TemplateNode | undefined>,\n\tdepth: number,\n): TemplateNode {\n\tif (depth >= MAX_DEPTH) return node\n\tconst next = depth + 1\n\tif (node.syntax === 'if') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst alternate = node.alternate?.map((child) =>\n\t\t\trewriteTemplateNode(child, rewrite, derivations, next),\n\t\t)\n\t\tconst bodyChanged = body.some((child, index) => child !== node.body[index])\n\t\tconst alternateChanged =\n\t\t\talternate !== undefined &&\n\t\t\tnode.alternate !== undefined &&\n\t\t\talternate.some((child, index) => child !== node.alternate?.[index])\n\t\tconst rebuilt: TemplateNode =\n\t\t\t!bodyChanged && !alternateChanged\n\t\t\t\t? node\n\t\t\t\t: {\n\t\t\t\t\t\tsyntax: 'if',\n\t\t\t\t\t\tcondition: node.condition,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t\t...(alternate !== undefined ? { alternate } : {}),\n\t\t\t\t\t}\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tif (node.syntax === 'for') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst changed = body.some((child, index) => child !== node.body[index])\n\t\tconst rebuilt: TemplateNode = changed\n\t\t\t? { syntax: 'for', targets: node.targets, sequence: node.sequence, body }\n\t\t\t: node\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tif (node.syntax === 'macro') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst changed = body.some((child, index) => child !== node.body[index])\n\t\tconst rebuilt: TemplateNode = changed\n\t\t\t? { syntax: 'macro', name: node.name, parameters: node.parameters, body }\n\t\t\t: node\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tconst candidate = rewrite(node)\n\tconst accepted = candidate.syntax === 'document' ? node : candidate\n\tif (accepted !== node) {\n\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t}\n\treturn accepted\n}\n\n/**\n * Rewrites a {@link TemplateDocument} bottom-up (copy-on-write) and returns the\n * rewritten document alongside its output-to-input derivation map.\n *\n * @param document - The document to rewrite\n * @param rewrite - The bottom-up node rewrite callback\n * @returns The rewritten document and its provenance derivations\n *\n * @example\n * ```ts\n * import { compileTemplate, mapTemplateDocument } from '@orkestrel/template'\n *\n * const [rewritten] = mapTemplateDocument(compileTemplate('hi'), (node) =>\n * node.syntax === 'text' ? { syntax: 'text', value: node.value.toUpperCase() } : node,\n * )\n * rewritten.children[0] // { syntax: 'text', value: 'HI' }\n * ```\n */\nexport function mapTemplateDocument(\n\tdocument: TemplateDocument,\n\trewrite: TemplateRewriteHandler,\n): TemplateDerivation<TemplateDocument> {\n\tconst derivations = new Map<TemplateNode, TemplateNode | undefined>()\n\tconst children = document.children.map((child) =>\n\t\trewriteTemplateNode(child, rewrite, derivations, 1),\n\t)\n\tconst changed = children.some((child, index) => child !== document.children[index])\n\tif (!changed) return [document, derivations]\n\tconst rebuilt: TemplateDocument = { syntax: 'document', children }\n\tderivations.set(rebuilt, document)\n\treturn [rebuilt, derivations]\n}\n\n/**\n * Creates a fresh, pull-based `ReadableStream` over a {@link TemplateDocument}'s\n * direct top-level children in source order.\n *\n * @param document - The document whose top-level children to stream\n * @returns A pull-based stream yielding one top-level node per pull\n *\n * @example\n * ```ts\n * import { compileTemplate, streamTemplateNodes } from '@orkestrel/template'\n *\n * const reader = streamTemplateNodes(compileTemplate('Hi {{ name }}')).getReader()\n * ```\n */\nexport function streamTemplateNodes(document: TemplateDocument): ReadableStream<TemplateNode> {\n\tconst children = document.children.values()\n\treturn new ReadableStream<TemplateNode>({\n\t\tpull(controller) {\n\t\t\tconst next = children.next()\n\t\t\tif (!next.done && next.value !== undefined) {\n\t\t\t\tcontroller.enqueue(next.value)\n\t\t\t} else {\n\t\t\t\tcontroller.close()\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Renders a {@link TemplateExpression} back to canonical Jinja expression syntax\n * that compiles back to an equivalent AST.\n *\n * @param expression - The expression to render\n * @returns Canonical Jinja expression text\n *\n * @example\n * ```ts\n * import { renderTemplateExpression } from '@orkestrel/template'\n *\n * renderTemplateExpression({ term: 'name', name: 'messages' }) // 'messages'\n * ```\n */\nexport function renderTemplateExpression(expression: TemplateExpression): string {\n\tswitch (expression.term) {\n\t\tcase 'literal': {\n\t\t\tif (expression.value === null) return 'none'\n\t\t\tif (typeof expression.value === 'boolean') return expression.value ? 'true' : 'false'\n\t\t\tif (typeof expression.value === 'number') return renderTemplateNumber(expression.value)\n\t\t\treturn JSON.stringify(expression.value)\n\t\t}\n\t\tcase 'name':\n\t\t\treturn expression.name\n\t\tcase 'member': {\n\t\t\tconst target =\n\t\t\t\texpression.object.term === 'name' ||\n\t\t\t\texpression.object.term === 'literal' ||\n\t\t\t\texpression.object.term === 'member' ||\n\t\t\t\texpression.object.term === 'slice' ||\n\t\t\t\texpression.object.term === 'call'\n\t\t\t\t\t? renderTemplateExpression(expression.object)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.object)})`\n\t\t\tif (\n\t\t\t\texpression.key.term === 'literal' &&\n\t\t\t\ttypeof expression.key.value === 'string' &&\n\t\t\t\t/^[\\p{XID_Start}_]\\p{XID_Continue}*$/u.test(expression.key.value)\n\t\t\t) {\n\t\t\t\treturn `${target}.${expression.key.value}`\n\t\t\t}\n\t\t\treturn `${target}[${renderTemplateExpression(expression.key)}]`\n\t\t}\n\t\tcase 'slice': {\n\t\t\tconst target =\n\t\t\t\texpression.object.term === 'name' ||\n\t\t\t\texpression.object.term === 'literal' ||\n\t\t\t\texpression.object.term === 'member' ||\n\t\t\t\texpression.object.term === 'slice' ||\n\t\t\t\texpression.object.term === 'call'\n\t\t\t\t\t? renderTemplateExpression(expression.object)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.object)})`\n\t\t\tconst start = expression.start === undefined ? '' : renderTemplateExpression(expression.start)\n\t\t\tconst stop = expression.stop === undefined ? '' : renderTemplateExpression(expression.stop)\n\t\t\tconst step =\n\t\t\t\texpression.step === undefined ? '' : `:${renderTemplateExpression(expression.step)}`\n\t\t\treturn `${target}[${start}:${stop}${step}]`\n\t\t}\n\t\tcase 'call': {\n\t\t\tconst callee =\n\t\t\t\texpression.callee.term === 'name' || expression.callee.term === 'member'\n\t\t\t\t\t? renderTemplateExpression(expression.callee)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.callee)})`\n\t\t\tconst argumentsList = [\n\t\t\t\t...expression.values.map((value) => renderTemplateExpression(value)),\n\t\t\t\t...expression.keywords.map(\n\t\t\t\t\t(keyword) => `${keyword.name}=${renderTemplateExpression(keyword.value)}`,\n\t\t\t\t),\n\t\t\t]\n\t\t\treturn `${callee}(${argumentsList.join(', ')})`\n\t\t}\n\t\tcase 'filter': {\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'name' ||\n\t\t\t\texpression.value.term === 'literal' ||\n\t\t\t\texpression.value.term === 'member' ||\n\t\t\t\texpression.value.term === 'slice' ||\n\t\t\t\texpression.value.term === 'call' ||\n\t\t\t\texpression.value.term === 'filter'\n\t\t\t\t\t? renderTemplateExpression(expression.value)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.value)})`\n\t\t\treturn `${inner} | ${expression.name}`\n\t\t}\n\t\tcase 'test': {\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'conditional' ||\n\t\t\t\texpression.value.term === 'test' ||\n\t\t\t\t(expression.value.term === 'unary' && expression.value.operator === 'not') ||\n\t\t\t\t(expression.value.term === 'binary' &&\n\t\t\t\t\t(expression.value.operator === 'and' ||\n\t\t\t\t\t\texpression.value.operator === 'or' ||\n\t\t\t\t\t\texpression.value.operator === 'in' ||\n\t\t\t\t\t\texpression.value.operator === 'not in' ||\n\t\t\t\t\t\texpression.value.operator === '==' ||\n\t\t\t\t\t\texpression.value.operator === '!=' ||\n\t\t\t\t\t\texpression.value.operator === '<' ||\n\t\t\t\t\t\texpression.value.operator === '>' ||\n\t\t\t\t\t\texpression.value.operator === '<=' ||\n\t\t\t\t\t\texpression.value.operator === '>='))\n\t\t\t\t\t? `(${renderTemplateExpression(expression.value)})`\n\t\t\t\t\t: renderTemplateExpression(expression.value)\n\t\t\treturn expression.negated\n\t\t\t\t? `${inner} is not ${expression.name}`\n\t\t\t\t: `${inner} is ${expression.name}`\n\t\t}\n\t\tcase 'unary': {\n\t\t\tif (expression.operator === 'not') {\n\t\t\t\tconst inner =\n\t\t\t\t\texpression.value.term === 'conditional' ||\n\t\t\t\t\t(expression.value.term === 'binary' &&\n\t\t\t\t\t\t(expression.value.operator === 'and' || expression.value.operator === 'or'))\n\t\t\t\t\t\t? `(${renderTemplateExpression(expression.value)})`\n\t\t\t\t\t\t: renderTemplateExpression(expression.value)\n\t\t\t\treturn `not ${inner}`\n\t\t\t}\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'name' ||\n\t\t\t\texpression.value.term === 'literal' ||\n\t\t\t\texpression.value.term === 'member' ||\n\t\t\t\texpression.value.term === 'slice' ||\n\t\t\t\texpression.value.term === 'call' ||\n\t\t\t\texpression.value.term === 'filter'\n\t\t\t\t\t? renderTemplateExpression(expression.value)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.value)})`\n\t\t\treturn `${expression.operator}${inner}`\n\t\t}\n\t\tcase 'binary': {\n\t\t\tconst left =\n\t\t\t\texpression.left.term === 'binary' ||\n\t\t\t\texpression.left.term === 'conditional' ||\n\t\t\t\texpression.left.term === 'test' ||\n\t\t\t\t(expression.left.term === 'unary' && expression.left.operator === 'not')\n\t\t\t\t\t? `(${renderTemplateExpression(expression.left)})`\n\t\t\t\t\t: renderTemplateExpression(expression.left)\n\t\t\tconst right =\n\t\t\t\texpression.right.term === 'binary' ||\n\t\t\t\texpression.right.term === 'conditional' ||\n\t\t\t\texpression.right.term === 'test' ||\n\t\t\t\t(expression.right.term === 'unary' && expression.right.operator === 'not')\n\t\t\t\t\t? `(${renderTemplateExpression(expression.right)})`\n\t\t\t\t\t: renderTemplateExpression(expression.right)\n\t\t\treturn `${left} ${expression.operator} ${right}`\n\t\t}\n\t\tcase 'conditional':\n\t\t\treturn `(${renderTemplateExpression(expression.consequent)} if ${renderTemplateExpression(expression.condition)} else ${renderTemplateExpression(expression.alternate)})`\n\t}\n}\n\n/**\n * Checks whether a trailing text node ends with a whitespace-only line that\n * Jinja's `lstrip_blocks` would strip before a following block or comment tag.\n *\n * @param node - The preceding sibling node, if any\n * @param atLineStart - Whether the text node itself opened at a line start\n * @returns True if a `+` marker is needed to keep the whitespace verbatim; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateIndent } from '@orkestrel/template'\n *\n * matchesTemplateIndent({ syntax: 'text', value: ' ' }, true) // true\n * ```\n */\nexport function matchesTemplateIndent(\n\tnode: TemplateNode | undefined,\n\tatLineStart: boolean,\n): boolean {\n\tif (node?.syntax !== 'text') return false\n\tconst breakIndex = node.value.lastIndexOf('\\n')\n\tconst tail = node.value.slice(breakIndex + 1)\n\tconst startsLine = breakIndex !== -1 || atLineStart\n\treturn startsLine && new RegExp(`^${TEMPLATE_SPACE}+$`, 'u').test(tail)\n}\n\n/**\n * Renders an ordered list of sibling {@link TemplateNode}s into canonical source\n * text, preserving leading whitespace and trailing newlines against Jinja's\n * `lstrip_blocks` and `trim_blocks` rules with `+` markers where needed.\n *\n * @param nodes - The sibling nodes to render\n * @param precedingNewline - Whether the list opens at a line boundary\n * @returns The canonical template source for the node list\n *\n * @example\n * ```ts\n * import { renderTemplateNodes } from '@orkestrel/template'\n *\n * renderTemplateNodes([{ syntax: 'text', value: 'Hi' }], true) // 'Hi'\n * ```\n */\nexport function renderTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tprecedingNewline: boolean,\n): string {\n\treturn nodes\n\t\t.map((node, index) => {\n\t\t\tconst previous = nodes[index - 1]\n\t\t\tconst next = nodes[index + 1]\n\t\t\tconst needsOpenPlus = matchesTemplateIndent(previous, index === 1 && precedingNewline)\n\t\t\tconst needsClosePlus = next?.syntax === 'text' && next.value.startsWith('\\n')\n\t\t\tconst openBlock = needsOpenPlus ? '{%+' : '{%'\n\t\t\tconst closeBlock = needsClosePlus ? '+%}' : '%}'\n\t\t\tswitch (node.syntax) {\n\t\t\t\tcase 'document':\n\t\t\t\t\treturn renderTemplateNodes(node.children, true)\n\t\t\t\tcase 'text':\n\t\t\t\t\treturn node.value\n\t\t\t\tcase 'placeholder':\n\t\t\t\t\treturn node.raw\n\t\t\t\tcase 'output':\n\t\t\t\t\treturn `{{ ${renderTemplateExpression(node.value)} }}`\n\t\t\t\tcase 'comment': {\n\t\t\t\t\tconst openComment = needsOpenPlus ? '{#+' : '{#'\n\t\t\t\t\tconst closeComment = needsClosePlus ? '+#}' : '#}'\n\t\t\t\t\treturn `${openComment}${node.value}${closeComment}`\n\t\t\t\t}\n\t\t\t\tcase 'control':\n\t\t\t\t\treturn `${openBlock} ${node.action} ${closeBlock}`\n\t\t\t\tcase 'set': {\n\t\t\t\t\tconst target =\n\t\t\t\t\t\tnode.target.scope === 'local'\n\t\t\t\t\t\t\t? node.target.name\n\t\t\t\t\t\t\t: `${node.target.object}.${node.target.name}`\n\t\t\t\t\treturn `${openBlock} set ${target} = ${renderTemplateExpression(node.value)} ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'html':\n\t\t\t\t\treturn renderHTML(node.document)\n\t\t\t\tcase 'markdown':\n\t\t\t\t\treturn renderMarkdown(node.document)\n\t\t\t\tcase 'for': {\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} for ${node.targets.join(', ')} in ${renderTemplateExpression(node.sequence)} ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endfor ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'macro': {\n\t\t\t\t\tconst parameters = node.parameters\n\t\t\t\t\t\t.map((parameter) =>\n\t\t\t\t\t\t\tparameter.fallback === undefined\n\t\t\t\t\t\t\t\t? parameter.name\n\t\t\t\t\t\t\t\t: `${parameter.name}=${renderTemplateExpression(parameter.fallback)}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(', ')\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} macro ${node.name}(${parameters}) ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endmacro ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'if': {\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst branchOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\tconst bodyText = renderTemplateNodes(node.body, false)\n\t\t\t\t\tif (node.alternate === undefined) {\n\t\t\t\t\t\treturn `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} endif ${closeBlock}`\n\t\t\t\t\t}\n\t\t\t\t\tconst altFirstNewline =\n\t\t\t\t\t\tnode.alternate[0]?.syntax === 'text' && node.alternate[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.alternate.at(-1), node.alternate.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst elseClose = altFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} else ${elseClose}${renderTemplateNodes(node.alternate, false)}${endOpen} endif ${closeBlock}`\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.join('')\n}\n\n/**\n * Renders a {@link TemplateNode} back to canonical template source text.\n *\n * @remarks\n * For every compiled pure-Jinja {@link TemplateDocument}, `compileTemplate(renderTemplate(doc))`\n * produces a structurally equal document and `renderTemplate(compileTemplate(renderTemplate(doc)))`\n * equals `renderTemplate(doc)`.\n *\n * @param node - The node or document to render\n * @returns The canonical template source text\n *\n * @example\n * ```ts\n * import { compileTemplate, renderTemplate } from '@orkestrel/template'\n *\n * renderTemplate(compileTemplate('Hi {{ name }}')) // 'Hi {{ name }}'\n * ```\n */\nexport function renderTemplate(node: TemplateNode): string {\n\tconst rendered =\n\t\tnode.syntax === 'document'\n\t\t\t? renderTemplateNodes(node.children, true)\n\t\t\t: renderTemplateNodes([node], true)\n\treturn node.syntax === 'document' && rendered.endsWith('\\n') ? `${rendered}\\n` : rendered\n}\n\n// === Markdown sanitization and template projection leaves\n\n/**\n * Sanitizes a fenced code block language info string to a single token free of\n * whitespace, line breaks, backticks, and tildes.\n *\n * @param lang - The raw fence info-string language value\n * @returns The sanitized single-token language tag, or `undefined` when empty\n *\n * @example\n * ```ts\n * import { sanitizeTemplateMarkdownLanguage } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownLanguage('ts\\n```\\n[x](javascript:alert(1))') // 'ts'\n * sanitizeTemplateMarkdownLanguage(' ') // undefined\n * ```\n */\nexport function sanitizeTemplateMarkdownLanguage(lang: string): string | undefined {\n\tconst token = /^[^\\s`~]+/u.exec(lang.trim())?.[0]\n\treturn token !== undefined && token.length > 0 ? token : undefined\n}\n\n/**\n * Collapses line breaks inside inline markdown text to single spaces so inline\n * spans stay on one line through round-trip parsing.\n *\n * @param value - The inline text string to normalize\n * @returns The single-line string with `\\r\\n`, `\\r`, and `\\n` replaced by `' '`\n *\n * @example\n * ```ts\n * import { normalizeTemplateMarkdownText } from '@orkestrel/template'\n *\n * normalizeTemplateMarkdownText('a\\n\\nb') // 'a b'\n * ```\n */\nexport function normalizeTemplateMarkdownText(value: string): string {\n\treturn value.replace(/\\r\\n?|\\n/gu, ' ')\n}\n\n/**\n * Sanitizes inline `@orkestrel/markdown` nodes recursively by unwrapping unsafe\n * `LinkNode` elements, dropping unsafe `ImageNode` elements, and collapsing\n * line breaks inside `CodeSpanNode` values.\n *\n * @param nodes - The inline nodes to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized inline nodes\n *\n * @example\n * ```ts\n * import { parseInline } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdownInlines } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownInlines(parseInline('[x](javascript:alert(1))')) // [{ element: 'text', value: 'x' }]\n * ```\n */\nexport function sanitizeTemplateMarkdownInlines(\n\tnodes: readonly InlineNode[],\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH) return []\n\tconst schemes = options?.schemes ?? SAFE_URL_SCHEMES\n\tconst sanitized: InlineNode[] = []\n\tfor (const child of nodes) {\n\t\tif (child.element === 'codeSpan') {\n\t\t\tsanitized.push({\n\t\t\t\telement: 'codeSpan',\n\t\t\t\tvalue: normalizeTemplateMarkdownText(child.value),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'link') {\n\t\t\tconst children = sanitizeTemplateMarkdownInlines(child.children, options, depth + 1)\n\t\t\tconst cleanHref = sanitizeURL(child.href, schemes)\n\t\t\tif (cleanHref === '') {\n\t\t\t\tfor (const inner of children) sanitized.push(inner)\n\t\t\t} else {\n\t\t\t\tsanitized.push({ element: 'link', href: cleanHref, children })\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'image') {\n\t\t\tconst cleanSrc = sanitizeURL(child.src, schemes)\n\t\t\tif (cleanSrc !== '') {\n\t\t\t\tsanitized.push({\n\t\t\t\t\telement: 'image',\n\t\t\t\t\tsrc: cleanSrc,\n\t\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1),\n\t\t\t\t})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'emphasis') {\n\t\t\tsanitized.push({\n\t\t\t\telement: 'emphasis',\n\t\t\t\tstrong: child.strong,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tsanitized.push(child)\n\t}\n\treturn coalesceText(sanitized)\n}\n\n/**\n * Sanitizes block `@orkestrel/markdown` nodes recursively through\n * `sanitizeTemplateMarkdown`, dropping any node that sanitizes to `undefined`.\n *\n * @param nodes - The block nodes to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized block nodes\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdownBlocks } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownBlocks(parseMarkdown('Hi').children).length // 1\n * ```\n */\nexport function sanitizeTemplateMarkdownBlocks(\n\tnodes: readonly BlockNode[],\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): readonly BlockNode[] {\n\tif (depth >= MAX_DEPTH) return []\n\tconst blocks: BlockNode[] = []\n\tfor (const block of nodes) {\n\t\tconst clean = sanitizeTemplateMarkdown(block, options, depth)\n\t\tif (clean !== undefined && isBlockNode(clean)) blocks.push(clean)\n\t}\n\treturn blocks\n}\n\n/**\n * Sanitizes a `@orkestrel/markdown` node recursively by unwrapping any\n * `LinkNode` whose `href` fails `sanitizeURL`, dropping any `ImageNode` whose\n * `src` fails `sanitizeURL`, collapsing `CodeSpanNode` line breaks, and\n * sanitizing `CodeBlockNode` fence languages.\n *\n * @param node - The markdown AST node to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized node, or `undefined` when dropped\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdown } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdown(parseMarkdown(')')) // { element: 'document', children: [{ element: 'paragraph', children: [] }] }\n * ```\n */\nexport function sanitizeTemplateMarkdown(\n\tnode: MarkdownNode,\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): MarkdownNode | undefined {\n\tif (depth >= MAX_DEPTH) return undefined\n\tconst schemes = options?.schemes ?? SAFE_URL_SCHEMES\n\tswitch (node.element) {\n\t\tcase 'text':\n\t\tcase 'break':\n\t\tcase 'thematicBreak':\n\t\t\treturn node\n\t\tcase 'codeSpan':\n\t\t\treturn {\n\t\t\t\telement: 'codeSpan',\n\t\t\t\tvalue: normalizeTemplateMarkdownText(node.value),\n\t\t\t}\n\t\tcase 'codeBlock': {\n\t\t\tconst lang = node.lang !== undefined ? sanitizeTemplateMarkdownLanguage(node.lang) : undefined\n\t\t\treturn {\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(lang !== undefined ? { lang } : {}),\n\t\t\t\tcode: node.code,\n\t\t\t}\n\t\t}\n\t\tcase 'image': {\n\t\t\tconst cleanSrc = sanitizeURL(node.src, schemes)\n\t\t\tif (cleanSrc === '') return undefined\n\t\t\treturn {\n\t\t\t\telement: 'image',\n\t\t\t\tsrc: cleanSrc,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\t}\n\t\tcase 'link': {\n\t\t\tconst children = sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)\n\t\t\tconst cleanHref = sanitizeURL(node.href, schemes)\n\t\t\tif (cleanHref === '') {\n\t\t\t\tif (children.length === 0) return undefined\n\t\t\t\tif (children.length === 1) return children[0]\n\t\t\t\treturn {\n\t\t\t\t\telement: 'text',\n\t\t\t\t\tvalue: children.map((child) => flattenText(child)).join(''),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { element: 'link', href: cleanHref, children }\n\t\t}\n\t\tcase 'emphasis':\n\t\t\treturn {\n\t\t\t\telement: 'emphasis',\n\t\t\t\tstrong: node.strong,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'heading':\n\t\t\treturn {\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: node.level,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'paragraph':\n\t\t\treturn {\n\t\t\t\telement: 'paragraph',\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'blockquote':\n\t\t\treturn {\n\t\t\t\telement: 'blockquote',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'listItem':\n\t\t\treturn {\n\t\t\t\telement: 'listItem',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'list': {\n\t\t\tconst items: ListItemNode[] = node.items.map((item) => ({\n\t\t\t\telement: 'listItem',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(item.children, options, depth + 1),\n\t\t\t}))\n\t\t\treturn { element: 'list', ordered: node.ordered, start: node.start, items }\n\t\t}\n\t\tcase 'table':\n\t\t\treturn {\n\t\t\t\telement: 'table',\n\t\t\t\theader: node.header.map((cell) =>\n\t\t\t\t\tsanitizeTemplateMarkdownInlines(cell, options, depth + 1),\n\t\t\t\t),\n\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\trow.map((cell) => sanitizeTemplateMarkdownInlines(cell, options, depth + 1)),\n\t\t\t\t),\n\t\t\t\talign: node.align,\n\t\t\t}\n\t\tcase 'document':\n\t\t\treturn {\n\t\t\t\telement: 'document',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t}\n}\n\n/**\n * Resolves a Private Use Area sentinel prefix guaranteed absent from `combined`.\n *\n * @param combined - Concatenated template text and fill values in one markdown run\n * @returns The collision-free sentinel prefix\n *\n * @example\n * ```ts\n * import { resolveMarkdownMarker } from '@orkestrel/template'\n *\n * resolveMarkdownMarker('plain text') // '\\uE000\\uE001'\n * ```\n */\nexport function resolveMarkdownMarker(combined: string): string {\n\tfor (let k = 0; k <= combined.length; k += 1) {\n\t\tconst candidate = `\\uE000${'\\uE002'.repeat(k)}\\uE001`\n\t\tif (!combined.includes(candidate)) return candidate\n\t}\n\treturn `\\uE000${'\\uE002'.repeat(combined.length + 1)}\\uE001`\n}\n\n/**\n * Replaces every sentinel slot in a parsed markdown leaf string with its\n * literal dynamic fill string in a single pass.\n *\n * @param text - Parsed leaf string possibly holding sentinel slots\n * @param pattern - RegExp matching sentinel slots for this run\n * @param fills - Indexed dynamic fill strings\n * @returns The restored literal string\n *\n * @example\n * ```ts\n * import { restoreMarkdownText } from '@orkestrel/template'\n *\n * restoreMarkdownText('\\uE000\\uE0010\\uE003', /\\uE000\\uE001(\\d+)\\uE003/gu, ['Ada']) // 'Ada'\n * ```\n */\nexport function restoreMarkdownText(\n\ttext: string,\n\tpattern: RegExp,\n\tfills: readonly string[],\n): string {\n\treturn text.replace(new RegExp(pattern.source, pattern.flags), (match, digits: string) => {\n\t\tconst value = fills[Number(digits)]\n\t\treturn value ?? match\n\t})\n}\n\n/**\n * Restores sentinel slots inside a list of parsed inline markdown nodes,\n * collapsing line breaks inside substituted dynamic fills and `CodeSpanNode`\n * values so inline content stays single-line across round-trips.\n *\n * @param nodes - Inline nodes parsed from sentinel-substituted markdown\n * @param pattern - RegExp matching sentinel slots\n * @param fills - Indexed dynamic fill strings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The inline nodes with dynamic fills restored as literal leaves\n *\n * @example\n * ```ts\n * import { restoreMarkdownInlines } from '@orkestrel/template'\n *\n * restoreMarkdownInlines([{ element: 'text', value: 'hi' }], /\\uE000\\uE001(\\d+)\\uE003/gu, []) // [{ element: 'text', value: 'hi' }]\n * ```\n */\nexport function restoreMarkdownInlines(\n\tnodes: readonly InlineNode[],\n\tpattern: RegExp,\n\tfills: readonly string[],\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH) return nodes\n\tconst inlineFills = fills.some((fill) => /[\\r\\n]/u.test(fill))\n\t\t? fills.map((fill) => normalizeTemplateMarkdownText(fill))\n\t\t: fills\n\treturn nodes.map((node) => {\n\t\tswitch (node.element) {\n\t\t\tcase 'text':\n\t\t\t\treturn { element: 'text', value: restoreMarkdownText(node.value, pattern, inlineFills) }\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'codeSpan',\n\t\t\t\t\tvalue: normalizeTemplateMarkdownText(\n\t\t\t\t\t\trestoreMarkdownText(node.value, pattern, inlineFills),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\tcase 'break':\n\t\t\t\treturn node\n\t\t\tcase 'emphasis':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'emphasis',\n\t\t\t\t\tstrong: node.strong,\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t\tcase 'link':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'link',\n\t\t\t\t\thref: restoreMarkdownText(node.href, pattern, inlineFills),\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t\tcase 'image':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'image',\n\t\t\t\t\tsrc: restoreMarkdownText(node.src, pattern, inlineFills),\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t}\n\t})\n}\n\n/**\n * Restores sentinel slots inside a parsed block markdown node, keeping\n * verbatim line breaks only inside `CodeBlockNode.code` and sanitizing\n * `CodeBlockNode.lang` to a single token.\n *\n * @param node - Block node parsed from sentinel-substituted markdown\n * @param pattern - RegExp matching sentinel slots\n * @param fills - Indexed dynamic fill strings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The block node with dynamic fills restored as literal leaves\n *\n * @example\n * ```ts\n * import { restoreMarkdownBlock } from '@orkestrel/template'\n *\n * restoreMarkdownBlock({ element: 'thematicBreak' }, /\\uE000\\uE001(\\d+)\\uE003/gu, []) // { element: 'thematicBreak' }\n * ```\n */\nexport function restoreMarkdownBlock(\n\tnode: BlockNode,\n\tpattern: RegExp,\n\tfills: readonly string[],\n\tdepth = 0,\n): BlockNode {\n\tif (depth >= MAX_DEPTH) return node\n\tswitch (node.element) {\n\t\tcase 'thematicBreak':\n\t\t\treturn node\n\t\tcase 'heading':\n\t\t\treturn {\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: node.level,\n\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, fills, depth + 1),\n\t\t\t}\n\t\tcase 'paragraph':\n\t\t\treturn {\n\t\t\t\telement: 'paragraph',\n\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, fills, depth + 1),\n\t\t\t}\n\t\tcase 'codeBlock': {\n\t\t\tconst lang =\n\t\t\t\tnode.lang !== undefined\n\t\t\t\t\t? sanitizeTemplateMarkdownLanguage(restoreMarkdownText(node.lang, pattern, fills))\n\t\t\t\t\t: undefined\n\t\t\treturn {\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(lang !== undefined ? { lang } : {}),\n\t\t\t\tcode: restoreMarkdownText(node.code, pattern, fills),\n\t\t\t}\n\t\t}\n\t\tcase 'blockquote':\n\t\t\treturn {\n\t\t\t\telement: 'blockquote',\n\t\t\t\tchildren: node.children.map((child) =>\n\t\t\t\t\trestoreMarkdownBlock(child, pattern, fills, depth + 1),\n\t\t\t\t),\n\t\t\t}\n\t\tcase 'list':\n\t\t\treturn {\n\t\t\t\telement: 'list',\n\t\t\t\tordered: node.ordered,\n\t\t\t\tstart: node.start,\n\t\t\t\titems: node.items.map((item) => ({\n\t\t\t\t\telement: 'listItem',\n\t\t\t\t\tchildren: item.children.map((child) =>\n\t\t\t\t\t\trestoreMarkdownBlock(child, pattern, fills, depth + 1),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t}\n\t\tcase 'table':\n\t\t\treturn {\n\t\t\t\telement: 'table',\n\t\t\t\theader: node.header.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1)),\n\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\trow.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1)),\n\t\t\t\t),\n\t\t\t\talign: node.align,\n\t\t\t}\n\t}\n}\n\n/**\n * Builds sanitized markdown blocks from a contiguous run of template-authored\n * literal text (`true`) and dynamic scalar fill strings (`false`), keeping\n * dynamic scalars strictly literal leaf text.\n *\n * @param run - Ordered `[literal, text]` entries in the run\n * @param options - Optional HTML sanitization allowlist settings\n * @returns The sanitized block nodes produced from the run\n *\n * @example\n * ```ts\n * import { buildTemplateMarkdownBlocks } from '@orkestrel/template'\n *\n * buildTemplateMarkdownBlocks([[true, '# '], [false, 'Ada']])[0]?.element // 'heading'\n * ```\n */\nexport function buildTemplateMarkdownBlocks(\n\trun: ReadonlyArray<readonly [literal: boolean, text: string]>,\n\toptions?: HTMLSanitizeOptions,\n): readonly BlockNode[] {\n\tconst hasFill = run.some(([literal, text]) => !literal && text.length > 0)\n\tif (!hasFill) {\n\t\tconst parsed = parseMarkdown(run.map(([, text]) => text).join(''))\n\t\tconst clean = sanitizeTemplateMarkdown(parsed, options)\n\t\treturn clean !== undefined && clean.element === 'document' ? clean.children : []\n\t}\n\tconst combined = run.map(([, text]) => text).join('')\n\tconst prefix = resolveMarkdownMarker(combined)\n\tconst fills: string[] = []\n\tconst markedParts: string[] = []\n\tfor (const [literal, text] of run) {\n\t\tif (literal || text.length === 0) {\n\t\t\tmarkedParts.push(text)\n\t\t\tcontinue\n\t\t}\n\t\tconst slot = `${prefix}${fills.length}\\uE003`\n\t\tfills.push(text)\n\t\tmarkedParts.push(slot)\n\t}\n\tconst parsed = parseMarkdown(markedParts.join(''))\n\tconst pattern = new RegExp(`${prefix}(\\\\d+)\\uE003`, 'gu')\n\tconst restored: MarkdownDocument = {\n\t\telement: 'document',\n\t\tchildren: parsed.children.map((block) => restoreMarkdownBlock(block, pattern, fills)),\n\t}\n\tconst clean = sanitizeTemplateMarkdown(restored, options)\n\treturn clean !== undefined && clean.element === 'document' ? clean.children : []\n}\n","import type {\n\tTemplateDocument,\n\tTemplateExpression,\n\tTemplateKeyword,\n\tTemplateNode,\n\tTemplateOperator,\n\tTemplateParameter,\n\tTemplateParseResult,\n\tTemplateSpan,\n\tTemplateToken,\n} from './types.js'\nimport { keyOf } from '@orkestrel/contract'\nimport {\n\tFILL_PATTERN,\n\tTEMPLATE_FILTERS,\n\tTEMPLATE_FUNCTIONS,\n\tTEMPLATE_LITERALS,\n\tTEMPLATE_OPERATOR_FEATURES,\n\tTEMPLATE_TESTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\nimport {\n\tbuildTemplateFormatError,\n\tcheckTemplateClose,\n\tcheckTemplateDepth,\n\tcheckTemplateLoopMember,\n\tcheckTemplateTarget,\n\tcheckTemplateToken,\n\tdecodeTemplateNumber,\n\tdecodeTemplateString,\n\tmatchesTemplateToken,\n\tquoteTemplateText,\n\treadTemplateToken,\n\trenderTemplateToken,\n\tscanTemplateTokens,\n} from './helpers.js'\nimport { isTemplateComparison } from './validators.js'\n\n// Throwing template compilers: full Jinja AST compilation with provenance spans\n// (`compileTemplate`, `compileTemplateProvenance`) plus plain `{{name}}`\n// placeholder compilation (`compilePlainTemplate`).\n\n/**\n * Compiles a Jinja template source string into a {@link TemplateDocument} AST\n * alongside its original-source {@link TemplateSpan} map.\n *\n * @param source - The template's Jinja source string\n * @returns The compiled document and its node-to-span map\n *\n * @example\n * ```ts\n * import { compileTemplateProvenance } from '@orkestrel/template'\n *\n * const [document, spans] = compileTemplateProvenance('Hi {{ name }}')\n * spans.get(document) // { start: 0, end: 13 }\n * ```\n */\nexport function compileTemplateProvenance(source: string): TemplateParseResult {\n\tif (typeof source !== 'string') {\n\t\tthrow new TemplateError('INVALID', 'A template compiles from a string of Jinja source.')\n\t}\n\tconst tokens = scanTemplateTokens(source)\n\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\tconst [children] = compileTemplateStatements(tokens, 0, 0, [], false, spans)\n\tconst document: TemplateDocument = { syntax: 'document', children }\n\tspans.set(document, { start: 0, end: source.length })\n\treturn [document, spans]\n}\n\n/**\n * Compiles a Jinja template source string into a {@link TemplateDocument} AST.\n *\n * @param source - The template's Jinja source string\n * @returns The compiled document AST\n *\n * @example\n * ```ts\n * import { compileTemplate } from '@orkestrel/template'\n *\n * compileTemplate('{{ bos_token }}').children[0] // { syntax: 'output', value: { term: 'name', name: 'bos_token' } }\n * ```\n */\nexport function compileTemplate(source: string): TemplateDocument {\n\treturn compileTemplateProvenance(source)[0]\n}\n\n/**\n * Compiles a plain `{{name}}` placeholder template into a {@link TemplateDocument}\n * AST of `text` and `placeholder` nodes alongside original-source UTF-16 spans.\n *\n * @param source - The plain placeholder template content\n * @returns The compiled document and its node-to-span map\n *\n * @example\n * ```ts\n * import { compilePlainTemplate } from '@orkestrel/template'\n *\n * const [document] = compilePlainTemplate('Hi {{name}}')\n * document.children[1] // { syntax: 'placeholder', name: 'name', raw: '{{name}}' }\n * ```\n */\nexport function compilePlainTemplate(source: string): TemplateParseResult {\n\tif (typeof source !== 'string') {\n\t\tthrow new TemplateError('INVALID', 'A plain template compiles from a string.')\n\t}\n\tconst children: TemplateNode[] = []\n\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst matches = Array.from(source.matchAll(pattern))\n\tlet cursor = 0\n\tlet pendingText = ''\n\tlet pendingStart = 0\n\tfor (let index = 0; index < matches.length; index += 1) {\n\t\tconst match = matches[index]\n\t\tif (match === undefined) break\n\t\tconst matchStart = match.index\n\t\tconst matchText = match[0]\n\t\tconst matchEnd = matchStart + matchText.length\n\t\tconst rawToken = match[1]\n\t\tif (matchStart > cursor) {\n\t\t\tif (pendingText === '') pendingStart = cursor\n\t\t\tpendingText += source.slice(cursor, matchStart)\n\t\t}\n\t\tif (rawToken === undefined) {\n\t\t\tif (pendingText === '') pendingStart = matchStart\n\t\t\tpendingText += '{{'\n\t\t\tcursor = matchEnd\n\t\t\tcontinue\n\t\t}\n\t\tif (pendingText.length > 0) {\n\t\t\tconst textNode: TemplateNode = { syntax: 'text', value: pendingText }\n\t\t\tchildren.push(textNode)\n\t\t\tspans.set(textNode, { start: pendingStart, end: matchStart })\n\t\t\tpendingText = ''\n\t\t}\n\t\tconst placeholderNode: TemplateNode = {\n\t\t\tsyntax: 'placeholder',\n\t\t\tname: rawToken.trim(),\n\t\t\traw: matchText,\n\t\t}\n\t\tchildren.push(placeholderNode)\n\t\tspans.set(placeholderNode, { start: matchStart, end: matchEnd })\n\t\tcursor = matchEnd\n\t}\n\tconst finalText = cursor < source.length ? pendingText + source.slice(cursor) : pendingText\n\tconst finalStart = pendingText === '' ? cursor : pendingStart\n\tif (finalText.length > 0) {\n\t\tconst textNode: TemplateNode = { syntax: 'text', value: finalText }\n\t\tchildren.push(textNode)\n\t\tspans.set(textNode, { start: finalStart, end: source.length })\n\t}\n\tconst document: TemplateDocument = { syntax: 'document', children }\n\tspans.set(document, { start: 0, end: source.length })\n\treturn [document, spans]\n}\n\n/**\n * Compiles a run of Jinja template statements up to end-of-source or one of the\n * closing block tag names in `ends`.\n *\n * @param tokens - The scanned token stream\n * @param start - The starting token index\n * @param depth - Current statement nesting depth\n * @param ends - Block tag names that terminate this statement run\n * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled statements, stopping token index, and maximum subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateStatements, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateStatements(scanTemplateTokens('Hi{% endif %}'), 0, 0, ['endif'], false)[1] // 1\n * ```\n */\nexport function compileTemplateStatements(\n\ttokens: readonly TemplateToken[],\n\tstart: number,\n\tdepth: number,\n\tends: readonly string[],\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statements: readonly TemplateNode[], end: number, height: number] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, start))\n\tconst statements: TemplateNode[] = []\n\tconst heights: number[] = []\n\tlet index = start\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, index)\n\t\tif (token.token === 'end') {\n\t\t\tif (ends.length === 0) break\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`ends before a ${ends.map((name) => `{% ${name} %}`).join(' or ')} tag closes the block`,\n\t\t\t)\n\t\t}\n\t\tif (token.token === 'text') {\n\t\t\tconst node: TemplateNode = { syntax: 'text', value: token.text }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: token.end })\n\t\t\theights.push(0)\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token === 'comment') {\n\t\t\tconst node: TemplateNode = { syntax: 'comment', value: token.text }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: token.end })\n\t\t\theights.push(0)\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token === 'variable') {\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true)\n\t\t\tcheckTemplateDepth(height + 1, token)\n\t\t\tconst after = checkTemplateClose(tokens, next, false)\n\t\t\tconst closeToken = readTemplateToken(tokens, after - 1)\n\t\t\tconst node: TemplateNode = { syntax: 'output', value }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: closeToken.end })\n\t\t\theights.push(height + 1)\n\t\t\tindex = after\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token !== 'block') {\n\t\t\tthrow buildTemplateFormatError(token, `holds ${renderTemplateToken(token)} outside a tag`)\n\t\t}\n\t\tconst name = readTemplateToken(tokens, index + 1)\n\t\tif (name.token === 'name' && ends.includes(name.text)) break\n\t\tconst [statement, next, height] = compileTemplateBlock(tokens, index + 1, depth, loop, spans)\n\t\tconst closeToken = readTemplateToken(tokens, next - 1)\n\t\tspans?.set(statement, { start: token.start, end: closeToken.end })\n\t\tstatements.push(statement)\n\t\theights.push(height)\n\t\tindex = next\n\t}\n\treturn [statements, index, heights.reduce((top, height) => Math.max(top, height), 0)]\n}\n\n/**\n * Compiles one Jinja block tag (`if`, `for`, `set`, `macro`, `break`, or `continue`).\n *\n * @param tokens - The scanned token stream\n * @param index - The index of the tag name token\n * @param depth - Current statement nesting depth\n * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled node, token index after closing delimiter, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateBlock, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateBlock(scanTemplateTokens('{% set turn = 1 %}'), 1, 0, false)[0].syntax // 'set'\n * ```\n */\nexport function compileTemplateBlock(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst name = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, name)\n\tif (name.token !== 'name') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`expects a tag name and finds ${renderTemplateToken(name)}`,\n\t\t)\n\t}\n\tswitch (name.text) {\n\t\tcase 'if':\n\t\t\treturn compileTemplateIf(tokens, index + 1, depth, loop, spans)\n\t\tcase 'for':\n\t\t\treturn compileTemplateFor(tokens, index + 1, depth, spans)\n\t\tcase 'macro':\n\t\t\treturn compileTemplateMacro(tokens, index + 1, depth, spans)\n\t\tcase 'set': {\n\t\t\tconst target = readTemplateToken(tokens, index + 1)\n\t\t\tcheckTemplateTarget(target)\n\t\t\tconst after = readTemplateToken(tokens, index + 2)\n\t\t\tif (matchesTemplateToken(after, 'operator', '.')) {\n\t\t\t\tconst property = readTemplateToken(tokens, index + 3)\n\t\t\t\tcheckTemplateTarget(property)\n\t\t\t\tcheckTemplateToken(tokens, index + 4, 'operator', '=')\n\t\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 5, depth + 1, true)\n\t\t\t\tcheckTemplateDepth(height + 1, name)\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsyntax: 'set',\n\t\t\t\t\t\ttarget: { scope: 'attribute', object: target.text, name: property.text },\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t},\n\t\t\t\t\tcheckTemplateClose(tokens, next, false),\n\t\t\t\t\theight + 1,\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst feature = matchesTemplateToken(after, 'operator', ',')\n\t\t\t\t? 'tuple target'\n\t\t\t\t: matchesTemplateToken(after, 'operator', '=')\n\t\t\t\t\t? target.text === 'loop'\n\t\t\t\t\t\t? 'loop assignment'\n\t\t\t\t\t\t: undefined\n\t\t\t\t\t: 'set block'\n\t\t\tif (feature !== undefined) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\tname,\n\t\t\t\t\t`writes a ${quoteTemplateText(feature)} form of {% set %}, which the subset does not admit`,\n\t\t\t\t\t{ feature },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 3, depth + 1, true)\n\t\t\tcheckTemplateDepth(height + 1, name)\n\t\t\treturn [\n\t\t\t\t{ syntax: 'set', target: { scope: 'local', name: target.text }, value },\n\t\t\t\tcheckTemplateClose(tokens, next, false),\n\t\t\t\theight + 1,\n\t\t\t]\n\t\t}\n\t\tcase 'break':\n\t\tcase 'continue': {\n\t\t\tif (!loop)\n\t\t\t\tthrow buildTemplateFormatError(name, `writes {% ${name.text} %} outside a for loop`)\n\t\t\treturn [\n\t\t\t\t{ syntax: 'control', action: name.text },\n\t\t\t\tcheckTemplateClose(tokens, index + 1, false),\n\t\t\t\t0,\n\t\t\t]\n\t\t}\n\t\tcase 'elif':\n\t\tcase 'else':\n\t\tcase 'endif':\n\t\tcase 'endfor':\n\t\tcase 'endmacro':\n\t\t\tthrow buildTemplateFormatError(name, `writes {% ${name.text} %}, which closes no open block`)\n\t\tdefault:\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`uses the tag ${quoteTemplateText(name.text)}, which the subset does not admit`,\n\t\t\t\t{ feature: name.text },\n\t\t\t)\n\t}\n}\n\n/**\n * Compiles a Jinja `if` / `elif` / `else` / `endif` conditional block.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `if` or `elif`\n * @param depth - Current statement nesting depth\n * @param loop - If `true`, inside a `for` loop; if `false`, outside\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `if` node, token index after `{% endif %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateIf, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateIf(scanTemplateTokens('{% if x %}A{% endif %}'), 2, 0, false)[0].syntax // 'if'\n * ```\n */\nexport function compileTemplateIf(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [condition, next, conditionHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tindex,\n\t\tdepth + 1,\n\t\tfalse,\n\t)\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, next, true),\n\t\tdepth + 1,\n\t\t['elif', 'else', 'endif'],\n\t\tloop,\n\t\tspans,\n\t)\n\tconst branchOpen = readTemplateToken(tokens, end)\n\tconst branch = readTemplateToken(tokens, end + 1)\n\tif (branch.text === 'elif') {\n\t\tconst [alternate, after, alternateHeight] = compileTemplateIf(\n\t\t\ttokens,\n\t\t\tend + 2,\n\t\t\tdepth + 1,\n\t\t\tloop,\n\t\t\tspans,\n\t\t)\n\t\tconst closeToken = readTemplateToken(tokens, after - 1)\n\t\tspans?.set(alternate, { start: branchOpen.start, end: closeToken.end })\n\t\tconst height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\treturn [{ syntax: 'if', condition, body, alternate: [alternate] }, after, height]\n\t}\n\tif (branch.text === 'else') {\n\t\tconst [alternate, close, alternateHeight] = compileTemplateStatements(\n\t\t\ttokens,\n\t\t\tcheckTemplateClose(tokens, end + 2, true),\n\t\t\tdepth + 1,\n\t\t\t['endif'],\n\t\t\tloop,\n\t\t\tspans,\n\t\t)\n\t\tconst height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\treturn [\n\t\t\t{ syntax: 'if', condition, body, alternate },\n\t\t\tcheckTemplateClose(tokens, close + 2, false),\n\t\t\theight,\n\t\t]\n\t}\n\tconst height = 1 + Math.max(conditionHeight, bodyHeight)\n\tcheckTemplateDepth(height, start)\n\treturn [{ syntax: 'if', condition, body }, checkTemplateClose(tokens, end + 2, false), height]\n}\n\n/**\n * Compiles a Jinja `for` loop supporting single targets and multi-target tuple\n * unpacking through `{% endfor %}`.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `for`\n * @param depth - Current statement nesting depth\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `for` node, token index after `{% endfor %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateFor, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateFor(scanTemplateTokens('{% for k, v in d|items %}{% endfor %}'), 2, 0)[0]\n * ```\n */\nexport function compileTemplateFor(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst firstTarget = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, firstTarget)\n\tconst targets: string[] = []\n\tlet position = index\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst target = readTemplateToken(tokens, position)\n\t\tcheckTemplateTarget(target)\n\t\tif (target.text === 'loop') {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttarget,\n\t\t\t\t'names \"loop\" as a for loop\\'s target, which Jinja refuses',\n\t\t\t)\n\t\t}\n\t\tif (targets.includes(target.text)) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttarget,\n\t\t\t\t`duplicates the for loop target ${quoteTemplateText(target.text)}`,\n\t\t\t)\n\t\t}\n\t\ttargets.push(target.text)\n\t\tposition += 1\n\t\tif (!matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ',')) break\n\t\tposition += 1\n\t}\n\tcheckTemplateToken(tokens, position, 'name', 'in')\n\tconst [sequence, next, sequenceHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tposition + 1,\n\t\tdepth + 1,\n\t\tfalse,\n\t)\n\tconst following = readTemplateToken(tokens, next)\n\tconst feature = matchesTemplateToken(following, 'name', 'if')\n\t\t? 'loop filter'\n\t\t: matchesTemplateToken(following, 'name', 'recursive')\n\t\t\t? 'recursive loop'\n\t\t\t: undefined\n\tif (feature !== undefined) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t`writes a ${feature}, which the subset does not admit`,\n\t\t\t{\n\t\t\t\tfeature,\n\t\t\t},\n\t\t)\n\t}\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, next, true),\n\t\tdepth + 1,\n\t\t['endfor', 'else'],\n\t\ttrue,\n\t\tspans,\n\t)\n\tconst branch = readTemplateToken(tokens, end + 1)\n\tif (branch.text === 'else') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tbranch,\n\t\t\t'writes {% else %} on a for loop, which the subset does not admit',\n\t\t\t{ feature: 'for else' },\n\t\t)\n\t}\n\tconst height = 1 + Math.max(sequenceHeight, bodyHeight)\n\tcheckTemplateDepth(height, firstTarget)\n\treturn [\n\t\t{ syntax: 'for', targets, sequence, body },\n\t\tcheckTemplateClose(tokens, end + 2, false),\n\t\theight,\n\t]\n}\n\n/**\n * Compiles a Jinja `{% macro name(a, b=default) %} ... {% endmacro %}` block.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `macro`\n * @param depth - Current statement nesting depth\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `macro` node, token index after `{% endmacro %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateMacro, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateMacro(scanTemplateTokens('{% macro greet(name=\"Ada\") %}{{ name }}{% endmacro %}'), 2, 0)[0].syntax // 'macro'\n * ```\n */\nexport function compileTemplateMacro(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst macroName = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, macroName)\n\tcheckTemplateTarget(macroName)\n\tif (macroName.text === 'loop') {\n\t\tthrow buildTemplateFormatError(macroName, 'names \"loop\" as a macro, which Jinja refuses')\n\t}\n\tcheckTemplateToken(tokens, index + 1, 'operator', '(')\n\tconst parameters: TemplateParameter[] = []\n\tconst heights: number[] = []\n\tlet position = index + 2\n\tlet seenDefault = false\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ')')) break\n\t\tconst later = parameters.length > 0\n\t\tif (later) {\n\t\t\tcheckTemplateToken(tokens, position, 'operator', ',')\n\t\t\tposition += 1\n\t\t}\n\t\tconst head = readTemplateToken(tokens, position)\n\t\tif (later && matchesTemplateToken(head, 'operator', ')')) break\n\t\tif (\n\t\t\tmatchesTemplateToken(head, 'operator', '*') ||\n\t\t\tmatchesTemplateToken(head, 'operator', '**')\n\t\t) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t'writes parameter unpacking in a macro, which the subset does not admit',\n\t\t\t\t{ feature: 'argument unpacking' },\n\t\t\t)\n\t\t}\n\t\tcheckTemplateTarget(head)\n\t\tif (parameters.some((parameter) => parameter.name === head.text)) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t`duplicates the macro parameter ${quoteTemplateText(head.text)}`,\n\t\t\t)\n\t\t}\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position + 1), 'operator', '=')) {\n\t\t\tseenDefault = true\n\t\t\tconst [fallback, next, fallbackHeight] = compileTemplateExpression(\n\t\t\t\ttokens,\n\t\t\t\tposition + 2,\n\t\t\t\tdepth + 1,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t\tparameters.push({ name: head.text, fallback })\n\t\t\theights.push(fallbackHeight)\n\t\t\tposition = next\n\t\t} else {\n\t\t\tif (seenDefault) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\thead,\n\t\t\t\t\t`places non-default parameter ${quoteTemplateText(head.text)} after a default parameter`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tparameters.push({ name: head.text })\n\t\t\tposition += 1\n\t\t}\n\t}\n\tcheckTemplateToken(tokens, position, 'operator', ')')\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, position + 1, true),\n\t\tdepth + 1,\n\t\t['endmacro'],\n\t\tfalse,\n\t\tspans,\n\t)\n\tconst height =\n\t\t1 +\n\t\tMath.max(\n\t\t\tbodyHeight,\n\t\t\theights.reduce((top, value) => Math.max(top, value), 0),\n\t\t)\n\tcheckTemplateDepth(height, macroName)\n\treturn [\n\t\t{ syntax: 'macro', name: macroName.text, parameters, body },\n\t\tcheckTemplateClose(tokens, end + 2, false),\n\t\theight,\n\t]\n}\n\n/**\n * Compiles one Jinja expression (`or` / `and` / `not` / comparisons / tests /\n * arithmetic / postfix / filters), plus inline `if ... else ...` when admitted.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @param conditional - If `true`, admits inline `x if c else y`; if `false`, stops before `if`\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateExpression, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateExpression(scanTemplateTokens(\"{{ 'a' if x else 'b' }}\"), 1, 1, true)[0].term // 'conditional'\n * ```\n */\nexport function compileTemplateExpression(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tconditional: boolean,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [value, next, height] = compileTemplateChain(\n\t\ttokens,\n\t\tindex,\n\t\tdepth,\n\t\t['or'],\n\t\t(inner, at, level) => compileTemplateChain(inner, at, level, ['and'], compileTemplateNegation),\n\t)\n\tconst branch = readTemplateToken(tokens, next)\n\tif (!conditional || !matchesTemplateToken(branch, 'name', 'if')) return [value, next, height]\n\tconst [condition, after, conditionHeight] = compileTemplateChain(\n\t\ttokens,\n\t\tnext + 1,\n\t\tdepth + 1,\n\t\t['or'],\n\t\t(inner, at, level) => compileTemplateChain(inner, at, level, ['and'], compileTemplateNegation),\n\t)\n\tif (!matchesTemplateToken(readTemplateToken(tokens, after), 'name', 'else')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tbranch,\n\t\t\t'writes an inline if without else, which the subset does not admit',\n\t\t\t{ feature: 'conditional without else' },\n\t\t)\n\t}\n\tconst [alternate, end, alternateHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tafter + 1,\n\t\tdepth + 1,\n\t\ttrue,\n\t)\n\tconst total = 1 + Math.max(height, conditionHeight, alternateHeight)\n\tcheckTemplateDepth(total, start)\n\treturn [{ term: 'conditional', condition, consequent: value, alternate }, end, total]\n}\n\n/**\n * Compiles a left-associative binary operator chain at one precedence level.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @param operators - Operators admitted at this precedence level\n * @param operand - Compiler for the next tighter precedence level\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateChain, compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateChain(scanTemplateTokens(\"{{ 'a' ~ 'b' }}\"), 1, 1, ['~'], compileTemplateUnary)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateChain(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\toperators: readonly TemplateOperator[],\n\toperand: (\n\t\ttokens: readonly TemplateToken[],\n\t\tindex: number,\n\t\tdepth: number,\n\t) => readonly [expression: TemplateExpression, end: number, height: number],\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [first, after, firstHeight] = operand(tokens, index, depth)\n\tlet expression = first\n\tlet height = firstHeight\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tconst operator = operators.find(\n\t\t\t(candidate) =>\n\t\t\t\t(token.token === 'name' || token.token === 'operator') && token.text === candidate,\n\t\t)\n\t\tif (operator === undefined) break\n\t\tconst [right, next, rightHeight] = operand(tokens, position + 1, depth + 1)\n\t\texpression = { term: 'binary', operator, left: expression, right }\n\t\theight = 1 + Math.max(height, rightHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\tposition = next\n\t}\n\treturn [expression, position, height]\n}\n\n/**\n * Compiles logical `not` negation over comparisons.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateNegation, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateNegation(scanTemplateTokens('{{ not x }}'), 1, 1)[0].term // 'unary'\n * ```\n */\nexport function compileTemplateNegation(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst token = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, token)\n\tif (!matchesTemplateToken(token, 'name', 'not')) {\n\t\treturn compileTemplateComparison(tokens, index, depth)\n\t}\n\tconst [value, next, height] = compileTemplateNegation(tokens, index + 1, depth + 1)\n\tcheckTemplateDepth(height + 1, token)\n\treturn [{ term: 'unary', operator: 'not', value }, next, height + 1]\n}\n\n/**\n * Compiles chained Python-style comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`,\n * `in`, `not in`) over test expressions.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateComparison, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateComparison(scanTemplateTokens(\"{{ role not in 'system' }}\"), 1, 1)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateComparison(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [first, after, firstHeight] = compileTemplateTest(tokens, index, depth)\n\tconst links: Array<\n\t\treadonly [operator: TemplateOperator, operand: TemplateExpression, height: number]\n\t> = []\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tconst negated =\n\t\t\tmatchesTemplateToken(token, 'name', 'not') &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, position + 1), 'name', 'in')\n\t\tconst operator: TemplateOperator | undefined =\n\t\t\ttoken.token === 'operator' && isTemplateComparison(token.text)\n\t\t\t\t? token.text\n\t\t\t\t: matchesTemplateToken(token, 'name', 'in')\n\t\t\t\t\t? 'in'\n\t\t\t\t\t: negated\n\t\t\t\t\t\t? 'not in'\n\t\t\t\t\t\t: undefined\n\t\tif (operator === undefined) break\n\t\tconst [operand, next, height] = compileTemplateTest(\n\t\t\ttokens,\n\t\t\tposition + (negated ? 2 : 1),\n\t\t\tdepth + 1,\n\t\t)\n\t\tlinks.push([operator, operand, height])\n\t\tposition = next\n\t}\n\tconst pairs = links.map(\n\t\t([operator, operand, height], link): readonly [TemplateExpression, number] => {\n\t\t\tconst left = links[link - 1]\n\t\t\treturn [\n\t\t\t\t{ term: 'binary', operator, left: left?.[1] ?? first, right: operand },\n\t\t\t\t1 + Math.max(left?.[2] ?? firstHeight, height),\n\t\t\t]\n\t\t},\n\t)\n\tconst [joined, joinedHeight] = pairs\n\t\t.slice(1)\n\t\t.reduce(\n\t\t\t(left, right): readonly [TemplateExpression, number] => [\n\t\t\t\t{ term: 'binary', operator: 'and', left: left[0], right: right[0] },\n\t\t\t\t1 + Math.max(left[1], right[1]),\n\t\t\t],\n\t\t\tpairs[0] ?? [first, firstHeight],\n\t\t)\n\tcheckTemplateDepth(joinedHeight, start)\n\treturn [joined, position, joinedHeight]\n}\n\n/**\n * Compiles an additive expression optionally followed by a Jinja `is` or\n * `is not` test (`defined`, `undefined`, `none`, `string`, `mapping`,\n * `iterable`, `sequence`, `true`, `false`).\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateTest, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateTest(scanTemplateTokens('{{ x is not mapping }}'), 1, 1)[0].term // 'test'\n * ```\n */\nexport function compileTemplateTest(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [value, next, valueHeight] = compileTemplateSum(tokens, index, depth)\n\tconst marker = readTemplateToken(tokens, next)\n\tif (!matchesTemplateToken(marker, 'name', 'is')) return [value, next, valueHeight]\n\tconst negated = matchesTemplateToken(readTemplateToken(tokens, next + 1), 'name', 'not')\n\tconst at = next + (negated ? 2 : 1)\n\tconst name = readTemplateToken(tokens, at)\n\tif (name.token !== 'name') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`expects a test name and finds ${renderTemplateToken(name)}`,\n\t\t)\n\t}\n\tconst dotted = matchesTemplateToken(readTemplateToken(tokens, at + 1), 'operator', '.')\n\tif (dotted || !TEMPLATE_TESTS.some((admitted) => admitted === name.text)) {\n\t\tconst spelled = dotted ? `${name.text}.${readTemplateToken(tokens, at + 2).text}` : name.text\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`uses the test ${quoteTemplateText(spelled)}, which the subset does not admit`,\n\t\t\t{ feature: spelled },\n\t\t)\n\t}\n\tconst following = readTemplateToken(tokens, at + 1)\n\tconst empty =\n\t\tmatchesTemplateToken(following, 'operator', '(') &&\n\t\tmatchesTemplateToken(readTemplateToken(tokens, at + 2), 'operator', ')')\n\tconst argued =\n\t\t!empty &&\n\t\t(matchesTemplateToken(following, 'operator', '(') ||\n\t\t\tmatchesTemplateToken(following, 'operator', '[') ||\n\t\t\tmatchesTemplateToken(following, 'operator', '{') ||\n\t\t\t['string', 'integer', 'float'].includes(following.token) ||\n\t\t\t(following.token === 'name' && !['else', 'or', 'and', 'in', 'not'].includes(following.text)))\n\tif (matchesTemplateToken(following, 'name', 'is')) {\n\t\tthrow buildTemplateFormatError(following, 'chains two tests with \"is\", which Jinja refuses')\n\t}\n\tif (argued) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t'passes test arguments, which the subset does not admit',\n\t\t\t{ feature: 'test arguments' },\n\t\t)\n\t}\n\tconst cursor = at + (empty ? 3 : 1)\n\tif (matchesTemplateToken(readTemplateToken(tokens, cursor), 'name', 'is')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\treadTemplateToken(tokens, cursor),\n\t\t\t'chains two tests with \"is\", which Jinja refuses',\n\t\t)\n\t}\n\tconst height = valueHeight + 1\n\tcheckTemplateDepth(height, start)\n\treturn [{ term: 'test', name: name.text, value, negated }, cursor, height]\n}\n\n/**\n * Compiles a left-associative `+` / `-` chain over `~` concatenations.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateSum, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateSum(scanTemplateTokens('{{ n - 1 }}'), 1, 1)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateSum(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\treturn compileTemplateChain(tokens, index, depth, ['+', '-'], (inner, at, level) =>\n\t\tcompileTemplateChain(inner, at, level, ['~'], compileTemplateUnary),\n\t)\n}\n\n/**\n * Compiles unary `-`/`+`, primaries, member reads, sequence slices, function\n * and string method calls, and `|` filter chains.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateUnary(scanTemplateTokens('{{ messages[::-1] }}'), 1, 1)[0].term // 'slice'\n * ```\n */\nexport function compileTemplateUnary(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tif (\n\t\tmatchesTemplateToken(start, 'operator', '-') ||\n\t\tmatchesTemplateToken(start, 'operator', '+')\n\t) {\n\t\tconst operator: '-' | '+' = start.text === '-' ? '-' : '+'\n\t\tconst [value, next, height] = compileTemplateUnary(tokens, index + 1, depth + 1)\n\t\tcheckTemplateDepth(height + 1, start)\n\t\treturn [{ term: 'unary', operator, value }, next, height + 1]\n\t}\n\tconst [primary, after, primaryHeight] = compileTemplatePrimary(tokens, index, depth)\n\tlet expression = primary\n\tlet height = primaryHeight\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tif (matchesTemplateToken(token, 'operator', '.')) {\n\t\t\tconst name = readTemplateToken(tokens, position + 1)\n\t\t\tif (name.token !== 'name' && name.token !== 'integer') {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\tname,\n\t\t\t\t\t`expects a name or an integer after \".\" and finds ${renderTemplateToken(name)}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst key: TemplateExpression = {\n\t\t\t\tterm: 'literal',\n\t\t\t\tvalue: name.token === 'name' ? name.text : decodeTemplateNumber(name),\n\t\t\t}\n\t\t\tcheckTemplateLoopMember(expression, key, name)\n\t\t\texpression = { term: 'member', object: expression, key }\n\t\t\theight = 1 + Math.max(height, 0)\n\t\t\tposition += 2\n\t\t} else if (matchesTemplateToken(token, 'operator', '[')) {\n\t\t\tconst [subscripted, next, subscriptHeight] = compileTemplateSubscript(\n\t\t\t\ttokens,\n\t\t\t\tposition,\n\t\t\t\tdepth + 1,\n\t\t\t\texpression,\n\t\t\t)\n\t\t\texpression = subscripted\n\t\t\theight = 1 + Math.max(height, subscriptHeight)\n\t\t\tposition = next\n\t\t} else if (matchesTemplateToken(token, 'operator', '(')) {\n\t\t\tif (expression.term !== 'name' && expression.term !== 'member') {\n\t\t\t\tthrow buildTemplateFormatError(token, 'writes a call, which the subset does not admit', {\n\t\t\t\t\tfeature: 'call',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [values, keywords, next, valuesHeight] = compileTemplateArguments(\n\t\t\t\ttokens,\n\t\t\t\tposition,\n\t\t\t\tdepth + 1,\n\t\t\t)\n\t\t\texpression = { term: 'call', callee: expression, values, keywords }\n\t\t\theight = 1 + Math.max(height, valuesHeight)\n\t\t\tposition = next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\tcheckTemplateDepth(height, start)\n\t}\n\tlet filtered = expression\n\tlet filteredHeight = height\n\tlet cursor = position\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, cursor)\n\t\tif (!matchesTemplateToken(token, 'operator', '|')) {\n\t\t\tif (matchesTemplateToken(token, 'operator', '(')) {\n\t\t\t\tthrow buildTemplateFormatError(token, 'calls a filter, which the subset does not admit', {\n\t\t\t\t\tfeature: 'call',\n\t\t\t\t})\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tconst name = readTemplateToken(tokens, cursor + 1)\n\t\tif (name.token !== 'name') {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`expects a filter name and finds ${renderTemplateToken(name)}`,\n\t\t\t)\n\t\t}\n\t\tconst dotted = matchesTemplateToken(readTemplateToken(tokens, cursor + 2), 'operator', '.')\n\t\tif (dotted || !TEMPLATE_FILTERS.some((admitted) => admitted === name.text)) {\n\t\t\tconst spelled = dotted\n\t\t\t\t? `${name.text}.${readTemplateToken(tokens, cursor + 3).text}`\n\t\t\t\t: name.text\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`uses the filter ${quoteTemplateText(spelled)}, which the subset does not admit`,\n\t\t\t\t{ feature: spelled },\n\t\t\t)\n\t\t}\n\t\tconst following = readTemplateToken(tokens, cursor + 2)\n\t\tconst empty =\n\t\t\tmatchesTemplateToken(following, 'operator', '(') &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, cursor + 3), 'operator', ')')\n\t\tif (!empty && matchesTemplateToken(following, 'operator', '(')) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tfollowing,\n\t\t\t\t'passes filter arguments, which the subset does not admit',\n\t\t\t\t{ feature: 'filter arguments' },\n\t\t\t)\n\t\t}\n\t\tfiltered = { term: 'filter', name: name.text, value: filtered }\n\t\tfilteredHeight += 1\n\t\tcursor = cursor + (empty ? 4 : 2)\n\t\tcheckTemplateDepth(filteredHeight, start)\n\t}\n\tconst following = readTemplateToken(tokens, cursor)\n\tconst arithmetic =\n\t\tfollowing.token === 'operator' && keyOf(TEMPLATE_OPERATOR_FEATURES)(following.text)\n\t\t\t? TEMPLATE_OPERATOR_FEATURES[following.text]\n\t\t\t: undefined\n\tif (arithmetic !== undefined) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t`writes ${arithmetic}, which the subset does not admit`,\n\t\t\t{ feature: arithmetic },\n\t\t)\n\t}\n\treturn [filtered, cursor, filteredHeight]\n}\n\n/**\n * Compiles one primary template expression: a literal, name, adjacent string\n * concatenation, or parenthesized sub-expression.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the primary\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplatePrimary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplatePrimary(scanTemplateTokens(\"{{ 'a' 'b' }}\"), 1, 1)[0] // { term: 'literal', value: 'ab' }\n * ```\n */\nexport function compileTemplatePrimary(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst token = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, token)\n\tswitch (token.token) {\n\t\tcase 'name': {\n\t\t\tif (keyOf(TEMPLATE_LITERALS)(token.text)) {\n\t\t\t\treturn [{ term: 'literal', value: TEMPLATE_LITERALS[token.text] }, index + 1, 0]\n\t\t\t}\n\t\t\tconst called =\n\t\t\t\t(token.text === 'raise_exception' || token.text === 'namespace') &&\n\t\t\t\tmatchesTemplateToken(readTemplateToken(tokens, index + 1), 'operator', '(')\n\t\t\tif (!called && TEMPLATE_FUNCTIONS.some((name) => name === token.text)) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`uses the function ${quoteTemplateText(token.text)}, which the subset does not admit`,\n\t\t\t\t\t{ feature: token.text },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [{ term: 'name', name: token.text }, index + 1, 0]\n\t\t}\n\t\tcase 'string': {\n\t\t\tconst parts: string[] = []\n\t\t\tlet position = index\n\t\t\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\t\t\tconst part = readTemplateToken(tokens, position)\n\t\t\t\tif (part.token !== 'string') break\n\t\t\t\tparts.push(decodeTemplateString(part))\n\t\t\t\tposition += 1\n\t\t\t}\n\t\t\treturn [{ term: 'literal', value: parts.join('') }, position, 0]\n\t\t}\n\t\tcase 'integer':\n\t\tcase 'float':\n\t\t\treturn [{ term: 'literal', value: decodeTemplateNumber(token) }, index + 1, 0]\n\t\tcase 'operator': {\n\t\t\tif (token.text === '(') {\n\t\t\t\tif (matchesTemplateToken(readTemplateToken(tokens, index + 1), 'operator', ')')) {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t'writes an empty tuple, which the subset does not admit',\n\t\t\t\t\t\t{ feature: 'tuple' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst [inner, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true)\n\t\t\t\tif (matchesTemplateToken(readTemplateToken(tokens, next), 'operator', ',')) {\n\t\t\t\t\tthrow buildTemplateFormatError(token, 'writes a tuple, which the subset does not admit', {\n\t\t\t\t\t\tfeature: 'tuple',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcheckTemplateToken(tokens, next, 'operator', ')')\n\t\t\t\treturn [inner, next + 1, height]\n\t\t\t}\n\t\t\tif (token.text === '[' || token.text === '{') {\n\t\t\t\tconst feature = token.text === '[' ? 'list literal' : 'dict literal'\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`writes a ${feature}, which the subset does not admit`,\n\t\t\t\t\t{\n\t\t\t\t\t\tfeature,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`expects a value and finds ${renderTemplateToken(token)}`,\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`expects a value and finds ${renderTemplateToken(token)}`,\n\t\t\t)\n\t}\n}\n\n/**\n * Compiles positional and named keyword arguments of a call from `(` through `)`.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the opening `(`\n * @param depth - Current expression depth\n * @returns Positional arguments, keyword arguments, next token index, and max height\n *\n * @example\n * ```ts\n * import { compileTemplateArguments, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateArguments(scanTemplateTokens('{{ namespace(value=0) }}'), 2, 1)[1][0]?.name // 'value'\n * ```\n */\nexport function compileTemplateArguments(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [\n\tvalues: readonly TemplateExpression[],\n\tkeywords: readonly TemplateKeyword[],\n\tend: number,\n\theight: number,\n] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, index))\n\tcheckTemplateToken(tokens, index, 'operator', '(')\n\tconst values: TemplateExpression[] = []\n\tconst keywords: TemplateKeyword[] = []\n\tconst heights: number[] = []\n\tlet position = index + 1\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ')')) break\n\t\tconst later = position > index + 1\n\t\tif (later) checkTemplateToken(tokens, position, 'operator', ',')\n\t\tconst at = later ? position + 1 : position\n\t\tconst head = readTemplateToken(tokens, at)\n\t\tif (later && matchesTemplateToken(head, 'operator', ')')) {\n\t\t\tposition = at\n\t\t\tbreak\n\t\t}\n\t\tif (\n\t\t\tmatchesTemplateToken(head, 'operator', '*') ||\n\t\t\tmatchesTemplateToken(head, 'operator', '**')\n\t\t) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t'passes argument unpacking, which the subset does not admit',\n\t\t\t\t{ feature: 'argument unpacking' },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\thead.token === 'name' &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, at + 1), 'operator', '=')\n\t\t) {\n\t\t\tif (keywords.some((keyword) => keyword.name === head.text)) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\thead,\n\t\t\t\t\t`duplicates the keyword argument ${quoteTemplateText(head.text)}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, at + 2, depth + 1, true)\n\t\t\tkeywords.push({ name: head.text, value })\n\t\t\theights.push(height)\n\t\t\tposition = next\n\t\t\tcontinue\n\t\t}\n\t\tif (keywords.length > 0) {\n\t\t\tthrow buildTemplateFormatError(head, 'places a positional argument after a keyword argument')\n\t\t}\n\t\tconst [value, next, height] = compileTemplateExpression(tokens, at, depth + 1, true)\n\t\tvalues.push(value)\n\t\theights.push(height)\n\t\tposition = next\n\t}\n\tcheckTemplateToken(tokens, position, 'operator', ')')\n\treturn [values, keywords, position + 1, heights.reduce((top, height) => Math.max(top, height), 0)]\n}\n\n/**\n * Compiles one `[key]` member lookup or `[start:stop:step]` slice subscript\n * starting at `[` and ending after `]`.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the opening `[`\n * @param depth - Current expression depth\n * @param object - The target expression being indexed or sliced\n * @returns The compiled member or slice expression, next token index, and argument height\n *\n * @example\n * ```ts\n * import { compileTemplateSubscript, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateSubscript(scanTemplateTokens('{{ a[::-1] }}'), 2, 1, { term: 'name', name: 'a' })[0].term // 'slice'\n * ```\n */\nexport function compileTemplateSubscript(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tobject: TemplateExpression,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, index))\n\tconst first = readTemplateToken(tokens, index + 1)\n\tif (matchesTemplateToken(first, 'operator', ']')) {\n\t\tthrow buildTemplateFormatError(first, 'writes an empty subscript')\n\t}\n\tconst [sliceStart, afterStart, startHeight] = matchesTemplateToken(first, 'operator', ':')\n\t\t? ([undefined, index + 1, 0] as const)\n\t\t: compileTemplateExpression(tokens, index + 1, depth, true)\n\tconst separator = readTemplateToken(tokens, afterStart)\n\tif (matchesTemplateToken(separator, 'operator', ',')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tseparator,\n\t\t\t'writes a tuple subscript, which the subset does not admit',\n\t\t\t{ feature: 'tuple' },\n\t\t)\n\t}\n\tif (!matchesTemplateToken(separator, 'operator', ':')) {\n\t\tcheckTemplateToken(tokens, afterStart, 'operator', ']')\n\t\tif (sliceStart === undefined) {\n\t\t\tthrow buildTemplateFormatError(first, 'writes an empty subscript')\n\t\t}\n\t\tcheckTemplateLoopMember(object, sliceStart, first)\n\t\treturn [{ term: 'member', object, key: sliceStart }, afterStart + 1, startHeight]\n\t}\n\tconst stopToken = readTemplateToken(tokens, afterStart + 1)\n\tconst [sliceStop, afterStop, stopHeight] =\n\t\tmatchesTemplateToken(stopToken, 'operator', ':') ||\n\t\tmatchesTemplateToken(stopToken, 'operator', ']')\n\t\t\t? ([undefined, afterStart + 1, 0] as const)\n\t\t\t: compileTemplateExpression(tokens, afterStart + 1, depth, true)\n\tconst hasStepColon = matchesTemplateToken(readTemplateToken(tokens, afterStop), 'operator', ':')\n\tconst stepToken = hasStepColon ? readTemplateToken(tokens, afterStop + 1) : undefined\n\tconst [sliceStep, afterStep, stepHeight] =\n\t\t!hasStepColon || (stepToken !== undefined && matchesTemplateToken(stepToken, 'operator', ']'))\n\t\t\t? ([undefined, hasStepColon ? afterStop + 1 : afterStop, 0] as const)\n\t\t\t: compileTemplateExpression(tokens, afterStop + 1, depth, true)\n\tcheckTemplateToken(tokens, afterStep, 'operator', ']')\n\treturn [\n\t\t{\n\t\t\tterm: 'slice',\n\t\t\tobject,\n\t\t\t...(sliceStart !== undefined ? { start: sliceStart } : {}),\n\t\t\t...(sliceStop !== undefined ? { stop: sliceStop } : {}),\n\t\t\t...(sliceStep !== undefined ? { step: sliceStep } : {}),\n\t\t},\n\t\tafterStep + 1,\n\t\tMath.max(startHeight, stopHeight, stepHeight),\n\t]\n}\n","import type { TemplateDocument } from './types.js'\nimport { attempt, isString } from '@orkestrel/contract'\nimport { compileTemplate } from './compilers.js'\nimport { isTemplateDocument } from './validators.js'\n\n// Total, non-throwing coercers for template sources and AST documents.\n\n/**\n * Parses an unknown input into a {@link TemplateDocument}, returning `undefined`\n * on malformed syntax, unadmitted constructs, exceeded depth, or off-shape input\n * without throwing.\n *\n * @param source - A Jinja template string or an already-built {@link TemplateDocument}\n * @returns A validated {@link TemplateDocument}, or `undefined` when invalid\n *\n * @example\n * ```ts\n * import { parseTemplate } from '@orkestrel/template'\n *\n * parseTemplate('Hi {{ name }}')?.syntax // 'document'\n * parseTemplate('{% if unclosed %}') // undefined\n * ```\n */\nexport function parseTemplate(source: unknown): TemplateDocument | undefined {\n\tif (isTemplateDocument(source)) return source\n\tif (!isString(source)) return undefined\n\tconst outcome = attempt(() => compileTemplate(source))\n\treturn outcome.success ? outcome.value : undefined\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport type { HTMLDocument, HTMLNode, HTMLSanitizeOptions } from '@orkestrel/html'\nimport type { BlockNode, MarkdownDocument, MarkdownNode } from '@orkestrel/markdown'\nimport type {\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateFillValues,\n\tTemplateHTMLOptions,\n\tTemplatePlaceholder,\n} from './types.js'\nimport { isArray, isString, objectShape, optionalShape, stringShape } from '@orkestrel/contract'\nimport { HTML, isHTMLDocument, isHTMLNode, mergeText } from '@orkestrel/html'\nimport { htmlToMarkdown, isBlockNode, isInlineNode, markdownToHTML } from '@orkestrel/markdown'\nimport { compileTemplate } from './compilers.js'\nimport { TemplateError } from './errors.js'\nimport {\n\tbuildTemplateMarkdownBlocks,\n\tevaluateTaggedTemplateParts,\n\tevaluateTemplateParts,\n\tsanitizeTemplateMarkdown,\n} from './helpers.js'\nimport { isTemplateDocument } from './validators.js'\n\n// The templates shape and projection inventory — layers over `helpers.ts` and\n// `validators.ts`, so constructing `@orkestrel/html`'s `HTML` sanitizer here\n// keeps the leaf pair strictly class-free.\n\n/**\n * Builds the `@orkestrel/contract` object shape describing a template's\n * declared placeholders.\n *\n * @remarks\n * Each placeholder becomes a `stringShape` carrying its `description`;\n * `required === false` wraps it in `optionalShape`. Used by `Template` to\n * compile its `parameters()` contract once per instance.\n *\n * @param placeholders - The declared placeholders to shape\n * @returns The contract shape for `createContract`\n *\n * @example\n * ```ts\n * import { placeholderShape } from '@orkestrel/template'\n * import { createContract } from '@orkestrel/contract'\n *\n * const contract = createContract(placeholderShape([{ name: 'city' }]))\n * ```\n */\nexport function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape {\n\tconst properties: Record<string, ContractShape> = {}\n\tfor (const placeholder of placeholders) {\n\t\tconst description = placeholder.description\n\t\tconst field = stringShape({\n\t\t\t...(description !== undefined ? { description } : {}),\n\t\t})\n\t\tproperties[placeholder.name] = placeholder.required === false ? optionalShape(field) : field\n\t}\n\treturn objectShape(properties)\n}\n\n/**\n * Normalizes an `@orkestrel/html` node into a document and enforces\n * `@orkestrel/html`'s unlowerable sanitize floor, failing closed to an empty\n * document on off-shape input.\n *\n * @param node - The HTML document or node to sanitize\n * @param options - Optional allowlist overrides (cannot lower `@orkestrel/html`'s security floor)\n * @returns The sanitized {@link HTMLDocument}\n *\n * @example\n * ```ts\n * import { sanitizeTemplateHTML } from '@orkestrel/template'\n *\n * sanitizeTemplateHTML({ category: 'element', name: 'script', attributes: [], children: [] }).children // []\n * ```\n */\nexport function sanitizeTemplateHTML(node: HTMLNode, options?: HTMLSanitizeOptions): HTMLDocument {\n\tconst document: HTMLDocument =\n\t\tnode.category === 'document' ? node : { category: 'document', children: [node] }\n\tif (!isHTMLDocument(document)) return { category: 'document', children: [] }\n\treturn new HTML(document).sanitize(options).document\n}\n\n/**\n * Projects a compiled template document or Jinja source into a sanitized\n * {@link HTMLDocument}.\n *\n * @remarks\n * Plain string template text and interpolated scalar values always become safe\n * `TextNode` leaves rather than raw HTML markup, eliminating XSS from fill\n * strings. Embedded `HTMLNode` leaves and fill values pass through\n * `sanitizeTemplateHTML`, and embedded `MarkdownNode` leaves and fill values\n * project through `markdownToHTML` then `sanitizeTemplateHTML`.\n *\n * @param source - A compiled {@link TemplateDocument} or Jinja source string\n * @param values - Optional runtime values record\n * @param options - Optional evaluation and HTML sanitization settings\n * @returns A sanitized {@link HTMLDocument}\n *\n * @example\n * ```ts\n * import { templateToHTML } from '@orkestrel/template'\n *\n * templateToHTML('Hi {{ name }}', { name: '<b>Ada</b>' }).children\n * // [{ category: 'text', value: 'Hi <b>Ada</b>' }]\n * ```\n */\nexport function templateToHTML(\n\tsource: TemplateDocument | string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateHTMLOptions,\n): HTMLDocument {\n\tconst document = isString(source) ? compileTemplate(source) : source\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError(\n\t\t\t'INVALID',\n\t\t\t'templateToHTML requires a valid TemplateDocument or source string.',\n\t\t)\n\t}\n\tconst parts = evaluateTemplateParts(document, values, options)\n\tconst children: HTMLNode[] = []\n\tfor (const part of parts) {\n\t\tif (typeof part === 'string') {\n\t\t\tif (part.length > 0) children.push({ category: 'text', value: part })\n\t\t\tcontinue\n\t\t}\n\t\tif (isHTMLNode(part)) {\n\t\t\tconst clean = sanitizeTemplateHTML(part, options?.sanitize)\n\t\t\tfor (const child of clean.children) children.push(child)\n\t\t\tcontinue\n\t\t}\n\t\tconst projected = markdownToHTML(part)\n\t\tconst clean = sanitizeTemplateHTML(projected, options?.sanitize)\n\t\tfor (const child of clean.children) children.push(child)\n\t}\n\treturn { category: 'document', children: mergeText(children) }\n}\n\n/**\n * Projects a compiled template document or Jinja source into a canonical\n * {@link MarkdownDocument}.\n *\n * @remarks\n * Template-authored literal text parses through `parseMarkdown`, while dynamic\n * scalar fill values stay literal leaves and are never parsed as Markdown\n * syntax. Inline dynamic fills and `CodeSpanNode` values collapse line breaks\n * (`\\r\\n`, `\\r`, `\\n`) to single spaces so round-tripping through\n * `renderMarkdown` and `parseMarkdown` never splits headings, table rows,\n * code spans, or paragraphs; `CodeBlockNode.lang` sanitizes to a single token\n * free of whitespace, backticks, and tildes; and `CodeBlockNode.code` preserves\n * line breaks verbatim inside dynamically sized fences. Embedded `HTMLNode`\n * values sanitize through `sanitizeTemplateHTML`, project through\n * `htmlToMarkdown`, and sanitize URL schemes; embedded `MarkdownNode` values\n * sanitize URL schemes by unwrapping unsafe `LinkNode` elements and dropping\n * unsafe `ImageNode` elements. `@orkestrel/markdown` has no raw-HTML AST node\n * and emits `TextRun` text verbatim in `renderMarkdown`, so callers targeting a\n * third-party raw-HTML Markdown renderer must use `templateToHTML` or sanitize\n * at that HTML boundary.\n *\n * @param source - A compiled {@link TemplateDocument} or Jinja source string\n * @param values - Optional runtime values record\n * @param options - Optional evaluation and HTML sanitization settings\n * @returns A {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * import { templateToMarkdown } from '@orkestrel/template'\n *\n * templateToMarkdown('# Hello {{ name }}', { name: 'Ada' }).children[0]?.element // 'heading'\n * ```\n */\nexport function templateToMarkdown(\n\tsource: TemplateDocument | string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): MarkdownDocument {\n\tconst document = isString(source) ? compileTemplate(source) : source\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError(\n\t\t\t'INVALID',\n\t\t\t'templateToMarkdown requires a valid TemplateDocument or source string.',\n\t\t)\n\t}\n\tconst parts = evaluateTaggedTemplateParts(document, values, options)\n\tconst grouped = parts.reduce<\n\t\tArray<ReadonlyArray<readonly [literal: boolean, text: string]> | HTMLNode | MarkdownNode>\n\t>((runs, [literal, part]) => {\n\t\tif (typeof part !== 'string') return [...runs, part]\n\t\tconst previous = runs.at(-1)\n\t\tif (isArray(previous)) {\n\t\t\tconst entry: readonly [boolean, string] = [literal, part]\n\t\t\treturn [...runs.slice(0, -1), [...previous, entry]]\n\t\t}\n\t\treturn [...runs, [[literal, part]]]\n\t}, [])\n\tconst blocks: BlockNode[] = []\n\tfor (const part of grouped) {\n\t\tif (isArray(part)) {\n\t\t\tfor (const block of buildTemplateMarkdownBlocks(part, options?.sanitize)) blocks.push(block)\n\t\t\tcontinue\n\t\t}\n\t\tif (isHTMLNode(part)) {\n\t\t\tconst clean = sanitizeTemplateHTML(part, options?.sanitize)\n\t\t\tconst projected = htmlToMarkdown(clean)\n\t\t\tconst sanitized = sanitizeTemplateMarkdown(projected, options?.sanitize)\n\t\t\tif (sanitized !== undefined && sanitized.element === 'document') {\n\t\t\t\tfor (const block of sanitized.children) blocks.push(block)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst sanitized = sanitizeTemplateMarkdown(part, options?.sanitize)\n\t\tif (sanitized === undefined) continue\n\t\tif (sanitized.element === 'document' || sanitized.element === 'listItem') {\n\t\t\tfor (const block of sanitized.children) blocks.push(block)\n\t\t} else if (isBlockNode(sanitized)) {\n\t\t\tblocks.push(sanitized)\n\t\t} else if (isInlineNode(sanitized)) {\n\t\t\tblocks.push({ element: 'paragraph', children: [sanitized] })\n\t\t}\n\t}\n\treturn { element: 'document', children: blocks }\n}\n","import type {\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateFillValues,\n\tTemplateHandlerMap,\n\tTemplateNode,\n\tTemplateRewriteHandler,\n\tTemplateSpan,\n\tTemplateTreeInterface,\n\tTemplateTreeOptions,\n} from '../types.js'\nimport { isMap, isObject, isString } from '@orkestrel/contract'\nimport { compileTemplateProvenance } from '../compilers.js'\nimport { TemplateError } from '../errors.js'\nimport {\n\tevaluateTemplate,\n\tfoldTemplateDocument,\n\tmapTemplateDocument,\n\trenderTemplate,\n\tstreamTemplateNodes,\n\twalkTemplateNodes,\n} from '../helpers.js'\nimport { isTemplateDocument, isTemplateNode, isTemplateSpan } from '../validators.js'\n\n/**\n * Wraps a compiled {@link TemplateDocument} AST as an immutable handle\n * exposing provenance lookup, depth-first traversal, queries, copy-on-write\n * rewrites, total folds, shallow streaming, evaluation, and canonical source\n * rendering.\n *\n * @remarks\n * Construct with `{ source }` to compile Jinja source with original UTF-16\n * provenance spans, or `{ document, spans? }` to adopt an existing validated\n * {@link TemplateDocument}. Every query and rewrite preserves immutability.\n *\n * @example\n * ```ts\n * import { TemplateTree } from '@orkestrel/template'\n *\n * const tree = new TemplateTree({ source: 'Hi {{ name }}' })\n * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateTree implements TemplateTreeInterface {\n\treadonly #document: TemplateDocument\n\treadonly #spans: Map<TemplateNode, TemplateSpan>\n\n\tconstructor(options: TemplateTreeOptions) {\n\t\tconst given: unknown = options\n\t\tif (!isObject(given)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree requires an options object.')\n\t\t}\n\t\tif ('source' in given) {\n\t\t\tconst source: unknown = Reflect.get(given, 'source')\n\t\t\tif (!isString(source)) {\n\t\t\t\tthrow new TemplateError('INVALID', 'TemplateTree source must be a string.')\n\t\t\t}\n\t\t\tconst [document, spans] = compileTemplateProvenance(source)\n\t\t\tthis.#document = document\n\t\t\tthis.#spans = new Map(spans)\n\t\t\treturn\n\t\t}\n\t\tconst document: unknown = Reflect.get(given, 'document')\n\t\tif (!isTemplateDocument(document)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree document must be a valid TemplateDocument.')\n\t\t}\n\t\tconst spans: unknown = Reflect.get(given, 'spans')\n\t\tif (spans !== undefined && !isMap(spans)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree spans must be a Map when provided.')\n\t\t}\n\t\tthis.#document = document\n\t\tconst copied = new Map<TemplateNode, TemplateSpan>()\n\t\tif (spans !== undefined) {\n\t\t\tfor (const [node, span] of spans.entries()) {\n\t\t\t\tif (isTemplateNode(node) && isTemplateSpan(span)) {\n\t\t\t\t\tcopied.set(node, { start: span.start, end: span.end })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.#spans = copied\n\t}\n\n\t/** Exposes the stored {@link TemplateDocument} AST root. */\n\tget document(): TemplateDocument {\n\t\treturn this.#document\n\t}\n\n\t/**\n\t * Returns the half-open original-source region for a node, or `undefined`\n\t * when this handle holds no provenance for that node.\n\t *\n\t * @param node - The node whose provenance to read\n\t * @returns A fresh {@link TemplateSpan}, or `undefined`\n\t */\n\tspan(node: TemplateNode): TemplateSpan | undefined {\n\t\tconst span = this.#spans.get(node)\n\t\treturn span === undefined ? undefined : { start: span.start, end: span.end }\n\t}\n\n\t/**\n\t * Walks every node in the document depth-first in pre-order, root first.\n\t *\n\t * @returns A lazy generator over every node in the document\n\t */\n\t*walk(): Generator<TemplateNode> {\n\t\tyield* walkTemplateNodes(this.#document)\n\t}\n\n\tfind<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): T | undefined\n\tfind(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined\n\tfind(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined {\n\t\tfor (const node of this.walk()) {\n\t\t\tif (predicate(node)) return node\n\t\t}\n\t\treturn undefined\n\t}\n\n\tfilter<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): readonly T[]\n\tfilter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[]\n\tfilter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[] {\n\t\treturn this.walk()\n\t\t\t.filter((node) => predicate(node))\n\t\t\t.toArray()\n\t}\n\n\t/**\n\t * Rewrites the document bottom-up with copy-on-write provenance preservation\n\t * and returns a derived {@link TemplateTreeInterface}.\n\t *\n\t * @param rewrite - The bottom-up node rewrite callback\n\t * @returns A derived handle over the rewritten document\n\t */\n\tmap(rewrite: TemplateRewriteHandler): TemplateTreeInterface {\n\t\tconst [document, derivations] = mapTemplateDocument(this.#document, rewrite)\n\t\treturn this.#derive(document, derivations)\n\t}\n\n\t/**\n\t * Reduces the document depth-first in pre-order into one accumulated value.\n\t *\n\t * @param callback - The reducer step combining value and node\n\t * @param initial - The initial accumulated value\n\t * @returns The final accumulated value\n\t */\n\treduce<T>(callback: (value: T, node: TemplateNode) => T, initial: T): T {\n\t\treturn this.walk().reduce((value, node) => callback(value, node), initial)\n\t}\n\n\t/**\n\t * Folds the document bottom-up through a total handler table covering every\n\t * syntax variant.\n\t *\n\t * @param handlers - Total handler map keyed by `syntax`\n\t * @returns The folded value of the document root\n\t */\n\tfold<T>(handlers: TemplateHandlerMap<T>): T {\n\t\treturn foldTemplateDocument(this.#document, handlers)\n\t}\n\n\t/**\n\t * Returns a fresh, pull-based stream over the document's top-level children\n\t * in source order.\n\t *\n\t * @returns A pull-based {@link ReadableStream} over top-level nodes\n\t */\n\tstream(): ReadableStream<TemplateNode> {\n\t\treturn streamTemplateNodes(this.#document)\n\t}\n\n\t/**\n\t * Evaluates the template document against runtime values and returns rendered\n\t * text.\n\t *\n\t * @param values - Optional runtime values record\n\t * @param options - Optional evaluation, placeholder, and sanitize settings\n\t * @returns The rendered text\n\t */\n\tevaluate(values?: TemplateFillValues, options?: TemplateEvaluateOptions): string {\n\t\treturn evaluateTemplate(this.#document, values, options)\n\t}\n\n\t/**\n\t * Renders the template document back to canonical template source text.\n\t *\n\t * @returns The canonical template source string\n\t */\n\trender(): string {\n\t\treturn renderTemplate(this.#document)\n\t}\n\n\t// Builds a derived handle carrying each output node's original-source span.\n\t#derive(\n\t\tdocument: TemplateDocument,\n\t\tderivations: ReadonlyMap<TemplateNode, TemplateNode | undefined>,\n\t): TemplateTree {\n\t\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\t\tfor (const node of walkTemplateNodes(document)) {\n\t\t\tconst own = this.#spans.get(node)\n\t\t\tif (own !== undefined) {\n\t\t\t\tspans.set(node, own)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst source = derivations.get(node)\n\t\t\tif (source === undefined) continue\n\t\t\tconst span = this.#spans.get(source)\n\t\t\tif (span !== undefined) spans.set(node, span)\n\t\t}\n\t\treturn new TemplateTree({ document, spans })\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tMissingPolicy,\n\tTemplateDefinition,\n\tTemplateFillOptions,\n\tTemplateFillValues,\n\tTemplateInterface,\n\tTemplateOptions,\n\tTemplatePlaceholder,\n\tTemplateTreeInterface,\n\tTemplateValidationResult,\n} from '../types.js'\nimport { createContract, isArray, isString, schemaToParameters } from '@orkestrel/contract'\nimport { compilePlainTemplate } from '../compilers.js'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN } from '../constants.js'\nimport { fillTemplate, resolveToken } from '../helpers.js'\nimport { placeholderShape } from '../shapers.js'\nimport { TemplateError } from '../errors.js'\nimport { TemplateTree } from './TemplateTree.js'\n\n/**\n * Represents a named, versionable template — `{{name}}` tokens in `content`,\n * filled against a values record — implementing `TemplateInterface` exactly.\n *\n * @remarks\n * `missing` / `locale` seed this instance's default {@link TemplateFillOptions},\n * overridable per `fill` call. Its `parameters()` contract (built from\n * `placeholders` through `placeholderShape`) compiles once, in the constructor.\n *\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * const greeting = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class Template implements TemplateInterface {\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\treadonly #contract: ContractInterface<unknown>\n\treadonly id: string\n\treadonly name: string\n\treadonly content: string\n\treadonly placeholders: readonly TemplatePlaceholder[]\n\treadonly summary?: string\n\treadonly description?: string\n\treadonly category?: string\n\treadonly tags?: readonly string[]\n\n\tconstructor(options: TemplateOptions) {\n\t\tconst placeholders = options.placeholders ?? []\n\t\tIterator.from(placeholders).reduce<readonly string[]>((names, placeholder) => {\n\t\t\tif (names.includes(placeholder.name)) {\n\t\t\t\tthrow new TemplateError('INVALID', `Duplicate placeholder name: ${placeholder.name}`, {\n\t\t\t\t\tname: placeholder.name,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst name = placeholder.name\n\t\t\tif (isArray(placeholder.path) && placeholder.path.length === 0) {\n\t\t\t\tthrow new TemplateError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Placeholder path must not be empty: ${placeholder.name}`,\n\t\t\t\t\t{ name: placeholder.name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [...names, name]\n\t\t}, [])\n\n\t\tthis.id = isString(options.id) ? options.id : crypto.randomUUID()\n\t\tthis.name = options.name\n\t\tthis.content = options.content\n\t\tthis.placeholders = placeholders\n\t\tif (options.summary !== undefined) this.summary = options.summary\n\t\tif (options.description !== undefined) this.description = options.description\n\t\tif (options.category !== undefined) this.category = options.category\n\t\tif (options.tags !== undefined) this.tags = options.tags\n\t\tthis.#missing = options.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options.locale ?? DEFAULT_LOCALE\n\t\tthis.#contract = createContract(placeholderShape(this.placeholders))\n\t}\n\n\t/**\n\t * Returns the plain, JSON-serializable data this template carries.\n\t *\n\t * @returns The {@link TemplateDefinition} record\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.definition().name // 'greeting'\n\t * ```\n\t */\n\tdefinition(): TemplateDefinition {\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\tcontent: this.content,\n\t\t\tplaceholders: this.placeholders,\n\t\t\t...(this.summary !== undefined ? { summary: this.summary } : {}),\n\t\t\t...(this.description !== undefined ? { description: this.description } : {}),\n\t\t\t...(this.category !== undefined ? { category: this.category } : {}),\n\t\t\t...(this.tags !== undefined ? { tags: this.tags } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * Substitutes every `{{name}}` token in `content` against `values`.\n\t *\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for this instance's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.fill({ name: 'Ada' }) // 'Hi Ada'\n\t * ```\n\t */\n\tfill(values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn fillTemplate(this.content, values, {\n\t\t\tmissing: options?.missing ?? this.#missing,\n\t\t\tlocale: options?.locale ?? this.#locale,\n\t\t\tplaceholders: this.placeholders,\n\t\t})\n\t}\n\n\t/**\n\t * Reports which required placeholders would stay unresolved, and which\n\t * `values` keys go unused, without producing output.\n\t *\n\t * @remarks\n\t * Content-token driven: scans `this.content` for every `{{name}}` token\n\t * (skipping escaped `\\{{` matches) the same way `fill` does, so `validate`\n\t * predicts `fill`'s `'error'`-{@link MissingPolicy} outcome exactly — a\n\t * token reported here as missing is precisely a token that would throw\n\t * under `fill(values, { missing: 'error' })`. For each distinct token\n\t * (first-appearance order, trimmed): `resolveToken` applies the one shared\n\t * token rule `fill` also applies — a declared {@link TemplatePlaceholder}\n\t * sharing its `name` supplies `path` (falling back to the token split on\n\t * `.`), and the value resolves through `resolveSafeField`. The token is `missing`\n\t * only when the value is unresolved, no `fallback` is declared, and the\n\t * placeholder is required (`required !== false`, including undeclared\n\t * tokens). `extra` lists every `values` key with no declared placeholder.\n\t *\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.validate({}).missing // ['name']\n\t * ```\n\t */\n\tvalidate(values?: TemplateFillValues): TemplateValidationResult {\n\t\tconst record = values ?? {}\n\t\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\t\tconst tokens = new Set(\n\t\t\tArray.from(this.content.matchAll(pattern)).flatMap((match) =>\n\t\t\t\tmatch[1] === undefined ? [] : [match[1].trim()],\n\t\t\t),\n\t\t)\n\t\tconst missing = [...tokens].filter((token) => {\n\t\t\tconst { value, declared, required } = resolveToken(record, this.placeholders, token)\n\t\t\treturn value === undefined && declared?.fallback === undefined && required\n\t\t})\n\n\t\tconst declaredNames = new Set(this.placeholders.map((placeholder) => placeholder.name))\n\t\tconst extra = Object.keys(record).filter((key) => !declaredNames.has(key))\n\n\t\treturn { valid: missing.length === 0, missing, extra }\n\t}\n\n\t/**\n\t * Projects this template's placeholders to the open tool-parameters record\n\t * shape.\n\t *\n\t * @returns The compiled parameters record, or `undefined` when `schemaToParameters` yields none\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.parameters()\n\t * ```\n\t */\n\tparameters(): Readonly<Record<string, unknown>> | undefined {\n\t\treturn schemaToParameters(this.#contract.schema)\n\t}\n\n\t/**\n\t * Returns an immutable compiled tree handle over this template's plain\n\t * placeholder content.\n\t *\n\t * @returns A {@link TemplateTreeInterface} parsed by `compilePlainTemplate`\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.tree().document.children.length // 2\n\t * ```\n\t */\n\ttree(): TemplateTreeInterface {\n\t\tconst [document, spans] = compilePlainTemplate(this.content)\n\t\treturn new TemplateTree({ document, spans })\n\t}\n}\n","import type {\n\tMissingPolicy,\n\tTemplateFillValues,\n\tTemplateFillOptions,\n\tTemplateInterface,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateQuery,\n\tTemplateRegisterOptions,\n\tTemplateValidationResult,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { isFunction, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY } from '../constants.js'\nimport { TemplateError } from '../errors.js'\nimport { Template } from './Template.js'\n\n/**\n * Represents the template registry — a self-owning, id-keyed record-holder for\n * the {@link TemplateInterface} instances a consumer registers, looks up,\n * fills, and validates by id — implementing `TemplateManagerInterface`\n * exactly.\n *\n * @remarks\n * Singular and plural accessors, the batch `remove` overloads, and ownership\n * of the emitter all sit here. `register` accepts either a constructed {@link TemplateInterface} (kept\n * as-is, including its own `missing` / `locale` defaults) or a plain\n * {@link TemplateOptions} bag — constructed into a `Template` with this\n * manager's `missing` / `locale` defaults applied wherever the bag omits\n * them. A duplicate `id` throws a {@link TemplateError} coded `CONFLICT`\n * unless `options.replace` is `true`, in which case the existing entry is\n * overwritten. `options.templates` seeds the registry at construction without\n * emitting `register` — only calls to `register` after construction emit.\n * The batch `remove(ids)` form removes every present id and returns\n * `true` only when every listed id was present.\n *\n * @example\n * ```ts\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const instance = manager.register({ name: 'greeting', content: 'Hi {{name}}' })\n * manager.fill(instance.id, { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #templates = new Map<string, TemplateInterface>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tconst on = options?.on\n\t\tconst error = options?.error\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t\tthis.#missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options?.locale ?? DEFAULT_LOCALE\n\t\tfor (const template of options?.templates ?? []) {\n\t\t\tconst instance = this.#instantiate(template)\n\t\t\tthis.#templates.set(instance.id, instance)\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#templates.size\n\t}\n\n\t/**\n\t * Registers a template — a constructed {@link TemplateInterface} (kept\n\t * as-is) or a plain {@link TemplateOptions} bag (constructed into a\n\t * `Template` with this manager's `missing` / `locale` defaults applied\n\t * wherever the bag omits them).\n\t *\n\t * @param template - The template instance or options to register\n\t * @param options - `replace` — overwrite an existing entry sharing the same id instead of throwing\n\t * @returns The registered {@link TemplateInterface}\n\t * @throws {@link TemplateError} Thrown when the id is already registered and `options.replace` is not `true` (coded `CONFLICT`), or when an options bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = manager.register({ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' })\n\t * ```\n\t */\n\tregister(\n\t\ttemplate: TemplateInterface | TemplateOptions,\n\t\toptions?: TemplateRegisterOptions,\n\t): TemplateInterface {\n\t\tconst instance = this.#instantiate(template)\n\t\tconst existing = this.#templates.get(instance.id)\n\t\tif (existing !== undefined && options?.replace !== true) {\n\t\t\tthrow new TemplateError('CONFLICT', `Template already registered: ${instance.id}`, {\n\t\t\t\tid: instance.id,\n\t\t\t})\n\t\t}\n\t\tthis.#templates.set(instance.id, instance)\n\t\tthis.#emitter.emit('register', instance)\n\t\treturn instance\n\t}\n\n\t/**\n\t * Returns one registered {@link TemplateInterface} by id.\n\t *\n\t * @param id - The template id\n\t * @returns The registered {@link TemplateInterface}, or `undefined` when `id` is unregistered\n\t */\n\ttemplate(id: string): TemplateInterface | undefined {\n\t\treturn this.#templates.get(id)\n\t}\n\n\t/**\n\t * Lists every registered template.\n\t *\n\t * @returns A snapshot array of every registered {@link TemplateInterface}\n\t */\n\ttemplates(): readonly TemplateInterface[] {\n\t\treturn [...this.#templates.values()]\n\t}\n\n\t/**\n\t * Filters registered templates by `name`, `category`, and `tag` — every\n\t * supplied field must match.\n\t *\n\t * @param query - The {@link TemplateQuery} to filter by; omit for every registered template\n\t * @returns The matching templates\n\t */\n\tfind(query?: TemplateQuery): readonly TemplateInterface[] {\n\t\tif (query === undefined) return this.templates()\n\t\treturn this.templates().filter((instance) => {\n\t\t\tif (query.name !== undefined && instance.name !== query.name) return false\n\t\t\tif (query.category !== undefined && instance.category !== query.category) return false\n\t\t\tif (query.tag !== undefined && !(instance.tags ?? []).includes(query.tag)) return false\n\t\t\treturn true\n\t\t})\n\t}\n\n\t/**\n\t * Tests whether a template id is registered.\n\t *\n\t * @param id - The template id\n\t * @returns True if `id` is registered; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#templates.has(id)\n\t}\n\n\t/**\n\t * Removes one, several, or every registered template.\n\t *\n\t * @remarks\n\t * `remove()` removes every registered template, emitting `remove` once per\n\t * instance. `remove(id)` removes one template by id, emitting `remove` and\n\t * returning `true` when it existed, `false` otherwise. `remove(ids)`\n\t * removes every listed id that is present, emitting `remove` once per\n\t * removed instance, and returns `true` only when every listed id was\n\t * present.\n\t *\n\t * @param target - Omit to remove all, a single id, or a list of ids\n\t * @returns `boolean` for the single-id / list-of-ids forms; `void` for the remove-all form\n\t */\n\t// `readonly string[]` is not assignable to `id: string`, so a list resolves to the\n\t// batch signature whatever order the signatures are declared in.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tif (target === undefined) {\n\t\t\tfor (const instance of this.#templates.values()) this.#emitter.emit('remove', instance)\n\t\t\tthis.#templates.clear()\n\t\t\treturn\n\t\t}\n\t\tif (isString(target)) {\n\t\t\tconst instance = this.#templates.get(target)\n\t\t\tif (instance === undefined) return false\n\t\t\tthis.#templates.delete(target)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\treturn true\n\t\t}\n\t\treturn this.#remove(target).reduce((all, removed) => removed && all, true)\n\t}\n\n\t/** Removes every registered template, emitting `clear`. */\n\tclear(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\t/**\n\t * Tears down the registry: drops every registered template and destroys the\n\t * owned emitter. Idempotent.\n\t *\n\t * @remarks\n\t * Teardown is not an observable registry operation and the emitter is being\n\t * released, so this emits neither `clear` nor `remove`. The emitter is torn\n\t * down last, after the registry is dropped.\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new TemplateManager()\n\t * manager.destroy()\n\t * manager.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t/**\n\t * Fills a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for the template's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t */\n\tfill(id: string, values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn this.#require(id).fill(values, options)\n\t}\n\n\t/**\n\t * Validates values against a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tvalidate(id: string, values?: TemplateFillValues): TemplateValidationResult {\n\t\treturn this.#require(id).validate(values)\n\t}\n\n\t/**\n\t * Projects a registered template's parameters by id.\n\t *\n\t * @param id - The template id\n\t * @returns The compiled parameters record, or `undefined` when the template has none\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tparameters(id: string): Readonly<Record<string, unknown>> | undefined {\n\t\treturn this.#require(id).parameters()\n\t}\n\n\t#instantiate(template: TemplateInterface | TemplateOptions): TemplateInterface {\n\t\tif (this.#isInstance(template)) return template\n\t\treturn new Template({\n\t\t\t...template,\n\t\t\tmissing: template.missing ?? this.#missing,\n\t\t\tlocale: template.locale ?? this.#locale,\n\t\t})\n\t}\n\n\t*#remove(target: readonly string[]): Generator<boolean> {\n\t\tfor (const id of target) {\n\t\t\tconst instance = this.#templates.get(id)\n\t\t\tif (instance === undefined) {\n\t\t\t\tyield false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.#templates.delete(id)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\tyield true\n\t\t}\n\t}\n\n\t// A TemplateOptions bag is plain data with no `fill` / `validate` /\n\t// `parameters` methods; a TemplateInterface instance always exposes all three.\n\t#isInstance(template: TemplateInterface | TemplateOptions): template is TemplateInterface {\n\t\treturn (\n\t\t\t'fill' in template &&\n\t\t\tisFunction(template.fill) &&\n\t\t\t'validate' in template &&\n\t\t\tisFunction(template.validate) &&\n\t\t\t'parameters' in template &&\n\t\t\tisFunction(template.parameters)\n\t\t)\n\t}\n\n\t// Every by-id operation that needs a template to proceed shares this lookup.\n\t// The `template` accessor deliberately does not, and returns `undefined`.\n\t#require(id: string): TemplateInterface {\n\t\tconst instance = this.#templates.get(id)\n\t\tif (instance === undefined) {\n\t\t\tthrow new TemplateError('NOTFOUND', `Unknown template id: ${id}`, { id })\n\t\t}\n\t\treturn instance\n\t}\n}\n","import type {\n\tTemplateInterface,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateTreeInterface,\n\tTemplateTreeOptions,\n} from './types.js'\nimport { Template } from './templates/Template.js'\nimport { TemplateManager } from './templates/TemplateManager.js'\nimport { TemplateTree } from './templates/TemplateTree.js'\n\n/**\n * Creates a working {@link TemplateInterface} from a {@link TemplateOptions}\n * bag, backed by the `Template` class.\n *\n * @param options - The template's `name` / `content`, an optional `id`\n * (defaults to a generated UUID), `placeholders`, catalog metadata, and\n * `missing` / `locale` fill defaults\n * @returns A working {@link TemplateInterface}\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example Create a template and a registry\n * ```ts\n * import { createTemplate, createTemplateManager } from '@orkestrel/template'\n *\n * const greeting = createTemplate({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [\n * \t\t{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}', category: 'mail' },\n * \t\t{ id: 'farewell', name: 'farewell', content: 'Bye {{name}}', category: 'mail' },\n * \t\t{ id: 'alert', name: 'alert', content: 'Alert: {{reason}}', category: 'ops' },\n * \t],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * templates.find({ category: 'mail' }).map((one) => one.id) // ['greeting', 'farewell']\n * templates.has('alert') // true\n * templates.has('missing') // false\n * ```\n */\nexport function createTemplate(options: TemplateOptions): TemplateInterface {\n\treturn new Template(options)\n}\n\n/**\n * Creates a working {@link TemplateManagerInterface}, optionally seeded with\n * the templates the options carry, backed by the `TemplateManager` class.\n *\n * @param options - Optional initial `templates` seed collection and\n * manager-wide `missing` / `locale` fill defaults, emitter `on` hooks, and\n * an `error` handler\n * @returns A working {@link TemplateManagerInterface}\n * @throws {@link TemplateError} Thrown when a seeded `options.templates` bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * import { createTemplateManager } from '@src/core'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' }],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n\n/**\n * Creates a working {@link TemplateTreeInterface} from Jinja `source` text or\n * an existing {@link TemplateDocument}, backed by the `TemplateTree` class.\n *\n * @param options - Either `{ source }` to compile or `{ document, spans? }` to adopt\n * @returns A working {@link TemplateTreeInterface}\n *\n * @example\n * ```ts\n * import { createTemplateTree } from '@orkestrel/template'\n *\n * const tree = createTemplateTree({ source: 'Hi {{ name }}' })\n * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateTree(options: TemplateTreeOptions): TemplateTreeInterface {\n\treturn new TemplateTree(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,eAAe;;;;;AAM5B,IAAa,yBAAwC;;;;;AAMrD,IAAa,iBAAiB;;;;;;AAO9B,IAAa,wBAA2C,OAAO,OAAO;CACrE;CACA;CACA;AACD,CAAC;;;;AAKD,IAAa,uBAAqD,OAAO,OAAO;CAC/E;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;AAOD,IAAa,iBACZ;;;;;AAMD,IAAa,2BACZ;;;;;AAMD,IAAa,yBAAyB,IAAI,OACzC,IAAI,eAAe,2UACnB,KACD;;;;AAKA,IAAa,oBAAoB,OAAO,OAAO;CAC9C,MAAM;CACN,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,MAAM;AACP,CAAU;;;;AAKV,IAAa,uBAAuB,OAAO,OAAO;CAAC;CAAM;CAAM;CAAK;CAAK;CAAM;AAAI,CAAU;;;;;AAM7F,IAAa,mBAAmB,OAAO,OAAO;CAC7C,MAAM;CACN,KAAK;CACL,MAAK;CACL,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACJ,CAAU;;;;;;AAOV,IAAa,qBAAqB,OAAO,OAAO;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;AAKV,IAAa,mBAAmB,OAAO,OAAO;CAC7C;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,iBAAiB,OAAO,OAAO;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,0BAA0B,OAAO,OAAO;CACpD;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,mBAAmB,OAAO,OAAO;CAC7C,QAAQ,OAAO,OAAO;EACrB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,MAAM,OAAO,OAAO;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,SAAS,OAAO,OAAO;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;AACF,CAAC;;;;;AAMD,IAAa,yBAAyB,OAAO,OAAO;CACnD;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,6BAA6B,OAAO,OAAO;CACvD,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;AACP,CAAU;;;;;;;;;;;;;;;AC/PV,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,WAAW,OAAO,MAAM,OAAO,IAAI,mCAAmC,GAAG,EAAE,OAAO,KAAK,CAAC;EACxF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,gBA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S,EAAE,CAAC,CAAC,SAAS,MAAM;CACzC;;;;;;;;CASA,WAAW,IAA2D;EACrE,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,WAAW;CACrC;CAEA,aAAa,UAAkE;EAC9E,IAAI,KAAK,YAAY,QAAQ,GAAG,OAAO;EACvC,OAAO,IAAI,SAAS;GACnB,GAAG;GACH,SAAS,SAAS,WAAW,KAAK;GAClC,QAAQ,SAAS,UAAU,KAAK;EACjC,CAAC;CACF;CAEA,CAAC,QAAQ,QAA+C;EACvD,KAAK,MAAM,MAAM,QAAQ;GACxB,MAAM,WAAW,KAAK,WAAW,IAAI,EAAE;GACvC,IAAI,aAAa,KAAA,GAAW;IAC3B,MAAM;IACN;GACD;GACA,KAAK,WAAW,OAAO,EAAE;GACzB,KAAK,SAAS,KAAK,UAAU,QAAQ;GACrC,MAAM;EACP;CACD;CAIA,YAAY,UAA8E;EACzF,OACC,UAAU,YACV,WAAW,SAAS,IAAI,KACxB,cAAc,YACd,WAAW,SAAS,QAAQ,KAC5B,gBAAgB,YAChB,WAAW,SAAS,UAAU;CAEhC;CAIA,SAAS,IAA+B;EACvC,MAAM,WAAW,KAAK,WAAW,IAAI,EAAE;EACvC,IAAI,aAAa,KAAA,GAChB,MAAM,IAAI,cAAc,YAAY,wBAAwB,MAAM,EAAE,GAAG,CAAC;EAEzE,OAAO;CACR;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AChQA,SAAgB,eAAe,SAA6C;CAC3E,OAAO,IAAI,SAAS,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBAAsB,SAA4D;CACjG,OAAO,IAAI,gBAAgB,OAAO;AACnC;;;;;;;;;;;;;;;;AAiBA,SAAgB,mBAAmB,SAAqD;CACvF,OAAO,IAAI,aAAa,OAAO;AAChC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/compilers.ts","../../../src/core/parsers.ts","../../../src/core/shapers.ts","../../../src/core/templates/TemplateTree.ts","../../../src/core/templates/Template.ts","../../../src/core/templates/TemplateManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MissingPolicy, TemplateErrorCode } from './types.js'\n\n// Frozen default data and Jinja grammar tables for the template module —\n// constants are UPPER_SNAKE_CASE data, the sole home for module-scope literal\n// defaults. `MAX_DEPTH` is imported directly from `@orkestrel/html` wherever\n// depth bounds are enforced and is never redeclared here.\n\n/**\n * Holds the single-pass `{{name}}` substitution pattern shared by\n * `Template#fill` and `Template#validate`.\n *\n * @remarks\n * Global-flagged, two-alternative pattern: a match of the first alternative\n * (`\\{{` — a literal backslash followed by `{{`) emits a literal `{{`. A match\n * populating capture group 1 (`\\{\\{([^{}]+?)\\}\\}`) resolves the trimmed token\n * name without backtracking on unclosed whitespace runs. Every call site builds\n * a fresh `RegExp` from `.source` and `.flags`.\n */\nexport const FILL_PATTERN = /\\\\\\{\\{|\\{\\{([^{}]+?)\\}\\}/g\n\n/**\n * Holds `'error'`, the default `missing` policy for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_MISSING_POLICY: MissingPolicy = 'error'\n\n/**\n * Holds `'en-US'`, the default `locale` for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_LOCALE = 'en-US'\n\n/**\n * Lists the prototype-pollution-unsafe field-path segments `'__proto__'`,\n * `'constructor'`, and `'prototype'` — a fill lookup refuses to resolve a path\n * containing one of them, treating the placeholder as unresolved.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'constructor',\n\t'prototype',\n])\n\n/**\n * Lists every machine-readable error code admitted on a {@link TemplateError}.\n */\nexport const TEMPLATE_ERROR_CODES: readonly TemplateErrorCode[] = Object.freeze([\n\t'MISSING',\n\t'NOTFOUND',\n\t'INVALID',\n\t'CONFLICT',\n\t'FORMAT',\n\t'EVALUATION',\n\t'RAISE',\n])\n\n/**\n * Holds the regular-expression character class Python's `str.isspace` reports\n * as whitespace for Jinja whitespace markers, `lstrip_blocks`, `trim`, `rstrip`,\n * `lstrip`, and default `split`.\n */\nexport const TEMPLATE_SPACE =\n\t'[\\\\t-\\\\r\\\\x1c-\\\\x20\\\\x85\\\\xa0\\\\u1680\\\\u2000-\\\\u200a\\\\u2028\\\\u2029\\\\u202f\\\\u205f\\\\u3000]'\n\n/**\n * Matches one root-level segment of a Jinja template source: a run of literal\n * text and the tag, comment, or unclosed delimiter that follows it.\n */\nexport const TEMPLATE_SEGMENT_PATTERN =\n\t/((?:[^{]|\\{(?![{%#]))*)(?:(\\{%[-+]?)((?:'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"|[^'\"])*?)([-+]?%\\})|(\\{\\{[-+]?)((?:'(?:[^'\\\\]|\\\\[^])*'|\"(?:[^\"\\\\]|\\\\[^])*\"|[^'\"])*?)(-?\\}\\})|(\\{#[-+]?)([^]*?)([-+]?#\\})|(\\{[{%#])[^]*|$)/gy\n\n/**\n * Matches one lexical token inside a Jinja template tag in lexer precedence\n * order: whitespace, float, integer, name, string literal, operator, or fault.\n */\nexport const TEMPLATE_TOKEN_PATTERN = new RegExp(\n\t`(${TEMPLATE_SPACE}+)|((?<!\\\\.)(?:\\\\d+_)*\\\\d+(?:(?:\\\\.(?:\\\\d+_)*\\\\d+)?[eE][-+]?(?:\\\\d+_)*\\\\d+|\\\\.(?:\\\\d+_)*\\\\d+))|(0[bB](?:_?[01])+|0[oO](?:_?[0-7])+|0[xX](?:_?[\\\\da-fA-F])+|[1-9](?:_?\\\\d)*|0(?:_?0)*)|([\\\\p{XID_Start}_]\\\\p{XID_Continue}*)|('(?:[^'\\\\\\\\]|\\\\\\\\[^])*'|\"(?:[^\"\\\\\\\\]|\\\\\\\\[^])*\")|(\\\\/\\\\/|\\\\*\\\\*|==|!=|>=|<=|[-+/*%~[\\\\](){}<>=.:|,;])|([^])`,\n\t'gyu',\n)\n\n/**\n * Maps each Jinja built-in constant spelling to its runtime literal value.\n */\nexport const TEMPLATE_LITERALS = Object.freeze({\n\ttrue: true,\n\tfalse: false,\n\tnone: null,\n\tTrue: true,\n\tFalse: false,\n\tNone: null,\n} as const)\n\n/**\n * Lists the single-token comparison operators admitted in template expressions.\n */\nexport const TEMPLATE_COMPARISONS = Object.freeze(['==', '!=', '<', '>', '<=', '>='] as const)\n\n/**\n * Maps each single-character Python `unicode-escape` sequence after `\\` to its\n * decoded character.\n */\nexport const TEMPLATE_ESCAPES = Object.freeze({\n\t'\\\\': '\\\\',\n\t\"'\": \"'\",\n\t'\"': '\"',\n\ta: '\\x07',\n\tb: '\\b',\n\tf: '\\f',\n\tn: '\\n',\n\tr: '\\r',\n\tt: '\\t',\n\tv: '\\v',\n} as const)\n\n/**\n * Lists the global Jinja and Hugging Face chat-template function names\n * recognized by the compiler, of which `raise_exception` and `namespace` are\n * admitted as calls.\n */\nexport const TEMPLATE_FUNCTIONS = Object.freeze([\n\t'raise_exception',\n\t'namespace',\n\t'strftime_now',\n\t'dict',\n\t'range',\n\t'lipsum',\n\t'cycler',\n\t'joiner',\n] as const)\n\n/**\n * Lists the Jinja `|` filters admitted by the template compiler and evaluator.\n */\nexport const TEMPLATE_FILTERS = Object.freeze([\n\t'trim',\n\t'length',\n\t'tojson',\n\t'items',\n\t'safe',\n\t'string',\n] as const)\n\n/**\n * Lists the Jinja `is` / `is not` tests admitted by the template compiler and\n * evaluator.\n */\nexport const TEMPLATE_TESTS = Object.freeze([\n\t'defined',\n\t'undefined',\n\t'none',\n\t'string',\n\t'mapping',\n\t'iterable',\n\t'sequence',\n\t'true',\n\t'false',\n] as const)\n\n/**\n * Lists the Python `str` methods admitted on string receivers in template\n * expressions.\n */\nexport const TEMPLATE_STRING_METHODS = Object.freeze([\n\t'startswith',\n\t'endswith',\n\t'split',\n\t'strip',\n\t'rstrip',\n\t'lstrip',\n] as const)\n\n/**\n * Lists Python attribute and method names on strings, lists, and mappings that\n * refuse bare property reads rather than returning unbound method objects.\n */\nexport const TEMPLATE_METHODS = Object.freeze({\n\tstring: Object.freeze([\n\t\t'capitalize',\n\t\t'casefold',\n\t\t'center',\n\t\t'count',\n\t\t'encode',\n\t\t'endswith',\n\t\t'expandtabs',\n\t\t'find',\n\t\t'format',\n\t\t'format_map',\n\t\t'index',\n\t\t'isalnum',\n\t\t'isalpha',\n\t\t'isascii',\n\t\t'isdecimal',\n\t\t'isdigit',\n\t\t'isidentifier',\n\t\t'islower',\n\t\t'isnumeric',\n\t\t'isprintable',\n\t\t'isspace',\n\t\t'istitle',\n\t\t'isupper',\n\t\t'join',\n\t\t'ljust',\n\t\t'lower',\n\t\t'lstrip',\n\t\t'maketrans',\n\t\t'partition',\n\t\t'removeprefix',\n\t\t'removesuffix',\n\t\t'replace',\n\t\t'rfind',\n\t\t'rindex',\n\t\t'rjust',\n\t\t'rpartition',\n\t\t'rsplit',\n\t\t'rstrip',\n\t\t'split',\n\t\t'splitlines',\n\t\t'startswith',\n\t\t'strip',\n\t\t'swapcase',\n\t\t'title',\n\t\t'translate',\n\t\t'upper',\n\t\t'zfill',\n\t]),\n\tlist: Object.freeze([\n\t\t'append',\n\t\t'clear',\n\t\t'copy',\n\t\t'count',\n\t\t'extend',\n\t\t'index',\n\t\t'insert',\n\t\t'pop',\n\t\t'remove',\n\t\t'reverse',\n\t\t'sort',\n\t]),\n\tmapping: Object.freeze([\n\t\t'clear',\n\t\t'copy',\n\t\t'fromkeys',\n\t\t'get',\n\t\t'items',\n\t\t'keys',\n\t\t'pop',\n\t\t'popitem',\n\t\t'setdefault',\n\t\t'update',\n\t\t'values',\n\t]),\n})\n\n/**\n * Lists the Jinja `loop` members refused by the template subset; `index`,\n * `index0`, `first`, `last`, `length`, `previtem`, and `nextitem` are admitted.\n */\nexport const TEMPLATE_LOOP_REFUSALS = Object.freeze([\n\t'revindex',\n\t'revindex0',\n\t'depth',\n\t'depth0',\n\t'cycle',\n\t'changed',\n] as const)\n\n/**\n * Maps each arithmetic operator outside the admitted template subset to the\n * feature label carried in its refusal context.\n */\nexport const TEMPLATE_OPERATOR_FEATURES = Object.freeze({\n\t'*': 'multiplication',\n\t'/': 'division',\n\t'//': 'floor division',\n\t'%': 'modulo',\n\t'**': 'power',\n} as const)\n","import type { TemplateErrorCode } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\nimport { TEMPLATE_ERROR_CODES } from './constants.js'\n\n// Misuse and compilation/evaluation failures in the template layer throw a\n// self-branded `TemplateError` carrying a machine-readable `code`, so callers\n// narrow safely through `isTemplateError` and branch on `error.code`.\n\n/**\n * Represents an error thrown by the template layer — a machine-readable\n * {@link TemplateErrorCode} and an optional `context` record naming the\n * offending id, placeholder name, source position, or feature.\n *\n * @remarks\n * Thrown for: an unresolved required placeholder under `'error'` (`MISSING`),\n * an unknown registry id (`NOTFOUND`), invalid construction or AST input\n * (`INVALID`), a duplicate registration id without `options.replace`\n * (`CONFLICT`), malformed or unadmitted template syntax or exceeded nesting\n * depth (`FORMAT`), a runtime operation error (`EVALUATION`), and a\n * template-authored `raise_exception(message)` call (`RAISE`).\n */\nexport class TemplateError extends Error {\n\treadonly code: TemplateErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: TemplateErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/template.TemplateError'), { value: this })\n\t\tthis.name = 'TemplateError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link TemplateError}.\n *\n * @remarks\n * Recognizes self-branded errors from other package copies and subclasses, and\n * refuses transparent proxies and unbranded look-alikes.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link TemplateError}; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateError, TemplateError } from '@orkestrel/template'\n *\n * try {\n * \tthrow new TemplateError('NOTFOUND', 'Unknown template id: missing', { id: 'missing' })\n * } catch (error) {\n * \tif (isTemplateError(error) && error.code === 'NOTFOUND') return\n * }\n * ```\n */\nexport function isTemplateError(value: unknown): value is TemplateError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tif (\n\t\t\tINTRINSICS.describe(value, Symbol.for('@orkestrel/template.TemplateError'))?.value !== value\n\t\t)\n\t\t\treturn false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\tTEMPLATE_ERROR_CODES.some((admitted) => admitted === code) &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n","import type {\n\tTemplateComparison,\n\tTemplateDocument,\n\tTemplateErrorCode,\n\tTemplateExpression,\n\tTemplateNamespace,\n\tTemplateNode,\n\tTemplateOperator,\n\tTemplateSpan,\n\tTemplateTarget,\n\tTemplateUnaryOperator,\n} from './types.js'\nimport {\n\tholds,\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisMap,\n\tisNonNegativeInteger,\n\tisObject,\n\tisRecord,\n\tisString,\n} from '@orkestrel/contract'\nimport { isHTMLDocument, MAX_DEPTH } from '@orkestrel/html'\nimport { isMarkdownDocument } from '@orkestrel/markdown'\nimport { TEMPLATE_COMPARISONS, TEMPLATE_ERROR_CODES } from './constants.js'\n\n// Total, class-free runtime guards for the template AST, expressions, spans,\n// namespaces, and error codes. Every recursive guard tracks ancestors with a\n// `WeakSet` and caps descent at `MAX_DEPTH` imported from `@orkestrel/html`.\n\n/**\n * Checks whether an unknown value is a declared {@link TemplateErrorCode}.\n *\n * @param value - The value to test\n * @returns True if `value` is one of `TEMPLATE_ERROR_CODES`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateErrorCode } from '@orkestrel/template'\n *\n * isTemplateErrorCode('FORMAT') // true\n * isTemplateErrorCode('OTHER') // false\n * ```\n */\nexport function isTemplateErrorCode(value: unknown): value is TemplateErrorCode {\n\treturn holds(() => isString(value) && TEMPLATE_ERROR_CODES.some((code) => code === value))\n}\n\n/**\n * Checks whether an unknown value is a valid half-open {@link TemplateSpan}.\n *\n * @param value - The value to test\n * @returns True if `value` carries non-negative integer `start <= end`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateSpan } from '@orkestrel/template'\n *\n * isTemplateSpan({ start: 0, end: 5 }) // true\n * isTemplateSpan({ start: 5, end: 2 }) // false\n * ```\n */\nexport function isTemplateSpan(value: unknown): value is TemplateSpan {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Object.keys(value)\n\t\tif (keys.length !== 2) return false\n\t\tconst start: unknown = value.start\n\t\tconst end: unknown = value.end\n\t\treturn isNonNegativeInteger(start) && isNonNegativeInteger(end) && start <= end\n\t})\n}\n\n/**\n * Checks whether a string token is one of the single-token {@link TemplateComparison} operators.\n *\n * @param value - The value to test\n * @returns True if `value` is in `TEMPLATE_COMPARISONS`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateComparison } from '@orkestrel/template'\n *\n * isTemplateComparison('==') // true\n * isTemplateComparison('in') // false\n * ```\n */\nexport function isTemplateComparison(value: unknown): value is TemplateComparison {\n\treturn holds(() => isString(value) && TEMPLATE_COMPARISONS.some((operator) => operator === value))\n}\n\n/**\n * Checks whether an unknown value is a runtime {@link TemplateNamespace} container.\n *\n * @param value - The value to test\n * @returns True if `value` is a namespace container with a `Map` of bindings; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateNamespace } from '@orkestrel/template'\n *\n * isTemplateNamespace({ namespace: true, values: new Map() }) // true\n * isTemplateNamespace(new Map()) // false\n * ```\n */\nexport function isTemplateNamespace(value: unknown): value is TemplateNamespace {\n\treturn holds(() => {\n\t\tif (!isObject(value) || isArray(value) || isMap(value)) return false\n\t\treturn Reflect.get(value, 'namespace') === true && isMap(Reflect.get(value, 'values'))\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateTarget} (`local` or `attribute`).\n *\n * @param value - The value to test\n * @returns True if `value` is a well-formed assignment target; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateTarget } from '@orkestrel/template'\n *\n * isTemplateTarget({ scope: 'local', name: 'x' }) // true\n * isTemplateTarget({ scope: 'attribute', object: 'ns', name: 'count' }) // true\n * ```\n */\nexport function isTemplateTarget(value: unknown): value is TemplateTarget {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst scope: unknown = value.scope\n\t\tif (scope === 'local') {\n\t\t\treturn Object.keys(value).length === 2 && isString(value.name) && value.name.length > 0\n\t\t}\n\t\tif (scope === 'attribute') {\n\t\t\treturn (\n\t\t\t\tObject.keys(value).length === 3 &&\n\t\t\t\tisString(value.object) &&\n\t\t\t\tvalue.object.length > 0 &&\n\t\t\t\tisString(value.name) &&\n\t\t\t\tvalue.name.length > 0\n\t\t\t)\n\t\t}\n\t\treturn false\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateExpression} within `MAX_DEPTH` and free of cycles.\n *\n * @param value - The value to test\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to refuse reference cycles\n * @returns True if `value` is a well-formed expression; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateExpression } from '@orkestrel/template'\n *\n * isTemplateExpression({ term: 'literal', value: 'Hi' }) // true\n * isTemplateExpression({ term: 'unknown' }) // false\n * ```\n */\nexport function isTemplateExpression(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): value is TemplateExpression {\n\treturn holds(() => {\n\t\tif (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false\n\t\tconst term: unknown = value.term\n\t\tif (!isString(term)) return false\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst keys = Object.keys(value)\n\t\t\tconst next = depth + 1\n\t\t\tswitch (term) {\n\t\t\t\tcase 'literal': {\n\t\t\t\t\tconst literal: unknown = value.value\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 2 &&\n\t\t\t\t\t\t(literal === null || isString(literal) || isBoolean(literal) || isFiniteNumber(literal))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'name':\n\t\t\t\t\treturn keys.length === 2 && isString(value.name) && value.name.length > 0\n\t\t\t\tcase 'member':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisTemplateExpression(value.object, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.key, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'slice': {\n\t\t\t\t\tconst allowed = keys.every(\n\t\t\t\t\t\t(key) =>\n\t\t\t\t\t\t\tkey === 'term' ||\n\t\t\t\t\t\t\tkey === 'object' ||\n\t\t\t\t\t\t\tkey === 'start' ||\n\t\t\t\t\t\t\tkey === 'stop' ||\n\t\t\t\t\t\t\tkey === 'step',\n\t\t\t\t\t)\n\t\t\t\t\treturn (\n\t\t\t\t\t\tallowed &&\n\t\t\t\t\t\tisTemplateExpression(value.object, next, ancestors) &&\n\t\t\t\t\t\t(value.start === undefined || isTemplateExpression(value.start, next, ancestors)) &&\n\t\t\t\t\t\t(value.stop === undefined || isTemplateExpression(value.stop, next, ancestors)) &&\n\t\t\t\t\t\t(value.step === undefined || isTemplateExpression(value.step, next, ancestors))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'call': {\n\t\t\t\t\tconst rawValues: unknown = value.values\n\t\t\t\t\tconst rawKeywords: unknown = value.keywords\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisTemplateExpression(value.callee, next, ancestors) &&\n\t\t\t\t\t\tisArray(rawValues) &&\n\t\t\t\t\t\trawValues.every((item) => isTemplateExpression(item, next, ancestors)) &&\n\t\t\t\t\t\tisArray(rawKeywords) &&\n\t\t\t\t\t\trawKeywords.every(\n\t\t\t\t\t\t\t(keyword) =>\n\t\t\t\t\t\t\t\tisRecord(keyword) &&\n\t\t\t\t\t\t\t\tObject.keys(keyword).length === 2 &&\n\t\t\t\t\t\t\t\tisString(keyword.name) &&\n\t\t\t\t\t\t\t\tkeyword.name.length > 0 &&\n\t\t\t\t\t\t\t\tisTemplateExpression(keyword.value, next, ancestors),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'filter':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'test':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisBoolean(value.negated) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'unary': {\n\t\t\t\t\tconst operator: unknown = value.operator\n\t\t\t\t\tconst admittedUnary: readonly TemplateUnaryOperator[] = ['not', '-', '+']\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisString(operator) &&\n\t\t\t\t\t\tadmittedUnary.some((candidate) => candidate === operator) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'binary': {\n\t\t\t\t\tconst operator: unknown = value.operator\n\t\t\t\t\tconst admittedBinary: readonly TemplateOperator[] = [\n\t\t\t\t\t\t'+',\n\t\t\t\t\t\t'-',\n\t\t\t\t\t\t'~',\n\t\t\t\t\t\t'==',\n\t\t\t\t\t\t'!=',\n\t\t\t\t\t\t'<',\n\t\t\t\t\t\t'>',\n\t\t\t\t\t\t'<=',\n\t\t\t\t\t\t'>=',\n\t\t\t\t\t\t'in',\n\t\t\t\t\t\t'not in',\n\t\t\t\t\t\t'and',\n\t\t\t\t\t\t'or',\n\t\t\t\t\t]\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(operator) &&\n\t\t\t\t\t\tadmittedBinary.some((candidate) => candidate === operator) &&\n\t\t\t\t\t\tisTemplateExpression(value.left, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.right, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'conditional':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisTemplateExpression(value.condition, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.consequent, next, ancestors) &&\n\t\t\t\t\t\tisTemplateExpression(value.alternate, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tdefault:\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t})\n}\n\n/**\n * Checks whether an unknown value is a valid {@link TemplateNode} within `MAX_DEPTH` and free of cycles.\n *\n * @param value - The value to test\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to refuse reference cycles\n * @returns True if `value` is a structurally valid template AST node; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateNode } from '@orkestrel/template'\n *\n * isTemplateNode({ syntax: 'text', value: 'Hello' }) // true\n * isTemplateNode({ syntax: 'unknown' }) // false\n * ```\n */\nexport function isTemplateNode(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): value is TemplateNode {\n\treturn holds(() => {\n\t\tif (depth > MAX_DEPTH || !isRecord(value) || ancestors.has(value)) return false\n\t\tconst syntax: unknown = value.syntax\n\t\tif (!isString(syntax)) return false\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst keys = Object.keys(value)\n\t\t\tconst next = depth + 1\n\t\t\tswitch (syntax) {\n\t\t\t\tcase 'document': {\n\t\t\t\t\tconst children: unknown = value.children\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 2 &&\n\t\t\t\t\t\tisArray(children) &&\n\t\t\t\t\t\tchildren.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'text':\n\t\t\t\t\treturn keys.length === 2 && isString(value.value)\n\t\t\t\tcase 'placeholder':\n\t\t\t\t\treturn keys.length === 3 && isString(value.name) && isString(value.raw)\n\t\t\t\tcase 'output':\n\t\t\t\t\treturn keys.length === 2 && isTemplateExpression(value.value, next, ancestors)\n\t\t\t\tcase 'if': {\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\tconst alternate: unknown = value.alternate\n\t\t\t\t\tconst allowed = keys.every(\n\t\t\t\t\t\t(key) =>\n\t\t\t\t\t\t\tkey === 'syntax' || key === 'condition' || key === 'body' || key === 'alternate',\n\t\t\t\t\t)\n\t\t\t\t\treturn (\n\t\t\t\t\t\tallowed &&\n\t\t\t\t\t\tisTemplateExpression(value.condition, next, ancestors) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\t(alternate === undefined ||\n\t\t\t\t\t\t\t(isArray(alternate) &&\n\t\t\t\t\t\t\t\talternate.every(\n\t\t\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t\t\t)))\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'for': {\n\t\t\t\t\tconst targets: unknown = value.targets\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisArray(targets) &&\n\t\t\t\t\t\ttargets.length > 0 &&\n\t\t\t\t\t\ttargets.every((target) => isString(target) && target.length > 0) &&\n\t\t\t\t\t\tisTemplateExpression(value.sequence, next, ancestors) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'set':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 3 &&\n\t\t\t\t\t\tisTemplateTarget(value.target) &&\n\t\t\t\t\t\tisTemplateExpression(value.value, next, ancestors)\n\t\t\t\t\t)\n\t\t\t\tcase 'macro': {\n\t\t\t\t\tconst parameters: unknown = value.parameters\n\t\t\t\t\tconst body: unknown = value.body\n\t\t\t\t\treturn (\n\t\t\t\t\t\tkeys.length === 4 &&\n\t\t\t\t\t\tisString(value.name) &&\n\t\t\t\t\t\tvalue.name.length > 0 &&\n\t\t\t\t\t\tisArray(parameters) &&\n\t\t\t\t\t\tparameters.every(\n\t\t\t\t\t\t\t(parameter) =>\n\t\t\t\t\t\t\t\tisRecord(parameter) &&\n\t\t\t\t\t\t\t\tObject.keys(parameter).every((key) => key === 'name' || key === 'fallback') &&\n\t\t\t\t\t\t\t\tisString(parameter.name) &&\n\t\t\t\t\t\t\t\tparameter.name.length > 0 &&\n\t\t\t\t\t\t\t\t(parameter.fallback === undefined ||\n\t\t\t\t\t\t\t\t\tisTemplateExpression(parameter.fallback, next, ancestors)),\n\t\t\t\t\t\t) &&\n\t\t\t\t\t\tisArray(body) &&\n\t\t\t\t\t\tbody.every(\n\t\t\t\t\t\t\t(child) => isTemplateNode(child, next, ancestors) && child.syntax !== 'document',\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tcase 'control':\n\t\t\t\t\treturn keys.length === 2 && (value.action === 'break' || value.action === 'continue')\n\t\t\t\tcase 'comment':\n\t\t\t\t\treturn keys.length === 2 && isString(value.value)\n\t\t\t\tcase 'html':\n\t\t\t\t\treturn keys.length === 2 && isHTMLDocument(value.document)\n\t\t\t\tcase 'markdown':\n\t\t\t\t\treturn keys.length === 2 && isMarkdownDocument(value.document)\n\t\t\t\tdefault:\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t})\n}\n\n/**\n * Checks whether an unknown value is a structurally valid root {@link TemplateDocument}.\n *\n * @param value - The value to test\n * @returns True if `value` is a complete, cycle-free document within `MAX_DEPTH`; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateDocument } from '@orkestrel/template'\n *\n * isTemplateDocument({ syntax: 'document', children: [] }) // true\n * isTemplateDocument({ syntax: 'text', value: 'Hi' }) // false\n * ```\n */\nexport function isTemplateDocument(value: unknown): value is TemplateDocument {\n\treturn isTemplateNode(value) && value.syntax === 'document'\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type { HTMLDocument, HTMLSanitizeOptions } from '@orkestrel/html'\nimport type {\n\tBlockNode,\n\tInlineNode,\n\tListItemNode,\n\tMarkdownDocument,\n\tMarkdownNode,\n} from '@orkestrel/markdown'\nimport type {\n\tTemplateDerivation,\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateExpression,\n\tTemplateFillContext,\n\tTemplateFillValues,\n\tTemplateHandlerMap,\n\tTemplateKeyword,\n\tTemplateLoop,\n\tTemplateMacro,\n\tTemplateNamespace,\n\tTemplateNode,\n\tTemplatePart,\n\tTemplatePlaceholder,\n\tTemplateRewriteHandler,\n\tTemplateRuntimeValue,\n\tTemplateScope,\n\tTemplateToken,\n\tTemplateTokenForm,\n\tTemplateTokenResolution,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisMap,\n\tisObject,\n\tisRecord,\n\tisString,\n\tkeyOf,\n\tresolveField,\n} from '@orkestrel/contract'\nimport {\n\tcreateHTML,\n\tisHTMLNode,\n\tMAX_DEPTH,\n\trenderHTML,\n\tSAFE_URL_SCHEMES,\n\tsanitizeURL,\n} from '@orkestrel/html'\nimport {\n\tcoalesceText,\n\tflattenText,\n\tisBlockNode,\n\tisMarkdownNode,\n\tparseMarkdown,\n\trenderMarkdown,\n} from '@orkestrel/markdown'\nimport {\n\tDEFAULT_LOCALE,\n\tDEFAULT_MISSING_POLICY,\n\tFILL_PATTERN,\n\tTEMPLATE_ESCAPES,\n\tTEMPLATE_FILTERS,\n\tTEMPLATE_FUNCTIONS,\n\tTEMPLATE_LITERALS,\n\tTEMPLATE_LOOP_REFUSALS,\n\tTEMPLATE_METHODS,\n\tTEMPLATE_SEGMENT_PATTERN,\n\tTEMPLATE_SPACE,\n\tTEMPLATE_STRING_METHODS,\n\tTEMPLATE_TESTS,\n\tTEMPLATE_TOKEN_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\nimport { isTemplateDocument, isTemplateNamespace } from './validators.js'\n\n// Pure, class-free leaves for plain template filling, Jinja lexing and\n// evaluation, AST traversal/fold/rewrite, and canonical source rendering.\n// HTML sanitization on tree-valued fills routes through `@orkestrel/html`'s\n// `createHTML` factory so no local class is imported here.\n\n// === Plain placeholder leaves (0.0.17 contract + tree-valued fill)\n\n/**\n * Formats a resolved fill value for substitution into a template's `content`.\n *\n * @remarks\n * A finite number renders with the given locale's thousand grouping through\n * `toLocaleString`. An `@orkestrel/html` node passes through `@orkestrel/html`'s\n * sanitize floor before rendering with `renderHTML`, and an `@orkestrel/markdown`\n * node renders with `renderMarkdown`. Every other value — including `null` —\n * String-coerces.\n *\n * @param value - The resolved value to format\n * @param locale - The locale used for finite-number formatting\n * @returns The formatted string\n *\n * @example\n * ```ts\n * import { formatValue } from '@orkestrel/template'\n *\n * formatValue(5010, 'en-US') // '5,010'\n * formatValue(null, 'en-US') // 'null'\n * ```\n */\nexport function formatValue(value: unknown, locale: string): string {\n\tif (isFiniteNumber(value)) return value.toLocaleString(locale)\n\tif (isHTMLNode(value)) {\n\t\tconst document: HTMLDocument =\n\t\t\tvalue.category === 'document' ? value : { category: 'document', children: [value] }\n\t\treturn renderHTML(createHTML(document).sanitize().document)\n\t}\n\tif (isMarkdownNode(value)) return renderMarkdown(value)\n\treturn String(value)\n}\n\n/**\n * Resolves a field path against a fill-values record, refusing any path that\n * touches a prototype-pollution-unsafe segment.\n *\n * @param record - The fill-values record to resolve against\n * @param path - The field path — a single segment or a segment array\n * @returns The resolved value, or `undefined` when unresolved or the path is unsafe\n *\n * @example\n * ```ts\n * import { resolveSafeField } from '@orkestrel/template'\n *\n * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1\n * resolveSafeField({}, ['__proto__', 'polluted']) // undefined\n * ```\n */\nexport function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown {\n\tconst segments = isArray(path) ? path : [path]\n\tif (segments.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return undefined\n\treturn resolveField(record, path)\n}\n\n/**\n * Resolves one `{{name}}` token against the declared placeholders and the\n * fill-values record.\n *\n * @param record - The fill-values record the token resolves against\n * @param placeholders - The declared placeholders the token matches by name\n * @param token - The trimmed token text, without its `{{` / `}}` delimiters\n * @returns The {@link TemplateTokenResolution} for the token\n *\n * @example\n * ```ts\n * import { resolveToken } from '@orkestrel/template'\n *\n * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'\n * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false\n * ```\n */\nexport function resolveToken(\n\trecord: TemplateFillValues,\n\tplaceholders: readonly TemplatePlaceholder[],\n\ttoken: string,\n): TemplateTokenResolution {\n\tconst declared = placeholders.find((placeholder) => placeholder.name === token)\n\tconst path = declared?.path ?? token.split('.')\n\treturn {\n\t\tvalue: resolveSafeField(record, path),\n\t\tdeclared,\n\t\trequired: declared === undefined || declared.required !== false,\n\t}\n}\n\n/**\n * Substitutes every `{{name}}` token in `content` in a single pass.\n *\n * @param content - The template content carrying `{{name}}` tokens\n * @param values - The values tokens resolve against\n * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and declared `placeholders`\n * @returns The substituted content\n *\n * @example\n * ```ts\n * import { fillTemplate } from '@orkestrel/template'\n *\n * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'\n * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'\n * ```\n */\nexport function fillTemplate(\n\tcontent: string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateFillContext,\n): string {\n\tconst placeholders = options?.placeholders ?? []\n\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\tconst record = values ?? {}\n\n\tconst missingNames: string[] = []\n\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst result = content.replace(pattern, (matchText: string, rawToken: string | undefined) => {\n\t\tif (rawToken === undefined) return '{{'\n\t\tconst token = rawToken.trim()\n\n\t\tconst { value, declared, required } = resolveToken(record, placeholders, token)\n\n\t\tif (value !== undefined) return formatValue(value, locale)\n\t\tif (declared?.fallback !== undefined) return formatValue(declared.fallback, locale)\n\n\t\tif (missing === 'literal') return matchText\n\t\tif (missing === 'empty') return ''\n\n\t\tif (required && !missingNames.includes(token)) {\n\t\t\tmissingNames.push(token)\n\t\t}\n\t\treturn ''\n\t})\n\n\tif (missing === 'error' && missingNames.length > 0) {\n\t\tthrow new TemplateError(\n\t\t\t'MISSING',\n\t\t\t`Missing required placeholder(s): ${missingNames.join(', ')}`,\n\t\t\t{ missing: missingNames },\n\t\t)\n\t}\n\n\treturn result\n}\n\n// === Lexing, source normalization, and compiler diagnostics\n\n/**\n * Quotes untrusted text for a template error message as a length-capped JSON\n * string literal.\n *\n * @param value - The raw text to quote\n * @returns The quoted diagnostic text\n *\n * @example\n * ```ts\n * import { quoteTemplateText } from '@orkestrel/template'\n *\n * quoteTemplateText('tojson') // '\"tojson\"'\n * ```\n */\nexport function quoteTemplateText(value: string): string {\n\tconst clipped = value.length > 120 ? `${value.slice(0, 120)}...` : value\n\treturn JSON.stringify(clipped)\n}\n\n/**\n * Normalizes a Jinja template source by converting every line ending to `\\n`\n * and dropping one trailing line ending when present.\n *\n * @param source - The raw template source\n * @returns The normalized source text\n *\n * @example\n * ```ts\n * import { normalizeTemplateSource } from '@orkestrel/template'\n *\n * normalizeTemplateSource('Hi\\r\\n\\r\\n') // 'Hi\\n'\n * ```\n */\nexport function normalizeTemplateSource(source: string): string {\n\tconst lines = source.split(/\\r\\n|\\r|\\n/)\n\treturn (lines.at(-1) === '' ? lines.slice(0, -1) : lines).join('\\n')\n}\n\n/**\n * Trims literal template text between adjacent Jinja tags under `trim_blocks`\n * and `lstrip_blocks`, honoring `-` and `+` delimiter markers.\n *\n * @param text - The text between the two tags\n * @param closer - The closing delimiter of the preceding tag, or `''` at start\n * @param opener - The opening delimiter of the following tag, or `''` at end\n * @returns The trimmed text\n *\n * @example\n * ```ts\n * import { trimTemplateText } from '@orkestrel/template'\n *\n * trimTemplateText('\\n ', '%}', '{%') // ''\n * trimTemplateText('Hi \\n', '}}', '{{-') // 'Hi'\n * ```\n */\nexport function trimTemplateText(text: string, closer: string, opener: string): string {\n\tconst kept = closer.startsWith('-')\n\t\t? text.replace(new RegExp(`^${TEMPLATE_SPACE}+`, 'u'), '')\n\t\t: (closer === '%}' || closer === '#}') && text.startsWith('\\n')\n\t\t\t? text.slice(1)\n\t\t\t: text\n\tif (opener.endsWith('-')) return kept.replace(new RegExp(`${TEMPLATE_SPACE}+$`, 'u'), '')\n\tif (opener !== '{%' && opener !== '{#') return kept\n\tconst start = kept.lastIndexOf('\\n') + 1\n\tconst starting = closer === '' || text.slice(0, text.length - kept.length).endsWith('\\n')\n\treturn (start > 0 || starting) && new RegExp(`^${TEMPLATE_SPACE}+$`, 'u').test(kept.slice(start))\n\t\t? kept.slice(0, start)\n\t\t: kept\n}\n\n/**\n * Locates a UTF-16 offset in a template source as a 1-based `[line, column]` pair.\n *\n * @param starts - The starting offset of each line in ascending order\n * @param offset - The offset to locate\n * @returns The 1-based line and column\n *\n * @example\n * ```ts\n * import { locateTemplateOffset } from '@orkestrel/template'\n *\n * locateTemplateOffset([0, 4], 5) // [2, 2]\n * ```\n */\nexport function locateTemplateOffset(\n\tstarts: readonly number[],\n\toffset: number,\n): readonly [line: number, column: number] {\n\tconst line = Math.max(\n\t\t0,\n\t\tstarts.findLastIndex((start) => start <= offset),\n\t)\n\treturn [line + 1, offset - (starts[line] ?? 0) + 1]\n}\n\n/**\n * Maps each character position of `normalizeTemplateSource(source)` back to its\n * UTF-16 offset in the original unnormalized source.\n *\n * @param source - The original unnormalized template source\n * @returns The normalized text and its boundary-to-original offset array\n *\n * @example\n * ```ts\n * import { mapTemplateOffsets } from '@orkestrel/template'\n *\n * mapTemplateOffsets('a\\r\\nb')[1] // [0, 1, 3, 4]\n * ```\n */\nexport function mapTemplateOffsets(\n\tsource: string,\n): readonly [normalized: string, offsets: readonly number[]] {\n\tconst chars: string[] = []\n\tconst offsets: number[] = []\n\tfor (let index = 0; index < source.length; index += 1) {\n\t\tconst code = source.charCodeAt(index)\n\t\tif (code === 10 && source.charCodeAt(index - 1) === 13) continue\n\t\toffsets.push(index)\n\t\tchars.push(code === 13 ? '\\n' : (source[index] ?? ''))\n\t}\n\tconst trailing = chars.at(-1) === '\\n'\n\tconst keptChars = trailing ? chars.slice(0, -1) : chars\n\tconst keptOffsets = trailing ? offsets.slice(0, -1) : offsets\n\tconst finalOffset = trailing ? (offsets.at(-1) ?? source.length) : source.length\n\treturn [keptChars.join(''), [...keptOffsets, finalOffset]]\n}\n\n/**\n * Scans the interior of one Jinja tag into lexical tokens with original UTF-16\n * offsets and 1-based line and column positions.\n *\n * @param text - The tag interior between delimiters\n * @param offset - The normalized-source offset of the tag interior's start\n * @param starts - Line-start offsets in the normalized source\n * @param offsets - Boundary map from normalized offsets to original UTF-16 offsets\n * @returns The scanned tokens inside the tag\n *\n * @example\n * ```ts\n * import { scanTemplateTag } from '@orkestrel/template'\n *\n * scanTemplateTag(' loop.first ', 2, [0]).map((token) => token.text) // ['loop', '.', 'first']\n * ```\n */\nexport function scanTemplateTag(\n\ttext: string,\n\toffset: number,\n\tstarts: readonly number[],\n\toffsets?: readonly number[],\n): readonly TemplateToken[] {\n\tconst pattern = new RegExp(TEMPLATE_TOKEN_PATTERN.source, TEMPLATE_TOKEN_PATTERN.flags)\n\treturn Array.from(text.matchAll(pattern)).flatMap((match): readonly TemplateToken[] => {\n\t\tconst normalizedStart = offset + match.index\n\t\tconst normalizedEnd = normalizedStart + match[0].length\n\t\tconst [line, column] = locateTemplateOffset(starts, normalizedStart)\n\t\tconst start = offsets?.[normalizedStart] ?? normalizedStart\n\t\tconst end = offsets?.[normalizedEnd] ?? normalizedEnd\n\t\tif (match[1] !== undefined) return []\n\t\tif (match[7] !== undefined) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttoken: 'fault',\n\t\t\t\t\ttext: `holds the character ${quoteTemplateText(match[0])}, which starts no token`,\n\t\t\t\t\tline,\n\t\t\t\t\tcolumn,\n\t\t\t\t\tstart,\n\t\t\t\t\tend,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tconst token: TemplateTokenForm =\n\t\t\tmatch[2] !== undefined\n\t\t\t\t? 'float'\n\t\t\t\t: match[3] !== undefined\n\t\t\t\t\t? 'integer'\n\t\t\t\t\t: match[4] !== undefined\n\t\t\t\t\t\t? 'name'\n\t\t\t\t\t\t: match[5] !== undefined\n\t\t\t\t\t\t\t? 'string'\n\t\t\t\t\t\t\t: 'operator'\n\t\treturn [{ token, text: match[0], line, column, start, end }]\n\t})\n}\n\n/**\n * Scans a raw Jinja template source into its token stream, including trimmed\n * text, comments, tag delimiters, inner tokens, and a closing `end` token.\n *\n * @param source - The template source\n * @returns The scanned tokens, ending with an `end` token\n *\n * @example\n * ```ts\n * import { scanTemplateTokens } from '@orkestrel/template'\n *\n * scanTemplateTokens('Hi {{ name }}').map((token) => token.token)\n * // ['text', 'variable', 'name', 'close', 'end']\n * ```\n */\nexport function scanTemplateTokens(source: string): readonly TemplateToken[] {\n\tconst [normalized, offsets] = mapTemplateOffsets(source)\n\tconst starts = [0, ...Array.from(normalized.matchAll(/\\n/g), (match) => match.index + 1)]\n\tconst pattern = new RegExp(TEMPLATE_SEGMENT_PATTERN.source, TEMPLATE_SEGMENT_PATTERN.flags)\n\tconst segments = Array.from(normalized.matchAll(pattern))\n\tconst tokens = segments.flatMap((segment, index): readonly TemplateToken[] => {\n\t\tconst previous = segments[index - 1]\n\t\tconst text = segment[1] ?? ''\n\t\tconst opener = segment[2] ?? segment[5] ?? segment[8] ?? segment[11] ?? ''\n\t\tconst kept = trimTemplateText(\n\t\t\ttext,\n\t\t\tprevious?.[4] ?? previous?.[7] ?? previous?.[10] ?? '',\n\t\t\topener,\n\t\t)\n\t\tconst [line, column] = locateTemplateOffset(starts, segment.index)\n\t\tconst textStart = offsets[segment.index] ?? segment.index\n\t\tconst textEnd = offsets[segment.index + text.length] ?? segment.index + text.length\n\t\tconst leading: readonly TemplateToken[] =\n\t\t\tkept === ''\n\t\t\t\t? []\n\t\t\t\t: [{ token: 'text', text: kept, line, column, start: textStart, end: textEnd }]\n\t\tconst tag = segment.index + text.length\n\t\tconst [tagLine, tagColumn] = locateTemplateOffset(starts, tag)\n\t\tconst tagStart = offsets[tag] ?? tag\n\t\tif (segment[11] !== undefined) {\n\t\t\tconst subject = segment[11] === '{#' ? 'comment' : 'tag'\n\t\t\treturn [\n\t\t\t\t...leading,\n\t\t\t\t{\n\t\t\t\t\ttoken: 'fault',\n\t\t\t\t\ttext: `opens a ${subject} that never closes`,\n\t\t\t\t\tline: tagLine,\n\t\t\t\t\tcolumn: tagColumn,\n\t\t\t\t\tstart: tagStart,\n\t\t\t\t\tend: source.length,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (segment[8] !== undefined && segment[9] !== undefined && segment[10] !== undefined) {\n\t\t\tconst commentEnd = tag + segment[8].length + segment[9].length + segment[10].length\n\t\t\treturn [\n\t\t\t\t...leading,\n\t\t\t\t{\n\t\t\t\t\ttoken: 'comment',\n\t\t\t\t\ttext: segment[9],\n\t\t\t\t\tline: tagLine,\n\t\t\t\t\tcolumn: tagColumn,\n\t\t\t\t\tstart: tagStart,\n\t\t\t\t\tend: offsets[commentEnd] ?? commentEnd,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tconst inside = segment[3] ?? segment[6]\n\t\tconst closer = segment[4] ?? segment[7]\n\t\tif (inside === undefined || closer === undefined) return leading\n\t\tconst closeOffset = tag + opener.length + inside.length\n\t\tconst [closeLine, closeColumn] = locateTemplateOffset(starts, closeOffset)\n\t\tconst openEnd = offsets[tag + opener.length] ?? tag + opener.length\n\t\tconst closeStart = offsets[closeOffset] ?? closeOffset\n\t\tconst closeEnd = offsets[closeOffset + closer.length] ?? closeOffset + closer.length\n\t\treturn [\n\t\t\t...leading,\n\t\t\t{\n\t\t\t\ttoken: segment[2] === undefined ? 'variable' : 'block',\n\t\t\t\ttext: opener,\n\t\t\t\tline: tagLine,\n\t\t\t\tcolumn: tagColumn,\n\t\t\t\tstart: tagStart,\n\t\t\t\tend: openEnd,\n\t\t\t},\n\t\t\t...scanTemplateTag(inside, tag + opener.length, starts, offsets),\n\t\t\t{\n\t\t\t\ttoken: 'close',\n\t\t\t\ttext: closer,\n\t\t\t\tline: closeLine,\n\t\t\t\tcolumn: closeColumn,\n\t\t\t\tstart: closeStart,\n\t\t\t\tend: closeEnd,\n\t\t\t},\n\t\t]\n\t})\n\tconst [line, column] = locateTemplateOffset(starts, normalized.length)\n\treturn [\n\t\t...tokens,\n\t\t{ token: 'end', text: '', line, column, start: source.length, end: source.length },\n\t]\n}\n\n/**\n * Builds a `FORMAT`-coded {@link TemplateError} anchored at a token's source location.\n *\n * @param token - The token locating the syntax or subset refusal\n * @param message - The diagnostic clause after \"the template\"\n * @param context - Additional context members carried beside `line`, `column`, `start`, and `end`\n * @returns The constructed {@link TemplateError}\n *\n * @example\n * ```ts\n * import { buildTemplateFormatError, scanTemplateTokens } from '@orkestrel/template'\n *\n * const [token] = scanTemplateTokens('{{ x }}')\n * buildTemplateFormatError(token, 'uses an unknown filter', { feature: 'unknown' }).code // 'FORMAT'\n * ```\n */\nexport function buildTemplateFormatError(\n\ttoken: TemplateToken,\n\tmessage: string,\n\tcontext?: Readonly<Record<string, unknown>>,\n): TemplateError {\n\treturn new TemplateError(\n\t\t'FORMAT',\n\t\t`At line ${token.line}, column ${token.column}, the template ${message}.`,\n\t\t{\n\t\t\t...context,\n\t\t\tline: token.line,\n\t\t\tcolumn: token.column,\n\t\t\tstart: token.start,\n\t\t\tend: token.end,\n\t\t},\n\t)\n}\n\n/**\n * Builds an `EVALUATION`-coded {@link TemplateError} for runtime evaluation refusals.\n *\n * @param message - The diagnostic clause after \"The template\"\n * @param context - Additional context members describing the failure\n * @returns The constructed {@link TemplateError}\n *\n * @example\n * ```ts\n * import { buildTemplateEvaluationError } from '@orkestrel/template'\n *\n * buildTemplateEvaluationError('adds a string to an integer').code // 'EVALUATION'\n * ```\n */\nexport function buildTemplateEvaluationError(\n\tmessage: string,\n\tcontext?: Readonly<Record<string, unknown>>,\n): TemplateError {\n\treturn new TemplateError('EVALUATION', `The template ${message}.`, context)\n}\n\n/**\n * Renders a scanned token into a readable label for syntax diagnostics.\n *\n * @param token - The token to describe\n * @returns The human-readable token description\n *\n * @example\n * ```ts\n * import { renderTemplateToken } from '@orkestrel/template'\n *\n * renderTemplateToken({ token: 'end', text: '', line: 1, column: 1, start: 0, end: 0 }) // 'the end of the template'\n * ```\n */\nexport function renderTemplateToken(token: TemplateToken): string {\n\tif (token.token === 'end') return 'the end of the template'\n\tif (token.token === 'text') return 'template text'\n\tif (token.token === 'comment') return 'a comment'\n\treturn quoteTemplateText(token.text)\n}\n\n/**\n * Checks whether a scanned token matches an expected form and optional text.\n *\n * @param token - The token to inspect\n * @param form - The required token form\n * @param text - Optional exact text to match\n * @returns True if `token` matches; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateToken } from '@orkestrel/template'\n *\n * matchesTemplateToken({ token: 'name', text: 'in', line: 1, column: 1, start: 0, end: 2 }, 'name', 'in') // true\n * ```\n */\nexport function matchesTemplateToken(\n\ttoken: TemplateToken,\n\tform: TemplateTokenForm,\n\ttext?: string,\n): boolean {\n\treturn token.token === form && (text === undefined || token.text === text)\n}\n\n/**\n * Reads the token at an index of a token stream, throwing on `fault` tokens or\n * an empty stream.\n *\n * @param tokens - The token stream\n * @param index - The index to read\n * @returns The resolved token\n *\n * @example\n * ```ts\n * import { readTemplateToken, scanTemplateTokens } from '@orkestrel/template'\n *\n * readTemplateToken(scanTemplateTokens('{{ x }}'), 1).text // 'x'\n * ```\n */\nexport function readTemplateToken(tokens: readonly TemplateToken[], index: number): TemplateToken {\n\tconst token = tokens[index] ?? tokens.at(-1)\n\tif (token === undefined) {\n\t\tthrow new TemplateError('INVALID', 'A template compiles from at least its end token.')\n\t}\n\tif (token.token === 'fault') throw buildTemplateFormatError(token, token.text)\n\treturn token\n}\n\n/**\n * Refuses a token that does not match an expected form and optional text with a\n * `FORMAT`-coded {@link TemplateError}.\n *\n * @param tokens - The token stream\n * @param index - The index to validate\n * @param form - The required token form\n * @param text - Optional exact text to require\n *\n * @example\n * ```ts\n * import { checkTemplateToken, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateToken(scanTemplateTokens('{{ x }}'), 1, 'name', 'x')\n * ```\n */\nexport function checkTemplateToken(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tform: TemplateTokenForm,\n\ttext?: string,\n): void {\n\tconst token = readTemplateToken(tokens, index)\n\tif (matchesTemplateToken(token, form, text)) return\n\tconst expected =\n\t\tform === 'close'\n\t\t\t? 'the tag to close'\n\t\t\t: text === undefined\n\t\t\t\t? `a ${form}`\n\t\t\t\t: quoteTemplateText(text)\n\tthrow buildTemplateFormatError(\n\t\ttoken,\n\t\t`expects ${expected} and finds ${renderTemplateToken(token)}`,\n\t)\n}\n\n/**\n * Consumes an optional trailing colon (where admitted) and closing tag delimiter.\n *\n * @param tokens - The token stream\n * @param index - The position after the tag's expression\n * @param colon - If `true`, admits one trailing colon before the closer; if `false`, requires the closer immediately\n * @returns The index after the closing delimiter\n *\n * @example\n * ```ts\n * import { checkTemplateClose, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateClose(scanTemplateTokens('{% else: %}'), 2, true) // 4\n * ```\n */\nexport function checkTemplateClose(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tcolon: boolean,\n): number {\n\tconst token = readTemplateToken(tokens, index)\n\tif (matchesTemplateToken(token, 'operator', ',')) {\n\t\tthrow buildTemplateFormatError(token, 'writes a tuple, which the subset does not admit', {\n\t\t\tfeature: 'tuple',\n\t\t})\n\t}\n\tconst start = colon && matchesTemplateToken(token, 'operator', ':') ? index + 1 : index\n\tcheckTemplateToken(tokens, start, 'close')\n\treturn start + 1\n}\n\n/**\n * Refuses template nesting deeper than `MAX_DEPTH` (`64`) with a `FORMAT`-coded\n * {@link TemplateError}.\n *\n * @param depth - The nesting level reached\n * @param token - The token locating the refusal\n *\n * @example\n * ```ts\n * import { checkTemplateDepth, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateDepth(4, scanTemplateTokens('{{ x }}')[0])\n * ```\n */\nexport function checkTemplateDepth(depth: number, token: TemplateToken): void {\n\tif (depth <= MAX_DEPTH) return\n\tthrow buildTemplateFormatError(token, `nests deeper than ${MAX_DEPTH} levels`, {\n\t\tlimit: MAX_DEPTH,\n\t})\n}\n\n/**\n * Refuses an invalid assignment target name such as a literal, reserved global\n * function, or private `__`-prefixed identifier.\n *\n * @param token - The target token to validate\n *\n * @example\n * ```ts\n * import { checkTemplateTarget, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateTarget(scanTemplateTokens('{% set count = 1 %}')[2])\n * ```\n */\nexport function checkTemplateTarget(token: TemplateToken): void {\n\tif (token.token !== 'name' || keyOf(TEMPLATE_LITERALS)(token.text)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to ${renderTemplateToken(token)}, which is not a name`,\n\t\t)\n\t}\n\tif (token.text.startsWith('__')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to the private name ${quoteTemplateText(token.text)}`,\n\t\t\t{ feature: 'private' },\n\t\t)\n\t}\n\tif (TEMPLATE_FUNCTIONS.some((name) => name === token.text)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`assigns to the function ${quoteTemplateText(token.text)}, which the subset does not admit`,\n\t\t\t{ feature: token.text },\n\t\t)\n\t}\n}\n\n/**\n * Refuses a compile-time read of a `loop` member listed in `TEMPLATE_LOOP_REFUSALS`.\n *\n * @param object - The target expression being indexed\n * @param key - The member key expression\n * @param token - The token locating the refusal\n *\n * @example\n * ```ts\n * import { checkTemplateLoopMember, scanTemplateTokens } from '@orkestrel/template'\n *\n * checkTemplateLoopMember(\n * { term: 'name', name: 'loop' },\n * { term: 'literal', value: 'previtem' },\n * scanTemplateTokens('{{ loop.previtem }}')[1],\n * )\n * ```\n */\nexport function checkTemplateLoopMember(\n\tobject: TemplateExpression,\n\tkey: TemplateExpression,\n\ttoken: TemplateToken,\n): void {\n\tif (object.term !== 'name' || object.name !== 'loop' || key.term !== 'literal') return\n\tconst name = key.value\n\tif (!TEMPLATE_LOOP_REFUSALS.some((member) => member === name)) return\n\tthrow buildTemplateFormatError(\n\t\ttoken,\n\t\t`reads ${quoteTemplateText(`loop.${String(name)}`)}, which the subset does not admit`,\n\t\t{ feature: `loop.${String(name)}` },\n\t)\n}\n\n/**\n * Decodes a quoted Jinja string token using Python `unicode-escape` rules.\n *\n * @param token - The string literal token including quotes\n * @returns The decoded string value\n *\n * @example\n * ```ts\n * import { decodeTemplateString, scanTemplateTokens } from '@orkestrel/template'\n *\n * decodeTemplateString(scanTemplateTokens(\"{{ 'a\\\\nb' }}\")[1]) // 'a\\nb'\n * ```\n */\nexport function decodeTemplateString(token: TemplateToken): string {\n\treturn token.text\n\t\t.slice(1, -1)\n\t\t.replace(\n\t\t\t/\\\\(x[\\da-fA-F]{2}|u[\\da-fA-F]{4}|U[\\da-fA-F]{8}|[0-7]{1,3}|N\\{[^}]*\\}|[^])/gu,\n\t\t\t(escape: string, body: string) => {\n\t\t\t\tconst lead = body[0] ?? ''\n\t\t\t\tif (body.length > 1 && lead === 'N') {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t`writes the named escape ${quoteTemplateText(escape)}, which the subset does not admit`,\n\t\t\t\t\t\t{ feature: 'named escape' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (body.length > 1 && (lead === 'x' || lead === 'u' || lead === 'U')) {\n\t\t\t\t\tconst point = Number.parseInt(body.slice(1), 16)\n\t\t\t\t\tif (point > 0x10ffff) {\n\t\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t\t`writes the escape ${quoteTemplateText(escape)}, past U+10FFFF`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\treturn String.fromCodePoint(point)\n\t\t\t\t}\n\t\t\t\tif (/^[0-7]/u.test(body)) return String.fromCodePoint(Number.parseInt(body, 8))\n\t\t\t\tif (body === 'x' || body === 'u' || body === 'U' || body === 'N') {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t`writes the truncated escape ${quoteTemplateText(escape)}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (body === '\\n') return ''\n\t\t\t\tif (keyOf(TEMPLATE_ESCAPES)(body)) return TEMPLATE_ESCAPES[body]\n\t\t\t\tconst point = body.codePointAt(0) ?? 0\n\t\t\t\tif (point < 0x80) return escape\n\t\t\t\tconst hex = point.toString(16)\n\t\t\t\treturn point < 0x100\n\t\t\t\t\t? `\\\\x${hex.padStart(2, '0')}`\n\t\t\t\t\t: point < 0x10000\n\t\t\t\t\t\t? `\\\\u${hex.padStart(4, '0')}`\n\t\t\t\t\t\t: `\\\\U${hex.padStart(8, '0')}`\n\t\t\t},\n\t\t)\n}\n\n/**\n * Decodes an `integer` or `float` token as Jinja reads numeric literals.\n *\n * @param token - The numeric literal token\n * @returns The decoded finite number\n *\n * @example\n * ```ts\n * import { decodeTemplateNumber, scanTemplateTokens } from '@orkestrel/template'\n *\n * decodeTemplateNumber(scanTemplateTokens('{{ 0x1F }}')[1]) // 31\n * ```\n */\nexport function decodeTemplateNumber(token: TemplateToken): number {\n\tconst value = Number(token.text.replaceAll('_', ''))\n\tif (token.token === 'integer' && !Number.isSafeInteger(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`writes the integer ${quoteTemplateText(token.text)}, past the integers JavaScript holds exactly`,\n\t\t\t{ feature: 'big integer' },\n\t\t)\n\t}\n\tif (token.token === 'float' && Number.isInteger(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`writes the float ${quoteTemplateText(token.text)}, whose whole value the subset holds as an integer`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tif (Number.isNaN(value)) {\n\t\tthrow buildTemplateFormatError(\n\t\t\ttoken,\n\t\t\t`expects a number and finds ${renderTemplateToken(token)}`,\n\t\t)\n\t}\n\treturn value\n}\n\n// === Runtime value normalization, operators, filters, tests, and methods\n\n/**\n * Normalizes a caller-supplied value into a runtime {@link TemplateRuntimeValue},\n * converting plain objects to string-keyed `Map`s while preserving `HTMLNode`,\n * `MarkdownNode`, and `TemplateNamespace` instances and capping depth at `MAX_DEPTH`.\n *\n * @param value - The value to normalize\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to guard against cycles\n * @returns The normalized runtime value\n *\n * @example\n * ```ts\n * import { normalizeTemplateValue } from '@orkestrel/template'\n *\n * normalizeTemplateValue({ role: 'user' }) // Map { 'role' => 'user' }\n * ```\n */\nexport function normalizeTemplateValue(\n\tvalue: unknown,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): TemplateRuntimeValue {\n\tif (\n\t\tvalue === undefined ||\n\t\tvalue === null ||\n\t\tisBoolean(value) ||\n\t\ttypeof value === 'number' ||\n\t\tisString(value)\n\t) {\n\t\treturn value\n\t}\n\tif (isHTMLNode(value) || isMarkdownNode(value) || isTemplateNamespace(value)) return value\n\tif (depth > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`nests runtime values deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (isArray(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic list in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\treturn value.map((item) => normalizeTemplateValue(item, depth + 1, ancestors))\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isMap(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic mapping in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\t\tfor (const [entryKey, entryValue] of value.entries()) {\n\t\t\t\tif (isString(entryKey) && entryValue !== undefined) {\n\t\t\t\t\tentries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)])\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Map(entries)\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isRecord(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('encounters a cyclic record in runtime values', {\n\t\t\t\tfeature: 'cycle',\n\t\t\t})\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\t\tfor (const [entryKey, entryValue] of Object.entries(value)) {\n\t\t\t\tif (entryValue !== undefined) {\n\t\t\t\t\tentries.push([entryKey, normalizeTemplateValue(entryValue, depth + 1, ancestors)])\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Map(entries)\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\treturn String(value)\n}\n\n/**\n * Checks whether a runtime value is a compiled {@link TemplateMacro} closure.\n *\n * @param value - The runtime value to inspect\n * @returns True if `value` is a macro closure; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateMacro } from '@orkestrel/template'\n *\n * isTemplateMacro('text') // false\n * ```\n */\nexport function isTemplateMacro(value: unknown): value is TemplateMacro {\n\treturn (\n\t\tisObject(value) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\tReflect.get(value, 'macro') === true &&\n\t\tisString(Reflect.get(value, 'name'))\n\t)\n}\n\n/**\n * Checks whether a runtime value is a `for` {@link TemplateLoop} state record.\n *\n * @param value - The runtime value to inspect\n * @returns True if `value` is a loop state record; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateLoop } from '@orkestrel/template'\n *\n * isTemplateLoop({ index0: 0, length: 1, previtem: undefined, nextitem: undefined }) // true\n * ```\n */\nexport function isTemplateLoop(value: unknown): value is TemplateLoop {\n\treturn (\n\t\tisObject(value) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\t!isTemplateNamespace(value) &&\n\t\t!isTemplateMacro(value) &&\n\t\t!isHTMLNode(value) &&\n\t\t!isMarkdownNode(value) &&\n\t\ttypeof Reflect.get(value, 'index0') === 'number' &&\n\t\ttypeof Reflect.get(value, 'length') === 'number'\n\t)\n}\n\n/**\n * Renders the Python-equivalent type label of a runtime value for diagnostics.\n *\n * @param value - The runtime value to describe\n * @returns The type description\n *\n * @example\n * ```ts\n * import { renderTemplateType } from '@orkestrel/template'\n *\n * renderTemplateType(new Map()) // 'a mapping'\n * ```\n */\nexport function renderTemplateType(value: TemplateRuntimeValue): string {\n\tif (value === undefined) return 'an undefined value'\n\tif (value === null) return 'none'\n\tif (typeof value === 'boolean') return 'a boolean'\n\tif (typeof value === 'number') return Number.isInteger(value) ? 'an integer' : 'a float'\n\tif (typeof value === 'string') return 'a string'\n\tif (isHTMLNode(value)) return 'an HTML node'\n\tif (isMarkdownNode(value)) return 'a Markdown node'\n\tif (isArray(value)) return 'a list'\n\tif (isMap(value)) return 'a mapping'\n\tif (isTemplateNamespace(value)) return 'a namespace'\n\tif (isTemplateMacro(value)) return 'a macro'\n\treturn 'a loop'\n}\n\n/**\n * Renders a finite or special number using Python `str` formatting.\n *\n * @param value - The number to format\n * @returns The Python-formatted numeric text\n *\n * @example\n * ```ts\n * import { renderTemplateNumber } from '@orkestrel/template'\n *\n * renderTemplateNumber(0.00001) // '1e-05'\n * ```\n */\nexport function renderTemplateNumber(value: number): string {\n\tif (Number.isNaN(value)) return 'nan'\n\tif (value === Infinity) return 'inf'\n\tif (value === -Infinity) return '-inf'\n\tif (Number.isInteger(value)) return Object.is(value, -0) ? '0' : String(value)\n\tconst [digits = '', power = '0'] = value.toExponential().split('e')\n\tconst exponent = Number(power)\n\tif (exponent >= -4 && exponent < 16) return String(value)\n\treturn `${digits}e${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`\n}\n\n/**\n * Renders a runtime template value as string output using Python/Jinja rules,\n * sanitizing `HTMLNode`s through `@orkestrel/html` and rendering `MarkdownNode`s\n * through `@orkestrel/markdown`.\n *\n * @param value - The runtime value to render\n * @returns The rendered text\n *\n * @example\n * ```ts\n * import { renderTemplateValue } from '@orkestrel/template'\n *\n * renderTemplateValue(true) // 'True'\n * renderTemplateValue(null) // 'None'\n * ```\n */\nexport function renderTemplateValue(value: TemplateRuntimeValue): string {\n\tif (typeof value === 'string') return value\n\tif (value === undefined) return ''\n\tif (value === null) return 'None'\n\tif (typeof value === 'boolean') return value ? 'True' : 'False'\n\tif (typeof value === 'number') return renderTemplateNumber(value)\n\tif (isHTMLNode(value)) {\n\t\tconst document: HTMLDocument =\n\t\t\tvalue.category === 'document' ? value : { category: 'document', children: [value] }\n\t\treturn renderHTML(createHTML(document).sanitize().document)\n\t}\n\tif (isMarkdownNode(value)) return renderMarkdown(value)\n\tthrow buildTemplateEvaluationError(\n\t\t`prints ${renderTemplateType(value)}, which Python prints as its repr and the subset does not`,\n\t\t{ feature: 'repr' },\n\t)\n}\n\n/**\n * Serializes a runtime template value to deterministic JSON matching `minja`\n * and Python `json.dumps` (`\", \"` and `\": \"` separators, insertion key order,\n * unescaped non-ASCII Unicode).\n *\n * @param value - The runtime value to serialize\n * @param depth - Current recursion depth. Default: `0`\n * @param ancestors - Ancestor set used to guard against cycles\n * @returns The serialized JSON string\n *\n * @example\n * ```ts\n * import { serializeTemplateJSON } from '@orkestrel/template'\n *\n * serializeTemplateJSON(new Map([['b', true], ['a', [1, 2]]])) // '{\"b\": true, \"a\": [1, 2]}'\n * ```\n */\nexport function serializeTemplateJSON(\n\tvalue: TemplateRuntimeValue,\n\tdepth = 0,\n\tancestors: WeakSet<object> = new WeakSet(),\n): string {\n\tif (depth > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`serializes JSON deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (value === null || value === undefined) return 'null'\n\tif (typeof value === 'boolean') return value ? 'true' : 'false'\n\tif (typeof value === 'number') {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a non-finite number to JSON', {\n\t\t\t\tfeature: 'tojson',\n\t\t\t})\n\t\t}\n\t\treturn Object.is(value, -0) ? '0' : String(value)\n\t}\n\tif (typeof value === 'string') return JSON.stringify(value)\n\tif (isArray(value)) {\n\t\tif (ancestors.has(value)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a cyclic list to JSON', { feature: 'tojson' })\n\t\t}\n\t\tancestors.add(value)\n\t\ttry {\n\t\t\tconst items = value.map((item) => serializeTemplateJSON(item, depth + 1, ancestors))\n\t\t\treturn `[${items.join(', ')}]`\n\t\t} finally {\n\t\t\tancestors.delete(value)\n\t\t}\n\t}\n\tif (isMap(value) || isTemplateNamespace(value)) {\n\t\tconst map = isTemplateNamespace(value) ? value.values : value\n\t\tif (ancestors.has(map)) {\n\t\t\tthrow buildTemplateEvaluationError('serializes a cyclic mapping to JSON', {\n\t\t\t\tfeature: 'tojson',\n\t\t\t})\n\t\t}\n\t\tancestors.add(map)\n\t\ttry {\n\t\t\tconst pairs = Array.from(map.entries()).map(\n\t\t\t\t([entryKey, entryValue]) =>\n\t\t\t\t\t`${JSON.stringify(entryKey)}: ${serializeTemplateJSON(entryValue, depth + 1, ancestors)}`,\n\t\t\t)\n\t\t\treturn `{${pairs.join(', ')}}`\n\t\t} finally {\n\t\t\tancestors.delete(map)\n\t\t}\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`serializes ${renderTemplateType(value)} to JSON, which is not JSON-serializable`,\n\t\t{ feature: 'tojson' },\n\t)\n}\n\n/**\n * Checks whether a runtime template value is truthy under Python `bool` rules.\n *\n * @param value - The value to test\n * @returns True if truthy; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateTruth } from '@orkestrel/template'\n *\n * matchesTemplateTruth('') // false\n * matchesTemplateTruth([0]) // true\n * ```\n */\nexport function matchesTemplateTruth(value: TemplateRuntimeValue): boolean {\n\tif (value === undefined || value === null) return false\n\tif (typeof value === 'boolean') return value\n\tif (typeof value === 'number') return value !== 0\n\tif (typeof value === 'string') return value.length > 0\n\tif (isHTMLNode(value) || isMarkdownNode(value) || isTemplateMacro(value)) return true\n\tif (isArray(value)) return value.length > 0\n\tif (isMap(value)) return value.size > 0\n\tif (isTemplateNamespace(value)) return value.values.size > 0\n\treturn value.length > 0\n}\n\n/**\n * Checks whether two runtime template values are equal under Python `==` rules.\n *\n * @param left - The first value\n * @param right - The second value\n * @returns True if equal; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateEqual } from '@orkestrel/template'\n *\n * matchesTemplateEqual(true, 1) // true\n * matchesTemplateEqual('1', 1) // false\n * ```\n */\nexport function matchesTemplateEqual(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): boolean {\n\tif (\n\t\t(typeof left === 'number' || typeof left === 'boolean') &&\n\t\t(typeof right === 'number' || typeof right === 'boolean')\n\t) {\n\t\treturn Number(left) === Number(right)\n\t}\n\tif (isArray(left)) {\n\t\treturn (\n\t\t\tisArray(right) &&\n\t\t\tleft.length === right.length &&\n\t\t\tleft.every((item, index) => matchesTemplateEqual(item, right[index]))\n\t\t)\n\t}\n\tif (isMap(left)) {\n\t\treturn (\n\t\t\tisMap(right) &&\n\t\t\tleft.size === right.size &&\n\t\t\tArray.from(left).every(\n\t\t\t\t([key, item]) => right.has(key) && matchesTemplateEqual(item, right.get(key)),\n\t\t\t)\n\t\t)\n\t}\n\treturn left === right\n}\n\n/**\n * Compares two runtime template values for ordering under Python `<` rules.\n *\n * @param left - The first value\n * @param right - The second value\n * @returns Negative when `left < right`, positive when `left > right`, and `0` when equal\n *\n * @example\n * ```ts\n * import { compareTemplateValues } from '@orkestrel/template'\n *\n * compareTemplateValues(1, 2) < 0 // true\n * ```\n */\nexport function compareTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): number {\n\tif (\n\t\t(typeof left === 'number' || typeof left === 'boolean') &&\n\t\t(typeof right === 'number' || typeof right === 'boolean')\n\t) {\n\t\treturn Number(left) < Number(right) ? -1 : Number(left) > Number(right) ? 1 : 0\n\t}\n\tif (typeof left === 'string' && typeof right === 'string') {\n\t\tconst one = Array.from(left, (character) => character.codePointAt(0) ?? 0)\n\t\tconst two = Array.from(right, (character) => character.codePointAt(0) ?? 0)\n\t\tconst index = one.findIndex((point, position) => point !== two[position])\n\t\tif (index === -1) return one.length - two.length\n\t\treturn (one[index] ?? 0) - (two[index] ?? -1)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`orders ${renderTemplateType(left)} against ${renderTemplateType(right)}, which the subset does not admit`,\n\t\t{ feature: 'ordering' },\n\t)\n}\n\n/**\n * Checks whether a container holds a value under Python `in` rules.\n *\n * @param value - The value to look for\n * @param container - The container to inspect\n * @returns True if `container` contains `value`; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateMember } from '@orkestrel/template'\n *\n * matchesTemplateMember('tool', 'tool_calls') // true\n * ```\n */\nexport function matchesTemplateMember(\n\tvalue: TemplateRuntimeValue,\n\tcontainer: TemplateRuntimeValue,\n): boolean {\n\tif (container === undefined) return false\n\tif (typeof container === 'string' && typeof value === 'string') {\n\t\tif (value.isWellFormed()) return container.includes(value)\n\t\treturn `,${Array.from(container, (character) => character.codePointAt(0)).join(',')},`.includes(\n\t\t\t`,${Array.from(value, (character) => character.codePointAt(0)).join(',')},`,\n\t\t)\n\t}\n\tif (isArray(container)) return container.some((item) => matchesTemplateEqual(value, item))\n\tif (isMap(container) && !isArray(value) && !isMap(value) && !isTemplateNamespace(value)) {\n\t\treturn typeof value === 'string' && container.has(value)\n\t}\n\tif (\n\t\tisTemplateNamespace(container) &&\n\t\t!isArray(value) &&\n\t\t!isMap(value) &&\n\t\t!isTemplateNamespace(value)\n\t) {\n\t\treturn typeof value === 'string' && container.values.has(value)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`looks for ${renderTemplateType(value)} in ${renderTemplateType(container)}, which the subset does not admit`,\n\t\t{ feature: 'membership' },\n\t)\n}\n\n/**\n * Adds two runtime template values under Python `+` rules for strings, numbers, and lists.\n *\n * @param left - The first operand\n * @param right - The second operand\n * @returns The sum or concatenation\n *\n * @example\n * ```ts\n * import { addTemplateValues } from '@orkestrel/template'\n *\n * addTemplateValues('<|im_start|>', 'user') // '<|im_start|>user'\n * ```\n */\nexport function addTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (typeof left === 'string' && typeof right === 'string') return left + right\n\tif (isArray(left) && isArray(right)) return [...left, ...right]\n\tif (typeof left === 'number' && typeof right === 'number') {\n\t\tconst sum = left + right\n\t\tif (Number.isInteger(left) && Number.isInteger(right)) {\n\t\t\tif (Number.isSafeInteger(sum)) return sum\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t'adds integers past the integers JavaScript holds exactly',\n\t\t\t\t{ feature: 'big integer' },\n\t\t\t)\n\t\t}\n\t\tif (!Number.isInteger(sum)) return sum\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`adds floats to the whole value ${String(sum)}, which Python prints as a float`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`adds ${renderTemplateType(right)} to ${renderTemplateType(left)}, which the subset does not admit`,\n\t\t{ feature: 'addition' },\n\t)\n}\n\n/**\n * Subtracts two numeric runtime template values under Python `-` rules.\n *\n * @param left - The left numeric operand\n * @param right - The right numeric operand\n * @returns The numeric difference\n *\n * @example\n * ```ts\n * import { subtractTemplateValues } from '@orkestrel/template'\n *\n * subtractTemplateValues(5, 1) // 4\n * ```\n */\nexport function subtractTemplateValues(\n\tleft: TemplateRuntimeValue,\n\tright: TemplateRuntimeValue,\n): number {\n\tif (typeof left === 'number' && typeof right === 'number') {\n\t\tconst difference = left - right\n\t\tif (Number.isInteger(left) && Number.isInteger(right)) {\n\t\t\tif (Number.isSafeInteger(difference)) return Object.is(difference, -0) ? 0 : difference\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t'subtracts integers past the integers JavaScript holds exactly',\n\t\t\t\t{ feature: 'big integer' },\n\t\t\t)\n\t\t}\n\t\tif (!Number.isInteger(difference)) return difference\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`subtracts floats to the whole value ${String(difference)}, which Python prints as a float`,\n\t\t\t{ feature: 'whole float' },\n\t\t)\n\t}\n\tthrow buildTemplateEvaluationError(\n\t\t`subtracts ${renderTemplateType(right)} from ${renderTemplateType(left)}, which the subset does not admit`,\n\t\t{ feature: 'subtraction' },\n\t)\n}\n\n/**\n * Applies unary `-` or `+` to a numeric runtime template value.\n *\n * @param operator - `'-'` for negation or `'+'` for numeric identity\n * @param value - The numeric operand\n * @returns The resulting number\n *\n * @example\n * ```ts\n * import { negateTemplateValue } from '@orkestrel/template'\n *\n * negateTemplateValue('-', 1) // -1\n * ```\n */\nexport function negateTemplateValue(operator: '-' | '+', value: TemplateRuntimeValue): number {\n\tif (typeof value !== 'number') {\n\t\tconst feature = operator === '-' ? 'unary minus' : 'unary plus'\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies ${feature} to ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t\t{ feature },\n\t\t)\n\t}\n\tif (operator === '+') return value\n\tconst negated = -value\n\tif (Number.isInteger(value) && !Number.isSafeInteger(negated)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t'negates an integer past the integers JavaScript holds exactly',\n\t\t\t{ feature: 'big integer' },\n\t\t)\n\t}\n\treturn Object.is(negated, -0) ? 0 : negated\n}\n\n/**\n * Reads a member or index of a runtime template value under sandboxed Jinja rules,\n * supporting negative sequence indexing, `TemplateNamespace` properties, and\n * `loop.previtem` / `loop.nextitem`.\n *\n * @param object - The object or sequence to read from\n * @param key - The member name or integer index\n * @returns The resolved member value, or `undefined` when absent\n *\n * @example\n * ```ts\n * import { readTemplateMember } from '@orkestrel/template'\n *\n * readTemplateMember(['a', 'b'], -1) // 'b'\n * ```\n */\nexport function readTemplateMember(\n\tobject: TemplateRuntimeValue,\n\tkey: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (object === undefined) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the member ${typeof key === 'string' ? quoteTemplateText(key) : renderTemplateType(key)} of an undefined value, which Jinja refuses`,\n\t\t\t{ feature: 'undefined' },\n\t\t)\n\t}\n\tif (typeof key === 'string' && key.startsWith('__')) {\n\t\tthrow buildTemplateEvaluationError(`reads the private member ${quoteTemplateText(key)}`, {\n\t\t\tfeature: 'private',\n\t\t})\n\t}\n\tif (object === null) return undefined\n\tif (typeof object === 'number' || typeof object === 'boolean') {\n\t\tif (typeof key !== 'string') return undefined\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the attribute ${quoteTemplateText(key)} of ${renderTemplateType(object)}`,\n\t\t\t{ feature: 'attribute' },\n\t\t)\n\t}\n\tif (isTemplateNamespace(object)) {\n\t\treturn typeof key === 'string' ? object.values.get(key) : undefined\n\t}\n\tconst methods =\n\t\ttypeof object === 'string'\n\t\t\t? TEMPLATE_METHODS.string\n\t\t\t: isArray(object)\n\t\t\t\t? TEMPLATE_METHODS.list\n\t\t\t\t: isMap(object)\n\t\t\t\t\t? TEMPLATE_METHODS.mapping\n\t\t\t\t\t: []\n\tif (typeof key === 'string' && methods.includes(key)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads the method ${quoteTemplateText(key)} of ${renderTemplateType(object)}, which the subset does not admit`,\n\t\t\t{ feature: 'method' },\n\t\t)\n\t}\n\tif (isMap(object)) return typeof key === 'string' ? object.get(key) : undefined\n\tif (typeof object === 'string' || isArray(object)) {\n\t\tconst index = typeof key === 'boolean' ? Number(key) : key\n\t\tif (typeof index !== 'number' || !Number.isInteger(index)) return undefined\n\t\tconst items = typeof object === 'string' ? Array.from(object) : object\n\t\tconst resolved = index < 0 ? items.length + index : index\n\t\treturn resolved >= 0 && resolved < items.length ? items[resolved] : undefined\n\t}\n\tif (!isTemplateLoop(object) || typeof key !== 'string') return undefined\n\tif (TEMPLATE_LOOP_REFUSALS.some((member) => member === key)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`reads ${quoteTemplateText(`loop.${key}`)}, which the subset does not admit`,\n\t\t\t{ feature: `loop.${key}` },\n\t\t)\n\t}\n\tswitch (key) {\n\t\tcase 'index':\n\t\t\treturn object.index0 + 1\n\t\tcase 'index0':\n\t\t\treturn object.index0\n\t\tcase 'first':\n\t\t\treturn object.index0 === 0\n\t\tcase 'last':\n\t\t\treturn object.index0 === object.length - 1\n\t\tcase 'length':\n\t\t\treturn object.length\n\t\tcase 'previtem':\n\t\t\treturn object.previtem\n\t\tcase 'nextitem':\n\t\t\treturn object.nextitem\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/**\n * Slices a string (by Unicode code points) or list under Python\n * `seq[start:stop:step]` semantics, including negative bounds and `[::-1]`.\n *\n * @param object - The string or list to slice\n * @param start - Optional inclusive start index (`undefined` or `null` for default)\n * @param stop - Optional exclusive stop index (`undefined` or `null` for default)\n * @param step - Optional non-zero stride (`undefined` or `null` for `1`)\n * @returns The sliced string or list\n *\n * @example\n * ```ts\n * import { sliceTemplateSequence } from '@orkestrel/template'\n *\n * sliceTemplateSequence(['a', 'b', 'c'], undefined, undefined, -1) // ['c', 'b', 'a']\n * ```\n */\nexport function sliceTemplateSequence(\n\tobject: TemplateRuntimeValue,\n\tstart: TemplateRuntimeValue,\n\tstop: TemplateRuntimeValue,\n\tstep: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (typeof object !== 'string' && !isArray(object)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`slices ${renderTemplateType(object)}, which is not a sequence`,\n\t\t\t{ feature: 'slice' },\n\t\t)\n\t}\n\tconst rawStep =\n\t\tstep === undefined || step === null ? 1 : typeof step === 'boolean' ? Number(step) : step\n\tif (typeof rawStep !== 'number' || !Number.isInteger(rawStep)) {\n\t\tthrow buildTemplateEvaluationError('slices with a non-integer step', { feature: 'slice' })\n\t}\n\tif (rawStep === 0) {\n\t\tthrow buildTemplateEvaluationError('slices with a step of 0', { feature: 'slice' })\n\t}\n\tconst rawStart =\n\t\tstart === undefined || start === null\n\t\t\t? undefined\n\t\t\t: typeof start === 'boolean'\n\t\t\t\t? Number(start)\n\t\t\t\t: start\n\tconst rawStop =\n\t\tstop === undefined || stop === null\n\t\t\t? undefined\n\t\t\t: typeof stop === 'boolean'\n\t\t\t\t? Number(stop)\n\t\t\t\t: stop\n\tif (\n\t\t(rawStart !== undefined && (typeof rawStart !== 'number' || !Number.isInteger(rawStart))) ||\n\t\t(rawStop !== undefined && (typeof rawStop !== 'number' || !Number.isInteger(rawStop)))\n\t) {\n\t\tthrow buildTemplateEvaluationError('slices with a non-integer bound', { feature: 'slice' })\n\t}\n\tconst items = typeof object === 'string' ? Array.from(object) : object\n\tconst length = items.length\n\tconst from =\n\t\trawStep > 0\n\t\t\t? rawStart === undefined\n\t\t\t\t? 0\n\t\t\t\t: rawStart < 0\n\t\t\t\t\t? Math.max(0, length + rawStart)\n\t\t\t\t\t: Math.min(length, rawStart)\n\t\t\t: rawStart === undefined\n\t\t\t\t? length - 1\n\t\t\t\t: rawStart < 0\n\t\t\t\t\t? Math.max(-1, length + rawStart)\n\t\t\t\t\t: Math.min(length - 1, rawStart)\n\tconst to =\n\t\trawStep > 0\n\t\t\t? rawStop === undefined\n\t\t\t\t? length\n\t\t\t\t: rawStop < 0\n\t\t\t\t\t? Math.max(0, length + rawStop)\n\t\t\t\t\t: Math.min(length, rawStop)\n\t\t\t: rawStop === undefined\n\t\t\t\t? -1\n\t\t\t\t: rawStop < 0\n\t\t\t\t\t? Math.max(-1, length + rawStop)\n\t\t\t\t\t: Math.min(length - 1, rawStop)\n\tconst picked: TemplateRuntimeValue[] = []\n\tif (rawStep > 0) {\n\t\tfor (let index = from; index < to; index += rawStep) {\n\t\t\tpicked.push(items[index])\n\t\t}\n\t} else {\n\t\tfor (let index = from; index > to; index += rawStep) {\n\t\t\tpicked.push(items[index])\n\t\t}\n\t}\n\treturn typeof object === 'string' ? picked.join('') : picked\n}\n\n/**\n * Collects the iterable elements of a runtime value for a `for` loop.\n *\n * @param value - The value to iterate\n * @returns The elements in iteration order\n *\n * @example\n * ```ts\n * import { collectTemplateItems } from '@orkestrel/template'\n *\n * collectTemplateItems(new Map([['role', 'user']])) // ['role']\n * ```\n */\nexport function collectTemplateItems(value: TemplateRuntimeValue): readonly TemplateRuntimeValue[] {\n\tif (value === undefined) return []\n\tif (typeof value === 'string') return Array.from(value)\n\tif (isArray(value)) return value\n\tif (isMap(value)) return Array.from(value.keys())\n\tif (isTemplateNamespace(value)) return Array.from(value.values.keys())\n\tthrow buildTemplateEvaluationError(\n\t\t`iterates ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t{ feature: 'iteration' },\n\t)\n}\n\n/**\n * Applies one of the admitted Jinja `|` filters (`trim`, `length`, `tojson`,\n * `items`, `safe`, `string`) to a runtime value.\n *\n * @param name - The filter name\n * @param value - The value to transform\n * @returns The filtered runtime value\n *\n * @example\n * ```ts\n * import { applyTemplateFilter } from '@orkestrel/template'\n *\n * applyTemplateFilter('trim', ' Hi\\n') // 'Hi'\n * applyTemplateFilter('length', 'héllo') // 5\n * ```\n */\nexport function applyTemplateFilter(\n\tname: string,\n\tvalue: TemplateRuntimeValue,\n): TemplateRuntimeValue {\n\tif (!TEMPLATE_FILTERS.some((filter) => filter === name)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t{ feature: name },\n\t\t)\n\t}\n\tswitch (name) {\n\t\tcase 'trim':\n\t\t\treturn renderTemplateValue(value).replace(\n\t\t\t\tnew RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, 'gu'),\n\t\t\t\t'',\n\t\t\t)\n\t\tcase 'length': {\n\t\t\tif (value === undefined) return 0\n\t\t\tif (typeof value === 'string') return Array.from(value).length\n\t\t\tif (isArray(value)) return value.length\n\t\t\tif (isMap(value)) return value.size\n\t\t\tif (isTemplateNamespace(value)) return value.values.size\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`measures the length of ${renderTemplateType(value)}, which the subset does not admit`,\n\t\t\t\t{ feature: 'length' },\n\t\t\t)\n\t\t}\n\t\tcase 'tojson':\n\t\t\treturn serializeTemplateJSON(value)\n\t\tcase 'items': {\n\t\t\tif (value === undefined) return []\n\t\t\tif (isMap(value))\n\t\t\t\treturn Array.from(value.entries(), ([entryKey, entryValue]) => [entryKey, entryValue])\n\t\t\tif (isTemplateNamespace(value)) {\n\t\t\t\treturn Array.from(value.values.entries(), ([entryKey, entryValue]) => [\n\t\t\t\t\tentryKey,\n\t\t\t\t\tentryValue,\n\t\t\t\t])\n\t\t\t}\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`reads items of ${renderTemplateType(value)}, which is not a mapping`,\n\t\t\t\t{ feature: 'items' },\n\t\t\t)\n\t\t}\n\t\tcase 'safe':\n\t\t\treturn value\n\t\tcase 'string':\n\t\t\treturn renderTemplateValue(value)\n\t\tdefault:\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`applies the filter ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t\t{ feature: name },\n\t\t\t)\n\t}\n}\n\n/**\n * Applies one of the admitted Jinja `is` tests (`defined`, `undefined`, `none`,\n * `string`, `mapping`, `iterable`, `sequence`, `true`, `false`) to a runtime value.\n *\n * @param name - The test name\n * @param value - The value to inspect\n * @returns True if `value` satisfies the test; false otherwise\n *\n * @example\n * ```ts\n * import { applyTemplateTest } from '@orkestrel/template'\n *\n * applyTemplateTest('true', true) // true\n * applyTemplateTest('true', 1) // false\n * ```\n */\nexport function applyTemplateTest(name: string, value: TemplateRuntimeValue): boolean {\n\tif (!TEMPLATE_TESTS.some((test) => test === name)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`applies the test ${quoteTemplateText(name)}, which the subset does not admit`,\n\t\t\t{ feature: name },\n\t\t)\n\t}\n\tswitch (name) {\n\t\tcase 'defined':\n\t\t\treturn value !== undefined\n\t\tcase 'undefined':\n\t\t\treturn value === undefined\n\t\tcase 'none':\n\t\t\treturn value === null\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string'\n\t\tcase 'mapping':\n\t\t\treturn isMap(value) || isTemplateNamespace(value)\n\t\tcase 'iterable':\n\t\t\treturn (\n\t\t\t\ttypeof value === 'string' || isArray(value) || isMap(value) || isTemplateNamespace(value)\n\t\t\t)\n\t\tcase 'sequence':\n\t\t\treturn typeof value === 'string' || isArray(value)\n\t\tcase 'true':\n\t\t\treturn value === true\n\t\tcase 'false':\n\t\t\treturn value === false\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\n/**\n * Invokes one of the admitted Python `str` methods (`startswith`, `endswith`,\n * `split`, `strip`, `rstrip`, `lstrip`) on a string receiver with exact Python\n * character-set and splitting semantics.\n *\n * @param receiver - The string receiver\n * @param method - The string method name\n * @param positional - Positional arguments\n * @param keywords - Named keyword arguments\n * @returns The method's return value\n *\n * @example\n * ```ts\n * import { callTemplateMethod } from '@orkestrel/template'\n *\n * callTemplateMethod('hello\\n\\n', 'rstrip', ['\\n'], []) // 'hello'\n * callTemplateMethod('a</think>b', 'split', ['</think>'], []) // ['a', 'b']\n * ```\n */\nexport function callTemplateMethod(\n\treceiver: string,\n\tmethod: string,\n\tpositional: readonly TemplateRuntimeValue[],\n\tkeywords: ReadonlyArray<readonly [name: string, value: TemplateRuntimeValue]>,\n): TemplateRuntimeValue {\n\tif (!TEMPLATE_STRING_METHODS.some((admitted) => admitted === method)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`,\n\t\t\t{ feature: method },\n\t\t)\n\t}\n\tswitch (method) {\n\t\tcase 'startswith':\n\t\tcase 'endswith': {\n\t\t\tif (keywords.length > 0 || positional.length < 1 || positional.length > 3) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with invalid arguments`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [needle, start, end] = positional\n\t\t\tconst target =\n\t\t\t\tstart === undefined && end === undefined\n\t\t\t\t\t? receiver\n\t\t\t\t\t: String(sliceTemplateSequence(receiver, start, end, 1))\n\t\t\tconst candidates = isArray(needle) ? needle : [needle]\n\t\t\tif (!candidates.every((candidate) => typeof candidate === 'string')) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with a non-string prefix or suffix`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn candidates.some((candidate) =>\n\t\t\t\tmethod === 'startswith' ? target.startsWith(candidate) : target.endsWith(candidate),\n\t\t\t)\n\t\t}\n\t\tcase 'strip': {\n\t\t\tconst trimmedLeft = callTemplateMethod(receiver, 'lstrip', positional, keywords)\n\t\t\treturn typeof trimmedLeft === 'string'\n\t\t\t\t? callTemplateMethod(trimmedLeft, 'rstrip', positional, keywords)\n\t\t\t\t: ''\n\t\t}\n\t\tcase 'rstrip':\n\t\tcase 'lstrip': {\n\t\t\tif (keywords.length > 0 || positional.length > 1) {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with invalid arguments`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [chars] = positional\n\t\t\tif (chars === undefined || chars === null) {\n\t\t\t\tconst stripPattern =\n\t\t\t\t\tmethod === 'rstrip'\n\t\t\t\t\t\t? new RegExp(`${TEMPLATE_SPACE}+$`, 'u')\n\t\t\t\t\t\t: new RegExp(`^${TEMPLATE_SPACE}+`, 'u')\n\t\t\t\treturn receiver.replace(stripPattern, '')\n\t\t\t}\n\t\t\tif (typeof chars !== 'string') {\n\t\t\t\tthrow buildTemplateEvaluationError(`calls ${method} with a non-string character set`, {\n\t\t\t\t\tfeature: method,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst charSet = new Set(Array.from(chars))\n\t\t\tconst points = Array.from(receiver)\n\t\t\tif (method === 'rstrip') {\n\t\t\t\tlet end = points.length\n\t\t\t\tfor (let index = points.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tif (!charSet.has(points[index] ?? '')) break\n\t\t\t\t\tend = index\n\t\t\t\t}\n\t\t\t\treturn points.slice(0, end).join('')\n\t\t\t}\n\t\t\tlet start = 0\n\t\t\tfor (let index = 0; index < points.length; index += 1) {\n\t\t\t\tif (!charSet.has(points[index] ?? '')) break\n\t\t\t\tstart = index + 1\n\t\t\t}\n\t\t\treturn points.slice(start).join('')\n\t\t}\n\t\tcase 'split': {\n\t\t\tconst unknownKeyword = keywords.find(([name]) => name !== 'sep' && name !== 'maxsplit')\n\t\t\tif (unknownKeyword !== undefined || positional.length > 2) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with invalid arguments', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst sepKeyword = keywords.find(([name]) => name === 'sep')\n\t\t\tconst maxsplitKeyword = keywords.find(([name]) => name === 'maxsplit')\n\t\t\tif (\n\t\t\t\t(sepKeyword !== undefined && positional.length >= 1) ||\n\t\t\t\t(maxsplitKeyword !== undefined && positional.length >= 2)\n\t\t\t) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with duplicate arguments', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst sep = sepKeyword !== undefined ? sepKeyword[1] : positional[0]\n\t\t\tconst rawMax = maxsplitKeyword !== undefined ? maxsplitKeyword[1] : positional[1]\n\t\t\tconst maxsplit =\n\t\t\t\trawMax === undefined ? -1 : typeof rawMax === 'boolean' ? Number(rawMax) : rawMax\n\t\t\tif (typeof maxsplit !== 'number' || !Number.isInteger(maxsplit)) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with a non-integer maxsplit', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (sep === undefined || sep === null) {\n\t\t\t\tif (maxsplit < 0) {\n\t\t\t\t\tconst trimmed = receiver.replace(\n\t\t\t\t\t\tnew RegExp(`^${TEMPLATE_SPACE}+|${TEMPLATE_SPACE}+$`, 'gu'),\n\t\t\t\t\t\t'',\n\t\t\t\t\t)\n\t\t\t\t\treturn trimmed === '' ? [] : trimmed.split(new RegExp(`${TEMPLATE_SPACE}+`, 'gu'))\n\t\t\t\t}\n\t\t\t\tconst leading = receiver.replace(new RegExp(`^${TEMPLATE_SPACE}+`, 'u'), '')\n\t\t\t\tif (leading === '') return []\n\t\t\t\tif (maxsplit === 0) return [leading]\n\t\t\t\tconst gaps = Array.from(leading.matchAll(new RegExp(`${TEMPLATE_SPACE}+`, 'gu')))\n\t\t\t\tconst parts: string[] = []\n\t\t\t\tlet from = 0\n\t\t\t\tfor (let index = 0; index < gaps.length && parts.length < maxsplit; index += 1) {\n\t\t\t\t\tconst gap = gaps[index]\n\t\t\t\t\tif (gap === undefined) break\n\t\t\t\t\tparts.push(leading.slice(from, gap.index))\n\t\t\t\t\tfrom = gap.index + gap[0].length\n\t\t\t\t}\n\t\t\t\tif (from < leading.length) parts.push(leading.slice(from))\n\t\t\t\treturn parts\n\t\t\t}\n\t\t\tif (typeof sep !== 'string') {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with a non-string separator', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (sep.length === 0) {\n\t\t\t\tthrow buildTemplateEvaluationError('calls split with an empty separator', {\n\t\t\t\t\tfeature: 'split',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (maxsplit < 0) return receiver.split(sep)\n\t\t\tif (maxsplit === 0) return [receiver]\n\t\t\tconst parts: string[] = []\n\t\t\tlet from = 0\n\t\t\tfor (let count = 0; count < maxsplit; count += 1) {\n\t\t\t\tconst found = receiver.indexOf(sep, from)\n\t\t\t\tif (found === -1) break\n\t\t\t\tparts.push(receiver.slice(from, found))\n\t\t\t\tfrom = found + sep.length\n\t\t\t}\n\t\t\tparts.push(receiver.slice(from))\n\t\t\treturn parts\n\t\t}\n\t\tdefault:\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls the string method ${quoteTemplateText(method)}, which the subset does not admit`,\n\t\t\t\t{ feature: method },\n\t\t\t)\n\t}\n}\n\n/**\n * Finds the binding for a variable name across lexical scope frames from innermost\n * to outermost.\n *\n * @param frames - The scope stack, outermost first\n * @param name - The variable name to resolve\n * @returns The bound runtime value, or `undefined` when unbound\n *\n * @example\n * ```ts\n * import { findTemplateName } from '@orkestrel/template'\n *\n * findTemplateName([new Map([['bos_token', '<s>']])], 'bos_token') // '<s>'\n * ```\n */\nexport function findTemplateName(frames: TemplateScope, name: string): TemplateRuntimeValue {\n\treturn frames.findLast((frame) => frame.has(name))?.get(name)\n}\n\n/**\n * Binds a variable name in a copy of the innermost scope frame without mutating\n * the input frames.\n *\n * @param frames - The scope stack, outermost first\n * @param name - The variable name to bind\n * @param value - The runtime value to bind\n * @returns A fresh scope stack carrying the updated innermost frame\n *\n * @example\n * ```ts\n * import { bindTemplateName, findTemplateName } from '@orkestrel/template'\n *\n * findTemplateName(bindTemplateName([new Map()], 'turn', 2), 'turn') // 2\n * ```\n */\nexport function bindTemplateName(\n\tframes: TemplateScope,\n\tname: string,\n\tvalue: TemplateRuntimeValue,\n): TemplateScope {\n\tconst inner = frames.at(-1) ?? new Map<string, TemplateRuntimeValue>()\n\treturn [...frames.slice(0, -1), new Map([...inner, [name, value]])]\n}\n\n// === Tree-valued template evaluator\n\n/**\n * Evaluates a single {@link TemplateExpression} against runtime scope frames and\n * namespace bindings.\n *\n * @param expression - The compiled expression to evaluate\n * @param frames - The lexical scope frames, outermost first\n * @param namespaces - Evaluation-owned map from `TemplateNamespace` to its mutable backing `Map`\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The evaluated runtime value\n *\n * @example\n * ```ts\n * import { evaluateTemplateExpression } from '@orkestrel/template'\n *\n * evaluateTemplateExpression({ term: 'literal', value: 42 }, [new Map()], new Map()) // 42\n * ```\n */\nexport function evaluateTemplateExpression(\n\texpression: TemplateExpression,\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): TemplateRuntimeValue {\n\tswitch (expression.term) {\n\t\tcase 'literal':\n\t\t\treturn expression.value\n\t\tcase 'name':\n\t\t\treturn findTemplateName(frames, expression.name)\n\t\tcase 'member':\n\t\t\treturn readTemplateMember(\n\t\t\t\tevaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth),\n\t\t\t\tevaluateTemplateExpression(expression.key, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'slice':\n\t\t\treturn sliceTemplateSequence(\n\t\t\t\tevaluateTemplateExpression(expression.object, frames, namespaces, options, callDepth),\n\t\t\t\texpression.start === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.start, frames, namespaces, options, callDepth),\n\t\t\t\texpression.stop === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.stop, frames, namespaces, options, callDepth),\n\t\t\t\texpression.step === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(expression.step, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'call':\n\t\t\treturn callTemplateExpression(\n\t\t\t\texpression.callee,\n\t\t\t\texpression.values,\n\t\t\t\texpression.keywords,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\tcase 'filter':\n\t\t\treturn applyTemplateFilter(\n\t\t\t\texpression.name,\n\t\t\t\tevaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\tcase 'test': {\n\t\t\tconst matched = applyTemplateTest(\n\t\t\t\texpression.name,\n\t\t\t\tevaluateTemplateExpression(expression.value, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\t\treturn expression.negated ? !matched : matched\n\t\t}\n\t\tcase 'unary': {\n\t\t\tconst operand = evaluateTemplateExpression(\n\t\t\t\texpression.value,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tif (expression.operator === 'not') return !matchesTemplateTruth(operand)\n\t\t\treturn negateTemplateValue(expression.operator, operand)\n\t\t}\n\t\tcase 'conditional':\n\t\t\treturn matchesTemplateTruth(\n\t\t\t\tevaluateTemplateExpression(expression.condition, frames, namespaces, options, callDepth),\n\t\t\t)\n\t\t\t\t? evaluateTemplateExpression(expression.consequent, frames, namespaces, options, callDepth)\n\t\t\t\t: evaluateTemplateExpression(expression.alternate, frames, namespaces, options, callDepth)\n\t\tcase 'binary': {\n\t\t\tconst left = evaluateTemplateExpression(\n\t\t\t\texpression.left,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tif (expression.operator === 'and') {\n\t\t\t\treturn matchesTemplateTruth(left)\n\t\t\t\t\t? evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth)\n\t\t\t\t\t: left\n\t\t\t}\n\t\t\tif (expression.operator === 'or') {\n\t\t\t\treturn matchesTemplateTruth(left)\n\t\t\t\t\t? left\n\t\t\t\t\t: evaluateTemplateExpression(expression.right, frames, namespaces, options, callDepth)\n\t\t\t}\n\t\t\tconst right = evaluateTemplateExpression(\n\t\t\t\texpression.right,\n\t\t\t\tframes,\n\t\t\t\tnamespaces,\n\t\t\t\toptions,\n\t\t\t\tcallDepth,\n\t\t\t)\n\t\t\tswitch (expression.operator) {\n\t\t\t\tcase '+':\n\t\t\t\t\treturn addTemplateValues(left, right)\n\t\t\t\tcase '-':\n\t\t\t\t\treturn subtractTemplateValues(left, right)\n\t\t\t\tcase '~':\n\t\t\t\t\treturn renderTemplateValue(left) + renderTemplateValue(right)\n\t\t\t\tcase '==':\n\t\t\t\t\treturn matchesTemplateEqual(left, right)\n\t\t\t\tcase '!=':\n\t\t\t\t\treturn !matchesTemplateEqual(left, right)\n\t\t\t\tcase '<':\n\t\t\t\t\treturn compareTemplateValues(left, right) < 0\n\t\t\t\tcase '>':\n\t\t\t\t\treturn compareTemplateValues(left, right) > 0\n\t\t\t\tcase '<=':\n\t\t\t\t\treturn compareTemplateValues(left, right) <= 0\n\t\t\t\tcase '>=':\n\t\t\t\t\treturn compareTemplateValues(left, right) >= 0\n\t\t\t\tcase 'in':\n\t\t\t\t\treturn matchesTemplateMember(left, right)\n\t\t\t\tcase 'not in':\n\t\t\t\t\treturn !matchesTemplateMember(left, right)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Evaluates a template call expression — dispatching built-in `raise_exception`\n * and `namespace`, string method calls, and user-defined `TemplateMacro` calls.\n *\n * @param callee - The callee expression\n * @param positionalExpressions - Positional argument expressions\n * @param keywordExpressions - Named keyword argument expressions\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth\n * @returns The call result\n *\n * @example\n * ```ts\n * import { callTemplateExpression } from '@orkestrel/template'\n *\n * callTemplateExpression({ term: 'name', name: 'namespace' }, [], [{ name: 'n', value: { term: 'literal', value: 1 } }], [new Map()], new Map(), undefined, 0)\n * ```\n */\nexport function callTemplateExpression(\n\tcallee: TemplateExpression,\n\tpositionalExpressions: readonly TemplateExpression[],\n\tkeywordExpressions: readonly TemplateKeyword[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions: TemplateEvaluateOptions | undefined,\n\tcallDepth: number,\n): TemplateRuntimeValue {\n\tif (callee.term === 'member') {\n\t\tconst receiver = evaluateTemplateExpression(\n\t\t\tcallee.object,\n\t\t\tframes,\n\t\t\tnamespaces,\n\t\t\toptions,\n\t\t\tcallDepth,\n\t\t)\n\t\tconst key = evaluateTemplateExpression(callee.key, frames, namespaces, options, callDepth)\n\t\tconst positional = positionalExpressions.map((value) =>\n\t\t\tevaluateTemplateExpression(value, frames, namespaces, options, callDepth),\n\t\t)\n\t\tconst keywords = keywordExpressions.map((keyword): readonly [string, TemplateRuntimeValue] => [\n\t\t\tkeyword.name,\n\t\t\tevaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth),\n\t\t])\n\t\tif (typeof receiver === 'string' && typeof key === 'string') {\n\t\t\treturn callTemplateMethod(receiver, key, positional, keywords)\n\t\t}\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls method ${typeof key === 'string' ? quoteTemplateText(key) : renderTemplateType(key)} on ${renderTemplateType(receiver)}, which the subset does not admit`,\n\t\t\t{ feature: 'method call' },\n\t\t)\n\t}\n\tconst positional = positionalExpressions.map((value) =>\n\t\tevaluateTemplateExpression(value, frames, namespaces, options, callDepth),\n\t)\n\tconst keywords = keywordExpressions.map((keyword): readonly [string, TemplateRuntimeValue] => [\n\t\tkeyword.name,\n\t\tevaluateTemplateExpression(keyword.value, frames, namespaces, options, callDepth),\n\t])\n\tif (callee.term === 'name' && callee.name === 'raise_exception') {\n\t\tif (positional.length !== 1 || keywords.length > 0) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls raise_exception with ${positional.length} positional and ${keywords.length} keyword arguments; it takes one message`,\n\t\t\t)\n\t\t}\n\t\tconst text = renderTemplateValue(positional[0])\n\t\tthrow new TemplateError(\n\t\t\t'RAISE',\n\t\t\t`The template raised an exception: ${quoteTemplateText(text)}.`,\n\t\t\t{\n\t\t\t\tmessage: text,\n\t\t\t},\n\t\t)\n\t}\n\tif (callee.term === 'name' && callee.name === 'namespace') {\n\t\tif (positional.length > 1) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls namespace with ${positional.length} positional arguments; it takes at most one mapping`,\n\t\t\t\t{ feature: 'namespace' },\n\t\t\t)\n\t\t}\n\t\tconst entries: Array<readonly [string, TemplateRuntimeValue]> = []\n\t\tconst [initial] = positional\n\t\tif (initial !== undefined) {\n\t\t\tif (isMap(initial)) {\n\t\t\t\tfor (const [entryKey, entryValue] of initial.entries()) {\n\t\t\t\t\tentries.push([entryKey, entryValue])\n\t\t\t\t}\n\t\t\t} else if (isTemplateNamespace(initial)) {\n\t\t\t\tfor (const [entryKey, entryValue] of initial.values.entries()) {\n\t\t\t\t\tentries.push([entryKey, entryValue])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t`calls namespace with ${renderTemplateType(initial)} instead of a mapping`,\n\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tfor (const [entryKey, entryValue] of keywords) {\n\t\t\tentries.push([entryKey, entryValue])\n\t\t}\n\t\tconst backing = new Map<string, TemplateRuntimeValue>(entries)\n\t\tconst container: TemplateNamespace = { namespace: true, values: backing }\n\t\tnamespaces.set(container, backing)\n\t\treturn container\n\t}\n\tconst target = evaluateTemplateExpression(callee, frames, namespaces, options, callDepth)\n\tif (!isTemplateMacro(target)) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls ${renderTemplateType(target)}, which is not a function`,\n\t\t\t{ feature: 'call' },\n\t\t)\n\t}\n\tif (callDepth + 1 > MAX_DEPTH) {\n\t\tthrow buildTemplateEvaluationError(`nests macro calls deeper than ${MAX_DEPTH} levels`, {\n\t\t\tlimit: MAX_DEPTH,\n\t\t})\n\t}\n\tif (positional.length > target.parameters.length) {\n\t\tthrow buildTemplateEvaluationError(\n\t\t\t`calls macro ${quoteTemplateText(target.name)} with ${positional.length} arguments; it accepts at most ${target.parameters.length}`,\n\t\t\t{ feature: 'macro' },\n\t\t)\n\t}\n\tconst bound = new Map<string, TemplateRuntimeValue>()\n\tfor (const [index, value] of positional.entries()) {\n\t\tconst parameter = target.parameters[index]\n\t\tif (parameter !== undefined) bound.set(parameter.name, value)\n\t}\n\tfor (const [keywordName, keywordValue] of keywords) {\n\t\tconst matches = target.parameters.some((parameter) => parameter.name === keywordName)\n\t\tif (!matches) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls macro ${quoteTemplateText(target.name)} with unexpected keyword ${quoteTemplateText(keywordName)}`,\n\t\t\t\t{ feature: 'macro' },\n\t\t\t)\n\t\t}\n\t\tif (bound.has(keywordName)) {\n\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t`calls macro ${quoteTemplateText(target.name)} with duplicate argument ${quoteTemplateText(keywordName)}`,\n\t\t\t\t{ feature: 'macro' },\n\t\t\t)\n\t\t}\n\t\tbound.set(keywordName, keywordValue)\n\t}\n\tconst rootFrame = frames[0]\n\tconst baseFrames: TemplateScope =\n\t\trootFrame !== undefined ? [rootFrame, ...target.closure] : target.closure\n\tfor (const parameter of target.parameters) {\n\t\tif (!bound.has(parameter.name)) {\n\t\t\tbound.set(\n\t\t\t\tparameter.name,\n\t\t\t\tparameter.fallback === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: evaluateTemplateExpression(\n\t\t\t\t\t\t\tparameter.fallback,\n\t\t\t\t\t\t\tbaseFrames,\n\t\t\t\t\t\t\tnamespaces,\n\t\t\t\t\t\t\toptions,\n\t\t\t\t\t\t\tcallDepth + 1,\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\tconst [parts] = executeTemplateNodes(\n\t\ttarget.body,\n\t\t[...baseFrames, bound],\n\t\tnamespaces,\n\t\toptions,\n\t\tcallDepth + 1,\n\t)\n\treturn parts.map((part) => renderTemplatePart(part, options)).join('')\n}\n\n/**\n * Executes a sequence of compiled {@link TemplateNode}s in order, tagging each\n * emitted part with whether it came from literal template text (`true`) or a\n * dynamic expression/placeholder (`false`).\n *\n * @param nodes - The nodes to execute in order\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The tagged emitted parts, updated scope frames, and optional loop control signal\n *\n * @example\n * ```ts\n * import { runTemplateNodes } from '@orkestrel/template'\n *\n * runTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // [[true, 'Hi']]\n * ```\n */\nexport function runTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): readonly [\n\tparts: ReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\tframes: TemplateScope,\n\tcontrol: 'break' | 'continue' | undefined,\n] {\n\tconst steps: Array<\n\t\treadonly [\n\t\t\tReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\t\t\tTemplateScope,\n\t\t\t'break' | 'continue' | undefined,\n\t\t]\n\t> = []\n\tfor (const node of nodes) {\n\t\tconst previous = steps.at(-1)\n\t\tif (previous?.[2] !== undefined) break\n\t\tconst active = previous?.[1] ?? frames\n\t\tswitch (node.syntax) {\n\t\t\tcase 'document':\n\t\t\t\tsteps.push(runTemplateNodes(node.children, active, namespaces, options, callDepth))\n\t\t\t\tbreak\n\t\t\tcase 'text':\n\t\t\t\tsteps.push([[[true, node.value]], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'comment':\n\t\t\t\tsteps.push([[], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'html': {\n\t\t\t\tconst sanitized = createHTML(node.document).sanitize(options?.sanitize).document\n\t\t\t\tsteps.push([[[false, sanitized]], active, undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'markdown':\n\t\t\t\tsteps.push([[[false, node.document]], active, undefined])\n\t\t\t\tbreak\n\t\t\tcase 'placeholder': {\n\t\t\t\tconst rawRecord: Record<string, unknown> = {}\n\t\t\t\tconst root = active[0]\n\t\t\t\tif (root !== undefined) {\n\t\t\t\t\tfor (const [entryKey, entryValue] of root.entries()) {\n\t\t\t\t\t\trawRecord[entryKey] = entryValue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst placeholders = options?.placeholders ?? []\n\t\t\t\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\t\t\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\t\t\t\tconst { value, declared, required } = resolveToken(rawRecord, placeholders, node.name)\n\t\t\t\tconst resolved = value !== undefined ? value : declared?.fallback\n\t\t\t\tif (resolved !== undefined) {\n\t\t\t\t\tif (isHTMLNode(resolved)) {\n\t\t\t\t\t\tconst document: HTMLDocument =\n\t\t\t\t\t\t\tresolved.category === 'document'\n\t\t\t\t\t\t\t\t? resolved\n\t\t\t\t\t\t\t\t: { category: 'document', children: [resolved] }\n\t\t\t\t\t\tsteps.push([\n\t\t\t\t\t\t\t[[false, createHTML(document).sanitize(options?.sanitize).document]],\n\t\t\t\t\t\t\tactive,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t])\n\t\t\t\t\t} else if (isMarkdownNode(resolved)) {\n\t\t\t\t\t\tsteps.push([[[false, resolved]], active, undefined])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsteps.push([[[false, formatValue(resolved, locale)]], active, undefined])\n\t\t\t\t\t}\n\t\t\t\t} else if (missing === 'literal') {\n\t\t\t\t\tsteps.push([[[false, node.raw]], active, undefined])\n\t\t\t\t} else if (missing === 'empty' || !required) {\n\t\t\t\t\tsteps.push([[[false, '']], active, undefined])\n\t\t\t\t} else {\n\t\t\t\t\tthrow new TemplateError('MISSING', `Missing required placeholder(s): ${node.name}`, {\n\t\t\t\t\t\tmissing: [node.name],\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'output': {\n\t\t\t\tconst evaluated = evaluateTemplateExpression(\n\t\t\t\t\tnode.value,\n\t\t\t\t\tactive,\n\t\t\t\t\tnamespaces,\n\t\t\t\t\toptions,\n\t\t\t\t\tcallDepth,\n\t\t\t\t)\n\t\t\t\tif (isHTMLNode(evaluated)) {\n\t\t\t\t\tconst document: HTMLDocument =\n\t\t\t\t\t\tevaluated.category === 'document'\n\t\t\t\t\t\t\t? evaluated\n\t\t\t\t\t\t\t: { category: 'document', children: [evaluated] }\n\t\t\t\t\tsteps.push([\n\t\t\t\t\t\t[[false, createHTML(document).sanitize(options?.sanitize).document]],\n\t\t\t\t\t\tactive,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t])\n\t\t\t\t} else if (isMarkdownNode(evaluated)) {\n\t\t\t\t\tsteps.push([[[false, evaluated]], active, undefined])\n\t\t\t\t} else {\n\t\t\t\t\tsteps.push([[[false, renderTemplateValue(evaluated)]], active, undefined])\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'if': {\n\t\t\t\tconst branch = matchesTemplateTruth(\n\t\t\t\t\tevaluateTemplateExpression(node.condition, active, namespaces, options, callDepth),\n\t\t\t\t)\n\t\t\t\t\t? node.body\n\t\t\t\t\t: (node.alternate ?? [])\n\t\t\t\tsteps.push(runTemplateNodes(branch, active, namespaces, options, callDepth))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'for': {\n\t\t\t\tconst items = collectTemplateItems(\n\t\t\t\t\tevaluateTemplateExpression(node.sequence, active, namespaces, options, callDepth),\n\t\t\t\t)\n\t\t\t\tconst turns: Array<\n\t\t\t\t\treadonly [\n\t\t\t\t\t\tReadonlyArray<readonly [literal: boolean, part: TemplatePart]>,\n\t\t\t\t\t\t'break' | 'continue' | undefined,\n\t\t\t\t\t]\n\t\t\t\t> = []\n\t\t\t\tfor (const [index0, item] of items.entries()) {\n\t\t\t\t\tif (turns.at(-1)?.[1] === 'break') break\n\t\t\t\t\tconst loopFrame = new Map<string, TemplateRuntimeValue>()\n\t\t\t\t\tif (node.targets.length === 1) {\n\t\t\t\t\t\tconst [targetName] = node.targets\n\t\t\t\t\t\tif (targetName !== undefined) loopFrame.set(targetName, item)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst unpacked = collectTemplateItems(item)\n\t\t\t\t\t\tif (unpacked.length !== node.targets.length) {\n\t\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t\t`unpacks ${unpacked.length} values into ${node.targets.length} loop targets`,\n\t\t\t\t\t\t\t\t{ feature: 'unpacking' },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const [position, targetName] of node.targets.entries()) {\n\t\t\t\t\t\t\tloopFrame.set(targetName, unpacked[position])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tloopFrame.set('loop', {\n\t\t\t\t\t\tindex0,\n\t\t\t\t\t\tlength: items.length,\n\t\t\t\t\t\tprevitem: index0 > 0 ? items[index0 - 1] : undefined,\n\t\t\t\t\t\tnextitem: index0 + 1 < items.length ? items[index0 + 1] : undefined,\n\t\t\t\t\t})\n\t\t\t\t\tconst [parts, , control] = runTemplateNodes(\n\t\t\t\t\t\tnode.body,\n\t\t\t\t\t\t[...active, loopFrame],\n\t\t\t\t\t\tnamespaces,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\tcallDepth,\n\t\t\t\t\t)\n\t\t\t\t\tturns.push([parts, control])\n\t\t\t\t}\n\t\t\t\tsteps.push([turns.flatMap(([parts]) => parts), active, undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'set': {\n\t\t\t\tconst value = evaluateTemplateExpression(node.value, active, namespaces, options, callDepth)\n\t\t\t\tif (node.target.scope === 'local') {\n\t\t\t\t\tsteps.push([[], bindTemplateName(active, node.target.name, value), undefined])\n\t\t\t\t} else {\n\t\t\t\t\tconst container = findTemplateName(active, node.target.object)\n\t\t\t\t\tif (!isTemplateNamespace(container)) {\n\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t`sets attribute ${quoteTemplateText(node.target.name)} on ${renderTemplateType(container)}, which is not a namespace`,\n\t\t\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst backing = namespaces.get(container)\n\t\t\t\t\tif (backing === undefined) {\n\t\t\t\t\t\tthrow buildTemplateEvaluationError(\n\t\t\t\t\t\t\t`sets attribute ${quoteTemplateText(node.target.name)} on a readonly namespace`,\n\t\t\t\t\t\t\t{ feature: 'namespace' },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tbacking.set(node.target.name, value)\n\t\t\t\t\tsteps.push([[], active, undefined])\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'macro': {\n\t\t\t\tconst macro: TemplateMacro = {\n\t\t\t\t\tmacro: true,\n\t\t\t\t\tname: node.name,\n\t\t\t\t\tparameters: node.parameters,\n\t\t\t\t\tbody: node.body,\n\t\t\t\t\tclosure: active,\n\t\t\t\t}\n\t\t\t\tsteps.push([[], bindTemplateName(active, node.name, macro), undefined])\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'control':\n\t\t\t\tsteps.push([[], active, node.action])\n\t\t\t\tbreak\n\t\t}\n\t}\n\tconst last = steps.at(-1)\n\treturn [steps.flatMap(([parts]) => parts), last?.[1] ?? frames, last?.[2]]\n}\n\n/**\n * Executes a sequence of compiled {@link TemplateNode}s in order, threading\n * lexical `set` and `macro` bindings into subsequent siblings until a loop\n * control (`break` or `continue`) terminates the run.\n *\n * @param nodes - The nodes to execute in order\n * @param frames - Active lexical scope frames\n * @param namespaces - Evaluation-owned mutable namespace registry\n * @param options - Optional evaluation settings\n * @param callDepth - Current macro call depth. Default: `0`\n * @returns The emitted parts, updated scope frames, and optional loop control signal\n *\n * @example\n * ```ts\n * import { executeTemplateNodes } from '@orkestrel/template'\n *\n * executeTemplateNodes([{ syntax: 'text', value: 'Hi' }], [new Map()], new Map())[0] // ['Hi']\n * ```\n */\nexport function executeTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tframes: TemplateScope,\n\tnamespaces: Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>,\n\toptions?: TemplateEvaluateOptions,\n\tcallDepth = 0,\n): readonly [\n\tparts: readonly TemplatePart[],\n\tframes: TemplateScope,\n\tcontrol: 'break' | 'continue' | undefined,\n] {\n\tconst [tagged, updated, control] = runTemplateNodes(nodes, frames, namespaces, options, callDepth)\n\treturn [tagged.map(([, part]) => part), updated, control]\n}\n\n/**\n * Renders one emitted {@link TemplatePart} to string text, sanitizing `HTMLNode`s\n * through `@orkestrel/html` and rendering `MarkdownNode`s through `@orkestrel/markdown`.\n *\n * @param part - The emitted template part\n * @param options - Optional evaluation and sanitize settings\n * @returns The rendered string\n *\n * @example\n * ```ts\n * import { renderTemplatePart } from '@orkestrel/template'\n *\n * renderTemplatePart({ category: 'text', value: 'a & b' }) // 'a & b'\n * ```\n */\nexport function renderTemplatePart(part: TemplatePart, options?: TemplateEvaluateOptions): string {\n\tif (typeof part === 'string') return part\n\tif (isHTMLNode(part)) {\n\t\tconst document: HTMLDocument =\n\t\t\tpart.category === 'document' ? part : { category: 'document', children: [part] }\n\t\treturn renderHTML(createHTML(document).sanitize(options?.sanitize).document)\n\t}\n\treturn renderMarkdown(part)\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} into tagged parts distinguishing\n * template-authored literal text (`true`) from dynamic fill output (`false`).\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The ordered list of tagged evaluated parts\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTaggedTemplateParts } from '@orkestrel/template'\n *\n * evaluateTaggedTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' })\n * // [[true, 'Hi '], [false, 'Ada']]\n * ```\n */\nexport function evaluateTaggedTemplateParts(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): ReadonlyArray<readonly [literal: boolean, part: TemplatePart]> {\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError('INVALID', 'A template evaluates a valid TemplateDocument.')\n\t}\n\tconst frame = new Map<string, TemplateRuntimeValue>()\n\tif (values !== undefined) {\n\t\tfor (const [entryKey, entryValue] of Object.entries(values)) {\n\t\t\tif (entryValue !== undefined) {\n\t\t\t\tframe.set(entryKey, normalizeTemplateValue(entryValue))\n\t\t\t}\n\t\t}\n\t}\n\tconst namespaces = new Map<TemplateNamespace, Map<string, TemplateRuntimeValue>>()\n\treturn runTemplateNodes(document.children, [frame], namespaces, options, 0)[0]\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} into an ordered list of\n * tree-valued {@link TemplatePart}s (`string`, sanitized `HTMLNode`, or `MarkdownNode`).\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The ordered list of evaluated parts\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTemplateParts } from '@orkestrel/template'\n *\n * evaluateTemplateParts(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // ['Hi ', 'Ada']\n * ```\n */\nexport function evaluateTemplateParts(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): readonly TemplatePart[] {\n\treturn evaluateTaggedTemplateParts(document, values, options).map(([, part]) => part)\n}\n\n/**\n * Evaluates a compiled {@link TemplateDocument} against runtime values and\n * joins every emitted part into a rendered string.\n *\n * @param document - The compiled template document\n * @param values - Optional runtime values record\n * @param options - Optional evaluation, placeholder, and sanitize settings\n * @returns The rendered output string\n *\n * @example\n * ```ts\n * import { compileTemplate, evaluateTemplate } from '@orkestrel/template'\n *\n * evaluateTemplate(compileTemplate('Hi {{ name }}'), { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function evaluateTemplate(\n\tdocument: TemplateDocument,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): string {\n\tconst parts = evaluateTemplateParts(document, values, options)\n\treturn parts.map((part) => renderTemplatePart(part, options)).join('')\n}\n\n// === AST traversal, queries, fold, rewrite, streaming, and canonical renderer\n\n/**\n * Walks a {@link TemplateNode} depth-first in pre-order, yielding the root\n * first and capping descent at `MAX_DEPTH`.\n *\n * @param root - The root node to traverse\n * @param depth - Current traversal depth. Default: `0`\n * @returns A lazy generator over every visited node\n *\n * @example\n * ```ts\n * import { compileTemplate, walkTemplateNodes } from '@orkestrel/template'\n *\n * Array.from(walkTemplateNodes(compileTemplate('Hi {{ name }}'))).map((node) => node.syntax)\n * // ['document', 'text', 'output']\n * ```\n */\nexport function* walkTemplateNodes(root: TemplateNode, depth = 0): Generator<TemplateNode> {\n\tyield root\n\tif (depth >= MAX_DEPTH) return\n\tconst next = depth + 1\n\tswitch (root.syntax) {\n\t\tcase 'document':\n\t\t\tfor (const child of root.children) yield* walkTemplateNodes(child, next)\n\t\t\treturn\n\t\tcase 'if':\n\t\t\tfor (const child of root.body) yield* walkTemplateNodes(child, next)\n\t\t\tif (root.alternate !== undefined) {\n\t\t\t\tfor (const child of root.alternate) yield* walkTemplateNodes(child, next)\n\t\t\t}\n\t\t\treturn\n\t\tcase 'for':\n\t\tcase 'macro':\n\t\t\tfor (const child of root.body) yield* walkTemplateNodes(child, next)\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn\n\t}\n}\n\n/**\n * Finds the first {@link TemplateNode} in depth-first pre-order matching a\n * guard or predicate.\n *\n * @param root - The root node to search\n * @param predicate - The guard or predicate to test each node\n * @returns The first matching node, or `undefined`\n *\n * @example\n * ```ts\n * import { compileTemplate, findTemplateNode } from '@orkestrel/template'\n *\n * findTemplateNode(compileTemplate('Hi {{ name }}'), (node) => node.syntax === 'output')?.syntax // 'output'\n * ```\n */\nexport function findTemplateNode<T extends TemplateNode>(\n\troot: TemplateNode,\n\tguard: (node: TemplateNode) => node is T,\n): T | undefined\nexport function findTemplateNode(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): TemplateNode | undefined\nexport function findTemplateNode(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): TemplateNode | undefined {\n\tfor (const node of walkTemplateNodes(root)) {\n\t\tif (predicate(node)) return node\n\t}\n\treturn undefined\n}\n\n/**\n * Collects every {@link TemplateNode} in depth-first pre-order matching a\n * guard or predicate.\n *\n * @param root - The root node to search\n * @param predicate - The guard or predicate to test each node\n * @returns The matching nodes in walk order\n *\n * @example\n * ```ts\n * import { compileTemplate, filterTemplateNodes } from '@orkestrel/template'\n *\n * filterTemplateNodes(compileTemplate('{{ a }}{{ b }}'), (node) => node.syntax === 'output').length // 2\n * ```\n */\nexport function filterTemplateNodes<T extends TemplateNode>(\n\troot: TemplateNode,\n\tguard: (node: TemplateNode) => node is T,\n): readonly T[]\nexport function filterTemplateNodes(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): readonly TemplateNode[]\nexport function filterTemplateNodes(\n\troot: TemplateNode,\n\tpredicate: (node: TemplateNode) => boolean,\n): readonly TemplateNode[] {\n\treturn walkTemplateNodes(root)\n\t\t.filter((node) => predicate(node))\n\t\t.toArray()\n}\n\n/**\n * Reduces a {@link TemplateNode} depth-first in pre-order into one accumulated value.\n *\n * @param root - The root node to reduce\n * @param callback - The step combining the accumulated value and each visited node\n * @param initial - The initial accumulated value\n * @returns The final accumulated value\n *\n * @example\n * ```ts\n * import { compileTemplate, reduceTemplateDocument } from '@orkestrel/template'\n *\n * reduceTemplateDocument(compileTemplate('Hi {{ name }}'), (count) => count + 1, 0) // 3\n * ```\n */\nexport function reduceTemplateDocument<T>(\n\troot: TemplateNode,\n\tcallback: (value: T, node: TemplateNode) => T,\n\tinitial: T,\n): T {\n\treturn walkTemplateNodes(root).reduce((value, node) => callback(value, node), initial)\n}\n\n/**\n * Folds a {@link TemplateNode} bottom-up through a total {@link TemplateHandlerMap}\n * covering every syntax variant, capped at `MAX_DEPTH`.\n *\n * @param node - The node to fold\n * @param handlers - Total handler map keyed by `syntax`\n * @param depth - Current recursion depth. Default: `0`\n * @returns The folded result\n *\n * @example\n * ```ts\n * import { compileTemplate, foldTemplateDocument } from '@orkestrel/template'\n *\n * const doc = compileTemplate('Hi')\n * foldTemplateDocument(doc, {\n * document: (_, children) => children.reduce((a, b) => a + b, 1),\n * text: () => 1,\n * placeholder: () => 1,\n * output: () => 1,\n * if: (_, children) => children.reduce((a, b) => a + b, 1),\n * for: (_, children) => children.reduce((a, b) => a + b, 1),\n * set: () => 1,\n * macro: (_, children) => children.reduce((a, b) => a + b, 1),\n * control: () => 1,\n * comment: () => 1,\n * html: () => 1,\n * markdown: () => 1,\n * }) // 2\n * ```\n */\nexport function foldTemplateDocument<T>(\n\tnode: TemplateNode,\n\thandlers: TemplateHandlerMap<T>,\n\tdepth = 0,\n): T {\n\tconst next = depth + 1\n\tconst capped = depth >= MAX_DEPTH\n\tswitch (node.syntax) {\n\t\tcase 'document':\n\t\t\treturn handlers.document(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.children.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'text':\n\t\t\treturn handlers.text(node, [])\n\t\tcase 'placeholder':\n\t\t\treturn handlers.placeholder(node, [])\n\t\tcase 'output':\n\t\t\treturn handlers.output(node, [])\n\t\tcase 'if': {\n\t\t\tconst children = capped\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t...node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t\t\t\t...(node.alternate ?? []).map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t\t\t]\n\t\t\treturn handlers.if(node, children)\n\t\t}\n\t\tcase 'for':\n\t\t\treturn handlers.for(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'set':\n\t\t\treturn handlers.set(node, [])\n\t\tcase 'macro':\n\t\t\treturn handlers.macro(\n\t\t\t\tnode,\n\t\t\t\tcapped ? [] : node.body.map((child) => foldTemplateDocument(child, handlers, next)),\n\t\t\t)\n\t\tcase 'control':\n\t\t\treturn handlers.control(node, [])\n\t\tcase 'comment':\n\t\t\treturn handlers.comment(node, [])\n\t\tcase 'html':\n\t\t\treturn handlers.html(node, [])\n\t\tcase 'markdown':\n\t\t\treturn handlers.markdown(node, [])\n\t}\n}\n\n/**\n * Rewrites one {@link TemplateNode} bottom-up with copy-on-write identity\n * preservation, recording each rebuilt node's direct source in `derivations`.\n *\n * @param node - The node to rewrite\n * @param rewrite - The bottom-up rewrite callback\n * @param derivations - Operation-owned derivation map\n * @param depth - Current recursion depth\n * @returns The rewritten node\n *\n * @example\n * ```ts\n * import { rewriteTemplateNode } from '@orkestrel/template'\n *\n * rewriteTemplateNode({ syntax: 'text', value: 'hi' }, (node) => node, new Map(), 0)\n * ```\n */\nexport function rewriteTemplateNode(\n\tnode: TemplateNode,\n\trewrite: TemplateRewriteHandler,\n\tderivations: Map<TemplateNode, TemplateNode | undefined>,\n\tdepth: number,\n): TemplateNode {\n\tif (depth >= MAX_DEPTH) return node\n\tconst next = depth + 1\n\tif (node.syntax === 'if') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst alternate = node.alternate?.map((child) =>\n\t\t\trewriteTemplateNode(child, rewrite, derivations, next),\n\t\t)\n\t\tconst bodyChanged = body.some((child, index) => child !== node.body[index])\n\t\tconst alternateChanged =\n\t\t\talternate !== undefined &&\n\t\t\tnode.alternate !== undefined &&\n\t\t\talternate.some((child, index) => child !== node.alternate?.[index])\n\t\tconst rebuilt: TemplateNode =\n\t\t\t!bodyChanged && !alternateChanged\n\t\t\t\t? node\n\t\t\t\t: {\n\t\t\t\t\t\tsyntax: 'if',\n\t\t\t\t\t\tcondition: node.condition,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t\t...(alternate !== undefined ? { alternate } : {}),\n\t\t\t\t\t}\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tif (node.syntax === 'for') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst changed = body.some((child, index) => child !== node.body[index])\n\t\tconst rebuilt: TemplateNode = changed\n\t\t\t? { syntax: 'for', targets: node.targets, sequence: node.sequence, body }\n\t\t\t: node\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tif (node.syntax === 'macro') {\n\t\tconst body = node.body.map((child) => rewriteTemplateNode(child, rewrite, derivations, next))\n\t\tconst changed = body.some((child, index) => child !== node.body[index])\n\t\tconst rebuilt: TemplateNode = changed\n\t\t\t? { syntax: 'macro', name: node.name, parameters: node.parameters, body }\n\t\t\t: node\n\t\tconst candidate = rewrite(rebuilt)\n\t\tconst accepted = candidate.syntax === 'document' ? rebuilt : candidate\n\t\tif (accepted !== node) {\n\t\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t\t}\n\t\treturn accepted\n\t}\n\tconst candidate = rewrite(node)\n\tconst accepted = candidate.syntax === 'document' ? node : candidate\n\tif (accepted !== node) {\n\t\tderivations.set(accepted, derivations.has(accepted) ? undefined : node)\n\t}\n\treturn accepted\n}\n\n/**\n * Rewrites a {@link TemplateDocument} bottom-up (copy-on-write) and returns the\n * rewritten document alongside its output-to-input derivation map.\n *\n * @param document - The document to rewrite\n * @param rewrite - The bottom-up node rewrite callback\n * @returns The rewritten document and its provenance derivations\n *\n * @example\n * ```ts\n * import { compileTemplate, mapTemplateDocument } from '@orkestrel/template'\n *\n * const [rewritten] = mapTemplateDocument(compileTemplate('hi'), (node) =>\n * node.syntax === 'text' ? { syntax: 'text', value: node.value.toUpperCase() } : node,\n * )\n * rewritten.children[0] // { syntax: 'text', value: 'HI' }\n * ```\n */\nexport function mapTemplateDocument(\n\tdocument: TemplateDocument,\n\trewrite: TemplateRewriteHandler,\n): TemplateDerivation<TemplateDocument> {\n\tconst derivations = new Map<TemplateNode, TemplateNode | undefined>()\n\tconst children = document.children.map((child) =>\n\t\trewriteTemplateNode(child, rewrite, derivations, 1),\n\t)\n\tconst changed = children.some((child, index) => child !== document.children[index])\n\tif (!changed) return [document, derivations]\n\tconst rebuilt: TemplateDocument = { syntax: 'document', children }\n\tderivations.set(rebuilt, document)\n\treturn [rebuilt, derivations]\n}\n\n/**\n * Creates a fresh, pull-based `ReadableStream` over a {@link TemplateDocument}'s\n * direct top-level children in source order.\n *\n * @param document - The document whose top-level children to stream\n * @returns A pull-based stream yielding one top-level node per pull\n *\n * @example\n * ```ts\n * import { compileTemplate, streamTemplateNodes } from '@orkestrel/template'\n *\n * const reader = streamTemplateNodes(compileTemplate('Hi {{ name }}')).getReader()\n * ```\n */\nexport function streamTemplateNodes(document: TemplateDocument): ReadableStream<TemplateNode> {\n\tconst children = document.children.values()\n\treturn new ReadableStream<TemplateNode>({\n\t\tpull(controller) {\n\t\t\tconst next = children.next()\n\t\t\tif (!next.done && next.value !== undefined) {\n\t\t\t\tcontroller.enqueue(next.value)\n\t\t\t} else {\n\t\t\t\tcontroller.close()\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Renders a {@link TemplateExpression} back to canonical Jinja expression syntax\n * that compiles back to an equivalent AST.\n *\n * @param expression - The expression to render\n * @returns Canonical Jinja expression text\n *\n * @example\n * ```ts\n * import { renderTemplateExpression } from '@orkestrel/template'\n *\n * renderTemplateExpression({ term: 'name', name: 'messages' }) // 'messages'\n * ```\n */\nexport function renderTemplateExpression(expression: TemplateExpression): string {\n\tswitch (expression.term) {\n\t\tcase 'literal': {\n\t\t\tif (expression.value === null) return 'none'\n\t\t\tif (typeof expression.value === 'boolean') return expression.value ? 'true' : 'false'\n\t\t\tif (typeof expression.value === 'number') return renderTemplateNumber(expression.value)\n\t\t\treturn JSON.stringify(expression.value)\n\t\t}\n\t\tcase 'name':\n\t\t\treturn expression.name\n\t\tcase 'member': {\n\t\t\tconst target =\n\t\t\t\texpression.object.term === 'name' ||\n\t\t\t\texpression.object.term === 'literal' ||\n\t\t\t\texpression.object.term === 'member' ||\n\t\t\t\texpression.object.term === 'slice' ||\n\t\t\t\texpression.object.term === 'call'\n\t\t\t\t\t? renderTemplateExpression(expression.object)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.object)})`\n\t\t\tif (\n\t\t\t\texpression.key.term === 'literal' &&\n\t\t\t\ttypeof expression.key.value === 'string' &&\n\t\t\t\t/^[\\p{XID_Start}_]\\p{XID_Continue}*$/u.test(expression.key.value)\n\t\t\t) {\n\t\t\t\treturn `${target}.${expression.key.value}`\n\t\t\t}\n\t\t\treturn `${target}[${renderTemplateExpression(expression.key)}]`\n\t\t}\n\t\tcase 'slice': {\n\t\t\tconst target =\n\t\t\t\texpression.object.term === 'name' ||\n\t\t\t\texpression.object.term === 'literal' ||\n\t\t\t\texpression.object.term === 'member' ||\n\t\t\t\texpression.object.term === 'slice' ||\n\t\t\t\texpression.object.term === 'call'\n\t\t\t\t\t? renderTemplateExpression(expression.object)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.object)})`\n\t\t\tconst start = expression.start === undefined ? '' : renderTemplateExpression(expression.start)\n\t\t\tconst stop = expression.stop === undefined ? '' : renderTemplateExpression(expression.stop)\n\t\t\tconst step =\n\t\t\t\texpression.step === undefined ? '' : `:${renderTemplateExpression(expression.step)}`\n\t\t\treturn `${target}[${start}:${stop}${step}]`\n\t\t}\n\t\tcase 'call': {\n\t\t\tconst callee =\n\t\t\t\texpression.callee.term === 'name' || expression.callee.term === 'member'\n\t\t\t\t\t? renderTemplateExpression(expression.callee)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.callee)})`\n\t\t\tconst argumentsList = [\n\t\t\t\t...expression.values.map((value) => renderTemplateExpression(value)),\n\t\t\t\t...expression.keywords.map(\n\t\t\t\t\t(keyword) => `${keyword.name}=${renderTemplateExpression(keyword.value)}`,\n\t\t\t\t),\n\t\t\t]\n\t\t\treturn `${callee}(${argumentsList.join(', ')})`\n\t\t}\n\t\tcase 'filter': {\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'name' ||\n\t\t\t\texpression.value.term === 'literal' ||\n\t\t\t\texpression.value.term === 'member' ||\n\t\t\t\texpression.value.term === 'slice' ||\n\t\t\t\texpression.value.term === 'call' ||\n\t\t\t\texpression.value.term === 'filter'\n\t\t\t\t\t? renderTemplateExpression(expression.value)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.value)})`\n\t\t\treturn `${inner} | ${expression.name}`\n\t\t}\n\t\tcase 'test': {\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'conditional' ||\n\t\t\t\texpression.value.term === 'test' ||\n\t\t\t\t(expression.value.term === 'unary' && expression.value.operator === 'not') ||\n\t\t\t\t(expression.value.term === 'binary' &&\n\t\t\t\t\t(expression.value.operator === 'and' ||\n\t\t\t\t\t\texpression.value.operator === 'or' ||\n\t\t\t\t\t\texpression.value.operator === 'in' ||\n\t\t\t\t\t\texpression.value.operator === 'not in' ||\n\t\t\t\t\t\texpression.value.operator === '==' ||\n\t\t\t\t\t\texpression.value.operator === '!=' ||\n\t\t\t\t\t\texpression.value.operator === '<' ||\n\t\t\t\t\t\texpression.value.operator === '>' ||\n\t\t\t\t\t\texpression.value.operator === '<=' ||\n\t\t\t\t\t\texpression.value.operator === '>='))\n\t\t\t\t\t? `(${renderTemplateExpression(expression.value)})`\n\t\t\t\t\t: renderTemplateExpression(expression.value)\n\t\t\treturn expression.negated\n\t\t\t\t? `${inner} is not ${expression.name}`\n\t\t\t\t: `${inner} is ${expression.name}`\n\t\t}\n\t\tcase 'unary': {\n\t\t\tif (expression.operator === 'not') {\n\t\t\t\tconst inner =\n\t\t\t\t\texpression.value.term === 'conditional' ||\n\t\t\t\t\t(expression.value.term === 'binary' &&\n\t\t\t\t\t\t(expression.value.operator === 'and' || expression.value.operator === 'or'))\n\t\t\t\t\t\t? `(${renderTemplateExpression(expression.value)})`\n\t\t\t\t\t\t: renderTemplateExpression(expression.value)\n\t\t\t\treturn `not ${inner}`\n\t\t\t}\n\t\t\tconst inner =\n\t\t\t\texpression.value.term === 'name' ||\n\t\t\t\texpression.value.term === 'literal' ||\n\t\t\t\texpression.value.term === 'member' ||\n\t\t\t\texpression.value.term === 'slice' ||\n\t\t\t\texpression.value.term === 'call' ||\n\t\t\t\texpression.value.term === 'filter'\n\t\t\t\t\t? renderTemplateExpression(expression.value)\n\t\t\t\t\t: `(${renderTemplateExpression(expression.value)})`\n\t\t\treturn `${expression.operator}${inner}`\n\t\t}\n\t\tcase 'binary': {\n\t\t\tconst left =\n\t\t\t\texpression.left.term === 'binary' ||\n\t\t\t\texpression.left.term === 'conditional' ||\n\t\t\t\texpression.left.term === 'test' ||\n\t\t\t\t(expression.left.term === 'unary' && expression.left.operator === 'not')\n\t\t\t\t\t? `(${renderTemplateExpression(expression.left)})`\n\t\t\t\t\t: renderTemplateExpression(expression.left)\n\t\t\tconst right =\n\t\t\t\texpression.right.term === 'binary' ||\n\t\t\t\texpression.right.term === 'conditional' ||\n\t\t\t\texpression.right.term === 'test' ||\n\t\t\t\t(expression.right.term === 'unary' && expression.right.operator === 'not')\n\t\t\t\t\t? `(${renderTemplateExpression(expression.right)})`\n\t\t\t\t\t: renderTemplateExpression(expression.right)\n\t\t\treturn `${left} ${expression.operator} ${right}`\n\t\t}\n\t\tcase 'conditional':\n\t\t\treturn `(${renderTemplateExpression(expression.consequent)} if ${renderTemplateExpression(expression.condition)} else ${renderTemplateExpression(expression.alternate)})`\n\t}\n}\n\n/**\n * Checks whether a trailing text node ends with a whitespace-only line that\n * Jinja's `lstrip_blocks` would strip before a following block or comment tag.\n *\n * @param node - The preceding sibling node, if any\n * @param atLineStart - Whether the text node itself opened at a line start\n * @returns True if a `+` marker is needed to keep the whitespace verbatim; false otherwise\n *\n * @example\n * ```ts\n * import { matchesTemplateIndent } from '@orkestrel/template'\n *\n * matchesTemplateIndent({ syntax: 'text', value: ' ' }, true) // true\n * ```\n */\nexport function matchesTemplateIndent(\n\tnode: TemplateNode | undefined,\n\tatLineStart: boolean,\n): boolean {\n\tif (node?.syntax !== 'text') return false\n\tconst breakIndex = node.value.lastIndexOf('\\n')\n\tconst tail = node.value.slice(breakIndex + 1)\n\tconst startsLine = breakIndex !== -1 || atLineStart\n\treturn startsLine && new RegExp(`^${TEMPLATE_SPACE}+$`, 'u').test(tail)\n}\n\n/**\n * Renders an ordered list of sibling {@link TemplateNode}s into canonical source\n * text, preserving leading whitespace and trailing newlines against Jinja's\n * `lstrip_blocks` and `trim_blocks` rules with `+` markers where needed.\n *\n * @param nodes - The sibling nodes to render\n * @param precedingNewline - Whether the list opens at a line boundary\n * @returns The canonical template source for the node list\n *\n * @example\n * ```ts\n * import { renderTemplateNodes } from '@orkestrel/template'\n *\n * renderTemplateNodes([{ syntax: 'text', value: 'Hi' }], true) // 'Hi'\n * ```\n */\nexport function renderTemplateNodes(\n\tnodes: readonly TemplateNode[],\n\tprecedingNewline: boolean,\n): string {\n\treturn nodes\n\t\t.map((node, index) => {\n\t\t\tconst previous = nodes[index - 1]\n\t\t\tconst next = nodes[index + 1]\n\t\t\tconst needsOpenPlus = matchesTemplateIndent(previous, index === 1 && precedingNewline)\n\t\t\tconst needsClosePlus = next?.syntax === 'text' && next.value.startsWith('\\n')\n\t\t\tconst openBlock = needsOpenPlus ? '{%+' : '{%'\n\t\t\tconst closeBlock = needsClosePlus ? '+%}' : '%}'\n\t\t\tswitch (node.syntax) {\n\t\t\t\tcase 'document':\n\t\t\t\t\treturn renderTemplateNodes(node.children, true)\n\t\t\t\tcase 'text':\n\t\t\t\t\treturn node.value\n\t\t\t\tcase 'placeholder':\n\t\t\t\t\treturn node.raw\n\t\t\t\tcase 'output':\n\t\t\t\t\treturn `{{ ${renderTemplateExpression(node.value)} }}`\n\t\t\t\tcase 'comment': {\n\t\t\t\t\tconst openComment = needsOpenPlus ? '{#+' : '{#'\n\t\t\t\t\tconst closeComment = needsClosePlus ? '+#}' : '#}'\n\t\t\t\t\treturn `${openComment}${node.value}${closeComment}`\n\t\t\t\t}\n\t\t\t\tcase 'control':\n\t\t\t\t\treturn `${openBlock} ${node.action} ${closeBlock}`\n\t\t\t\tcase 'set': {\n\t\t\t\t\tconst target =\n\t\t\t\t\t\tnode.target.scope === 'local'\n\t\t\t\t\t\t\t? node.target.name\n\t\t\t\t\t\t\t: `${node.target.object}.${node.target.name}`\n\t\t\t\t\treturn `${openBlock} set ${target} = ${renderTemplateExpression(node.value)} ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'html':\n\t\t\t\t\treturn renderHTML(node.document)\n\t\t\t\tcase 'markdown':\n\t\t\t\t\treturn renderMarkdown(node.document)\n\t\t\t\tcase 'for': {\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} for ${node.targets.join(', ')} in ${renderTemplateExpression(node.sequence)} ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endfor ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'macro': {\n\t\t\t\t\tconst parameters = node.parameters\n\t\t\t\t\t\t.map((parameter) =>\n\t\t\t\t\t\t\tparameter.fallback === undefined\n\t\t\t\t\t\t\t\t? parameter.name\n\t\t\t\t\t\t\t\t: `${parameter.name}=${renderTemplateExpression(parameter.fallback)}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(', ')\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} macro ${node.name}(${parameters}) ${headerClose}${renderTemplateNodes(node.body, false)}${endOpen} endmacro ${closeBlock}`\n\t\t\t\t}\n\t\t\t\tcase 'if': {\n\t\t\t\t\tconst bodyFirstNewline =\n\t\t\t\t\t\tnode.body[0]?.syntax === 'text' && node.body[0].value.startsWith('\\n')\n\t\t\t\t\tconst branchOpen = matchesTemplateIndent(node.body.at(-1), node.body.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst headerClose = bodyFirstNewline ? '+%}' : '%}'\n\t\t\t\t\tconst bodyText = renderTemplateNodes(node.body, false)\n\t\t\t\t\tif (node.alternate === undefined) {\n\t\t\t\t\t\treturn `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} endif ${closeBlock}`\n\t\t\t\t\t}\n\t\t\t\t\tconst altFirstNewline =\n\t\t\t\t\t\tnode.alternate[0]?.syntax === 'text' && node.alternate[0].value.startsWith('\\n')\n\t\t\t\t\tconst endOpen = matchesTemplateIndent(node.alternate.at(-1), node.alternate.length === 1)\n\t\t\t\t\t\t? '{%+'\n\t\t\t\t\t\t: '{%'\n\t\t\t\t\tconst elseClose = altFirstNewline ? '+%}' : '%}'\n\t\t\t\t\treturn `${openBlock} if ${renderTemplateExpression(node.condition)} ${headerClose}${bodyText}${branchOpen} else ${elseClose}${renderTemplateNodes(node.alternate, false)}${endOpen} endif ${closeBlock}`\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.join('')\n}\n\n/**\n * Renders a {@link TemplateNode} back to canonical template source text.\n *\n * @remarks\n * For every compiled pure-Jinja {@link TemplateDocument}, `compileTemplate(renderTemplate(doc))`\n * produces a structurally equal document and `renderTemplate(compileTemplate(renderTemplate(doc)))`\n * equals `renderTemplate(doc)`.\n *\n * @param node - The node or document to render\n * @returns The canonical template source text\n *\n * @example\n * ```ts\n * import { compileTemplate, renderTemplate } from '@orkestrel/template'\n *\n * renderTemplate(compileTemplate('Hi {{ name }}')) // 'Hi {{ name }}'\n * ```\n */\nexport function renderTemplate(node: TemplateNode): string {\n\tconst rendered =\n\t\tnode.syntax === 'document'\n\t\t\t? renderTemplateNodes(node.children, true)\n\t\t\t: renderTemplateNodes([node], true)\n\treturn node.syntax === 'document' && rendered.endsWith('\\n') ? `${rendered}\\n` : rendered\n}\n\n// === Markdown sanitization and template projection leaves\n\n/**\n * Sanitizes a fenced code block language info string to a single token free of\n * whitespace, line breaks, backticks, and tildes.\n *\n * @param lang - The raw fence info-string language value\n * @returns The sanitized single-token language tag, or `undefined` when empty\n *\n * @example\n * ```ts\n * import { sanitizeTemplateMarkdownLanguage } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownLanguage('ts\\n```\\n[x](javascript:alert(1))') // 'ts'\n * sanitizeTemplateMarkdownLanguage(' ') // undefined\n * ```\n */\nexport function sanitizeTemplateMarkdownLanguage(lang: string): string | undefined {\n\tconst token = /^[^\\s`~]+/u.exec(lang.trim())?.[0]\n\treturn token !== undefined && token.length > 0 ? token : undefined\n}\n\n/**\n * Collapses line breaks inside inline markdown text to single spaces so inline\n * spans stay on one line through round-trip parsing.\n *\n * @param value - The inline text string to normalize\n * @returns The single-line string with `\\r\\n`, `\\r`, and `\\n` replaced by `' '`\n *\n * @example\n * ```ts\n * import { normalizeTemplateMarkdownText } from '@orkestrel/template'\n *\n * normalizeTemplateMarkdownText('a\\n\\nb') // 'a b'\n * ```\n */\nexport function normalizeTemplateMarkdownText(value: string): string {\n\treturn value.replace(/\\r\\n?|\\n/gu, ' ')\n}\n\n/**\n * Sanitizes inline `@orkestrel/markdown` nodes recursively by unwrapping unsafe\n * `LinkNode` elements, dropping unsafe `ImageNode` elements, and collapsing\n * line breaks inside `CodeSpanNode` values.\n *\n * @param nodes - The inline nodes to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized inline nodes\n *\n * @example\n * ```ts\n * import { parseInline } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdownInlines } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownInlines(parseInline('[x](javascript:alert(1))')) // [{ element: 'text', value: 'x' }]\n * ```\n */\nexport function sanitizeTemplateMarkdownInlines(\n\tnodes: readonly InlineNode[],\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH) return []\n\tconst schemes = options?.schemes ?? SAFE_URL_SCHEMES\n\tconst sanitized: InlineNode[] = []\n\tfor (const child of nodes) {\n\t\tif (child.element === 'codeSpan') {\n\t\t\tsanitized.push({\n\t\t\t\telement: 'codeSpan',\n\t\t\t\tvalue: normalizeTemplateMarkdownText(child.value),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'link') {\n\t\t\tconst children = sanitizeTemplateMarkdownInlines(child.children, options, depth + 1)\n\t\t\tconst cleanHref = sanitizeURL(child.href, schemes)\n\t\t\tif (cleanHref === '') {\n\t\t\t\tfor (const inner of children) sanitized.push(inner)\n\t\t\t} else {\n\t\t\t\tsanitized.push({ element: 'link', href: cleanHref, children })\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'image') {\n\t\t\tconst cleanSrc = sanitizeURL(child.src, schemes)\n\t\t\tif (cleanSrc !== '') {\n\t\t\t\tsanitized.push({\n\t\t\t\t\telement: 'image',\n\t\t\t\t\tsrc: cleanSrc,\n\t\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1),\n\t\t\t\t})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif (child.element === 'emphasis') {\n\t\t\tsanitized.push({\n\t\t\t\telement: 'emphasis',\n\t\t\t\tstrong: child.strong,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(child.children, options, depth + 1),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tsanitized.push(child)\n\t}\n\treturn coalesceText(sanitized)\n}\n\n/**\n * Sanitizes block `@orkestrel/markdown` nodes recursively through\n * `sanitizeTemplateMarkdown`, dropping any node that sanitizes to `undefined`.\n *\n * @param nodes - The block nodes to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized block nodes\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdownBlocks } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdownBlocks(parseMarkdown('Hi').children).length // 1\n * ```\n */\nexport function sanitizeTemplateMarkdownBlocks(\n\tnodes: readonly BlockNode[],\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): readonly BlockNode[] {\n\tif (depth >= MAX_DEPTH) return []\n\tconst blocks: BlockNode[] = []\n\tfor (const block of nodes) {\n\t\tconst clean = sanitizeTemplateMarkdown(block, options, depth)\n\t\tif (clean !== undefined && isBlockNode(clean)) blocks.push(clean)\n\t}\n\treturn blocks\n}\n\n/**\n * Sanitizes a `@orkestrel/markdown` node recursively by unwrapping any\n * `LinkNode` whose `href` fails `sanitizeURL`, dropping any `ImageNode` whose\n * `src` fails `sanitizeURL`, collapsing `CodeSpanNode` line breaks, and\n * sanitizing `CodeBlockNode` fence languages.\n *\n * @param node - The markdown AST node to sanitize\n * @param options - Optional HTML sanitization allowlist settings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The sanitized node, or `undefined` when dropped\n *\n * @example\n * ```ts\n * import { parseMarkdown } from '@orkestrel/markdown'\n * import { sanitizeTemplateMarkdown } from '@orkestrel/template'\n *\n * sanitizeTemplateMarkdown(parseMarkdown(')')) // { element: 'document', children: [{ element: 'paragraph', children: [] }] }\n * ```\n */\nexport function sanitizeTemplateMarkdown(\n\tnode: MarkdownNode,\n\toptions?: HTMLSanitizeOptions,\n\tdepth = 0,\n): MarkdownNode | undefined {\n\tif (depth >= MAX_DEPTH) return undefined\n\tconst schemes = options?.schemes ?? SAFE_URL_SCHEMES\n\tswitch (node.element) {\n\t\tcase 'text':\n\t\tcase 'break':\n\t\tcase 'thematicBreak':\n\t\t\treturn node\n\t\tcase 'codeSpan':\n\t\t\treturn {\n\t\t\t\telement: 'codeSpan',\n\t\t\t\tvalue: normalizeTemplateMarkdownText(node.value),\n\t\t\t}\n\t\tcase 'codeBlock': {\n\t\t\tconst lang = node.lang !== undefined ? sanitizeTemplateMarkdownLanguage(node.lang) : undefined\n\t\t\treturn {\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(lang !== undefined ? { lang } : {}),\n\t\t\t\tcode: node.code,\n\t\t\t}\n\t\t}\n\t\tcase 'image': {\n\t\t\tconst cleanSrc = sanitizeURL(node.src, schemes)\n\t\t\tif (cleanSrc === '') return undefined\n\t\t\treturn {\n\t\t\t\telement: 'image',\n\t\t\t\tsrc: cleanSrc,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\t}\n\t\tcase 'link': {\n\t\t\tconst children = sanitizeTemplateMarkdownInlines(node.children, options, depth + 1)\n\t\t\tconst cleanHref = sanitizeURL(node.href, schemes)\n\t\t\tif (cleanHref === '') {\n\t\t\t\tif (children.length === 0) return undefined\n\t\t\t\tif (children.length === 1) return children[0]\n\t\t\t\treturn {\n\t\t\t\t\telement: 'text',\n\t\t\t\t\tvalue: children.map((child) => flattenText(child)).join(''),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { element: 'link', href: cleanHref, children }\n\t\t}\n\t\tcase 'emphasis':\n\t\t\treturn {\n\t\t\t\telement: 'emphasis',\n\t\t\t\tstrong: node.strong,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'heading':\n\t\t\treturn {\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: node.level,\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'paragraph':\n\t\t\treturn {\n\t\t\t\telement: 'paragraph',\n\t\t\t\tchildren: sanitizeTemplateMarkdownInlines(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'blockquote':\n\t\t\treturn {\n\t\t\t\telement: 'blockquote',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'listItem':\n\t\t\treturn {\n\t\t\t\telement: 'listItem',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t\tcase 'list': {\n\t\t\tconst items: ListItemNode[] = node.items.map((item) => ({\n\t\t\t\telement: 'listItem',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(item.children, options, depth + 1),\n\t\t\t}))\n\t\t\treturn { element: 'list', ordered: node.ordered, start: node.start, items }\n\t\t}\n\t\tcase 'table':\n\t\t\treturn {\n\t\t\t\telement: 'table',\n\t\t\t\theader: node.header.map((cell) =>\n\t\t\t\t\tsanitizeTemplateMarkdownInlines(cell, options, depth + 1),\n\t\t\t\t),\n\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\trow.map((cell) => sanitizeTemplateMarkdownInlines(cell, options, depth + 1)),\n\t\t\t\t),\n\t\t\t\talign: node.align,\n\t\t\t}\n\t\tcase 'document':\n\t\t\treturn {\n\t\t\t\telement: 'document',\n\t\t\t\tchildren: sanitizeTemplateMarkdownBlocks(node.children, options, depth + 1),\n\t\t\t}\n\t}\n}\n\n/**\n * Resolves a Private Use Area sentinel prefix guaranteed absent from `combined`.\n *\n * @param combined - Concatenated template text and fill values in one markdown run\n * @returns The collision-free sentinel prefix\n *\n * @example\n * ```ts\n * import { resolveMarkdownMarker } from '@orkestrel/template'\n *\n * resolveMarkdownMarker('plain text') // '\\uE000\\uE001'\n * ```\n */\nexport function resolveMarkdownMarker(combined: string): string {\n\tfor (let k = 0; k <= combined.length; k += 1) {\n\t\tconst candidate = `\\uE000${'\\uE002'.repeat(k)}\\uE001`\n\t\tif (!combined.includes(candidate)) return candidate\n\t}\n\treturn `\\uE000${'\\uE002'.repeat(combined.length + 1)}\\uE001`\n}\n\n/**\n * Replaces every sentinel slot in a parsed markdown leaf string with its\n * literal dynamic fill string in a single pass.\n *\n * @param text - Parsed leaf string possibly holding sentinel slots\n * @param pattern - RegExp matching sentinel slots for this run\n * @param fills - Indexed dynamic fill strings\n * @returns The restored literal string\n *\n * @example\n * ```ts\n * import { restoreMarkdownText } from '@orkestrel/template'\n *\n * restoreMarkdownText('\\uE000\\uE0010\\uE003', /\\uE000\\uE001(\\d+)\\uE003/gu, ['Ada']) // 'Ada'\n * ```\n */\nexport function restoreMarkdownText(\n\ttext: string,\n\tpattern: RegExp,\n\tfills: readonly string[],\n): string {\n\treturn text.replace(new RegExp(pattern.source, pattern.flags), (match, digits: string) => {\n\t\tconst value = fills[Number(digits)]\n\t\treturn value ?? match\n\t})\n}\n\n/**\n * Restores sentinel slots inside a list of parsed inline markdown nodes,\n * collapsing line breaks inside substituted dynamic fills and `CodeSpanNode`\n * values so inline content stays single-line across round-trips.\n *\n * @param nodes - Inline nodes parsed from sentinel-substituted markdown\n * @param pattern - RegExp matching sentinel slots\n * @param fills - Indexed dynamic fill strings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The inline nodes with dynamic fills restored as literal leaves\n *\n * @example\n * ```ts\n * import { restoreMarkdownInlines } from '@orkestrel/template'\n *\n * restoreMarkdownInlines([{ element: 'text', value: 'hi' }], /\\uE000\\uE001(\\d+)\\uE003/gu, []) // [{ element: 'text', value: 'hi' }]\n * ```\n */\nexport function restoreMarkdownInlines(\n\tnodes: readonly InlineNode[],\n\tpattern: RegExp,\n\tfills: readonly string[],\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH) return nodes\n\tconst inlineFills = fills.some((fill) => /[\\r\\n]/u.test(fill))\n\t\t? fills.map((fill) => normalizeTemplateMarkdownText(fill))\n\t\t: fills\n\treturn nodes.map((node) => {\n\t\tswitch (node.element) {\n\t\t\tcase 'text':\n\t\t\t\treturn { element: 'text', value: restoreMarkdownText(node.value, pattern, inlineFills) }\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'codeSpan',\n\t\t\t\t\tvalue: normalizeTemplateMarkdownText(\n\t\t\t\t\t\trestoreMarkdownText(node.value, pattern, inlineFills),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\tcase 'break':\n\t\t\t\treturn node\n\t\t\tcase 'emphasis':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'emphasis',\n\t\t\t\t\tstrong: node.strong,\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t\tcase 'link':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'link',\n\t\t\t\t\thref: restoreMarkdownText(node.href, pattern, inlineFills),\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t\tcase 'image':\n\t\t\t\treturn {\n\t\t\t\t\telement: 'image',\n\t\t\t\t\tsrc: restoreMarkdownText(node.src, pattern, inlineFills),\n\t\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, inlineFills, depth + 1),\n\t\t\t\t}\n\t\t}\n\t})\n}\n\n/**\n * Restores sentinel slots inside a parsed block markdown node, keeping\n * verbatim line breaks only inside `CodeBlockNode.code` and sanitizing\n * `CodeBlockNode.lang` to a single token.\n *\n * @param node - Block node parsed from sentinel-substituted markdown\n * @param pattern - RegExp matching sentinel slots\n * @param fills - Indexed dynamic fill strings\n * @param depth - Current recursion depth. Default: `0`\n * @returns The block node with dynamic fills restored as literal leaves\n *\n * @example\n * ```ts\n * import { restoreMarkdownBlock } from '@orkestrel/template'\n *\n * restoreMarkdownBlock({ element: 'thematicBreak' }, /\\uE000\\uE001(\\d+)\\uE003/gu, []) // { element: 'thematicBreak' }\n * ```\n */\nexport function restoreMarkdownBlock(\n\tnode: BlockNode,\n\tpattern: RegExp,\n\tfills: readonly string[],\n\tdepth = 0,\n): BlockNode {\n\tif (depth >= MAX_DEPTH) return node\n\tswitch (node.element) {\n\t\tcase 'thematicBreak':\n\t\t\treturn node\n\t\tcase 'heading':\n\t\t\treturn {\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: node.level,\n\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, fills, depth + 1),\n\t\t\t}\n\t\tcase 'paragraph':\n\t\t\treturn {\n\t\t\t\telement: 'paragraph',\n\t\t\t\tchildren: restoreMarkdownInlines(node.children, pattern, fills, depth + 1),\n\t\t\t}\n\t\tcase 'codeBlock': {\n\t\t\tconst lang =\n\t\t\t\tnode.lang !== undefined\n\t\t\t\t\t? sanitizeTemplateMarkdownLanguage(restoreMarkdownText(node.lang, pattern, fills))\n\t\t\t\t\t: undefined\n\t\t\treturn {\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(lang !== undefined ? { lang } : {}),\n\t\t\t\tcode: restoreMarkdownText(node.code, pattern, fills),\n\t\t\t}\n\t\t}\n\t\tcase 'blockquote':\n\t\t\treturn {\n\t\t\t\telement: 'blockquote',\n\t\t\t\tchildren: node.children.map((child) =>\n\t\t\t\t\trestoreMarkdownBlock(child, pattern, fills, depth + 1),\n\t\t\t\t),\n\t\t\t}\n\t\tcase 'list':\n\t\t\treturn {\n\t\t\t\telement: 'list',\n\t\t\t\tordered: node.ordered,\n\t\t\t\tstart: node.start,\n\t\t\t\titems: node.items.map((item) => ({\n\t\t\t\t\telement: 'listItem',\n\t\t\t\t\tchildren: item.children.map((child) =>\n\t\t\t\t\t\trestoreMarkdownBlock(child, pattern, fills, depth + 1),\n\t\t\t\t\t),\n\t\t\t\t})),\n\t\t\t}\n\t\tcase 'table':\n\t\t\treturn {\n\t\t\t\telement: 'table',\n\t\t\t\theader: node.header.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1)),\n\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\trow.map((cell) => restoreMarkdownInlines(cell, pattern, fills, depth + 1)),\n\t\t\t\t),\n\t\t\t\talign: node.align,\n\t\t\t}\n\t}\n}\n\n/**\n * Builds sanitized markdown blocks from a contiguous run of template-authored\n * literal text (`true`) and dynamic scalar fill strings (`false`), keeping\n * dynamic scalars strictly literal leaf text.\n *\n * @param run - Ordered `[literal, text]` entries in the run\n * @param options - Optional HTML sanitization allowlist settings\n * @returns The sanitized block nodes produced from the run\n *\n * @example\n * ```ts\n * import { buildTemplateMarkdownBlocks } from '@orkestrel/template'\n *\n * buildTemplateMarkdownBlocks([[true, '# '], [false, 'Ada']])[0]?.element // 'heading'\n * ```\n */\nexport function buildTemplateMarkdownBlocks(\n\trun: ReadonlyArray<readonly [literal: boolean, text: string]>,\n\toptions?: HTMLSanitizeOptions,\n): readonly BlockNode[] {\n\tconst hasFill = run.some(([literal, text]) => !literal && text.length > 0)\n\tif (!hasFill) {\n\t\tconst parsed = parseMarkdown(run.map(([, text]) => text).join(''))\n\t\tconst clean = sanitizeTemplateMarkdown(parsed, options)\n\t\treturn clean !== undefined && clean.element === 'document' ? clean.children : []\n\t}\n\tconst combined = run.map(([, text]) => text).join('')\n\tconst prefix = resolveMarkdownMarker(combined)\n\tconst fills: string[] = []\n\tconst markedParts: string[] = []\n\tfor (const [literal, text] of run) {\n\t\tif (literal || text.length === 0) {\n\t\t\tmarkedParts.push(text)\n\t\t\tcontinue\n\t\t}\n\t\tconst slot = `${prefix}${fills.length}\\uE003`\n\t\tfills.push(text)\n\t\tmarkedParts.push(slot)\n\t}\n\tconst parsed = parseMarkdown(markedParts.join(''))\n\tconst pattern = new RegExp(`${prefix}(\\\\d+)\\uE003`, 'gu')\n\tconst restored: MarkdownDocument = {\n\t\telement: 'document',\n\t\tchildren: parsed.children.map((block) => restoreMarkdownBlock(block, pattern, fills)),\n\t}\n\tconst clean = sanitizeTemplateMarkdown(restored, options)\n\treturn clean !== undefined && clean.element === 'document' ? clean.children : []\n}\n","import type {\n\tTemplateDocument,\n\tTemplateExpression,\n\tTemplateKeyword,\n\tTemplateNode,\n\tTemplateOperator,\n\tTemplateParameter,\n\tTemplateParseResult,\n\tTemplateSpan,\n\tTemplateToken,\n} from './types.js'\nimport { keyOf } from '@orkestrel/contract'\nimport {\n\tFILL_PATTERN,\n\tTEMPLATE_FILTERS,\n\tTEMPLATE_FUNCTIONS,\n\tTEMPLATE_LITERALS,\n\tTEMPLATE_OPERATOR_FEATURES,\n\tTEMPLATE_TESTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\nimport {\n\tbuildTemplateFormatError,\n\tcheckTemplateClose,\n\tcheckTemplateDepth,\n\tcheckTemplateLoopMember,\n\tcheckTemplateTarget,\n\tcheckTemplateToken,\n\tdecodeTemplateNumber,\n\tdecodeTemplateString,\n\tmatchesTemplateToken,\n\tquoteTemplateText,\n\treadTemplateToken,\n\trenderTemplateToken,\n\tscanTemplateTokens,\n} from './helpers.js'\nimport { isTemplateComparison } from './validators.js'\n\n// Throwing template compilers: full Jinja AST compilation with provenance spans\n// (`compileTemplate`, `compileTemplateProvenance`) plus plain `{{name}}`\n// placeholder compilation (`compilePlainTemplate`).\n\n/**\n * Compiles a Jinja template source string into a {@link TemplateDocument} AST\n * alongside its original-source {@link TemplateSpan} map.\n *\n * @param source - The template's Jinja source string\n * @returns The compiled document and its node-to-span map\n *\n * @example\n * ```ts\n * import { compileTemplateProvenance } from '@orkestrel/template'\n *\n * const [document, spans] = compileTemplateProvenance('Hi {{ name }}')\n * spans.get(document) // { start: 0, end: 13 }\n * ```\n */\nexport function compileTemplateProvenance(source: string): TemplateParseResult {\n\tif (typeof source !== 'string') {\n\t\tthrow new TemplateError('INVALID', 'A template compiles from a string of Jinja source.')\n\t}\n\tconst tokens = scanTemplateTokens(source)\n\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\tconst [children] = compileTemplateStatements(tokens, 0, 0, [], false, spans)\n\tconst document: TemplateDocument = { syntax: 'document', children }\n\tspans.set(document, { start: 0, end: source.length })\n\treturn [document, spans]\n}\n\n/**\n * Compiles a Jinja template source string into a {@link TemplateDocument} AST.\n *\n * @param source - The template's Jinja source string\n * @returns The compiled document AST\n *\n * @example\n * ```ts\n * import { compileTemplate } from '@orkestrel/template'\n *\n * compileTemplate('{{ bos_token }}').children[0] // { syntax: 'output', value: { term: 'name', name: 'bos_token' } }\n * ```\n */\nexport function compileTemplate(source: string): TemplateDocument {\n\treturn compileTemplateProvenance(source)[0]\n}\n\n/**\n * Compiles a plain `{{name}}` placeholder template into a {@link TemplateDocument}\n * AST of `text` and `placeholder` nodes alongside original-source UTF-16 spans.\n *\n * @param source - The plain placeholder template content\n * @returns The compiled document and its node-to-span map\n *\n * @example\n * ```ts\n * import { compilePlainTemplate } from '@orkestrel/template'\n *\n * const [document] = compilePlainTemplate('Hi {{name}}')\n * document.children[1] // { syntax: 'placeholder', name: 'name', raw: '{{name}}' }\n * ```\n */\nexport function compilePlainTemplate(source: string): TemplateParseResult {\n\tif (typeof source !== 'string') {\n\t\tthrow new TemplateError('INVALID', 'A plain template compiles from a string.')\n\t}\n\tconst children: TemplateNode[] = []\n\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst matches = Array.from(source.matchAll(pattern))\n\tlet cursor = 0\n\tlet pendingText = ''\n\tlet pendingStart = 0\n\tfor (let index = 0; index < matches.length; index += 1) {\n\t\tconst match = matches[index]\n\t\tif (match === undefined) break\n\t\tconst matchStart = match.index\n\t\tconst matchText = match[0]\n\t\tconst matchEnd = matchStart + matchText.length\n\t\tconst rawToken = match[1]\n\t\tif (matchStart > cursor) {\n\t\t\tif (pendingText === '') pendingStart = cursor\n\t\t\tpendingText += source.slice(cursor, matchStart)\n\t\t}\n\t\tif (rawToken === undefined) {\n\t\t\tif (pendingText === '') pendingStart = matchStart\n\t\t\tpendingText += '{{'\n\t\t\tcursor = matchEnd\n\t\t\tcontinue\n\t\t}\n\t\tif (pendingText.length > 0) {\n\t\t\tconst textNode: TemplateNode = { syntax: 'text', value: pendingText }\n\t\t\tchildren.push(textNode)\n\t\t\tspans.set(textNode, { start: pendingStart, end: matchStart })\n\t\t\tpendingText = ''\n\t\t}\n\t\tconst placeholderNode: TemplateNode = {\n\t\t\tsyntax: 'placeholder',\n\t\t\tname: rawToken.trim(),\n\t\t\traw: matchText,\n\t\t}\n\t\tchildren.push(placeholderNode)\n\t\tspans.set(placeholderNode, { start: matchStart, end: matchEnd })\n\t\tcursor = matchEnd\n\t}\n\tconst finalText = cursor < source.length ? pendingText + source.slice(cursor) : pendingText\n\tconst finalStart = pendingText === '' ? cursor : pendingStart\n\tif (finalText.length > 0) {\n\t\tconst textNode: TemplateNode = { syntax: 'text', value: finalText }\n\t\tchildren.push(textNode)\n\t\tspans.set(textNode, { start: finalStart, end: source.length })\n\t}\n\tconst document: TemplateDocument = { syntax: 'document', children }\n\tspans.set(document, { start: 0, end: source.length })\n\treturn [document, spans]\n}\n\n/**\n * Compiles a run of Jinja template statements up to end-of-source or one of the\n * closing block tag names in `ends`.\n *\n * @param tokens - The scanned token stream\n * @param start - The starting token index\n * @param depth - Current statement nesting depth\n * @param ends - Block tag names that terminate this statement run\n * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled statements, stopping token index, and maximum subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateStatements, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateStatements(scanTemplateTokens('Hi{% endif %}'), 0, 0, ['endif'], false)[1] // 1\n * ```\n */\nexport function compileTemplateStatements(\n\ttokens: readonly TemplateToken[],\n\tstart: number,\n\tdepth: number,\n\tends: readonly string[],\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statements: readonly TemplateNode[], end: number, height: number] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, start))\n\tconst statements: TemplateNode[] = []\n\tconst heights: number[] = []\n\tlet index = start\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, index)\n\t\tif (token.token === 'end') {\n\t\t\tif (ends.length === 0) break\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`ends before a ${ends.map((name) => `{% ${name} %}`).join(' or ')} tag closes the block`,\n\t\t\t)\n\t\t}\n\t\tif (token.token === 'text') {\n\t\t\tconst node: TemplateNode = { syntax: 'text', value: token.text }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: token.end })\n\t\t\theights.push(0)\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token === 'comment') {\n\t\t\tconst node: TemplateNode = { syntax: 'comment', value: token.text }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: token.end })\n\t\t\theights.push(0)\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token === 'variable') {\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true)\n\t\t\tcheckTemplateDepth(height + 1, token)\n\t\t\tconst after = checkTemplateClose(tokens, next, false)\n\t\t\tconst closeToken = readTemplateToken(tokens, after - 1)\n\t\t\tconst node: TemplateNode = { syntax: 'output', value }\n\t\t\tstatements.push(node)\n\t\t\tspans?.set(node, { start: token.start, end: closeToken.end })\n\t\t\theights.push(height + 1)\n\t\t\tindex = after\n\t\t\tcontinue\n\t\t}\n\t\tif (token.token !== 'block') {\n\t\t\tthrow buildTemplateFormatError(token, `holds ${renderTemplateToken(token)} outside a tag`)\n\t\t}\n\t\tconst name = readTemplateToken(tokens, index + 1)\n\t\tif (name.token === 'name' && ends.includes(name.text)) break\n\t\tconst [statement, next, height] = compileTemplateBlock(tokens, index + 1, depth, loop, spans)\n\t\tconst closeToken = readTemplateToken(tokens, next - 1)\n\t\tspans?.set(statement, { start: token.start, end: closeToken.end })\n\t\tstatements.push(statement)\n\t\theights.push(height)\n\t\tindex = next\n\t}\n\treturn [statements, index, heights.reduce((top, height) => Math.max(top, height), 0)]\n}\n\n/**\n * Compiles one Jinja block tag (`if`, `for`, `set`, `macro`, `break`, or `continue`).\n *\n * @param tokens - The scanned token stream\n * @param index - The index of the tag name token\n * @param depth - Current statement nesting depth\n * @param loop - If `true`, admits `break` and `continue`; if `false`, refuses them\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled node, token index after closing delimiter, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateBlock, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateBlock(scanTemplateTokens('{% set turn = 1 %}'), 1, 0, false)[0].syntax // 'set'\n * ```\n */\nexport function compileTemplateBlock(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst name = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, name)\n\tif (name.token !== 'name') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`expects a tag name and finds ${renderTemplateToken(name)}`,\n\t\t)\n\t}\n\tswitch (name.text) {\n\t\tcase 'if':\n\t\t\treturn compileTemplateIf(tokens, index + 1, depth, loop, spans)\n\t\tcase 'for':\n\t\t\treturn compileTemplateFor(tokens, index + 1, depth, spans)\n\t\tcase 'macro':\n\t\t\treturn compileTemplateMacro(tokens, index + 1, depth, spans)\n\t\tcase 'set': {\n\t\t\tconst target = readTemplateToken(tokens, index + 1)\n\t\t\tcheckTemplateTarget(target)\n\t\t\tconst after = readTemplateToken(tokens, index + 2)\n\t\t\tif (matchesTemplateToken(after, 'operator', '.')) {\n\t\t\t\tconst property = readTemplateToken(tokens, index + 3)\n\t\t\t\tcheckTemplateTarget(property)\n\t\t\t\tcheckTemplateToken(tokens, index + 4, 'operator', '=')\n\t\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 5, depth + 1, true)\n\t\t\t\tcheckTemplateDepth(height + 1, name)\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsyntax: 'set',\n\t\t\t\t\t\ttarget: { scope: 'attribute', object: target.text, name: property.text },\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t},\n\t\t\t\t\tcheckTemplateClose(tokens, next, false),\n\t\t\t\t\theight + 1,\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst feature = matchesTemplateToken(after, 'operator', ',')\n\t\t\t\t? 'tuple target'\n\t\t\t\t: matchesTemplateToken(after, 'operator', '=')\n\t\t\t\t\t? target.text === 'loop'\n\t\t\t\t\t\t? 'loop assignment'\n\t\t\t\t\t\t: undefined\n\t\t\t\t\t: 'set block'\n\t\t\tif (feature !== undefined) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\tname,\n\t\t\t\t\t`writes a ${quoteTemplateText(feature)} form of {% set %}, which the subset does not admit`,\n\t\t\t\t\t{ feature },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, index + 3, depth + 1, true)\n\t\t\tcheckTemplateDepth(height + 1, name)\n\t\t\treturn [\n\t\t\t\t{ syntax: 'set', target: { scope: 'local', name: target.text }, value },\n\t\t\t\tcheckTemplateClose(tokens, next, false),\n\t\t\t\theight + 1,\n\t\t\t]\n\t\t}\n\t\tcase 'break':\n\t\tcase 'continue': {\n\t\t\tif (!loop)\n\t\t\t\tthrow buildTemplateFormatError(name, `writes {% ${name.text} %} outside a for loop`)\n\t\t\treturn [\n\t\t\t\t{ syntax: 'control', action: name.text },\n\t\t\t\tcheckTemplateClose(tokens, index + 1, false),\n\t\t\t\t0,\n\t\t\t]\n\t\t}\n\t\tcase 'elif':\n\t\tcase 'else':\n\t\tcase 'endif':\n\t\tcase 'endfor':\n\t\tcase 'endmacro':\n\t\t\tthrow buildTemplateFormatError(name, `writes {% ${name.text} %}, which closes no open block`)\n\t\tdefault:\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`uses the tag ${quoteTemplateText(name.text)}, which the subset does not admit`,\n\t\t\t\t{ feature: name.text },\n\t\t\t)\n\t}\n}\n\n/**\n * Compiles a Jinja `if` / `elif` / `else` / `endif` conditional block.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `if` or `elif`\n * @param depth - Current statement nesting depth\n * @param loop - If `true`, inside a `for` loop; if `false`, outside\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `if` node, token index after `{% endif %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateIf, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateIf(scanTemplateTokens('{% if x %}A{% endif %}'), 2, 0, false)[0].syntax // 'if'\n * ```\n */\nexport function compileTemplateIf(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tloop: boolean,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [condition, next, conditionHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tindex,\n\t\tdepth + 1,\n\t\tfalse,\n\t)\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, next, true),\n\t\tdepth + 1,\n\t\t['elif', 'else', 'endif'],\n\t\tloop,\n\t\tspans,\n\t)\n\tconst branchOpen = readTemplateToken(tokens, end)\n\tconst branch = readTemplateToken(tokens, end + 1)\n\tif (branch.text === 'elif') {\n\t\tconst [alternate, after, alternateHeight] = compileTemplateIf(\n\t\t\ttokens,\n\t\t\tend + 2,\n\t\t\tdepth + 1,\n\t\t\tloop,\n\t\t\tspans,\n\t\t)\n\t\tconst closeToken = readTemplateToken(tokens, after - 1)\n\t\tspans?.set(alternate, { start: branchOpen.start, end: closeToken.end })\n\t\tconst height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\treturn [{ syntax: 'if', condition, body, alternate: [alternate] }, after, height]\n\t}\n\tif (branch.text === 'else') {\n\t\tconst [alternate, close, alternateHeight] = compileTemplateStatements(\n\t\t\ttokens,\n\t\t\tcheckTemplateClose(tokens, end + 2, true),\n\t\t\tdepth + 1,\n\t\t\t['endif'],\n\t\t\tloop,\n\t\t\tspans,\n\t\t)\n\t\tconst height = 1 + Math.max(conditionHeight, bodyHeight, alternateHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\treturn [\n\t\t\t{ syntax: 'if', condition, body, alternate },\n\t\t\tcheckTemplateClose(tokens, close + 2, false),\n\t\t\theight,\n\t\t]\n\t}\n\tconst height = 1 + Math.max(conditionHeight, bodyHeight)\n\tcheckTemplateDepth(height, start)\n\treturn [{ syntax: 'if', condition, body }, checkTemplateClose(tokens, end + 2, false), height]\n}\n\n/**\n * Compiles a Jinja `for` loop supporting single targets and multi-target tuple\n * unpacking through `{% endfor %}`.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `for`\n * @param depth - Current statement nesting depth\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `for` node, token index after `{% endfor %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateFor, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateFor(scanTemplateTokens('{% for k, v in d|items %}{% endfor %}'), 2, 0)[0]\n * ```\n */\nexport function compileTemplateFor(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst firstTarget = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, firstTarget)\n\tconst targets: string[] = []\n\tlet position = index\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst target = readTemplateToken(tokens, position)\n\t\tcheckTemplateTarget(target)\n\t\tif (target.text === 'loop') {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttarget,\n\t\t\t\t'names \"loop\" as a for loop\\'s target, which Jinja refuses',\n\t\t\t)\n\t\t}\n\t\tif (targets.includes(target.text)) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttarget,\n\t\t\t\t`duplicates the for loop target ${quoteTemplateText(target.text)}`,\n\t\t\t)\n\t\t}\n\t\ttargets.push(target.text)\n\t\tposition += 1\n\t\tif (!matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ',')) break\n\t\tposition += 1\n\t}\n\tcheckTemplateToken(tokens, position, 'name', 'in')\n\tconst [sequence, next, sequenceHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tposition + 1,\n\t\tdepth + 1,\n\t\tfalse,\n\t)\n\tconst following = readTemplateToken(tokens, next)\n\tconst feature = matchesTemplateToken(following, 'name', 'if')\n\t\t? 'loop filter'\n\t\t: matchesTemplateToken(following, 'name', 'recursive')\n\t\t\t? 'recursive loop'\n\t\t\t: undefined\n\tif (feature !== undefined) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t`writes a ${feature}, which the subset does not admit`,\n\t\t\t{\n\t\t\t\tfeature,\n\t\t\t},\n\t\t)\n\t}\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, next, true),\n\t\tdepth + 1,\n\t\t['endfor', 'else'],\n\t\ttrue,\n\t\tspans,\n\t)\n\tconst branch = readTemplateToken(tokens, end + 1)\n\tif (branch.text === 'else') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tbranch,\n\t\t\t'writes {% else %} on a for loop, which the subset does not admit',\n\t\t\t{ feature: 'for else' },\n\t\t)\n\t}\n\tconst height = 1 + Math.max(sequenceHeight, bodyHeight)\n\tcheckTemplateDepth(height, firstTarget)\n\treturn [\n\t\t{ syntax: 'for', targets, sequence, body },\n\t\tcheckTemplateClose(tokens, end + 2, false),\n\t\theight,\n\t]\n}\n\n/**\n * Compiles a Jinja `{% macro name(a, b=default) %} ... {% endmacro %}` block.\n *\n * @param tokens - The scanned token stream\n * @param index - The token index after `macro`\n * @param depth - Current statement nesting depth\n * @param spans - Optional operation-owned span recorder\n * @returns The compiled `macro` node, token index after `{% endmacro %}`, and subtree height\n *\n * @example\n * ```ts\n * import { compileTemplateMacro, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateMacro(scanTemplateTokens('{% macro greet(name=\"Ada\") %}{{ name }}{% endmacro %}'), 2, 0)[0].syntax // 'macro'\n * ```\n */\nexport function compileTemplateMacro(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tspans?: Map<TemplateNode, TemplateSpan>,\n): readonly [statement: TemplateNode, end: number, height: number] {\n\tconst macroName = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, macroName)\n\tcheckTemplateTarget(macroName)\n\tif (macroName.text === 'loop') {\n\t\tthrow buildTemplateFormatError(macroName, 'names \"loop\" as a macro, which Jinja refuses')\n\t}\n\tcheckTemplateToken(tokens, index + 1, 'operator', '(')\n\tconst parameters: TemplateParameter[] = []\n\tconst heights: number[] = []\n\tlet position = index + 2\n\tlet seenDefault = false\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ')')) break\n\t\tconst later = parameters.length > 0\n\t\tif (later) {\n\t\t\tcheckTemplateToken(tokens, position, 'operator', ',')\n\t\t\tposition += 1\n\t\t}\n\t\tconst head = readTemplateToken(tokens, position)\n\t\tif (later && matchesTemplateToken(head, 'operator', ')')) break\n\t\tif (\n\t\t\tmatchesTemplateToken(head, 'operator', '*') ||\n\t\t\tmatchesTemplateToken(head, 'operator', '**')\n\t\t) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t'writes parameter unpacking in a macro, which the subset does not admit',\n\t\t\t\t{ feature: 'argument unpacking' },\n\t\t\t)\n\t\t}\n\t\tcheckTemplateTarget(head)\n\t\tif (parameters.some((parameter) => parameter.name === head.text)) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t`duplicates the macro parameter ${quoteTemplateText(head.text)}`,\n\t\t\t)\n\t\t}\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position + 1), 'operator', '=')) {\n\t\t\tseenDefault = true\n\t\t\tconst [fallback, next, fallbackHeight] = compileTemplateExpression(\n\t\t\t\ttokens,\n\t\t\t\tposition + 2,\n\t\t\t\tdepth + 1,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t\tparameters.push({ name: head.text, fallback })\n\t\t\theights.push(fallbackHeight)\n\t\t\tposition = next\n\t\t} else {\n\t\t\tif (seenDefault) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\thead,\n\t\t\t\t\t`places non-default parameter ${quoteTemplateText(head.text)} after a default parameter`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tparameters.push({ name: head.text })\n\t\t\tposition += 1\n\t\t}\n\t}\n\tcheckTemplateToken(tokens, position, 'operator', ')')\n\tconst [body, end, bodyHeight] = compileTemplateStatements(\n\t\ttokens,\n\t\tcheckTemplateClose(tokens, position + 1, true),\n\t\tdepth + 1,\n\t\t['endmacro'],\n\t\tfalse,\n\t\tspans,\n\t)\n\tconst height =\n\t\t1 +\n\t\tMath.max(\n\t\t\tbodyHeight,\n\t\t\theights.reduce((top, value) => Math.max(top, value), 0),\n\t\t)\n\tcheckTemplateDepth(height, macroName)\n\treturn [\n\t\t{ syntax: 'macro', name: macroName.text, parameters, body },\n\t\tcheckTemplateClose(tokens, end + 2, false),\n\t\theight,\n\t]\n}\n\n/**\n * Compiles one Jinja expression (`or` / `and` / `not` / comparisons / tests /\n * arithmetic / postfix / filters), plus inline `if ... else ...` when admitted.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @param conditional - If `true`, admits inline `x if c else y`; if `false`, stops before `if`\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateExpression, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateExpression(scanTemplateTokens(\"{{ 'a' if x else 'b' }}\"), 1, 1, true)[0].term // 'conditional'\n * ```\n */\nexport function compileTemplateExpression(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tconditional: boolean,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [value, next, height] = compileTemplateChain(\n\t\ttokens,\n\t\tindex,\n\t\tdepth,\n\t\t['or'],\n\t\t(inner, at, level) => compileTemplateChain(inner, at, level, ['and'], compileTemplateNegation),\n\t)\n\tconst branch = readTemplateToken(tokens, next)\n\tif (!conditional || !matchesTemplateToken(branch, 'name', 'if')) return [value, next, height]\n\tconst [condition, after, conditionHeight] = compileTemplateChain(\n\t\ttokens,\n\t\tnext + 1,\n\t\tdepth + 1,\n\t\t['or'],\n\t\t(inner, at, level) => compileTemplateChain(inner, at, level, ['and'], compileTemplateNegation),\n\t)\n\tif (!matchesTemplateToken(readTemplateToken(tokens, after), 'name', 'else')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tbranch,\n\t\t\t'writes an inline if without else, which the subset does not admit',\n\t\t\t{ feature: 'conditional without else' },\n\t\t)\n\t}\n\tconst [alternate, end, alternateHeight] = compileTemplateExpression(\n\t\ttokens,\n\t\tafter + 1,\n\t\tdepth + 1,\n\t\ttrue,\n\t)\n\tconst total = 1 + Math.max(height, conditionHeight, alternateHeight)\n\tcheckTemplateDepth(total, start)\n\treturn [{ term: 'conditional', condition, consequent: value, alternate }, end, total]\n}\n\n/**\n * Compiles a left-associative binary operator chain at one precedence level.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @param operators - Operators admitted at this precedence level\n * @param operand - Compiler for the next tighter precedence level\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateChain, compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateChain(scanTemplateTokens(\"{{ 'a' ~ 'b' }}\"), 1, 1, ['~'], compileTemplateUnary)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateChain(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\toperators: readonly TemplateOperator[],\n\toperand: (\n\t\ttokens: readonly TemplateToken[],\n\t\tindex: number,\n\t\tdepth: number,\n\t) => readonly [expression: TemplateExpression, end: number, height: number],\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [first, after, firstHeight] = operand(tokens, index, depth)\n\tlet expression = first\n\tlet height = firstHeight\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tconst operator = operators.find(\n\t\t\t(candidate) =>\n\t\t\t\t(token.token === 'name' || token.token === 'operator') && token.text === candidate,\n\t\t)\n\t\tif (operator === undefined) break\n\t\tconst [right, next, rightHeight] = operand(tokens, position + 1, depth + 1)\n\t\texpression = { term: 'binary', operator, left: expression, right }\n\t\theight = 1 + Math.max(height, rightHeight)\n\t\tcheckTemplateDepth(height, start)\n\t\tposition = next\n\t}\n\treturn [expression, position, height]\n}\n\n/**\n * Compiles logical `not` negation over comparisons.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateNegation, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateNegation(scanTemplateTokens('{{ not x }}'), 1, 1)[0].term // 'unary'\n * ```\n */\nexport function compileTemplateNegation(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst token = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, token)\n\tif (!matchesTemplateToken(token, 'name', 'not')) {\n\t\treturn compileTemplateComparison(tokens, index, depth)\n\t}\n\tconst [value, next, height] = compileTemplateNegation(tokens, index + 1, depth + 1)\n\tcheckTemplateDepth(height + 1, token)\n\treturn [{ term: 'unary', operator: 'not', value }, next, height + 1]\n}\n\n/**\n * Compiles chained Python-style comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`,\n * `in`, `not in`) over test expressions.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateComparison, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateComparison(scanTemplateTokens(\"{{ role not in 'system' }}\"), 1, 1)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateComparison(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [first, after, firstHeight] = compileTemplateTest(tokens, index, depth)\n\tconst links: Array<\n\t\treadonly [operator: TemplateOperator, operand: TemplateExpression, height: number]\n\t> = []\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tconst negated =\n\t\t\tmatchesTemplateToken(token, 'name', 'not') &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, position + 1), 'name', 'in')\n\t\tconst operator: TemplateOperator | undefined =\n\t\t\ttoken.token === 'operator' && isTemplateComparison(token.text)\n\t\t\t\t? token.text\n\t\t\t\t: matchesTemplateToken(token, 'name', 'in')\n\t\t\t\t\t? 'in'\n\t\t\t\t\t: negated\n\t\t\t\t\t\t? 'not in'\n\t\t\t\t\t\t: undefined\n\t\tif (operator === undefined) break\n\t\tconst [operand, next, height] = compileTemplateTest(\n\t\t\ttokens,\n\t\t\tposition + (negated ? 2 : 1),\n\t\t\tdepth + 1,\n\t\t)\n\t\tlinks.push([operator, operand, height])\n\t\tposition = next\n\t}\n\tconst pairs = links.map(\n\t\t([operator, operand, height], link): readonly [TemplateExpression, number] => {\n\t\t\tconst left = links[link - 1]\n\t\t\treturn [\n\t\t\t\t{ term: 'binary', operator, left: left?.[1] ?? first, right: operand },\n\t\t\t\t1 + Math.max(left?.[2] ?? firstHeight, height),\n\t\t\t]\n\t\t},\n\t)\n\tconst [joined, joinedHeight] = pairs\n\t\t.slice(1)\n\t\t.reduce(\n\t\t\t(left, right): readonly [TemplateExpression, number] => [\n\t\t\t\t{ term: 'binary', operator: 'and', left: left[0], right: right[0] },\n\t\t\t\t1 + Math.max(left[1], right[1]),\n\t\t\t],\n\t\t\tpairs[0] ?? [first, firstHeight],\n\t\t)\n\tcheckTemplateDepth(joinedHeight, start)\n\treturn [joined, position, joinedHeight]\n}\n\n/**\n * Compiles an additive expression optionally followed by a Jinja `is` or\n * `is not` test (`defined`, `undefined`, `none`, `string`, `mapping`,\n * `iterable`, `sequence`, `true`, `false`).\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateTest, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateTest(scanTemplateTokens('{{ x is not mapping }}'), 1, 1)[0].term // 'test'\n * ```\n */\nexport function compileTemplateTest(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tconst [value, next, valueHeight] = compileTemplateSum(tokens, index, depth)\n\tconst marker = readTemplateToken(tokens, next)\n\tif (!matchesTemplateToken(marker, 'name', 'is')) return [value, next, valueHeight]\n\tconst negated = matchesTemplateToken(readTemplateToken(tokens, next + 1), 'name', 'not')\n\tconst at = next + (negated ? 2 : 1)\n\tconst name = readTemplateToken(tokens, at)\n\tif (name.token !== 'name') {\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`expects a test name and finds ${renderTemplateToken(name)}`,\n\t\t)\n\t}\n\tconst dotted = matchesTemplateToken(readTemplateToken(tokens, at + 1), 'operator', '.')\n\tif (dotted || !TEMPLATE_TESTS.some((admitted) => admitted === name.text)) {\n\t\tconst spelled = dotted ? `${name.text}.${readTemplateToken(tokens, at + 2).text}` : name.text\n\t\tthrow buildTemplateFormatError(\n\t\t\tname,\n\t\t\t`uses the test ${quoteTemplateText(spelled)}, which the subset does not admit`,\n\t\t\t{ feature: spelled },\n\t\t)\n\t}\n\tconst following = readTemplateToken(tokens, at + 1)\n\tconst empty =\n\t\tmatchesTemplateToken(following, 'operator', '(') &&\n\t\tmatchesTemplateToken(readTemplateToken(tokens, at + 2), 'operator', ')')\n\tconst argued =\n\t\t!empty &&\n\t\t(matchesTemplateToken(following, 'operator', '(') ||\n\t\t\tmatchesTemplateToken(following, 'operator', '[') ||\n\t\t\tmatchesTemplateToken(following, 'operator', '{') ||\n\t\t\t['string', 'integer', 'float'].includes(following.token) ||\n\t\t\t(following.token === 'name' && !['else', 'or', 'and', 'in', 'not'].includes(following.text)))\n\tif (matchesTemplateToken(following, 'name', 'is')) {\n\t\tthrow buildTemplateFormatError(following, 'chains two tests with \"is\", which Jinja refuses')\n\t}\n\tif (argued) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t'passes test arguments, which the subset does not admit',\n\t\t\t{ feature: 'test arguments' },\n\t\t)\n\t}\n\tconst cursor = at + (empty ? 3 : 1)\n\tif (matchesTemplateToken(readTemplateToken(tokens, cursor), 'name', 'is')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\treadTemplateToken(tokens, cursor),\n\t\t\t'chains two tests with \"is\", which Jinja refuses',\n\t\t)\n\t}\n\tconst height = valueHeight + 1\n\tcheckTemplateDepth(height, start)\n\treturn [{ term: 'test', name: name.text, value, negated }, cursor, height]\n}\n\n/**\n * Compiles a left-associative `+` / `-` chain over `~` concatenations.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateSum, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateSum(scanTemplateTokens('{{ n - 1 }}'), 1, 1)[0].term // 'binary'\n * ```\n */\nexport function compileTemplateSum(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\treturn compileTemplateChain(tokens, index, depth, ['+', '-'], (inner, at, level) =>\n\t\tcompileTemplateChain(inner, at, level, ['~'], compileTemplateUnary),\n\t)\n}\n\n/**\n * Compiles unary `-`/`+`, primaries, member reads, sequence slices, function\n * and string method calls, and `|` filter chains.\n *\n * @param tokens - The scanned token stream\n * @param index - Starting token index\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplateUnary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateUnary(scanTemplateTokens('{{ messages[::-1] }}'), 1, 1)[0].term // 'slice'\n * ```\n */\nexport function compileTemplateUnary(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst start = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, start)\n\tif (\n\t\tmatchesTemplateToken(start, 'operator', '-') ||\n\t\tmatchesTemplateToken(start, 'operator', '+')\n\t) {\n\t\tconst operator: '-' | '+' = start.text === '-' ? '-' : '+'\n\t\tconst [value, next, height] = compileTemplateUnary(tokens, index + 1, depth + 1)\n\t\tcheckTemplateDepth(height + 1, start)\n\t\treturn [{ term: 'unary', operator, value }, next, height + 1]\n\t}\n\tconst [primary, after, primaryHeight] = compileTemplatePrimary(tokens, index, depth)\n\tlet expression = primary\n\tlet height = primaryHeight\n\tlet position = after\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, position)\n\t\tif (matchesTemplateToken(token, 'operator', '.')) {\n\t\t\tconst name = readTemplateToken(tokens, position + 1)\n\t\t\tif (name.token !== 'name' && name.token !== 'integer') {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\tname,\n\t\t\t\t\t`expects a name or an integer after \".\" and finds ${renderTemplateToken(name)}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst key: TemplateExpression = {\n\t\t\t\tterm: 'literal',\n\t\t\t\tvalue: name.token === 'name' ? name.text : decodeTemplateNumber(name),\n\t\t\t}\n\t\t\tcheckTemplateLoopMember(expression, key, name)\n\t\t\texpression = { term: 'member', object: expression, key }\n\t\t\theight = 1 + Math.max(height, 0)\n\t\t\tposition += 2\n\t\t} else if (matchesTemplateToken(token, 'operator', '[')) {\n\t\t\tconst [subscripted, next, subscriptHeight] = compileTemplateSubscript(\n\t\t\t\ttokens,\n\t\t\t\tposition,\n\t\t\t\tdepth + 1,\n\t\t\t\texpression,\n\t\t\t)\n\t\t\texpression = subscripted\n\t\t\theight = 1 + Math.max(height, subscriptHeight)\n\t\t\tposition = next\n\t\t} else if (matchesTemplateToken(token, 'operator', '(')) {\n\t\t\tif (expression.term !== 'name' && expression.term !== 'member') {\n\t\t\t\tthrow buildTemplateFormatError(token, 'writes a call, which the subset does not admit', {\n\t\t\t\t\tfeature: 'call',\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst [values, keywords, next, valuesHeight] = compileTemplateArguments(\n\t\t\t\ttokens,\n\t\t\t\tposition,\n\t\t\t\tdepth + 1,\n\t\t\t)\n\t\t\texpression = { term: 'call', callee: expression, values, keywords }\n\t\t\theight = 1 + Math.max(height, valuesHeight)\n\t\t\tposition = next\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\tcheckTemplateDepth(height, start)\n\t}\n\tlet filtered = expression\n\tlet filteredHeight = height\n\tlet cursor = position\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tconst token = readTemplateToken(tokens, cursor)\n\t\tif (!matchesTemplateToken(token, 'operator', '|')) {\n\t\t\tif (matchesTemplateToken(token, 'operator', '(')) {\n\t\t\t\tthrow buildTemplateFormatError(token, 'calls a filter, which the subset does not admit', {\n\t\t\t\t\tfeature: 'call',\n\t\t\t\t})\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tconst name = readTemplateToken(tokens, cursor + 1)\n\t\tif (name.token !== 'name') {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`expects a filter name and finds ${renderTemplateToken(name)}`,\n\t\t\t)\n\t\t}\n\t\tconst dotted = matchesTemplateToken(readTemplateToken(tokens, cursor + 2), 'operator', '.')\n\t\tif (dotted || !TEMPLATE_FILTERS.some((admitted) => admitted === name.text)) {\n\t\t\tconst spelled = dotted\n\t\t\t\t? `${name.text}.${readTemplateToken(tokens, cursor + 3).text}`\n\t\t\t\t: name.text\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tname,\n\t\t\t\t`uses the filter ${quoteTemplateText(spelled)}, which the subset does not admit`,\n\t\t\t\t{ feature: spelled },\n\t\t\t)\n\t\t}\n\t\tconst following = readTemplateToken(tokens, cursor + 2)\n\t\tconst empty =\n\t\t\tmatchesTemplateToken(following, 'operator', '(') &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, cursor + 3), 'operator', ')')\n\t\tif (!empty && matchesTemplateToken(following, 'operator', '(')) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\tfollowing,\n\t\t\t\t'passes filter arguments, which the subset does not admit',\n\t\t\t\t{ feature: 'filter arguments' },\n\t\t\t)\n\t\t}\n\t\tfiltered = { term: 'filter', name: name.text, value: filtered }\n\t\tfilteredHeight += 1\n\t\tcursor = cursor + (empty ? 4 : 2)\n\t\tcheckTemplateDepth(filteredHeight, start)\n\t}\n\tconst following = readTemplateToken(tokens, cursor)\n\tconst arithmetic =\n\t\tfollowing.token === 'operator' && keyOf(TEMPLATE_OPERATOR_FEATURES)(following.text)\n\t\t\t? TEMPLATE_OPERATOR_FEATURES[following.text]\n\t\t\t: undefined\n\tif (arithmetic !== undefined) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tfollowing,\n\t\t\t`writes ${arithmetic}, which the subset does not admit`,\n\t\t\t{ feature: arithmetic },\n\t\t)\n\t}\n\treturn [filtered, cursor, filteredHeight]\n}\n\n/**\n * Compiles one primary template expression: a literal, name, adjacent string\n * concatenation, or parenthesized sub-expression.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the primary\n * @param depth - Current expression depth\n * @returns The compiled expression, next token index, and expression height\n *\n * @example\n * ```ts\n * import { compileTemplatePrimary, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplatePrimary(scanTemplateTokens(\"{{ 'a' 'b' }}\"), 1, 1)[0] // { term: 'literal', value: 'ab' }\n * ```\n */\nexport function compileTemplatePrimary(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tconst token = readTemplateToken(tokens, index)\n\tcheckTemplateDepth(depth, token)\n\tswitch (token.token) {\n\t\tcase 'name': {\n\t\t\tif (keyOf(TEMPLATE_LITERALS)(token.text)) {\n\t\t\t\treturn [{ term: 'literal', value: TEMPLATE_LITERALS[token.text] }, index + 1, 0]\n\t\t\t}\n\t\t\tconst called =\n\t\t\t\t(token.text === 'raise_exception' || token.text === 'namespace') &&\n\t\t\t\tmatchesTemplateToken(readTemplateToken(tokens, index + 1), 'operator', '(')\n\t\t\tif (!called && TEMPLATE_FUNCTIONS.some((name) => name === token.text)) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`uses the function ${quoteTemplateText(token.text)}, which the subset does not admit`,\n\t\t\t\t\t{ feature: token.text },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [{ term: 'name', name: token.text }, index + 1, 0]\n\t\t}\n\t\tcase 'string': {\n\t\t\tconst parts: string[] = []\n\t\t\tlet position = index\n\t\t\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\t\t\tconst part = readTemplateToken(tokens, position)\n\t\t\t\tif (part.token !== 'string') break\n\t\t\t\tparts.push(decodeTemplateString(part))\n\t\t\t\tposition += 1\n\t\t\t}\n\t\t\treturn [{ term: 'literal', value: parts.join('') }, position, 0]\n\t\t}\n\t\tcase 'integer':\n\t\tcase 'float':\n\t\t\treturn [{ term: 'literal', value: decodeTemplateNumber(token) }, index + 1, 0]\n\t\tcase 'operator': {\n\t\t\tif (token.text === '(') {\n\t\t\t\tif (matchesTemplateToken(readTemplateToken(tokens, index + 1), 'operator', ')')) {\n\t\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\t'writes an empty tuple, which the subset does not admit',\n\t\t\t\t\t\t{ feature: 'tuple' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst [inner, next, height] = compileTemplateExpression(tokens, index + 1, depth + 1, true)\n\t\t\t\tif (matchesTemplateToken(readTemplateToken(tokens, next), 'operator', ',')) {\n\t\t\t\t\tthrow buildTemplateFormatError(token, 'writes a tuple, which the subset does not admit', {\n\t\t\t\t\t\tfeature: 'tuple',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcheckTemplateToken(tokens, next, 'operator', ')')\n\t\t\t\treturn [inner, next + 1, height]\n\t\t\t}\n\t\t\tif (token.text === '[' || token.text === '{') {\n\t\t\t\tconst feature = token.text === '[' ? 'list literal' : 'dict literal'\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`writes a ${feature}, which the subset does not admit`,\n\t\t\t\t\t{\n\t\t\t\t\t\tfeature,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`expects a value and finds ${renderTemplateToken(token)}`,\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\ttoken,\n\t\t\t\t`expects a value and finds ${renderTemplateToken(token)}`,\n\t\t\t)\n\t}\n}\n\n/**\n * Compiles positional and named keyword arguments of a call from `(` through `)`.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the opening `(`\n * @param depth - Current expression depth\n * @returns Positional arguments, keyword arguments, next token index, and max height\n *\n * @example\n * ```ts\n * import { compileTemplateArguments, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateArguments(scanTemplateTokens('{{ namespace(value=0) }}'), 2, 1)[1][0]?.name // 'value'\n * ```\n */\nexport function compileTemplateArguments(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n): readonly [\n\tvalues: readonly TemplateExpression[],\n\tkeywords: readonly TemplateKeyword[],\n\tend: number,\n\theight: number,\n] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, index))\n\tcheckTemplateToken(tokens, index, 'operator', '(')\n\tconst values: TemplateExpression[] = []\n\tconst keywords: TemplateKeyword[] = []\n\tconst heights: number[] = []\n\tlet position = index + 1\n\tfor (let step = 0; step < tokens.length; step += 1) {\n\t\tif (matchesTemplateToken(readTemplateToken(tokens, position), 'operator', ')')) break\n\t\tconst later = position > index + 1\n\t\tif (later) checkTemplateToken(tokens, position, 'operator', ',')\n\t\tconst at = later ? position + 1 : position\n\t\tconst head = readTemplateToken(tokens, at)\n\t\tif (later && matchesTemplateToken(head, 'operator', ')')) {\n\t\t\tposition = at\n\t\t\tbreak\n\t\t}\n\t\tif (\n\t\t\tmatchesTemplateToken(head, 'operator', '*') ||\n\t\t\tmatchesTemplateToken(head, 'operator', '**')\n\t\t) {\n\t\t\tthrow buildTemplateFormatError(\n\t\t\t\thead,\n\t\t\t\t'passes argument unpacking, which the subset does not admit',\n\t\t\t\t{ feature: 'argument unpacking' },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\thead.token === 'name' &&\n\t\t\tmatchesTemplateToken(readTemplateToken(tokens, at + 1), 'operator', '=')\n\t\t) {\n\t\t\tif (keywords.some((keyword) => keyword.name === head.text)) {\n\t\t\t\tthrow buildTemplateFormatError(\n\t\t\t\t\thead,\n\t\t\t\t\t`duplicates the keyword argument ${quoteTemplateText(head.text)}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [value, next, height] = compileTemplateExpression(tokens, at + 2, depth + 1, true)\n\t\t\tkeywords.push({ name: head.text, value })\n\t\t\theights.push(height)\n\t\t\tposition = next\n\t\t\tcontinue\n\t\t}\n\t\tif (keywords.length > 0) {\n\t\t\tthrow buildTemplateFormatError(head, 'places a positional argument after a keyword argument')\n\t\t}\n\t\tconst [value, next, height] = compileTemplateExpression(tokens, at, depth + 1, true)\n\t\tvalues.push(value)\n\t\theights.push(height)\n\t\tposition = next\n\t}\n\tcheckTemplateToken(tokens, position, 'operator', ')')\n\treturn [values, keywords, position + 1, heights.reduce((top, height) => Math.max(top, height), 0)]\n}\n\n/**\n * Compiles one `[key]` member lookup or `[start:stop:step]` slice subscript\n * starting at `[` and ending after `]`.\n *\n * @param tokens - The scanned token stream\n * @param index - Token index of the opening `[`\n * @param depth - Current expression depth\n * @param object - The target expression being indexed or sliced\n * @returns The compiled member or slice expression, next token index, and argument height\n *\n * @example\n * ```ts\n * import { compileTemplateSubscript, scanTemplateTokens } from '@orkestrel/template'\n *\n * compileTemplateSubscript(scanTemplateTokens('{{ a[::-1] }}'), 2, 1, { term: 'name', name: 'a' })[0].term // 'slice'\n * ```\n */\nexport function compileTemplateSubscript(\n\ttokens: readonly TemplateToken[],\n\tindex: number,\n\tdepth: number,\n\tobject: TemplateExpression,\n): readonly [expression: TemplateExpression, end: number, height: number] {\n\tcheckTemplateDepth(depth, readTemplateToken(tokens, index))\n\tconst first = readTemplateToken(tokens, index + 1)\n\tif (matchesTemplateToken(first, 'operator', ']')) {\n\t\tthrow buildTemplateFormatError(first, 'writes an empty subscript')\n\t}\n\tconst [sliceStart, afterStart, startHeight] = matchesTemplateToken(first, 'operator', ':')\n\t\t? ([undefined, index + 1, 0] as const)\n\t\t: compileTemplateExpression(tokens, index + 1, depth, true)\n\tconst separator = readTemplateToken(tokens, afterStart)\n\tif (matchesTemplateToken(separator, 'operator', ',')) {\n\t\tthrow buildTemplateFormatError(\n\t\t\tseparator,\n\t\t\t'writes a tuple subscript, which the subset does not admit',\n\t\t\t{ feature: 'tuple' },\n\t\t)\n\t}\n\tif (!matchesTemplateToken(separator, 'operator', ':')) {\n\t\tcheckTemplateToken(tokens, afterStart, 'operator', ']')\n\t\tif (sliceStart === undefined) {\n\t\t\tthrow buildTemplateFormatError(first, 'writes an empty subscript')\n\t\t}\n\t\tcheckTemplateLoopMember(object, sliceStart, first)\n\t\treturn [{ term: 'member', object, key: sliceStart }, afterStart + 1, startHeight]\n\t}\n\tconst stopToken = readTemplateToken(tokens, afterStart + 1)\n\tconst [sliceStop, afterStop, stopHeight] =\n\t\tmatchesTemplateToken(stopToken, 'operator', ':') ||\n\t\tmatchesTemplateToken(stopToken, 'operator', ']')\n\t\t\t? ([undefined, afterStart + 1, 0] as const)\n\t\t\t: compileTemplateExpression(tokens, afterStart + 1, depth, true)\n\tconst hasStepColon = matchesTemplateToken(readTemplateToken(tokens, afterStop), 'operator', ':')\n\tconst stepToken = hasStepColon ? readTemplateToken(tokens, afterStop + 1) : undefined\n\tconst [sliceStep, afterStep, stepHeight] =\n\t\t!hasStepColon || (stepToken !== undefined && matchesTemplateToken(stepToken, 'operator', ']'))\n\t\t\t? ([undefined, hasStepColon ? afterStop + 1 : afterStop, 0] as const)\n\t\t\t: compileTemplateExpression(tokens, afterStop + 1, depth, true)\n\tcheckTemplateToken(tokens, afterStep, 'operator', ']')\n\treturn [\n\t\t{\n\t\t\tterm: 'slice',\n\t\t\tobject,\n\t\t\t...(sliceStart !== undefined ? { start: sliceStart } : {}),\n\t\t\t...(sliceStop !== undefined ? { stop: sliceStop } : {}),\n\t\t\t...(sliceStep !== undefined ? { step: sliceStep } : {}),\n\t\t},\n\t\tafterStep + 1,\n\t\tMath.max(startHeight, stopHeight, stepHeight),\n\t]\n}\n","import type { TemplateDocument } from './types.js'\nimport { attempt, isString } from '@orkestrel/contract'\nimport { compileTemplate } from './compilers.js'\nimport { isTemplateDocument } from './validators.js'\n\n// Total, non-throwing coercers for template sources and AST documents.\n\n/**\n * Parses an unknown input into a {@link TemplateDocument}, returning `undefined`\n * on malformed syntax, unadmitted constructs, exceeded depth, or off-shape input\n * without throwing.\n *\n * @param source - A Jinja template string or an already-built {@link TemplateDocument}\n * @returns A validated {@link TemplateDocument}, or `undefined` when invalid\n *\n * @example\n * ```ts\n * import { parseTemplate } from '@orkestrel/template'\n *\n * parseTemplate('Hi {{ name }}')?.syntax // 'document'\n * parseTemplate('{% if unclosed %}') // undefined\n * ```\n */\nexport function parseTemplate(source: unknown): TemplateDocument | undefined {\n\tif (isTemplateDocument(source)) return source\n\tif (!isString(source)) return undefined\n\tconst outcome = attempt(() => compileTemplate(source))\n\treturn outcome.success ? outcome.value : undefined\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport type { HTMLDocument, HTMLNode, HTMLSanitizeOptions } from '@orkestrel/html'\nimport type { BlockNode, MarkdownDocument, MarkdownNode } from '@orkestrel/markdown'\nimport type {\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateFillValues,\n\tTemplateHTMLOptions,\n\tTemplatePlaceholder,\n} from './types.js'\nimport { isArray, isString, objectShape, optionalShape, stringShape } from '@orkestrel/contract'\nimport { HTML, isHTMLDocument, isHTMLNode, mergeText } from '@orkestrel/html'\nimport { htmlToMarkdown, isBlockNode, isInlineNode, markdownToHTML } from '@orkestrel/markdown'\nimport { compileTemplate } from './compilers.js'\nimport { TemplateError } from './errors.js'\nimport {\n\tbuildTemplateMarkdownBlocks,\n\tevaluateTaggedTemplateParts,\n\tevaluateTemplateParts,\n\tsanitizeTemplateMarkdown,\n} from './helpers.js'\nimport { isTemplateDocument } from './validators.js'\n\n// The templates shape and projection inventory — layers over `helpers.ts` and\n// `validators.ts`, so constructing `@orkestrel/html`'s `HTML` sanitizer here\n// keeps the leaf pair strictly class-free.\n\n/**\n * Builds the `@orkestrel/contract` object shape describing a template's\n * declared placeholders.\n *\n * @remarks\n * Each placeholder becomes a `stringShape` carrying its `description`;\n * `required === false` wraps it in `optionalShape`. Used by `Template` to\n * compile its `parameters()` contract once per instance.\n *\n * @param placeholders - The declared placeholders to shape\n * @returns The contract shape for `createContract`\n *\n * @example\n * ```ts\n * import { placeholderShape } from '@orkestrel/template'\n * import { createContract } from '@orkestrel/contract'\n *\n * const contract = createContract(placeholderShape([{ name: 'city' }]))\n * ```\n */\nexport function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape {\n\tconst properties: Record<string, ContractShape> = {}\n\tfor (const placeholder of placeholders) {\n\t\tconst description = placeholder.description\n\t\tconst field = stringShape({\n\t\t\t...(description !== undefined ? { description } : {}),\n\t\t})\n\t\tproperties[placeholder.name] = placeholder.required === false ? optionalShape(field) : field\n\t}\n\treturn objectShape(properties)\n}\n\n/**\n * Normalizes an `@orkestrel/html` node into a document and enforces\n * `@orkestrel/html`'s unlowerable sanitize floor, failing closed to an empty\n * document on off-shape input.\n *\n * @param node - The HTML document or node to sanitize\n * @param options - Optional allowlist overrides (cannot lower `@orkestrel/html`'s security floor)\n * @returns The sanitized {@link HTMLDocument}\n *\n * @example\n * ```ts\n * import { sanitizeTemplateHTML } from '@orkestrel/template'\n *\n * sanitizeTemplateHTML({ category: 'element', name: 'script', attributes: [], children: [] }).children // []\n * ```\n */\nexport function sanitizeTemplateHTML(node: HTMLNode, options?: HTMLSanitizeOptions): HTMLDocument {\n\tconst document: HTMLDocument =\n\t\tnode.category === 'document' ? node : { category: 'document', children: [node] }\n\tif (!isHTMLDocument(document)) return { category: 'document', children: [] }\n\treturn new HTML(document).sanitize(options).document\n}\n\n/**\n * Projects a compiled template document or Jinja source into a sanitized\n * {@link HTMLDocument}.\n *\n * @remarks\n * Plain string template text and interpolated scalar values always become safe\n * `TextNode` leaves rather than raw HTML markup, eliminating XSS from fill\n * strings. Embedded `HTMLNode` leaves and fill values pass through\n * `sanitizeTemplateHTML`, and embedded `MarkdownNode` leaves and fill values\n * project through `markdownToHTML` then `sanitizeTemplateHTML`.\n *\n * @param source - A compiled {@link TemplateDocument} or Jinja source string\n * @param values - Optional runtime values record\n * @param options - Optional evaluation and HTML sanitization settings\n * @returns A sanitized {@link HTMLDocument}\n *\n * @example\n * ```ts\n * import { templateToHTML } from '@orkestrel/template'\n *\n * templateToHTML('Hi {{ name }}', { name: '<b>Ada</b>' }).children\n * // [{ category: 'text', value: 'Hi <b>Ada</b>' }]\n * ```\n */\nexport function templateToHTML(\n\tsource: TemplateDocument | string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateHTMLOptions,\n): HTMLDocument {\n\tconst document = isString(source) ? compileTemplate(source) : source\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError(\n\t\t\t'INVALID',\n\t\t\t'templateToHTML requires a valid TemplateDocument or source string.',\n\t\t)\n\t}\n\tconst parts = evaluateTemplateParts(document, values, options)\n\tconst children: HTMLNode[] = []\n\tfor (const part of parts) {\n\t\tif (typeof part === 'string') {\n\t\t\tif (part.length > 0) children.push({ category: 'text', value: part })\n\t\t\tcontinue\n\t\t}\n\t\tif (isHTMLNode(part)) {\n\t\t\tconst clean = sanitizeTemplateHTML(part, options?.sanitize)\n\t\t\tfor (const child of clean.children) children.push(child)\n\t\t\tcontinue\n\t\t}\n\t\tconst projected = markdownToHTML(part)\n\t\tconst clean = sanitizeTemplateHTML(projected, options?.sanitize)\n\t\tfor (const child of clean.children) children.push(child)\n\t}\n\treturn { category: 'document', children: mergeText(children) }\n}\n\n/**\n * Projects a compiled template document or Jinja source into a canonical\n * {@link MarkdownDocument}.\n *\n * @remarks\n * Template-authored literal text parses through `parseMarkdown`, while dynamic\n * scalar fill values stay literal leaves and are never parsed as Markdown\n * syntax. Inline dynamic fills and `CodeSpanNode` values collapse line breaks\n * (`\\r\\n`, `\\r`, `\\n`) to single spaces so round-tripping through\n * `renderMarkdown` and `parseMarkdown` never splits headings, table rows,\n * code spans, or paragraphs; `CodeBlockNode.lang` sanitizes to a single token\n * free of whitespace, backticks, and tildes; and `CodeBlockNode.code` preserves\n * line breaks verbatim inside dynamically sized fences. Embedded `HTMLNode`\n * values sanitize through `sanitizeTemplateHTML`, project through\n * `htmlToMarkdown`, and sanitize URL schemes; embedded `MarkdownNode` values\n * sanitize URL schemes by unwrapping unsafe `LinkNode` elements and dropping\n * unsafe `ImageNode` elements. `@orkestrel/markdown` has no raw-HTML AST node\n * and emits `TextRun` text verbatim in `renderMarkdown`, so callers targeting a\n * third-party raw-HTML Markdown renderer must use `templateToHTML` or sanitize\n * at that HTML boundary.\n *\n * @param source - A compiled {@link TemplateDocument} or Jinja source string\n * @param values - Optional runtime values record\n * @param options - Optional evaluation and HTML sanitization settings\n * @returns A {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * import { templateToMarkdown } from '@orkestrel/template'\n *\n * templateToMarkdown('# Hello {{ name }}', { name: 'Ada' }).children[0]?.element // 'heading'\n * ```\n */\nexport function templateToMarkdown(\n\tsource: TemplateDocument | string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateEvaluateOptions,\n): MarkdownDocument {\n\tconst document = isString(source) ? compileTemplate(source) : source\n\tif (!isTemplateDocument(document)) {\n\t\tthrow new TemplateError(\n\t\t\t'INVALID',\n\t\t\t'templateToMarkdown requires a valid TemplateDocument or source string.',\n\t\t)\n\t}\n\tconst parts = evaluateTaggedTemplateParts(document, values, options)\n\tconst grouped = parts.reduce<\n\t\tArray<ReadonlyArray<readonly [literal: boolean, text: string]> | HTMLNode | MarkdownNode>\n\t>((runs, [literal, part]) => {\n\t\tif (typeof part !== 'string') return [...runs, part]\n\t\tconst previous = runs.at(-1)\n\t\tif (isArray(previous)) {\n\t\t\tconst entry: readonly [boolean, string] = [literal, part]\n\t\t\treturn [...runs.slice(0, -1), [...previous, entry]]\n\t\t}\n\t\treturn [...runs, [[literal, part]]]\n\t}, [])\n\tconst blocks: BlockNode[] = []\n\tfor (const part of grouped) {\n\t\tif (isArray(part)) {\n\t\t\tfor (const block of buildTemplateMarkdownBlocks(part, options?.sanitize)) blocks.push(block)\n\t\t\tcontinue\n\t\t}\n\t\tif (isHTMLNode(part)) {\n\t\t\tconst clean = sanitizeTemplateHTML(part, options?.sanitize)\n\t\t\tconst projected = htmlToMarkdown(clean)\n\t\t\tconst sanitized = sanitizeTemplateMarkdown(projected, options?.sanitize)\n\t\t\tif (sanitized !== undefined && sanitized.element === 'document') {\n\t\t\t\tfor (const block of sanitized.children) blocks.push(block)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst sanitized = sanitizeTemplateMarkdown(part, options?.sanitize)\n\t\tif (sanitized === undefined) continue\n\t\tif (sanitized.element === 'document' || sanitized.element === 'listItem') {\n\t\t\tfor (const block of sanitized.children) blocks.push(block)\n\t\t} else if (isBlockNode(sanitized)) {\n\t\t\tblocks.push(sanitized)\n\t\t} else if (isInlineNode(sanitized)) {\n\t\t\tblocks.push({ element: 'paragraph', children: [sanitized] })\n\t\t}\n\t}\n\treturn { element: 'document', children: blocks }\n}\n","import type {\n\tTemplateDocument,\n\tTemplateEvaluateOptions,\n\tTemplateFillValues,\n\tTemplateHandlerMap,\n\tTemplateNode,\n\tTemplateRewriteHandler,\n\tTemplateSpan,\n\tTemplateTreeInterface,\n\tTemplateTreeOptions,\n} from '../types.js'\nimport { isMap, isObject, isString } from '@orkestrel/contract'\nimport { compileTemplateProvenance } from '../compilers.js'\nimport { TemplateError } from '../errors.js'\nimport {\n\tevaluateTemplate,\n\tfoldTemplateDocument,\n\tmapTemplateDocument,\n\trenderTemplate,\n\tstreamTemplateNodes,\n\twalkTemplateNodes,\n} from '../helpers.js'\nimport { isTemplateDocument, isTemplateNode, isTemplateSpan } from '../validators.js'\n\n/**\n * Wraps a compiled {@link TemplateDocument} AST as an immutable handle\n * exposing provenance lookup, depth-first traversal, queries, copy-on-write\n * rewrites, total folds, shallow streaming, evaluation, and canonical source\n * rendering.\n *\n * @remarks\n * Construct with `{ source }` to compile Jinja source with original UTF-16\n * provenance spans, or `{ document, spans? }` to adopt an existing validated\n * {@link TemplateDocument}. Every query and rewrite preserves immutability.\n *\n * @example\n * ```ts\n * import { TemplateTree } from '@orkestrel/template'\n *\n * const tree = new TemplateTree({ source: 'Hi {{ name }}' })\n * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateTree implements TemplateTreeInterface {\n\treadonly #document: TemplateDocument\n\treadonly #spans: Map<TemplateNode, TemplateSpan>\n\n\tconstructor(options: TemplateTreeOptions) {\n\t\tconst given: unknown = options\n\t\tif (!isObject(given)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree requires an options object.')\n\t\t}\n\t\tif ('source' in given) {\n\t\t\tconst source: unknown = Reflect.get(given, 'source')\n\t\t\tif (!isString(source)) {\n\t\t\t\tthrow new TemplateError('INVALID', 'TemplateTree source must be a string.')\n\t\t\t}\n\t\t\tconst [document, spans] = compileTemplateProvenance(source)\n\t\t\tthis.#document = document\n\t\t\tthis.#spans = new Map(spans)\n\t\t\treturn\n\t\t}\n\t\tconst document: unknown = Reflect.get(given, 'document')\n\t\tif (!isTemplateDocument(document)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree document must be a valid TemplateDocument.')\n\t\t}\n\t\tconst spans: unknown = Reflect.get(given, 'spans')\n\t\tif (spans !== undefined && !isMap(spans)) {\n\t\t\tthrow new TemplateError('INVALID', 'TemplateTree spans must be a Map when provided.')\n\t\t}\n\t\tthis.#document = document\n\t\tconst copied = new Map<TemplateNode, TemplateSpan>()\n\t\tif (spans !== undefined) {\n\t\t\tfor (const [node, span] of spans.entries()) {\n\t\t\t\tif (isTemplateNode(node) && isTemplateSpan(span)) {\n\t\t\t\t\tcopied.set(node, { start: span.start, end: span.end })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.#spans = copied\n\t}\n\n\t/** Exposes the stored {@link TemplateDocument} AST root. */\n\tget document(): TemplateDocument {\n\t\treturn this.#document\n\t}\n\n\t/**\n\t * Returns the half-open original-source region for a node, or `undefined`\n\t * when this handle holds no provenance for that node.\n\t *\n\t * @param node - The node whose provenance to read\n\t * @returns A fresh {@link TemplateSpan}, or `undefined`\n\t */\n\tspan(node: TemplateNode): TemplateSpan | undefined {\n\t\tconst span = this.#spans.get(node)\n\t\treturn span === undefined ? undefined : { start: span.start, end: span.end }\n\t}\n\n\t/**\n\t * Walks every node in the document depth-first in pre-order, root first.\n\t *\n\t * @returns A lazy generator over every node in the document\n\t */\n\t*walk(): Generator<TemplateNode> {\n\t\tyield* walkTemplateNodes(this.#document)\n\t}\n\n\tfind<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): T | undefined\n\tfind(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined\n\tfind(predicate: (node: TemplateNode) => boolean): TemplateNode | undefined {\n\t\tfor (const node of this.walk()) {\n\t\t\tif (predicate(node)) return node\n\t\t}\n\t\treturn undefined\n\t}\n\n\tfilter<T extends TemplateNode>(guard: (node: TemplateNode) => node is T): readonly T[]\n\tfilter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[]\n\tfilter(predicate: (node: TemplateNode) => boolean): readonly TemplateNode[] {\n\t\treturn this.walk()\n\t\t\t.filter((node) => predicate(node))\n\t\t\t.toArray()\n\t}\n\n\t/**\n\t * Rewrites the document bottom-up with copy-on-write provenance preservation\n\t * and returns a derived {@link TemplateTreeInterface}.\n\t *\n\t * @param rewrite - The bottom-up node rewrite callback\n\t * @returns A derived handle over the rewritten document\n\t */\n\tmap(rewrite: TemplateRewriteHandler): TemplateTreeInterface {\n\t\tconst [document, derivations] = mapTemplateDocument(this.#document, rewrite)\n\t\treturn this.#derive(document, derivations)\n\t}\n\n\t/**\n\t * Reduces the document depth-first in pre-order into one accumulated value.\n\t *\n\t * @param callback - The reducer step combining value and node\n\t * @param initial - The initial accumulated value\n\t * @returns The final accumulated value\n\t */\n\treduce<T>(callback: (value: T, node: TemplateNode) => T, initial: T): T {\n\t\treturn this.walk().reduce((value, node) => callback(value, node), initial)\n\t}\n\n\t/**\n\t * Folds the document bottom-up through a total handler table covering every\n\t * syntax variant.\n\t *\n\t * @param handlers - Total handler map keyed by `syntax`\n\t * @returns The folded value of the document root\n\t */\n\tfold<T>(handlers: TemplateHandlerMap<T>): T {\n\t\treturn foldTemplateDocument(this.#document, handlers)\n\t}\n\n\t/**\n\t * Returns a fresh, pull-based stream over the document's top-level children\n\t * in source order.\n\t *\n\t * @returns A pull-based {@link ReadableStream} over top-level nodes\n\t */\n\tstream(): ReadableStream<TemplateNode> {\n\t\treturn streamTemplateNodes(this.#document)\n\t}\n\n\t/**\n\t * Evaluates the template document against runtime values and returns rendered\n\t * text.\n\t *\n\t * @param values - Optional runtime values record\n\t * @param options - Optional evaluation, placeholder, and sanitize settings\n\t * @returns The rendered text\n\t */\n\tevaluate(values?: TemplateFillValues, options?: TemplateEvaluateOptions): string {\n\t\treturn evaluateTemplate(this.#document, values, options)\n\t}\n\n\t/**\n\t * Renders the template document back to canonical template source text.\n\t *\n\t * @returns The canonical template source string\n\t */\n\trender(): string {\n\t\treturn renderTemplate(this.#document)\n\t}\n\n\t// Builds a derived handle carrying each output node's original-source span.\n\t#derive(\n\t\tdocument: TemplateDocument,\n\t\tderivations: ReadonlyMap<TemplateNode, TemplateNode | undefined>,\n\t): TemplateTree {\n\t\tconst spans = new Map<TemplateNode, TemplateSpan>()\n\t\tfor (const node of walkTemplateNodes(document)) {\n\t\t\tconst own = this.#spans.get(node)\n\t\t\tif (own !== undefined) {\n\t\t\t\tspans.set(node, own)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst source = derivations.get(node)\n\t\t\tif (source === undefined) continue\n\t\t\tconst span = this.#spans.get(source)\n\t\t\tif (span !== undefined) spans.set(node, span)\n\t\t}\n\t\treturn new TemplateTree({ document, spans })\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tMissingPolicy,\n\tTemplateDefinition,\n\tTemplateFillOptions,\n\tTemplateFillValues,\n\tTemplateInterface,\n\tTemplateOptions,\n\tTemplatePlaceholder,\n\tTemplateTreeInterface,\n\tTemplateValidationResult,\n} from '../types.js'\nimport { createContract, isArray, isString, schemaToParameters } from '@orkestrel/contract'\nimport { compilePlainTemplate } from '../compilers.js'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN } from '../constants.js'\nimport { fillTemplate, resolveToken } from '../helpers.js'\nimport { placeholderShape } from '../shapers.js'\nimport { TemplateError } from '../errors.js'\nimport { TemplateTree } from './TemplateTree.js'\n\n/**\n * Represents a named, versionable template — `{{name}}` tokens in `content`,\n * filled against a values record — implementing `TemplateInterface` exactly.\n *\n * @remarks\n * `missing` / `locale` seed this instance's default {@link TemplateFillOptions},\n * overridable per `fill` call. Its `parameters()` contract (built from\n * `placeholders` through `placeholderShape`) compiles once, in the constructor.\n *\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * const greeting = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class Template implements TemplateInterface {\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\treadonly #contract: ContractInterface<unknown>\n\treadonly id: string\n\treadonly name: string\n\treadonly content: string\n\treadonly placeholders: readonly TemplatePlaceholder[]\n\treadonly summary?: string\n\treadonly description?: string\n\treadonly category?: string\n\treadonly tags?: readonly string[]\n\n\tconstructor(options: TemplateOptions) {\n\t\tconst placeholders = options.placeholders ?? []\n\t\tIterator.from(placeholders).reduce<readonly string[]>((names, placeholder) => {\n\t\t\tif (names.includes(placeholder.name)) {\n\t\t\t\tthrow new TemplateError('INVALID', `Duplicate placeholder name: ${placeholder.name}`, {\n\t\t\t\t\tname: placeholder.name,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst name = placeholder.name\n\t\t\tif (isArray(placeholder.path) && placeholder.path.length === 0) {\n\t\t\t\tthrow new TemplateError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Placeholder path must not be empty: ${placeholder.name}`,\n\t\t\t\t\t{ name: placeholder.name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [...names, name]\n\t\t}, [])\n\n\t\tthis.id = isString(options.id) ? options.id : crypto.randomUUID()\n\t\tthis.name = options.name\n\t\tthis.content = options.content\n\t\tthis.placeholders = placeholders\n\t\tif (options.summary !== undefined) this.summary = options.summary\n\t\tif (options.description !== undefined) this.description = options.description\n\t\tif (options.category !== undefined) this.category = options.category\n\t\tif (options.tags !== undefined) this.tags = options.tags\n\t\tthis.#missing = options.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options.locale ?? DEFAULT_LOCALE\n\t\tthis.#contract = createContract(placeholderShape(this.placeholders))\n\t}\n\n\t/**\n\t * Returns the plain, JSON-serializable data this template carries.\n\t *\n\t * @returns The {@link TemplateDefinition} record\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.definition().name // 'greeting'\n\t * ```\n\t */\n\tdefinition(): TemplateDefinition {\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\tcontent: this.content,\n\t\t\tplaceholders: this.placeholders,\n\t\t\t...(this.summary !== undefined ? { summary: this.summary } : {}),\n\t\t\t...(this.description !== undefined ? { description: this.description } : {}),\n\t\t\t...(this.category !== undefined ? { category: this.category } : {}),\n\t\t\t...(this.tags !== undefined ? { tags: this.tags } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * Substitutes every `{{name}}` token in `content` against `values`.\n\t *\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for this instance's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.fill({ name: 'Ada' }) // 'Hi Ada'\n\t * ```\n\t */\n\tfill(values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn fillTemplate(this.content, values, {\n\t\t\tmissing: options?.missing ?? this.#missing,\n\t\t\tlocale: options?.locale ?? this.#locale,\n\t\t\tplaceholders: this.placeholders,\n\t\t})\n\t}\n\n\t/**\n\t * Reports which required placeholders would stay unresolved, and which\n\t * `values` keys go unused, without producing output.\n\t *\n\t * @remarks\n\t * Content-token driven: scans `this.content` for every `{{name}}` token\n\t * (skipping escaped `\\{{` matches) the same way `fill` does, so `validate`\n\t * predicts `fill`'s `'error'`-{@link MissingPolicy} outcome exactly — a\n\t * token reported here as missing is precisely a token that would throw\n\t * under `fill(values, { missing: 'error' })`. For each distinct token\n\t * (first-appearance order, trimmed): `resolveToken` applies the one shared\n\t * token rule `fill` also applies — a declared {@link TemplatePlaceholder}\n\t * sharing its `name` supplies `path` (falling back to the token split on\n\t * `.`), and the value resolves through `resolveSafeField`. The token is `missing`\n\t * only when the value is unresolved, no `fallback` is declared, and the\n\t * placeholder is required (`required !== false`, including undeclared\n\t * tokens). `extra` lists every `values` key with no declared placeholder.\n\t *\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.validate({}).missing // ['name']\n\t * ```\n\t */\n\tvalidate(values?: TemplateFillValues): TemplateValidationResult {\n\t\tconst record = values ?? {}\n\t\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\t\tconst tokens = new Set(\n\t\t\tArray.from(this.content.matchAll(pattern)).flatMap((match) =>\n\t\t\t\tmatch[1] === undefined ? [] : [match[1].trim()],\n\t\t\t),\n\t\t)\n\t\tconst missing = [...tokens].filter((token) => {\n\t\t\tconst { value, declared, required } = resolveToken(record, this.placeholders, token)\n\t\t\treturn value === undefined && declared?.fallback === undefined && required\n\t\t})\n\n\t\tconst declaredNames = new Set(this.placeholders.map((placeholder) => placeholder.name))\n\t\tconst extra = Object.keys(record).filter((key) => !declaredNames.has(key))\n\n\t\treturn { valid: missing.length === 0, missing, extra }\n\t}\n\n\t/**\n\t * Projects this template's placeholders to the open tool-parameters record\n\t * shape.\n\t *\n\t * @returns The compiled parameters record, or `undefined` when `schemaToParameters` yields none\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.parameters()\n\t * ```\n\t */\n\tparameters(): Readonly<Record<string, unknown>> | undefined {\n\t\treturn schemaToParameters(this.#contract.schema)\n\t}\n\n\t/**\n\t * Returns an immutable compiled tree handle over this template's plain\n\t * placeholder content.\n\t *\n\t * @returns A {@link TemplateTreeInterface} parsed by `compilePlainTemplate`\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.tree().document.children.length // 2\n\t * ```\n\t */\n\ttree(): TemplateTreeInterface {\n\t\tconst [document, spans] = compilePlainTemplate(this.content)\n\t\treturn new TemplateTree({ document, spans })\n\t}\n}\n","import type {\n\tMissingPolicy,\n\tTemplateFillValues,\n\tTemplateFillOptions,\n\tTemplateInterface,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateQuery,\n\tTemplateRegisterOptions,\n\tTemplateValidationResult,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { isFunction, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY } from '../constants.js'\nimport { TemplateError } from '../errors.js'\nimport { Template } from './Template.js'\n\n/**\n * Represents the template registry — a self-owning, id-keyed record-holder for\n * the {@link TemplateInterface} instances a consumer registers, looks up,\n * fills, and validates by id — implementing `TemplateManagerInterface`\n * exactly.\n *\n * @remarks\n * Singular and plural accessors, the batch `remove` overloads, and ownership\n * of the emitter all sit here. `register` accepts either a constructed {@link TemplateInterface} (kept\n * as-is, including its own `missing` / `locale` defaults) or a plain\n * {@link TemplateOptions} bag — constructed into a `Template` with this\n * manager's `missing` / `locale` defaults applied wherever the bag omits\n * them. A duplicate `id` throws a {@link TemplateError} coded `CONFLICT`\n * unless `options.replace` is `true`, in which case the existing entry is\n * overwritten. `options.templates` seeds the registry at construction without\n * emitting `register` — only calls to `register` after construction emit.\n * The batch `remove(ids)` form removes every present id and returns\n * `true` only when every listed id was present.\n *\n * @example\n * ```ts\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const instance = manager.register({ name: 'greeting', content: 'Hi {{name}}' })\n * manager.fill(instance.id, { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #templates = new Map<string, TemplateInterface>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tconst on = options?.on\n\t\tconst error = options?.error\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t\tthis.#missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options?.locale ?? DEFAULT_LOCALE\n\t\tfor (const template of options?.templates ?? []) {\n\t\t\tconst instance = this.#instantiate(template)\n\t\t\tthis.#templates.set(instance.id, instance)\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#templates.size\n\t}\n\n\t/**\n\t * Registers a template — a constructed {@link TemplateInterface} (kept\n\t * as-is) or a plain {@link TemplateOptions} bag (constructed into a\n\t * `Template` with this manager's `missing` / `locale` defaults applied\n\t * wherever the bag omits them).\n\t *\n\t * @param template - The template instance or options to register\n\t * @param options - `replace` — overwrite an existing entry sharing the same id instead of throwing\n\t * @returns The registered {@link TemplateInterface}\n\t * @throws {@link TemplateError} Thrown when the id is already registered and `options.replace` is not `true` (coded `CONFLICT`), or when an options bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = manager.register({ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' })\n\t * ```\n\t */\n\tregister(\n\t\ttemplate: TemplateInterface | TemplateOptions,\n\t\toptions?: TemplateRegisterOptions,\n\t): TemplateInterface {\n\t\tconst instance = this.#instantiate(template)\n\t\tconst existing = this.#templates.get(instance.id)\n\t\tif (existing !== undefined && options?.replace !== true) {\n\t\t\tthrow new TemplateError('CONFLICT', `Template already registered: ${instance.id}`, {\n\t\t\t\tid: instance.id,\n\t\t\t})\n\t\t}\n\t\tthis.#templates.set(instance.id, instance)\n\t\tthis.#emitter.emit('register', instance)\n\t\treturn instance\n\t}\n\n\t/**\n\t * Returns one registered {@link TemplateInterface} by id.\n\t *\n\t * @param id - The template id\n\t * @returns The registered {@link TemplateInterface}, or `undefined` when `id` is unregistered\n\t */\n\ttemplate(id: string): TemplateInterface | undefined {\n\t\treturn this.#templates.get(id)\n\t}\n\n\t/**\n\t * Lists every registered template.\n\t *\n\t * @returns A snapshot array of every registered {@link TemplateInterface}\n\t */\n\ttemplates(): readonly TemplateInterface[] {\n\t\treturn [...this.#templates.values()]\n\t}\n\n\t/**\n\t * Filters registered templates by `name`, `category`, and `tag` — every\n\t * supplied field must match.\n\t *\n\t * @param query - The {@link TemplateQuery} to filter by; omit for every registered template\n\t * @returns The matching templates\n\t */\n\tfind(query?: TemplateQuery): readonly TemplateInterface[] {\n\t\tif (query === undefined) return this.templates()\n\t\treturn this.templates().filter((instance) => {\n\t\t\tif (query.name !== undefined && instance.name !== query.name) return false\n\t\t\tif (query.category !== undefined && instance.category !== query.category) return false\n\t\t\tif (query.tag !== undefined && !(instance.tags ?? []).includes(query.tag)) return false\n\t\t\treturn true\n\t\t})\n\t}\n\n\t/**\n\t * Tests whether a template id is registered.\n\t *\n\t * @param id - The template id\n\t * @returns True if `id` is registered; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#templates.has(id)\n\t}\n\n\t/**\n\t * Removes one, several, or every registered template.\n\t *\n\t * @remarks\n\t * `remove()` removes every registered template, emitting `remove` once per\n\t * instance. `remove(id)` removes one template by id, emitting `remove` and\n\t * returning `true` when it existed, `false` otherwise. `remove(ids)`\n\t * removes every listed id that is present, emitting `remove` once per\n\t * removed instance, and returns `true` only when every listed id was\n\t * present.\n\t *\n\t * @param target - Omit to remove all, a single id, or a list of ids\n\t * @returns `boolean` for the single-id / list-of-ids forms; `void` for the remove-all form\n\t */\n\t// `readonly string[]` is not assignable to `id: string`, so a list resolves to the\n\t// batch signature whatever order the signatures are declared in.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tif (target === undefined) {\n\t\t\tfor (const instance of this.#templates.values()) this.#emitter.emit('remove', instance)\n\t\t\tthis.#templates.clear()\n\t\t\treturn\n\t\t}\n\t\tif (isString(target)) {\n\t\t\tconst instance = this.#templates.get(target)\n\t\t\tif (instance === undefined) return false\n\t\t\tthis.#templates.delete(target)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\treturn true\n\t\t}\n\t\treturn this.#remove(target).reduce((all, removed) => removed && all, true)\n\t}\n\n\t/** Removes every registered template, emitting `clear`. */\n\tclear(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\t/**\n\t * Tears down the registry: drops every registered template and destroys the\n\t * owned emitter. Idempotent.\n\t *\n\t * @remarks\n\t * Teardown is not an observable registry operation and the emitter is being\n\t * released, so this emits neither `clear` nor `remove`. The emitter is torn\n\t * down last, after the registry is dropped.\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new TemplateManager()\n\t * manager.destroy()\n\t * manager.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t/**\n\t * Fills a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for the template's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t */\n\tfill(id: string, values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn this.#require(id).fill(values, options)\n\t}\n\n\t/**\n\t * Validates values against a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tvalidate(id: string, values?: TemplateFillValues): TemplateValidationResult {\n\t\treturn this.#require(id).validate(values)\n\t}\n\n\t/**\n\t * Projects a registered template's parameters by id.\n\t *\n\t * @param id - The template id\n\t * @returns The compiled parameters record, or `undefined` when the template has none\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tparameters(id: string): Readonly<Record<string, unknown>> | undefined {\n\t\treturn this.#require(id).parameters()\n\t}\n\n\t#instantiate(template: TemplateInterface | TemplateOptions): TemplateInterface {\n\t\tif (this.#isInstance(template)) return template\n\t\treturn new Template({\n\t\t\t...template,\n\t\t\tmissing: template.missing ?? this.#missing,\n\t\t\tlocale: template.locale ?? this.#locale,\n\t\t})\n\t}\n\n\t*#remove(target: readonly string[]): Generator<boolean> {\n\t\tfor (const id of target) {\n\t\t\tconst instance = this.#templates.get(id)\n\t\t\tif (instance === undefined) {\n\t\t\t\tyield false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.#templates.delete(id)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\tyield true\n\t\t}\n\t}\n\n\t// A TemplateOptions bag is plain data with no `fill` / `validate` /\n\t// `parameters` methods; a TemplateInterface instance always exposes all three.\n\t#isInstance(template: TemplateInterface | TemplateOptions): template is TemplateInterface {\n\t\treturn (\n\t\t\t'fill' in template &&\n\t\t\tisFunction(template.fill) &&\n\t\t\t'validate' in template &&\n\t\t\tisFunction(template.validate) &&\n\t\t\t'parameters' in template &&\n\t\t\tisFunction(template.parameters)\n\t\t)\n\t}\n\n\t// Every by-id operation that needs a template to proceed shares this lookup.\n\t// The `template` accessor deliberately does not, and returns `undefined`.\n\t#require(id: string): TemplateInterface {\n\t\tconst instance = this.#templates.get(id)\n\t\tif (instance === undefined) {\n\t\t\tthrow new TemplateError('NOTFOUND', `Unknown template id: ${id}`, { id })\n\t\t}\n\t\treturn instance\n\t}\n}\n","import type {\n\tTemplateInterface,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateTreeInterface,\n\tTemplateTreeOptions,\n} from './types.js'\nimport { Template } from './templates/Template.js'\nimport { TemplateManager } from './templates/TemplateManager.js'\nimport { TemplateTree } from './templates/TemplateTree.js'\n\n/**\n * Creates a working {@link TemplateInterface} from a {@link TemplateOptions}\n * bag, backed by the `Template` class.\n *\n * @param options - The template's `name` / `content`, an optional `id`\n * (defaults to a generated UUID), `placeholders`, catalog metadata, and\n * `missing` / `locale` fill defaults\n * @returns A working {@link TemplateInterface}\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example Create a template and a registry\n * ```ts\n * import { createTemplate, createTemplateManager } from '@orkestrel/template'\n *\n * const greeting = createTemplate({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [\n * \t\t{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}', category: 'mail' },\n * \t\t{ id: 'farewell', name: 'farewell', content: 'Bye {{name}}', category: 'mail' },\n * \t\t{ id: 'alert', name: 'alert', content: 'Alert: {{reason}}', category: 'ops' },\n * \t],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * templates.find({ category: 'mail' }).map((one) => one.id) // ['greeting', 'farewell']\n * templates.has('alert') // true\n * templates.has('missing') // false\n * ```\n */\nexport function createTemplate(options: TemplateOptions): TemplateInterface {\n\treturn new Template(options)\n}\n\n/**\n * Creates a working {@link TemplateManagerInterface}, optionally seeded with\n * the templates the options carry, backed by the `TemplateManager` class.\n *\n * @param options - Optional initial `templates` seed collection and\n * manager-wide `missing` / `locale` fill defaults, emitter `on` hooks, and\n * an `error` handler\n * @returns A working {@link TemplateManagerInterface}\n * @throws {@link TemplateError} Thrown when a seeded `options.templates` bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * import { createTemplateManager } from '@src/core'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' }],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n\n/**\n * Creates a working {@link TemplateTreeInterface} from Jinja `source` text or\n * an existing {@link TemplateDocument}, backed by the `TemplateTree` class.\n *\n * @param options - Either `{ source }` to compile or `{ document, spans? }` to adopt\n * @returns A working {@link TemplateTreeInterface}\n *\n * @example\n * ```ts\n * import { createTemplateTree } from '@orkestrel/template'\n *\n * const tree = createTemplateTree({ source: 'Hi {{ name }}' })\n * tree.evaluate({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateTree(options: TemplateTreeOptions): TemplateTreeInterface {\n\treturn new TemplateTree(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,eAAe;;;;;AAM5B,IAAa,yBAAwC;;;;;AAMrD,IAAa,iBAAiB;;;;;;AAO9B,IAAa,wBAA2C,OAAO,OAAO;CACrE;CACA;CACA;AACD,CAAC;;;;AAKD,IAAa,uBAAqD,OAAO,OAAO;CAC/E;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;AAOD,IAAa,iBACZ;;;;;AAMD,IAAa,2BACZ;;;;;AAMD,IAAa,yBAAyB,IAAI,OACzC,IAAI,eAAe,2UACnB,KACD;;;;AAKA,IAAa,oBAAoB,OAAO,OAAO;CAC9C,MAAM;CACN,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,MAAM;AACP,CAAU;;;;AAKV,IAAa,uBAAuB,OAAO,OAAO;CAAC;CAAM;CAAM;CAAK;CAAK;CAAM;AAAI,CAAU;;;;;AAM7F,IAAa,mBAAmB,OAAO,OAAO;CAC7C,MAAM;CACN,KAAK;CACL,MAAK;CACL,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACJ,CAAU;;;;;;AAOV,IAAa,qBAAqB,OAAO,OAAO;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;AAKV,IAAa,mBAAmB,OAAO,OAAO;CAC7C;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,iBAAiB,OAAO,OAAO;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,0BAA0B,OAAO,OAAO;CACpD;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,mBAAmB,OAAO,OAAO;CAC7C,QAAQ,OAAO,OAAO;EACrB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,MAAM,OAAO,OAAO;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,SAAS,OAAO,OAAO;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;AACF,CAAC;;;;;AAMD,IAAa,yBAAyB,OAAO,OAAO;CACnD;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AAMV,IAAa,6BAA6B,OAAO,OAAO;CACvD,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;AACP,CAAU;;;;;;;;;;;;;;;AC/PV,IAAa,gBAAb,cAAmC,MAAM;CAC/B;CACA;CAET,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,WAAW,OAAO,MAAM,OAAO,IAAI,mCAAmC,GAAG,EAAE,OAAO,KAAK,CAAC;EACxF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,YAAY;EAClB,IAAI,EAAE,iBAAiB,UAAU,WAAW,UAAU,KAAK,MAAM,MAAM,WAAW,OAAO;EACzF,IACC,WAAW,SAAS,OAAO,OAAO,IAAI,mCAAmC,CAAC,CAAC,EAAE,UAAU,OAEvF,OAAO;EACR,MAAM,OAAgB,WAAW,QAAQ,KAAK,OA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