src/template.js
// Mustache-like templates. Supported: {{name}} (escaped), {{{name}}} and {{& name}} (not escaped),
// dotted names ({{vars.week}}), {{.}} (current item), sections {{#rows}}...{{/rows}} (repeat for each
// item of a list, or once for a non-empty value), inverted sections {{^rows}}...{{/rows}} and
// comments {{! ... }}. Section tags alone on a line do not leave blank lines (as in Mustache).
// Extensions: filters after "|" ({{title | slug}}, {{amount | fixed:2}}) and, inside a section,
// {{@index}} (0-based), {{@number}} (1-based), {{@first}}, {{@last}}.
// Refused: partials {{> name}}, delimiter changes {{= =}}. Nothing in a template is ever run as code:
// names are looked up as own properties of the data, filters come from the fixed list below.
import { ToolError } from "./errors.js";
import { formatDate, toNumber, toDateMs, isFloatingDate } from "./values.js";
export const TEMPLATE_LIMITS = { maxTemplateChars: 100_000, maxDepth: 10, maxOutputChars: 5_000_000 };
const NAME_RE = /^(?:\.|@(?:index|number|first|last)|[A-Za-z_][\w-]*(?:\.[\w-]+)*)$/;
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function lineOf(src, pos) {
let n = 1;
for (let i = 0; i < pos && i < src.length; i++) if (src.charCodeAt(i) === 10) n++;
return n;
}
function fail(field, src, pos, message) {
throw new ToolError("invalid_template", `${field}: ${message} (line ${lineOf(src, pos)}).`);
}
// ---------------------------------------------------------------------------------------------
// Filters (fixed list; arguments are quoted strings or numbers)
// ---------------------------------------------------------------------------------------------
const FILTERS = {
lower: (v) => str(v).toLowerCase(),
upper: (v) => str(v).toUpperCase(),
trim: (v) => str(v).trim(),
title: (v) => str(v).toLowerCase().replace(/(^|[\s\-_/])(\p{L})/gu, (m, a, b) => a + b.toUpperCase()),
slug: (v) => slugify(str(v)),
default: (v, d = "") => (v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length) ? d : v),
fixed: (v, n = 2) => {
const x = toNumber(v);
return Number.isFinite(x) ? x.toFixed(clampInt(n, 0, 10)) : v;
},
round: (v) => {
const x = toNumber(v);
return Number.isFinite(x) ? Math.round(x) : v;
},
thousands: (v) => {
const x = toNumber(v);
if (!Number.isFinite(x)) return v;
const [i, d] = String(Math.abs(x)).split(".");
return (x < 0 ? "-" : "") + i.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (d ? "." + d : "");
},
pad: (v, n = 2) => str(v).padStart(clampInt(n, 1, 20), "0"),
truncate: (v, n = 80) => {
const s = str(v);
const k = clampInt(n, 1, 100000);
return s.length > k ? s.slice(0, Math.max(1, k - 1)) + "…" : s;
},
// Dates without a zone ("2026-11-30", "2026-11-30T09:00") are formatted as written; dates with Z or
// an offset (and file times) are shown in the recipe's time zone.
date: (v, fmt = "YYYY-MM-DD", tz) => {
const ms = toDateMs(v);
return Number.isFinite(ms) ? formatDate(ms, String(fmt), isFloatingDate(v) ? "UTC" : tz) : v;
},
json: (v) => JSON.stringify(v ?? null),
length: (v) => (Array.isArray(v) ? v.length : typeof v === "string" ? v.length : v && typeof v === "object" ? Object.keys(v).length : 0),
join: (v, sep = ", ") => (Array.isArray(v) ? v.map(str).join(String(sep)) : v),
};
export const FILTER_NAMES = Object.keys(FILTERS);
function clampInt(n, lo, hi) {
const x = Math.trunc(Number(n));
return Number.isFinite(x) ? Math.min(hi, Math.max(lo, x)) : lo;
}
export function slugify(s) {
return s
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 80)
.replace(/-+$/g, "");
}
// ---------------------------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------------------------
function parseArgs(raw, field, src, pos) {
const args = [];
let rest = raw;
while (rest.length) {
const m = /^\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|(-?\d+(?:\.\d+)?))\s*(?::|$)/.exec(rest);
if (!m) fail(field, src, pos, `cannot read filter arguments "${raw.slice(0, 40)}" (use "text" or numbers, separated by ":")`);
args.push(m[1] !== undefined ? m[1].replace(/\\(.)/g, "$1") : m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : Number(m[3]));
rest = rest.slice(m[0].length);
}
return args;
}
function parseExpr(inner, field, src, pos) {
const parts = splitPipes(inner);
const name = parts[0].trim();
if (!NAME_RE.test(name)) fail(field, src, pos, `"${name.slice(0, 60)}" is not a valid name (letters, digits, _, - and dots)`);
if (name.split(".").some((p) => BLOCKED.has(p))) fail(field, src, pos, `"${name}" is not allowed`);
const filters = parts.slice(1).map((f) => {
const m = /^\s*([a-z]+)\s*(?::(.*))?$/s.exec(f);
if (!m || !Object.hasOwn(FILTERS, m[1])) fail(field, src, pos, `unknown filter "${f.trim().slice(0, 30)}" (available: ${FILTER_NAMES.join(", ")})`);
return { name: m[1], args: m[2] !== undefined ? parseArgs(m[2], field, src, pos) : [] };
});
return { name, filters };
}
// Splits on "|" outside quotes.
function splitPipes(s) {
const out = [];
let cur = "";
let q = null;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (q) {
cur += c;
if (c === "\\" && i + 1 < s.length) cur += s[++i];
else if (c === q) q = null;
} else if (c === '"' || c === "'") {
q = c;
cur += c;
} else if (c === "|") {
out.push(cur);
cur = "";
} else cur += c;
}
out.push(cur);
return out;
}
const isBlank = (s) => /^[ \t\r]*$/.test(s);
/** Parses a template into a tree. Throws ToolError("invalid_template") with a line number on syntax errors. */
export function parseTemplate(src, field = "template") {
if (typeof src !== "string") throw new ToolError("invalid_template", `${field}: must be a string.`);
if (src.length > TEMPLATE_LIMITS.maxTemplateChars) throw new ToolError("limit_exceeded", `${field}: template is longer than ${TEMPLATE_LIMITS.maxTemplateChars} characters.`);
const root = { type: "root", children: [] };
const stack = [root];
let i = 0;
const pushText = (t) => t && stack[stack.length - 1].children.push({ type: "text", text: t });
while (i < src.length) {
const open = src.indexOf("{{", i);
if (open < 0) {
pushText(src.slice(i));
break;
}
const triple = src.startsWith("{{{", open);
const close = triple ? src.indexOf("}}}", open + 3) : src.indexOf("}}", open + 2);
if (close < 0) fail(field, src, open, "a {{ tag is not closed");
const end = close + (triple ? 3 : 2);
const inner = src.slice(open + (triple ? 3 : 2), close).trim();
const sigil = triple ? "" : inner[0];
// Standalone section/comment tags (alone on their line) remove the whole line, as in Mustache.
let textEnd = open;
let next = end;
if (!triple && (sigil === "#" || sigil === "^" || sigil === "/" || sigil === "!")) {
const ls = src.lastIndexOf("\n", open - 1) + 1;
const nl = src.indexOf("\n", end);
const lineEnd = nl < 0 ? src.length : nl;
if (ls >= i && isBlank(src.slice(ls, open)) && isBlank(src.slice(end, lineEnd))) {
textEnd = ls;
next = nl < 0 ? src.length : nl + 1;
}
}
pushText(src.slice(i, textEnd));
i = next;
if (triple) {
stack[stack.length - 1].children.push({ type: "var", raw: true, ...parseExpr(inner, field, src, open) });
continue;
}
if (sigil === "!") continue;
if (sigil === ">") fail(field, src, open, "partials ({{> name}}) are not supported");
if (sigil === "=") fail(field, src, open, "changing delimiters ({{= =}}) is not supported");
if (sigil === "#" || sigil === "^") {
const name = inner.slice(1).trim();
const expr = parseExpr(name, field, src, open);
if (expr.filters.length) fail(field, src, open, "filters are not allowed on section tags");
const node = { type: sigil === "#" ? "section" : "inverted", name: expr.name, children: [] };
stack[stack.length - 1].children.push(node);
stack.push(node);
if (stack.length - 1 > TEMPLATE_LIMITS.maxDepth) fail(field, src, open, `sections are nested more than ${TEMPLATE_LIMITS.maxDepth} deep`);
continue;
}
if (sigil === "/") {
const name = inner.slice(1).trim();
const top = stack.pop();
if (top === root) fail(field, src, open, `{{/${name}}} closes a section that was never opened`);
if (top.name !== name) fail(field, src, open, `{{/${name}}} does not match the open section {{#${top.name}}}`);
continue;
}
if (sigil === "&") {
stack[stack.length - 1].children.push({ type: "var", raw: true, ...parseExpr(inner.slice(1).trim(), field, src, open) });
continue;
}
if (!inner) fail(field, src, open, "empty tag {{}}");
stack[stack.length - 1].children.push({ type: "var", raw: false, ...parseExpr(inner, field, src, open) });
}
if (stack.length > 1) fail(field, src, src.length, `section {{#${stack[stack.length - 1].name}}} is not closed`);
return root;
}
/** Names used by a template (top-level parts), for validation messages. */
export function templateNames(ast) {
const out = new Set();
const walk = (n) => {
if (n.type === "var" || n.type === "section" || n.type === "inverted") out.add(n.name);
for (const c of n.children ?? []) walk(c);
};
walk(ast);
return [...out];
}
// ---------------------------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------------------------
export function str(v) {
if (v === undefined || v === null) return "";
if (typeof v === "string") return v;
if (typeof v === "number") return Number.isFinite(v) ? String(v) : "";
if (typeof v === "boolean") return v ? "true" : "false";
if (Array.isArray(v)) return v.map((x) => (x !== null && typeof x === "object" ? JSON.stringify(x) : str(x))).join(", ");
return JSON.stringify(v);
}
const HTML = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
export const ESCAPERS = {
html: (s) => s.replace(/[&<>"']/g, (c) => HTML[c]),
// Backslash-escapes Markdown syntax characters and joins lines, so data cannot add links, images,
// HTML, headings or table cells.
// Line-start markers (headings, list items, rules) are escaped only where Markdown would read them as such.
markdown: (s) =>
s
.replace(/\r\n?|\n/g, " ")
.replace(/[\\`*_[\]<>|~&]/g, "\\$&")
.replace(/^(\s*)([#+\-=])(?=\s|$|[-=]+\s*$)/, "$1\\$2")
.replace(/^(\s*\d{1,9})([.)])(?=\s|$)/, "$1\\$2"),
none: (s) => s,
// For file and folder names: separators, ':' and other characters Windows refuses become "-",
// leading/trailing dots and spaces are removed, so a value is always one safe name.
path: (s) => {
const t = s.replace(/[\\/:*?"<>|\u0000-\u001f\u007f]+/g, "-").replace(/\s+/g, " ").replace(/^[\s.]+|[\s.]+$/g, "");
return t || "_";
},
};
const MISSING = Symbol("missing");
function lookup(stack, name) {
if (name === ".") return stack[stack.length - 1];
const parts = name.split(".");
for (let s = stack.length - 1; s >= 0; s--) {
const frame = stack[s];
if (frame === null || typeof frame !== "object" || !Object.hasOwn(frame, parts[0])) continue;
let v = frame[parts[0]];
for (const p of parts.slice(1)) {
if (v !== null && typeof v === "object" && Object.hasOwn(v, p)) v = v[p];
else return MISSING;
}
return v;
}
return MISSING;
}
/**
* Renders a parsed template. opts: escape ("html" | "markdown" | "none" | "path"), timezone (for the
* date filter), strict (throw on unknown names), maxChars, tick (called regularly; may throw).
* Returns { text, missing: [names] }.
*/
export function renderTemplate(ast, context, opts = {}) {
const escape = ESCAPERS[opts.escape ?? "html"];
const maxChars = opts.maxChars ?? TEMPLATE_LIMITS.maxOutputChars;
const missing = new Set();
const out = [];
let size = 0;
let nodes = 0;
const emit = (s) => {
size += s.length;
if (size > maxChars) throw new ToolError("limit_exceeded", `${opts.field ?? "template"}: output is longer than ${maxChars} characters.`);
out.push(s);
};
const value = (stack, node) => {
let v = lookup(stack, node.name);
if (v === MISSING) {
missing.add(node.name);
if (opts.strict) throw new ToolError("missing_value", `${opts.field ?? "template"}: {{${node.name}}} has no value.`);
v = undefined;
}
for (const f of node.filters ?? []) {
const args = f.name === "date" && f.args.length < 2 && opts.timezone ? [f.args[0] ?? "YYYY-MM-DD", opts.timezone] : f.args;
v = FILTERS[f.name](v, ...args);
}
return v;
};
const walk = (children, stack) => {
for (const n of children) {
if (++nodes % 2000 === 0) opts.tick?.();
if (n.type === "text") emit(n.text);
else if (n.type === "var") {
const s = str(value(stack, n));
emit(n.raw && opts.escape !== "path" ? s : escape(s));
} else {
const v = value(stack, n);
const truthy = Array.isArray(v) ? v.length > 0 : !!v && v !== "0" && v !== "false";
if (n.type === "inverted") {
if (!truthy) walk(n.children, stack);
} else if (Array.isArray(v)) {
v.forEach((item, idx) => {
walk(n.children, [...stack, { "@index": idx, "@number": idx + 1, "@first": idx === 0, "@last": idx === v.length - 1 }, item]);
});
} else if (truthy) walk(n.children, v !== null && typeof v === "object" ? [...stack, v] : stack);
}
}
};
walk(ast.children, Array.isArray(context) ? context : [context]);
return { text: out.join(""), missing: [...missing] };
}