@x12i/reportic-core 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // packages/reportic-core/src/types.ts
2
2
  var FORMAT_VERSION = "0.2";
3
- var VERSION = "0.2.2";
3
+ var VERSION = "0.2.4";
4
4
 
5
5
  // packages/reportic-core/src/safety.ts
6
6
  import { createHash } from "crypto";
@@ -81,10 +81,15 @@ function formatValue(value, format, locale = "en-US", timezone = "UTC") {
81
81
  if (kind !== "currency" && digits !== void 0 && (!Number.isInteger(digits) || digits < 0 || digits > 20)) fail("INVALID_FORMAT", "Decimal precision must be between 0 and 20.");
82
82
  return new Intl.NumberFormat(locale, kind === "currency" ? { style: "currency", currency: precision } : { style: kind === "percent" ? "percent" : "decimal", minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value);
83
83
  }
84
- if (kind === "date" || kind === "datetime") {
85
- if (typeof value !== "string" || (kind === "date" ? !/^\d{4}-\d{2}-\d{2}$/.test(value) : !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value))) fail("INVALID_FORMAT_VALUE", `${kind} requires ${kind === "date" ? "an ISO calendar date" : "an ISO timestamp with an explicit offset"}.`);
86
- const d = new Date(kind === "date" ? `${value}T00:00:00Z` : value);
87
- if (Number.isNaN(d.getTime()) || kind === "date" && d.toISOString().slice(0, 10) !== value) fail("INVALID_FORMAT_VALUE", "Invalid calendar date.");
84
+ if (kind === "date" || kind === "datetime" || kind === "shortdate") {
85
+ const calendar = kind !== "datetime";
86
+ if (typeof value !== "string" || (calendar ? !/^\d{4}-\d{2}-\d{2}$/.test(value) : !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value))) fail("INVALID_FORMAT_VALUE", `${kind} requires ${calendar ? "an ISO calendar date" : "an ISO timestamp with an explicit offset"}.`);
87
+ const d = new Date(calendar ? `${value}T00:00:00Z` : value);
88
+ if (Number.isNaN(d.getTime()) || calendar && d.toISOString().slice(0, 10) !== value) fail("INVALID_FORMAT_VALUE", "Invalid calendar date.");
89
+ if (kind === "shortdate") {
90
+ const out = new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(d);
91
+ return /^en(?:-|$)/i.test(locale) ? out.replace(/\bSept\b/, "Sep") : out;
92
+ }
88
93
  return new Intl.DateTimeFormat(locale, { dateStyle: "medium", ...kind === "datetime" ? { timeStyle: "short" } : {}, timeZone: kind === "date" ? "UTC" : timezone }).format(d);
89
94
  }
90
95
  fail("INVALID_FORMAT", `Unknown format "${format}".`);
@@ -102,6 +107,26 @@ function themeTokens(theme = {}) {
102
107
  };
103
108
  return { ...baseTokens, ...presets[theme.name ?? "editorial"], ...theme.tokens };
104
109
  }
110
+ var hexColor = /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
111
+ function relativeLuminance(hex) {
112
+ const s = hex.replace("#", "");
113
+ const full = s.length <= 4 ? s.slice(0, 3).split("").map((c) => c + c).join("") : s.slice(0, 6);
114
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16) / 255);
115
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
116
+ }
117
+ function semanticColors(tokens) {
118
+ const dark = relativeLuminance(tokens.background) < 0.4;
119
+ const base = dark ? { ok: "#6bc28f", warn: "#e2bc7b", bad: "#e08a80", na: tokens.muted, ink: tokens.text, grey: "#5b6778", grid: tokens.border, axis: "#6b7686", okSoft: "#6bc28f26", warnSoft: "#e2bc7b26", badSoft: "#e08a8026", accentSoft: `${tokens.accent}26`, zebra: `${tokens.accent}0d`, head: `${tokens.accent}1a`, page: tokens.background } : { ok: "#2f7d4f", warn: "#b07a1a", bad: "#bb4f46", na: tokens.muted, ink: tokens.text, grey: "#b9bec9", grid: tokens.border, axis: "#9aa0ad", okSoft: "#2f7d4f1a", warnSoft: "#b07a1a1f", badSoft: "#bb4f461a", accentSoft: `${tokens.accent}14`, zebra: `${tokens.accent}08`, head: `${tokens.accent}0d`, page: tokens.background };
120
+ return { ...base, ...tokens.semantic };
121
+ }
122
+ var tones = ["ok", "warn", "bad", "na"];
123
+ function statusTone(label) {
124
+ const k = String(label ?? "").trim().toLowerCase();
125
+ if (["done", "closed", "complete", "completed", "met"].includes(k)) return "done";
126
+ if (["late", "overdue", "off target", "not met"].includes(k)) return "late";
127
+ if (["in progress", "started", "at risk"].includes(k)) return "progress";
128
+ return "";
129
+ }
105
130
  function validateStyles(o, format) {
106
131
  if (o.css && /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:/i.test(o.css)) fail("UNSAFE_CSS", "External CSS resources and executable CSS are not allowed.");
107
132
  const tokens = themeTokens(o.theme);
@@ -109,6 +134,8 @@ function validateStyles(o, format) {
109
134
  if (typeof tokens.fontFamily !== "string" || typeof tokens.headingFont !== "string" || /[;{}<>@]/.test(tokens.fontFamily + tokens.headingFont)) fail("INVALID_THEME", "Invalid font family.");
110
135
  for (const key of ["bodySize", "headingSize", "contentWidth", "spacing", "logoWidth"]) if (!Number.isFinite(tokens[key]) || tokens[key] < 1 || tokens[key] > 5e3) fail("INVALID_THEME", `Invalid theme token ${key}.`);
111
136
  if (!Array.isArray(tokens.chartPalette) || tokens.chartPalette.length === 0 || tokens.chartPalette.some((c) => !/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i.test(c))) fail("INVALID_THEME", "Chart palette must contain hex colors.");
137
+ if (tokens.semantic !== void 0 && (!isRecord(tokens.semantic) || Object.values(tokens.semantic).some((c) => typeof c !== "string" || !hexColor.test(c)))) fail("INVALID_THEME", "Semantic colors must be hex colors.");
138
+ if (tokens.layout !== void 0 && tokens.layout !== "page" && tokens.layout !== "card") fail("INVALID_THEME", 'Theme layout must be "page" or "card".');
112
139
  for (const [selector, rule] of Object.entries(o.theme?.rules ?? {})) {
113
140
  if (!/^[a-zA-Z0-9_.-]+$/.test(selector)) fail("INVALID_THEME", "Style rule selectors must be semantic types or element IDs.");
114
141
  for (const [property, value] of Object.entries(rule)) if (!["color", "backgroundColor", "fontSize", "fontFamily", "fontWeight", "textAlign", "marginTop", "marginBottom", "padding", "borderColor", "borderWidth"].includes(property) || /[;{}<>@]|url\s*\(/i.test(String(value))) fail("INVALID_THEME", `Unsupported or unsafe semantic style property ${property}.`);
@@ -156,7 +183,7 @@ function parseTemplate(source) {
156
183
  if (!Array.isArray(e.props.children)) fail("INVALID_ELEMENT", `${e.type} children must be authored element mappings.`, { phase: "parse", line, elementId: e.id });
157
184
  e.props.children = e.props.children.map((child) => validateElement(child, line, depth + 1));
158
185
  }
159
- return { id: e.id, type: e.type, props: e.props, fallback: e.fallback, line };
186
+ return { id: e.id, type: e.type, props: e.props, fallback: e.fallback, ...e.when !== void 0 ? { when: e.when } : {}, line };
160
187
  };
161
188
  let offset = metadataMatch?.[0].length ?? 0;
162
189
  let body = "";
@@ -186,6 +213,169 @@ import Ajv from "ajv";
186
213
  import Ajv2020 from "ajv/dist/2020.js";
187
214
  import addFormats from "ajv-formats";
188
215
  import { lexer as lexer2, marked } from "marked";
216
+
217
+ // packages/reportic-core/src/figure.ts
218
+ var figureKinds = ["hbar", "bar", "grouped", "stacked", "line", "matrix", "dots", "flow"];
219
+ var figureTones = ["accent", "grey", "muted", "ok", "warn", "bad"];
220
+ var MAX_ITEMS = 300;
221
+ var MAX_SERIES = 12;
222
+ var MAX_NODES = 120;
223
+ var MAX_EDGES = 400;
224
+ var bad = (message) => fail("INVALID_ELEMENT_PROPS", `Figure: ${message}`);
225
+ var text = (v, name, max = 400) => {
226
+ if (typeof v !== "string" || v.length > max) bad(`${name} must be text of at most ${max} characters.`);
227
+ return v;
228
+ };
229
+ var optText = (v, name, max = 400) => v === void 0 || v === null ? void 0 : text(v, name, max);
230
+ var num = (v, name) => {
231
+ if (typeof v !== "number" || !Number.isFinite(v)) bad(`${name} must be a finite number.`);
232
+ return v;
233
+ };
234
+ var bounded = (v, name, lo, hi) => {
235
+ if (v === void 0 || v === null) return void 0;
236
+ const n = num(v, name);
237
+ if (n < lo || n > hi) bad(`${name} must be between ${lo} and ${hi}.`);
238
+ return n;
239
+ };
240
+ var list = (v, name, max = MAX_ITEMS) => {
241
+ if (!Array.isArray(v) || v.length > max) bad(`${name} must be a list of at most ${max} items.`);
242
+ return v;
243
+ };
244
+ var tone = (v, name) => {
245
+ if (v === void 0 || v === null || v === "") return void 0;
246
+ if (!figureTones.includes(v)) bad(`${name} must be one of ${figureTones.join(", ")}.`);
247
+ return v;
248
+ };
249
+ var strings = (v, name, max = MAX_ITEMS) => list(v, name, max).map((s, i) => text(s, `${name}[${i}]`));
250
+ var reference = (v) => {
251
+ if (v === void 0 || v === null) return void 0;
252
+ if (!isRecord(v)) bad("reference must be {value, label}.");
253
+ const r = v;
254
+ return { value: num(r.value, "reference.value"), ...r.label !== void 0 ? { label: text(r.label, "reference.label") } : {} };
255
+ };
256
+ var numbers = (v, name, length, allowNull = false) => {
257
+ const items = list(v, name);
258
+ if (items.length !== length) bad(`${name} needs ${length} values, one per category.`);
259
+ return items.map((n, i) => allowNull && (n === null || n === void 0) ? null : num(n, `${name}[${i}]`));
260
+ };
261
+ var tones2 = (v, name, length) => v === void 0 || v === null ? void 0 : list(v, name).slice(0, length).map((t, i) => tone(t, `${name}[${i}]`) ?? null);
262
+ function parseFigure(raw) {
263
+ if (!isRecord(raw)) return bad("spec must be an object.");
264
+ const s = raw;
265
+ if (!figureKinds.includes(s.type)) bad(`spec.type must be one of ${figureKinds.join(", ")}.`);
266
+ const kind = s.type;
267
+ const figure = { kind, title: text(s.title, "title"), subtitle: optText(s.subtitle, "subtitle"), note: optText(s.note, "note", 600) };
268
+ if (s.unit !== void 0 && s.unit !== null) figure.unit = text(s.unit, "unit", 8);
269
+ figure.reference = reference(s.reference);
270
+ figure.labelWidth = bounded(s.labelWidth, "labelWidth", 40, 600);
271
+ figure.rowHeight = bounded(s.rowHeight, "rowHeight", 12, 80);
272
+ figure.height = bounded(s.height, "height", 120, 900);
273
+ figure.min = s.min === void 0 || s.min === null ? void 0 : num(s.min, "min");
274
+ figure.max = s.max === void 0 || s.max === null ? void 0 : num(s.max, "max");
275
+ if (figure.min !== void 0 && figure.max !== void 0 && figure.max <= figure.min) bad("max must be greater than min.");
276
+ figure.nodeHeight = bounded(s.nodeHeight, "nodeHeight", 24, 200);
277
+ if (kind === "hbar" || kind === "dots") {
278
+ figure.categories = strings(s.categories, "categories");
279
+ figure.values = numbers(s.values, "values", figure.categories.length);
280
+ if (s.highlight !== void 0) figure.highlight = list(s.highlight, "highlight").map((i, k) => {
281
+ if (!Number.isInteger(i) || i < 0 || i >= figure.categories.length) bad(`highlight[${k}] must be a valid category index.`);
282
+ return i;
283
+ });
284
+ figure.tones = tones2(s.tones, "tones", figure.categories.length);
285
+ } else if (kind === "bar" || kind === "grouped" || kind === "stacked" || kind === "line") {
286
+ figure.categories = strings(s.categories, "categories");
287
+ figure.series = list(s.series, "series", MAX_SERIES).map((x, i) => {
288
+ if (!isRecord(x)) bad(`series[${i}] must be an object.`);
289
+ return { name: text(x.name, `series[${i}].name`, 120), values: numbers(x.values, `series[${i}].values`, figure.categories.length, true), tone: tone(x.tone, `series[${i}].tone`) };
290
+ });
291
+ if (!figure.series.length) bad("series needs at least one entry.");
292
+ } else if (kind === "matrix") {
293
+ figure.rows = strings(s.rows, "rows");
294
+ figure.cols = strings(s.cols, "cols", 60);
295
+ const grid = list(s.values, "values");
296
+ if (grid.length !== figure.rows.length) bad("values needs one row per entry in rows.");
297
+ figure.matrix = grid.map((r, i) => numbers(r, `values[${i}]`, figure.cols.length, true));
298
+ if (s.cellTones !== void 0 && s.cellTones !== null) figure.cellTones = list(s.cellTones, "cellTones").slice(0, figure.rows.length).map((r, i) => list(r ?? [], `cellTones[${i}]`, 60).map((t, j) => tone(t, `cellTones[${i}][${j}]`) ?? null));
299
+ figure.rowTones = tones2(s.rowTones, "rowTones", figure.rows.length);
300
+ figure.colTones = tones2(s.colTones, "colTones", figure.cols.length);
301
+ } else {
302
+ const ids = /* @__PURE__ */ new Set();
303
+ let total = 0;
304
+ figure.columns = list(s.columns, "columns", 12).map((c, i) => {
305
+ if (!isRecord(c)) bad(`columns[${i}] must be an object.`);
306
+ const nodes = list(c.nodes, `columns[${i}].nodes`, MAX_NODES).map((n, j) => {
307
+ if (!isRecord(n)) bad(`columns[${i}].nodes[${j}] must be an object.`);
308
+ const id = text(n.id, `columns[${i}].nodes[${j}].id`, 80);
309
+ if (ids.has(id)) bad(`node id "${id}" is used more than once.`);
310
+ ids.add(id);
311
+ total++;
312
+ const sub = n.sub === void 0 || n.sub === null ? void 0 : Array.isArray(n.sub) ? strings(n.sub, `columns[${i}].nodes[${j}].sub`, 8) : [text(n.sub, `columns[${i}].nodes[${j}].sub`)];
313
+ return { id, label: text(n.label, `columns[${i}].nodes[${j}].label`, 160), sub, tone: tone(n.tone, `columns[${i}].nodes[${j}].tone`), dashed: n.dashed === true };
314
+ });
315
+ return { title: optText(c.title, `columns[${i}].title`, 80), nodes };
316
+ });
317
+ if (!figure.columns.length || total === 0) bad("flow needs at least one column with a node.");
318
+ if (total > MAX_NODES) bad(`flow supports at most ${MAX_NODES} nodes.`);
319
+ figure.edges = list(s.edges ?? [], "edges", MAX_EDGES).map((e, i) => {
320
+ if (!isRecord(e)) bad(`edges[${i}] must be an object.`);
321
+ const from = text(e.from, `edges[${i}].from`, 80), to = text(e.to, `edges[${i}].to`, 80);
322
+ if (!ids.has(from) || !ids.has(to)) bad(`edges[${i}] refers to a node that does not exist.`);
323
+ return { from, to, tone: tone(e.tone, `edges[${i}].tone`), dashed: e.dashed === true, label: optText(e.label, `edges[${i}].label`, 120) };
324
+ });
325
+ }
326
+ return figure;
327
+ }
328
+ function figureTable(figure, locale = "en-US") {
329
+ const n = (v) => v === null || v === void 0 ? "" : figure.unit === "%" ? `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(v)}%` : new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(v);
330
+ const target = figure.reference ? figure.reference.label || "Reference" : "";
331
+ if (figure.kind === "hbar" || figure.kind === "dots") return { columns: [{ label: "Item" }, { label: "Value", align: "right" }], cells: [...figure.categories.map((c, i) => [c, n(figure.values[i])]), ...figure.reference ? [[target, n(figure.reference.value)]] : []] };
332
+ if (figure.series) return { columns: [{ label: "Item" }, ...figure.series.map((s) => ({ label: s.name, align: "right" }))], cells: [...figure.categories.map((c, i) => [c, ...figure.series.map((s) => n(s.values[i]))]), ...figure.reference ? [[target, ...figure.series.map((_, j) => figure.kind === "stacked" && j > 0 ? "" : n(figure.reference.value))]] : []] };
333
+ if (figure.kind === "matrix") return { columns: [{ label: "" }, ...figure.cols.map((c) => ({ label: c, align: "right" }))], cells: figure.rows.map((r, i) => [r, ...figure.matrix[i].map(n)]) };
334
+ const nodes = figure.columns.flatMap((c) => c.nodes), label = new Map(nodes.map((x) => [x.id, x.label]));
335
+ const linked = new Set(figure.edges.flatMap((e) => [e.from, e.to]));
336
+ const described = nodes.filter((x) => x.sub?.length || !linked.has(x.id)).map((x) => [x.label, "", (x.sub ?? []).join(" \xB7 ")]);
337
+ return { columns: [{ label: "From" }, { label: "To" }, { label: "Note" }], cells: [...figure.edges.map((e) => [label.get(e.from), label.get(e.to), e.label ?? ""]), ...described] };
338
+ }
339
+ function figureSpec(figure) {
340
+ const spec = { type: figure.kind, title: figure.title };
341
+ const put = (key, value) => {
342
+ if (value !== void 0 && value !== null) spec[key] = value;
343
+ };
344
+ put("subtitle", figure.subtitle);
345
+ put("note", figure.note);
346
+ put("unit", figure.unit);
347
+ put("reference", figure.reference);
348
+ put("labelWidth", figure.labelWidth);
349
+ put("rowHeight", figure.rowHeight);
350
+ put("height", figure.height);
351
+ put("min", figure.min);
352
+ put("max", figure.max);
353
+ put("nodeHeight", figure.nodeHeight);
354
+ const pruned = (tones3) => tones3 && tones3.some(Boolean) ? tones3 : void 0;
355
+ if (figure.kind === "hbar" || figure.kind === "dots") {
356
+ put("categories", figure.categories);
357
+ put("values", figure.values);
358
+ put("highlight", figure.highlight?.length ? figure.highlight : void 0);
359
+ put("tones", pruned(figure.tones));
360
+ } else if (figure.series) {
361
+ put("categories", figure.categories);
362
+ put("series", figure.series.map((s) => ({ name: s.name, values: s.values, ...s.tone ? { tone: s.tone } : {} })));
363
+ } else if (figure.kind === "matrix") {
364
+ put("rows", figure.rows);
365
+ put("cols", figure.cols);
366
+ put("values", figure.matrix);
367
+ put("cellTones", figure.cellTones?.some((r) => r.some(Boolean)) ? figure.cellTones : void 0);
368
+ put("rowTones", pruned(figure.rowTones));
369
+ put("colTones", pruned(figure.colTones));
370
+ } else {
371
+ put("columns", figure.columns.map((c) => ({ ...c.title ? { title: c.title } : {}, nodes: c.nodes.map((x) => ({ id: x.id, label: x.label, ...x.sub?.length ? { sub: x.sub } : {}, ...x.tone ? { tone: x.tone } : {}, ...x.dashed ? { dashed: true } : {} })) })));
372
+ put("edges", figure.edges?.length ? figure.edges.map((e) => ({ from: e.from, to: e.to, ...e.tone ? { tone: e.tone } : {}, ...e.dashed ? { dashed: true } : {}, ...e.label ? { label: e.label } : {} })) : void 0);
373
+ }
374
+ return spec;
375
+ }
376
+ var figureAlt = (figure) => `${figure.title}${figure.subtitle ? ` \u2014 ${figure.subtitle}` : ""}`;
377
+
378
+ // packages/reportic-core/src/prepare.ts
189
379
  var ajv = new Ajv({ allErrors: true, strict: false });
190
380
  var MISSING = /* @__PURE__ */ Symbol("missing");
191
381
  function resolvePath(path, context) {
@@ -201,9 +391,12 @@ function resolvePath(path, context) {
201
391
  }
202
392
  function bind(value, context, skip = /* @__PURE__ */ new Set()) {
203
393
  if (isRecord(value) && own(value, "$bind")) {
204
- if (Object.keys(value).length !== 1) fail("INVALID_BINDING", "A binding may contain only $bind.");
394
+ if (Object.keys(value).some((k) => k !== "$bind" && k !== "default")) fail("INVALID_BINDING", "A binding may contain only $bind and an optional default.");
205
395
  const result = resolvePath(value.$bind, context);
206
- if (result === MISSING) fail("MISSING_REQUIRED_INPUT", `Missing value at ${value.$bind}.`, { bindingPath: value.$bind });
396
+ if (result === MISSING) {
397
+ if (own(value, "default")) return structuredClone(value.default);
398
+ fail("MISSING_REQUIRED_INPUT", `Missing value at ${value.$bind}.`, { bindingPath: value.$bind });
399
+ }
207
400
  return structuredClone(result);
208
401
  }
209
402
  if (Array.isArray(value)) return value.map((v) => bind(v, context));
@@ -248,8 +441,8 @@ function validateInput(dataSets, variables, options, declarations) {
248
441
  return indexed;
249
442
  }
250
443
  function validateSvg(bytes) {
251
- const text = Buffer.from(bytes).toString("utf8");
252
- if (!/^\s*(?:<\?xml[^>]*>\s*)?<svg[\s>]/i.test(text) || /<\s*[\w-]+:|<\s*(script|foreignObject|iframe|object|embed|image|use|a|style|animate\w*|set)\b|\bon\w+\s*=|(?:href|src)\s*=|url\s*\(|<!DOCTYPE|<!ENTITY|javascript:|data:/i.test(text)) fail("UNSAFE_SVG", "SVG must contain only static, self-contained vector content.");
444
+ const text2 = Buffer.from(bytes).toString("utf8");
445
+ if (!/^\s*(?:<\?xml[^>]*>\s*)?<svg[\s>]/i.test(text2) || /<\s*[\w-]+:|<\s*(script|foreignObject|iframe|object|embed|image|use|a|style|animate\w*|set)\b|\bon\w+\s*=|(?:href|src)\s*=|url\s*\(|<!DOCTYPE|<!ENTITY|javascript:|data:/i.test(text2)) fail("UNSAFE_SVG", "SVG must contain only static, self-contained vector content.");
253
446
  }
254
447
  function assetReference(ref, alt, options, assets) {
255
448
  if (typeof alt !== "string" || !alt.trim()) fail("INVALID_ELEMENT_PROPS", "Managed images require nonempty alt text.");
@@ -345,20 +538,111 @@ async function prepareReportModel(template, dataSets, variables, options, regist
345
538
  let nodeCount = 0;
346
539
  const context = { dataSets: map, variables };
347
540
  const display = (v, format) => formatValue(v, format, locale, timezone);
541
+ const optionalBind = (value, scope, element) => {
542
+ try {
543
+ return bind(value, scope);
544
+ } catch (e) {
545
+ if (e instanceof ReporticError && e.diagnostics.every((d) => d.code === "MISSING_REQUIRED_INPUT")) {
546
+ if (element) diagnostics.push({ code: "OPTIONAL_VALUE_OMITTED", severity: "info", phase: "prepare", message: `An optional value is missing and was left out: ${e.diagnostics[0]?.bindingPath ?? "binding"}.`, elementId: element.id, bindingPath: e.diagnostics[0]?.bindingPath });
547
+ return void 0;
548
+ }
549
+ throw e;
550
+ }
551
+ };
552
+ const kindCell = (column, raw, tone2) => {
553
+ const kind = column.kind, format = column.format;
554
+ if (!kind) return { raw, text: display(raw, format) };
555
+ if (kind === "rating") {
556
+ if (raw === null || raw === void 0 || raw === "") return { raw, text: "", kind };
557
+ if (tone2 !== void 0 && tone2 !== null && tone2 !== "" && !isRecord(raw)) {
558
+ if (!tones.includes(tone2) || !["string", "number"].includes(typeof raw)) fail("INVALID_ELEMENT_PROPS", "A rating column tone must be ok, warn, bad, or na, and its value text or a number.");
559
+ return { raw, text: display(raw, format), kind, tone: tone2 };
560
+ }
561
+ if (!isRecord(raw) || !tones.includes(raw.tone) || typeof raw.label !== "string") fail("INVALID_ELEMENT_PROPS", "A rating cell needs { tone: ok | warn | bad | na, label }.");
562
+ return { raw, text: raw.label, kind, tone: raw.tone };
563
+ }
564
+ if (kind === "list") {
565
+ if (raw === null || raw === void 0 || raw === "") return { raw, text: "", kind };
566
+ if (!Array.isArray(raw) || raw.length > 200 || raw.some((x) => !["string", "number", "boolean"].includes(typeof x))) fail("INVALID_ELEMENT_PROPS", "A list cell needs a list of text or numbers.");
567
+ return { raw, text: raw.map((x) => display(x, format)).join(", "), kind };
568
+ }
569
+ if (kind === "date") return { raw, text: raw === null || raw === void 0 || raw === "" ? "" : display(raw, format ?? "date"), kind };
570
+ const text2 = display(raw, format);
571
+ return { raw, text: text2, kind, ...kind === "status" ? { status: statusTone(text2) } : {} };
572
+ };
573
+ const partKeys = /* @__PURE__ */ new Set(["value", "format", "kind", "prefix", "suffix", "optional", "join"]);
574
+ const composeCell = (column, scope) => {
575
+ if (column.value.length > 12) fail("INVALID_ELEMENT_PROPS", "A composed cell supports at most 12 parts.");
576
+ const runs = [];
577
+ const push = (text3, style = {}) => {
578
+ if (text3) runs.push({ text: text3, ...style });
579
+ };
580
+ for (const part of column.value) {
581
+ if (["string", "number", "boolean"].includes(typeof part)) {
582
+ push(String(part));
583
+ continue;
584
+ }
585
+ const spec = isRecord(part) && own(part, "$bind") ? { value: part } : part;
586
+ if (!isRecord(spec) || !own(spec, "value") || Object.keys(spec).some((k) => !partKeys.has(k))) fail("INVALID_ELEMENT_PROPS", "A composed cell part must be text, a binding, or { value, format?, kind?, prefix?, suffix?, join?, optional? }.");
587
+ let v = spec.value;
588
+ if (isRecord(v) && own(v, "$bind")) {
589
+ if (Object.keys(v).some((k) => k !== "$bind" && k !== "default")) fail("INVALID_BINDING", "A binding may contain only $bind and an optional default.");
590
+ const found = resolvePath(v.$bind, scope);
591
+ if (found === MISSING) {
592
+ if (own(v, "default")) v = v.default;
593
+ else if (spec.optional === true) continue;
594
+ else fail("MISSING_REQUIRED_INPUT", `Missing value at ${v.$bind}.`, { bindingPath: v.$bind });
595
+ } else v = found;
596
+ }
597
+ if (spec.join !== void 0) {
598
+ if (typeof spec.join !== "string") fail("INVALID_ELEMENT_PROPS", "A part join must be text.");
599
+ if (v !== null && v !== void 0 && v !== "" && !Array.isArray(v)) fail("INVALID_ELEMENT_PROPS", "A part with join needs a list.");
600
+ if (Array.isArray(v)) {
601
+ if (v.length > 200 || v.some((x) => !["string", "number", "boolean"].includes(typeof x))) fail("INVALID_ELEMENT_PROPS", "A joined part needs a list of at most 200 text or number items.");
602
+ v = v.map((x) => display(x, spec.format)).join(spec.join);
603
+ }
604
+ }
605
+ if (v === null || v === void 0 || v === "") continue;
606
+ let text3, style = {};
607
+ if (isRecord(v) && spec.kind === "rating") {
608
+ if (!tones.includes(v.tone) || typeof v.label !== "string") fail("INVALID_ELEMENT_PROPS", "A rating needs { tone: ok | warn | bad | na, label }.");
609
+ text3 = v.label;
610
+ style = { tone: v.tone };
611
+ } else {
612
+ text3 = spec.join !== void 0 ? String(v) : display(v, spec.format);
613
+ if (spec.kind === "code") style = { code: true };
614
+ else if (spec.kind === "strong") style = { strong: true };
615
+ }
616
+ const suffix = Array.isArray(spec.suffix) ? v === 1 ? spec.suffix[0] : spec.suffix[1] : spec.suffix;
617
+ if (spec.prefix !== void 0) push(String(spec.prefix));
618
+ push(text3, style);
619
+ if (suffix !== void 0) push(String(suffix));
620
+ }
621
+ const text2 = runs.map((r) => r.text).join("");
622
+ return { raw: text2, text: text2, runs };
623
+ };
624
+ const textOf = (spec, scope, what) => {
625
+ if (Array.isArray(spec)) return composeCell({ value: spec }, scope).text;
626
+ const text2 = bind(spec, scope);
627
+ if (typeof text2 !== "string") fail("INVALID_ELEMENT_PROPS", `${what} must be text.`);
628
+ return text2;
629
+ };
630
+ const truthy = (v) => v === void 0 || v === null || v === false || v === 0 || v === "" ? false : Array.isArray(v) ? v.length > 0 : isRecord(v) ? Object.keys(v).length > 0 : true;
348
631
  const normalize = (element, row) => {
349
632
  checkAbort(options);
633
+ const local = { ...context, ...row !== void 0 ? { row } : {} };
634
+ if (element.when !== void 0 && !truthy(optionalBind(element.when, local))) return void 0;
350
635
  if (++nodeCount > limit.nodes) fail("LIMIT_EXCEEDED", `Report exceeds ${limit.nodes} semantic nodes.`);
351
636
  const occurrence = (occurrences.get(element.id) ?? 0) + 1;
352
637
  occurrences.set(element.id, occurrence);
353
638
  const node = { id: element.id, occurrenceId: `${element.id}-${occurrence}`, type: element.type, componentType: element.type, props: {}, line: element.line };
354
- const local = { ...context, ...row !== void 0 ? { row } : {} };
355
639
  const definition = registry.get(element.type);
356
640
  if (!definition) {
357
641
  if (element.fallback !== void 0) {
358
- const text = bind(element.fallback, local);
359
- if (typeof text !== "string") fail("INVALID_ELEMENT_PROPS", "Fallback must resolve to text.");
642
+ const text2 = bind(element.fallback, local);
643
+ if (typeof text2 !== "string") fail("INVALID_ELEMENT_PROPS", "Fallback must resolve to text.");
360
644
  diagnostics.push({ code: "ELEMENT_FALLBACK", severity: "warning", phase: "prepare", message: `Using authored fallback for ${element.type}.`, elementId: element.id });
361
- return { ...node, type: "narrative", fallbackUsed: true, props: { text } };
645
+ return { ...node, type: "narrative", fallbackUsed: true, props: { text: text2 } };
362
646
  }
363
647
  fail("UNKNOWN_COMPONENT", `Component "${element.type}" is not registered.`, { elementId: element.id });
364
648
  }
@@ -366,20 +650,86 @@ async function prepareReportModel(template, dataSets, variables, options, regist
366
650
  let p;
367
651
  try {
368
652
  const skip = /* @__PURE__ */ new Set(["children"]);
369
- if (element.type === "table") skip.add("columns");
653
+ if (element.type === "table") {
654
+ skip.add("columns");
655
+ skip.add("dataColumns");
656
+ }
657
+ if (element.type === "reportic.grid.v1") {
658
+ skip.add("columns");
659
+ skip.add("rows");
660
+ }
370
661
  if (element.type === "chart") {
371
662
  skip.add("x");
372
663
  skip.add("series");
373
664
  }
374
- if (element.type === "list") skip.add("text");
665
+ if (element.type === "list") {
666
+ skip.add("text");
667
+ skip.add("lead");
668
+ }
669
+ if (element.type === "reportic.masthead.v1") {
670
+ skip.add("marking");
671
+ skip.add("kicker");
672
+ skip.add("lead");
673
+ }
674
+ if (element.type === "reportic.heading.v1" || element.type === "reportic.footer.v1" || element.type === "narrative" && Array.isArray(element.props.text)) skip.add("text");
675
+ if (element.type === "reportic.figure.v1") skip.add("source");
375
676
  p = bind(element.props, local, skip);
677
+ const resolveColumn = (c) => {
678
+ const column = bind(c, local, /* @__PURE__ */ new Set(["value", "tone"]));
679
+ if (Array.isArray(column.label)) column.label = column.label.map((x) => String(x ?? "")).join("");
680
+ return column;
681
+ };
682
+ const primitives = (a) => a.every((x) => ["string", "number", "boolean"].includes(typeof x));
683
+ const cellFor = (column, scope) => Array.isArray(column.value) && !(column.kind === "list" && primitives(column.value)) ? composeCell(column, scope) : kindCell(column, bind(column.value, scope), column.tone === void 0 ? void 0 : bind(column.tone, scope));
684
+ if (element.type === "narrative" && Array.isArray(element.props.text)) p.text = textOf(element.props.text, local, "Narrative text");
685
+ if (element.type === "reportic.heading.v1") {
686
+ p.text = textOf(element.props.text, local, "A heading");
687
+ if (!p.text.trim()) fail("INVALID_ELEMENT_PROPS", "A heading needs text.");
688
+ }
689
+ if (element.type === "reportic.footer.v1") p.text = textOf(element.props.text, local, "A footer");
690
+ if (element.type === "reportic.figure.v1" && element.props.source !== void 0) {
691
+ const source = optionalBind(element.props.source, local, element);
692
+ if (source === void 0 || source === null || source === "") delete p.source;
693
+ else p.source = source;
694
+ }
695
+ if (element.type === "reportic.grid.v1") {
696
+ if (!Array.isArray(p.columns) || !p.columns.length || p.columns.length > 50 || !Array.isArray(p.rows) || p.rows.length > 500) fail("INVALID_ELEMENT_PROPS", "A grid needs at least one column and a list of rows.");
697
+ p.columns = p.columns.map(resolveColumn);
698
+ p.cells = p.rows.map((r) => {
699
+ if (!Array.isArray(r) || r.length !== p.columns.length) fail("INVALID_ELEMENT_PROPS", "A grid row needs exactly one cell for each column.");
700
+ return r.map((spec, i) => cellFor({ ...p.columns[i], ...isRecord(spec) && own(spec, "value") && !own(spec, "$bind") ? spec : { value: spec } }, local));
701
+ });
702
+ p.rows = p.cells;
703
+ }
376
704
  if (element.type === "table") {
377
705
  if (!Array.isArray(p.rows) || !Array.isArray(p.columns) || !p.columns.length || p.rows.some((r) => !isRecord(r))) fail("INVALID_ELEMENT_PROPS", "A table requires record rows and at least one column.");
378
- p.columns = p.columns.map((c) => ({ ...bind(c, local, /* @__PURE__ */ new Set(["value"])) }));
379
- p.cells = p.rows.map((r) => p.columns.map((c) => {
380
- const raw = bind(c.value, { ...local, row: r });
381
- return { raw, text: display(raw, c.format) };
382
- }));
706
+ p.columns = p.columns.map(resolveColumn);
707
+ let extra = [];
708
+ if (p.dataColumns !== void 0) {
709
+ const dc = p.dataColumns;
710
+ if (!isRecord(dc) || dc.labels === void 0 || dc.values === void 0) fail("INVALID_ELEMENT_PROPS", "dataColumns needs labels and values.");
711
+ const labels = bind(dc.labels, local);
712
+ if (!Array.isArray(labels) || labels.length > 100 || labels.some((l) => !["string", "number"].includes(typeof l))) fail("INVALID_ELEMENT_PROPS", "dataColumns.labels must be a list of at most 100 labels.");
713
+ extra = labels.map((l) => ({ label: String(l), value: null, ...dc.align ? { align: dc.align } : {}, ...dc.format ? { format: dc.format } : {}, ...dc.kind ? { kind: dc.kind } : {} }));
714
+ }
715
+ const fixed = p.columns;
716
+ const cellsFor = (r, total) => {
717
+ const scope = { ...local, row: r };
718
+ const cells = fixed.map((c) => cellFor(c, scope));
719
+ if (extra.length) {
720
+ const values = bind(p.dataColumns.values, scope);
721
+ if (!Array.isArray(values)) fail("INVALID_ELEMENT_PROPS", "dataColumns.values must resolve to a list for every row.");
722
+ extra.forEach((c, i) => cells.push(kindCell(c, values[i] ?? null)));
723
+ }
724
+ return total ? cells.map((cell) => ({ ...cell, total: true })) : cells;
725
+ };
726
+ p.cells = p.rows.map((r) => cellsFor(r, false));
727
+ if (p.total !== void 0 && p.total !== null) {
728
+ if (!isRecord(p.total)) fail("INVALID_ELEMENT_PROPS", "A table total must be a record.");
729
+ if (p.rows.length) p.cells.push(cellsFor(p.total, true));
730
+ }
731
+ if (p.total === null) delete p.total;
732
+ p.columns = [...fixed, ...extra];
383
733
  } else if (element.type === "chart") {
384
734
  if (!Array.isArray(p.rows) || p.rows.some((r) => !isRecord(r)) || !isRecord(p.x) || !Array.isArray(p.series) || !p.series.length) fail("INVALID_ELEMENT_PROPS", "A chart requires record rows, an x axis, and numeric series.");
385
735
  p.x = bind(p.x, local, /* @__PURE__ */ new Set(["value"]));
@@ -399,16 +749,41 @@ async function prepareReportModel(template, dataSets, variables, options, regist
399
749
  });
400
750
  } else if (element.type === "list") {
401
751
  if (!Array.isArray(p.rows)) fail("INVALID_ELEMENT_PROPS", "List rows must be an array.");
402
- p.items = p.rows.map((r) => {
403
- const text = bind(p.text, { ...local, row: r });
404
- if (typeof text !== "string") fail("INVALID_ELEMENT_PROPS", "List item text must be a string.");
405
- return text;
752
+ p.items = p.rows.map((r) => textOf(p.text, { ...local, row: r }, "List item text"));
753
+ if (p.lead !== void 0) p.leads = p.rows.map((r) => {
754
+ const scope = { ...local, row: r };
755
+ if (Array.isArray(p.lead)) return composeCell({ value: p.lead }, scope).text;
756
+ const lead = optionalBind(p.lead, scope);
757
+ return lead === void 0 || lead === null ? "" : String(display(lead));
406
758
  });
407
759
  } else if (element.type === "metrics") {
408
- if (Array.isArray(p.items)) p.items = p.items.map((item) => ({ ...item, display: display(item.value, item.format) }));
760
+ const key = p.comparisonKey;
761
+ if (key !== void 0 && (typeof key !== "string" || !/^[A-Za-z0-9_-]+$/.test(key) || badKeys.has(key))) fail("INVALID_ELEMENT_PROPS", "comparisonKey must name a field of each item.");
762
+ if (Array.isArray(p.items)) p.items = p.items.map((item) => {
763
+ if (!isRecord(item)) return item;
764
+ const tile = { ...item, display: display(item.value, item.format) };
765
+ if (key !== void 0 && tile.comparison === void 0 && own(item, key) && typeof item[key] === "string" && item[key]) tile.comparison = item[key];
766
+ if (key !== void 0 && (tile.tone === "" || tile.tone === null)) delete tile.tone;
767
+ return tile;
768
+ });
769
+ } else if (element.type === "reportic.masthead.v1") {
770
+ for (const key of ["marking", "kicker", "lead"]) if (p[key] !== void 0) {
771
+ const v = optionalBind(p[key], local, element);
772
+ if (v === void 0 || v === null || v === "") delete p[key];
773
+ else p[key] = String(display(v));
774
+ }
775
+ if (Array.isArray(p.byline)) p.byline = p.byline.map((item) => ({ ...item, display: item.value === null || item.value === void 0 || item.value === "" ? "" : display(item.value, item.format ?? (item.kind === "date" ? "date" : void 0)) })).filter((item) => item.display !== "");
409
776
  }
410
777
  const errors = definition.validate(p);
411
778
  if (errors.length) fail("INVALID_ELEMENT_PROPS", `${definition.title}: ${errors.join("; ")}`);
779
+ if (element.type === "reportic.footer.v1" && p.logo !== void 0) {
780
+ const ref = assetReference(p.logo, p.logoAlt ?? "Logo", options, assets);
781
+ p = { ...p, logoImage: { src: ref.src, alt: ref.alt }, ...ref.remote ? { remote: true } : {} };
782
+ }
783
+ if (element.type === "reportic.figure.v1") {
784
+ const figure = parseFigure(p.spec);
785
+ p = { ...p, figure, alt: p.alt ?? figureAlt(figure), table: figureTable(figure, locale) };
786
+ }
412
787
  if (element.type === "image") p = { ...p, ...assetReference(p.src, p.alt, options, assets) };
413
788
  if (element.type === "diagram") {
414
789
  if (p.source !== void 0 && (p.model !== void 0 || p.adapter !== void 0)) fail("INVALID_DIAGRAM", "Use source or model and adapter, not both.");
@@ -430,8 +805,8 @@ async function prepareReportModel(template, dataSets, variables, options, regist
430
805
  if (element.type === "sources") {
431
806
  for (const source of Object.values(p.records)) if (source.url) safeUrl(source.url);
432
807
  }
433
- if (element.type === "group") node.children = p.children.map((e) => normalize(e, row));
434
- if (element.type === "repeat") node.children = p.rows.flatMap((r) => p.children.map((e) => normalize(e, r)));
808
+ if (element.type === "group") node.children = p.children.map((e) => normalize(e, row)).filter(Boolean);
809
+ if (element.type === "repeat") node.children = p.rows.flatMap((r) => p.children.map((e) => normalize(e, r))).filter(Boolean);
435
810
  if (definition.normalize) {
436
811
  const normalized = definition.normalize(p);
437
812
  node.type = normalized.type;
@@ -444,10 +819,10 @@ async function prepareReportModel(template, dataSets, variables, options, regist
444
819
  if (e instanceof ReporticError) {
445
820
  const missing = e.diagnostics.every((d) => d.code === "MISSING_REQUIRED_INPUT");
446
821
  if (missing && element.fallback !== void 0) {
447
- const text = bind(element.fallback, local);
448
- if (typeof text !== "string") throw e;
822
+ const text2 = bind(element.fallback, local);
823
+ if (typeof text2 !== "string") throw e;
449
824
  diagnostics.push({ code: "OPTIONAL_VALUE_FALLBACK", severity: "warning", phase: "prepare", message: "Using authored fallback for a missing value.", elementId: element.id });
450
- return { ...node, type: "narrative", fallbackUsed: true, props: { text } };
825
+ return { ...node, type: "narrative", fallbackUsed: true, props: { text: text2 } };
451
826
  }
452
827
  throw new ReporticError(e.diagnostics.map((d) => ({ ...d, elementId: element.id, line: element.line, occurrenceId: node.occurrenceId })));
453
828
  }
@@ -509,7 +884,8 @@ async function prepareReportModel(template, dataSets, variables, options, regist
509
884
  const element = parsed.elements.get(match[1]);
510
885
  if (element) {
511
886
  try {
512
- nodes.push(normalize(element));
887
+ const node = normalize(element);
888
+ if (node) nodes.push(node);
513
889
  } catch (e) {
514
890
  if (e instanceof ReporticError) diagnostics.push(...e.diagnostics);
515
891
  else throw e;
@@ -518,7 +894,7 @@ async function prepareReportModel(template, dataSets, variables, options, regist
518
894
  end = pattern.lastIndex;
519
895
  }
520
896
  addMarkdown(output.slice(end));
521
- const flat = (list) => list.flatMap((n) => [n, ...flat(n.children ?? [])]);
897
+ const flat = (list2) => list2.flatMap((n) => [n, ...flat(n.children ?? [])]);
522
898
  const visible = flat(nodes);
523
899
  const sources = visible.filter((n) => n.type === "sources");
524
900
  const citations = /* @__PURE__ */ new Map();
@@ -540,6 +916,10 @@ async function prepareReportModel(template, dataSets, variables, options, regist
540
916
  let title = parsed.metadata.id ?? "Untitled report";
541
917
  const heading = visible.find((n) => n.type === "markdown" && n.props.token.type === "heading" && n.props.token.depth === 1);
542
918
  if (heading) title = heading.props.token.text;
919
+ else {
920
+ const masthead = visible.find((n) => n.type === "masthead");
921
+ if (masthead) title = masthead.props.title;
922
+ }
543
923
  for (const asset of assets) {
544
924
  const snapshot = new Uint8Array(asset.bytes);
545
925
  Object.defineProperty(asset, "bytes", { enumerable: true, get: () => new Uint8Array(snapshot) });
@@ -573,13 +953,13 @@ function preflightReport(report, options) {
573
953
  import { lexer as lexer3 } from "marked";
574
954
  import { parseDocument as parseDocument2, isMap as isMap2, isAlias as isAlias2, visit as visit2, stringify } from "yaml";
575
955
  var unsafe = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
576
- var sourceFingerprint = (text) => {
956
+ var sourceFingerprint = (text2) => {
577
957
  let hash = 2166136261;
578
- for (let i = 0; i < text.length; i++) {
579
- hash ^= text.charCodeAt(i);
958
+ for (let i = 0; i < text2.length; i++) {
959
+ hash ^= text2.charCodeAt(i);
580
960
  hash = Math.imul(hash, 16777619);
581
961
  }
582
- return `${text.length.toString(36)}-${(hash >>> 0).toString(16)}`;
962
+ return `${text2.length.toString(36)}-${(hash >>> 0).toString(16)}`;
583
963
  };
584
964
  function sourceRange(source, from, to) {
585
965
  const before = source.slice(0, from);
@@ -589,8 +969,8 @@ function sourceRange(source, from, to) {
589
969
  function validBindingPath(path) {
590
970
  return /^(dataSets|variables|row)(?:\.[A-Za-z0-9_-]+)*$/.test(path) && !path.split(".").some((p) => unsafe.has(p));
591
971
  }
592
- function parseAuthoringYaml(text) {
593
- const doc = parseDocument2(text, { uniqueKeys: true, keepSourceTokens: true });
972
+ function parseAuthoringYaml(text2) {
973
+ const doc = parseDocument2(text2, { uniqueKeys: true, keepSourceTokens: true });
594
974
  if (doc.errors.length) throw new Error(doc.errors[0].message.split("\n")[0]);
595
975
  visit2(doc, (_key, node) => {
596
976
  if (isAlias2(node) || node && typeof node === "object" && ("anchor" in node && node.anchor || "tag" in node && node.tag)) throw new Error("Aliases, anchors, and custom tags are not permitted.");
@@ -651,9 +1031,9 @@ function indexSource(source) {
651
1031
  if (Object.hasOwn(v, "$bind")) {
652
1032
  const n = doc.getIn([...path, ...keys, "$bind"], true);
653
1033
  const r = n?.range ? sourceRange(source, contentStart + n.range[0], contentStart + n.range[1]) : entryRange;
654
- const binding = { path: v.$bind, slot, range: r, elementId: entry.id };
1034
+ const binding = { path: v.$bind, slot, range: r, elementId: entry.id, ...slot === "when" || Object.hasOwn(v, "default") ? { guarded: true } : {} };
655
1035
  entry.bindings.push(binding);
656
- if (typeof v.$bind !== "string" || !validBindingPath(v.$bind) || Object.keys(v).length !== 1) index.diagnostics.push({ code: "INVALID_BINDING_PATH", severity: "error", message: "Use an exact dataSets, variables, or row path without prototype keys.", elementId: entry.id, slot, range: r });
1036
+ if (typeof v.$bind !== "string" || !validBindingPath(v.$bind) || Object.keys(v).some((k) => k !== "$bind" && k !== "default")) index.diagnostics.push({ code: "INVALID_BINDING_PATH", severity: "error", message: "Use an exact dataSets, variables, or row path without prototype keys.", elementId: entry.id, slot, range: r });
657
1037
  return;
658
1038
  }
659
1039
  if (Array.isArray(v)) v.forEach((child, i) => bindings(child, [...keys, i], slot + "[" + i + "]"));
@@ -663,6 +1043,7 @@ function indexSource(source) {
663
1043
  }
664
1044
  };
665
1045
  bindings(element.props, ["props"], "props");
1046
+ if (element.when && typeof element.when === "object") bindings(element.when, ["when"], "when");
666
1047
  if (Array.isArray(element.props?.children)) element.props.children.forEach((child, i) => walk(child, [...path, "props", "children", i], entry.id));
667
1048
  };
668
1049
  walk(value, []);
@@ -681,15 +1062,15 @@ function indexSource(source) {
681
1062
  return index;
682
1063
  }
683
1064
  var serialize = (value) => JSON.stringify(value);
684
- function patchYaml(text, path, value) {
685
- const doc = parseAuthoringYaml(text), existing = doc.getIn(path, true);
1065
+ function patchYaml(text2, path, value) {
1066
+ const doc = parseAuthoringYaml(text2), existing = doc.getIn(path, true);
686
1067
  if (!doc.contents) {
687
1068
  let result = value;
688
1069
  for (let i = path.length - 1; i >= 0; i--) result = { [path[i]]: result };
689
1070
  return stringify(result);
690
1071
  }
691
1072
  if (existing?.range) {
692
- return text.slice(0, existing.range[0]) + serialize(value) + text.slice(existing.range[1]);
1073
+ return text2.slice(0, existing.range[0]) + serialize(value) + text2.slice(existing.range[1]);
693
1074
  }
694
1075
  const parent = doc.getIn(path.slice(0, -1), true);
695
1076
  const key = path[path.length - 1];
@@ -697,23 +1078,23 @@ function patchYaml(text, path, value) {
697
1078
  const pairs = parent.items;
698
1079
  const last = pairs[pairs.length - 1];
699
1080
  const firstKey = pairs[0]?.key;
700
- const indent = firstKey?.range ? firstKey.range[0] - (text.lastIndexOf("\n", firstKey.range[0] - 1) + 1) : Math.max(0, (path.length - 1) * 2);
1081
+ const indent = firstKey?.range ? firstKey.range[0] - (text2.lastIndexOf("\n", firstKey.range[0] - 1) + 1) : Math.max(0, (path.length - 1) * 2);
701
1082
  if (parent.flow) {
702
1083
  const at = parent.range[1] - 1;
703
- return text.slice(0, at) + (pairs.length ? ", " : "") + JSON.stringify(key) + ": " + serialize(value) + text.slice(at);
1084
+ return text2.slice(0, at) + (pairs.length ? ", " : "") + JSON.stringify(key) + ": " + serialize(value) + text2.slice(at);
704
1085
  }
705
1086
  const lastValue = last?.value;
706
1087
  const lastKey = last?.key;
707
- const end = lastValue?.range?.[2] ?? lastValue?.range?.[1] ?? lastKey?.range?.[2] ?? parent.range?.[1] ?? text.length;
708
- const prefix = text.slice(0, end);
709
- const suffix = text.slice(end);
1088
+ const end = lastValue?.range?.[2] ?? lastValue?.range?.[1] ?? lastKey?.range?.[2] ?? parent.range?.[1] ?? text2.length;
1089
+ const prefix = text2.slice(0, end);
1090
+ const suffix = text2.slice(end);
710
1091
  return prefix + (prefix.endsWith("\n") ? "" : "\n") + " ".repeat(indent) + key + ": " + serialize(value) + "\n" + suffix;
711
1092
  }
712
1093
  let ancestor = path.length - 1;
713
1094
  while (ancestor > 0 && !doc.getIn(path.slice(0, ancestor), true)) ancestor--;
714
1095
  let nested = value;
715
1096
  for (let i = path.length - 1; i > ancestor; i--) nested = { [path[i]]: nested };
716
- return patchYaml(text, path.slice(0, ancestor + 1), nested);
1097
+ return patchYaml(text2, path.slice(0, ancestor + 1), nested);
717
1098
  }
718
1099
  function editElementProperty(source, elementId, path, value, expectedFingerprint = sourceFingerprint(source)) {
719
1100
  if (sourceFingerprint(source) !== expectedFingerprint) throw new Error("STALE_SOURCE: The source changed. Reload this form before applying it.");
@@ -728,14 +1109,14 @@ function declareDataset(source, alias, schemaRef, required) {
728
1109
  if (!/^[A-Za-z_][\w]*$/.test(alias) || unsafe.has(alias)) throw new Error("Use an identifier-style local dataset name.");
729
1110
  const index = indexSource(source);
730
1111
  if (index.metadataRange) {
731
- let text = source.slice(index.metadataRange.from, index.metadataRange.to);
732
- if (!index.metadata.reportic) text = patchYaml(text, ["reportic"], "0.2");
1112
+ let text2 = source.slice(index.metadataRange.from, index.metadataRange.to);
1113
+ if (!index.metadata.reportic) text2 = patchYaml(text2, ["reportic"], "0.2");
733
1114
  const existing = index.metadata.dataSets?.[alias];
734
1115
  if (existing && typeof existing === "object") {
735
- text = patchYaml(text, ["dataSets", alias, "schema"], schemaRef);
736
- if (required !== void 0) text = patchYaml(text, ["dataSets", alias, "required"], required);
737
- } else text = patchYaml(text, ["dataSets", alias], { schema: schemaRef, ...required === false ? { required: false } : {} });
738
- return source.slice(0, index.metadataRange.from) + text + source.slice(index.metadataRange.to);
1116
+ text2 = patchYaml(text2, ["dataSets", alias, "schema"], schemaRef);
1117
+ if (required !== void 0) text2 = patchYaml(text2, ["dataSets", alias, "required"], required);
1118
+ } else text2 = patchYaml(text2, ["dataSets", alias], { schema: schemaRef, ...required === false ? { required: false } : {} });
1119
+ return source.slice(0, index.metadataRange.from) + text2 + source.slice(index.metadataRange.to);
739
1120
  }
740
1121
  return "---\n" + stringify({ reportic: "0.2", dataSets: { [alias]: { schema: schemaRef, ...required === false ? { required: false } : {} } } }) + "---\n\n" + source;
741
1122
  }
@@ -759,8 +1140,8 @@ function replaceElement(source, elementId, value, expectedFingerprint = sourceFi
759
1140
  const content = patchYaml(source.slice(block.contentRange.from, block.contentRange.to), entry.yamlPath, value);
760
1141
  return source.slice(0, block.contentRange.from) + content + source.slice(block.contentRange.to);
761
1142
  }
762
- const text = stringify(value, { lineWidth: 100 }).trimEnd();
763
- return source.slice(0, entry.contentRange.from) + text + source.slice(entry.contentRange.to);
1143
+ const text2 = stringify(value, { lineWidth: 100 }).trimEnd();
1144
+ return source.slice(0, entry.contentRange.from) + text2 + source.slice(entry.contentRange.to);
764
1145
  }
765
1146
  function insertElement(source, value, at = source.length) {
766
1147
  const originalLength = source.length;
@@ -821,7 +1202,9 @@ function inferBindingSlots(schema, rowScopes = []) {
821
1202
  function getBindingSlot(definition, path, props) {
822
1203
  const slot = (definition.bindingSlots ?? inferBindingSlots(definition.schema, definition.rowScopes)).find((s) => s.path === path.replace(/\[\d+\]/g, "[]"));
823
1204
  if (slot?.expectedBy && props) {
824
- const key = slot.expectedBy.property.replace(/^props\./, "").split(".").reduce((value, key2) => value?.[key2], props);
1205
+ const indexes = [...path.matchAll(/\[(\d+)\]/g)].map((m) => m[1]);
1206
+ let next = 0;
1207
+ const key = slot.expectedBy.property.replace(/^props\./, "").replace(/\[\]/g, () => "." + (indexes[next++] ?? "0")).split(".").filter(Boolean).reduce((value, key2) => value?.[key2], props);
825
1208
  return { ...slot, expected: slot.expectedBy.values[String(key)] ?? slot.expected };
826
1209
  }
827
1210
  return slot;
@@ -845,6 +1228,11 @@ export {
845
1228
  escapeHtml,
846
1229
  escapeMd,
847
1230
  fail,
1231
+ figureAlt,
1232
+ figureKinds,
1233
+ figureSpec,
1234
+ figureTable,
1235
+ figureTones,
848
1236
  flowchartSource,
849
1237
  formatValue,
850
1238
  getBindingSlot,
@@ -857,6 +1245,7 @@ export {
857
1245
  officeColor,
858
1246
  own,
859
1247
  parseAuthoringYaml,
1248
+ parseFigure,
860
1249
  parseTemplate,
861
1250
  preflightReport,
862
1251
  prepareReportModel,
@@ -866,10 +1255,13 @@ export {
866
1255
  safeRelative,
867
1256
  safeUrl,
868
1257
  safeYaml,
1258
+ semanticColors,
869
1259
  semanticRule,
870
1260
  sourceFingerprint,
871
1261
  sourceRange,
1262
+ statusTone,
872
1263
  themeTokens,
1264
+ tones,
873
1265
  validBindingPath,
874
1266
  validateStyles,
875
1267
  walkNodes