buntic 0.3.1 → 0.4.0

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/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  // src/cli.ts
5
5
  import { existsSync as existsSync22, rmSync as rmSync4 } from "fs";
6
- import { relative as relative10 } from "path";
6
+ import { relative as relative11 } from "path";
7
7
 
8
8
  // src/config.ts
9
9
  import { resolve as resolve2, join as join2, dirname as dirname2, basename } from "path";
@@ -234,7 +234,7 @@ async function resolveConfig(cliRootDir = ".", overrides = {}) {
234
234
 
235
235
  // src/builder/builder.ts
236
236
  import { cpSync as cpSync2, existsSync as existsSync18, mkdirSync as mkdirSync3, rmSync as rmSync3 } from "fs";
237
- import { dirname as dirname9, join as join17, relative as relative9 } from "path";
237
+ import { dirname as dirname9, join as join17, relative as relative10 } from "path";
238
238
 
239
239
  // src/assets/photo-tag.ts
240
240
  import { existsSync as existsSync6, statSync as statSync4 } from "fs";
@@ -1484,7 +1484,184 @@ ${urlsXml.join(`
1484
1484
 
1485
1485
  // src/template/engine.ts
1486
1486
  import { existsSync as existsSync16 } from "fs";
1487
- import { extname as extname4, relative as relative7 } from "path";
1487
+ import { extname as extname4, relative as relative8 } from "path";
1488
+
1489
+ // src/template/block-scanner.ts
1490
+ function isTagNameChar(ch) {
1491
+ const code = ch.charCodeAt(0);
1492
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95;
1493
+ }
1494
+ function isAsciiLetter(ch) {
1495
+ const code = ch.charCodeAt(0);
1496
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
1497
+ }
1498
+ function findTagClose(html, start) {
1499
+ const len = html.length;
1500
+ let quote = null;
1501
+ for (let i = start;i < len; i++) {
1502
+ const ch = html[i];
1503
+ if (quote) {
1504
+ if (ch === quote) {
1505
+ quote = null;
1506
+ }
1507
+ continue;
1508
+ }
1509
+ if (ch === '"' || ch === "'") {
1510
+ quote = ch;
1511
+ } else if (ch === ">") {
1512
+ return i;
1513
+ }
1514
+ }
1515
+ return -1;
1516
+ }
1517
+ function skipRawElement(html, start, tagName) {
1518
+ const openEnd = findTagClose(html, start + 1 + tagName.length);
1519
+ if (openEnd === -1)
1520
+ return html.length;
1521
+ const closePattern = new RegExp(`<\\/${tagName}\\s*>`, "i");
1522
+ const rest = html.slice(openEnd + 1);
1523
+ const closeMatch = closePattern.exec(rest);
1524
+ if (!closeMatch)
1525
+ return html.length;
1526
+ return openEnd + 1 + closeMatch.index + closeMatch[0].length;
1527
+ }
1528
+ function scanBlocks(html, targetTags, nestedScopeTags) {
1529
+ const results = [];
1530
+ const stack = [];
1531
+ const len = html.length;
1532
+ let i = 0;
1533
+ while (i < len) {
1534
+ const lt = html.indexOf("<", i);
1535
+ if (lt === -1)
1536
+ break;
1537
+ i = lt;
1538
+ if (html.startsWith("<!--", i)) {
1539
+ const commentEnd = html.indexOf("-->", i + 4);
1540
+ i = commentEnd === -1 ? len : commentEnd + 3;
1541
+ continue;
1542
+ }
1543
+ if (html[i + 1] === "!" || html[i + 1] === "?") {
1544
+ const closeIdx = html.indexOf(">", i + 2);
1545
+ i = closeIdx === -1 ? len : closeIdx + 1;
1546
+ continue;
1547
+ }
1548
+ if (html[i + 1] === "/") {
1549
+ let j = i + 2;
1550
+ if (j < len && isAsciiLetter(html[j])) {
1551
+ const nameStart = j;
1552
+ while (j < len && isTagNameChar(html[j]))
1553
+ j++;
1554
+ const closeTag = html.slice(nameStart, j).toLowerCase();
1555
+ while (j < len && /\s/.test(html[j]))
1556
+ j++;
1557
+ if (j < len && html[j] === ">") {
1558
+ if (stack.length > 0 && stack[stack.length - 1].tag === closeTag) {
1559
+ const frame = stack.pop();
1560
+ if (stack.length === 0 && frame.isTarget) {
1561
+ const end = j + 1;
1562
+ results.push({
1563
+ tag: frame.tag,
1564
+ fullMatch: html.slice(frame.start, end),
1565
+ openTag: frame.openTag,
1566
+ attrString: frame.attrString,
1567
+ inner: html.slice(frame.openTagEnd, i),
1568
+ start: frame.start,
1569
+ end
1570
+ });
1571
+ }
1572
+ }
1573
+ i = j + 1;
1574
+ continue;
1575
+ }
1576
+ }
1577
+ i += 2;
1578
+ continue;
1579
+ }
1580
+ if (i + 1 < len && isAsciiLetter(html[i + 1])) {
1581
+ let j = i + 1;
1582
+ const nameStart = j;
1583
+ while (j < len && isTagNameChar(html[j]))
1584
+ j++;
1585
+ const openTagName = html.slice(nameStart, j).toLowerCase();
1586
+ if (j < len && !/[\s>/]/.test(html[j])) {
1587
+ i = j;
1588
+ continue;
1589
+ }
1590
+ if (openTagName === "script" || openTagName === "style") {
1591
+ i = skipRawElement(html, i, openTagName);
1592
+ continue;
1593
+ }
1594
+ const closeIdx = findTagClose(html, j);
1595
+ if (closeIdx === -1) {
1596
+ i = j;
1597
+ continue;
1598
+ }
1599
+ const rawAttrs = html.slice(j, closeIdx);
1600
+ const trimmedAttrs = rawAttrs.trimEnd();
1601
+ const isSelfClosing = trimmedAttrs.endsWith("/");
1602
+ const attrString = isSelfClosing ? trimmedAttrs.slice(0, -1).trim() : rawAttrs.trim();
1603
+ if (!isSelfClosing) {
1604
+ if (stack.length === 0) {
1605
+ if (targetTags.has(openTagName)) {
1606
+ stack.push({
1607
+ tag: openTagName,
1608
+ isTarget: true,
1609
+ start: i,
1610
+ openTagEnd: closeIdx + 1,
1611
+ openTag: html.slice(i, closeIdx + 1),
1612
+ attrString
1613
+ });
1614
+ } else if (nestedScopeTags.has(openTagName)) {
1615
+ stack.push({
1616
+ tag: openTagName,
1617
+ isTarget: false,
1618
+ start: i,
1619
+ openTagEnd: closeIdx + 1,
1620
+ openTag: html.slice(i, closeIdx + 1),
1621
+ attrString
1622
+ });
1623
+ }
1624
+ } else {
1625
+ const topTag = stack[stack.length - 1].tag;
1626
+ if (openTagName === topTag || nestedScopeTags.has(openTagName)) {
1627
+ stack.push({
1628
+ tag: openTagName,
1629
+ isTarget: false,
1630
+ start: i,
1631
+ openTagEnd: closeIdx + 1,
1632
+ openTag: html.slice(i, closeIdx + 1),
1633
+ attrString
1634
+ });
1635
+ }
1636
+ }
1637
+ }
1638
+ i = closeIdx + 1;
1639
+ continue;
1640
+ }
1641
+ i++;
1642
+ }
1643
+ return results;
1644
+ }
1645
+ function findTopLevelBlocks(html, tagNames) {
1646
+ const targetSet = new Set(tagNames.map((t) => t.toLowerCase()));
1647
+ return scanBlocks(html, targetSet, targetSet);
1648
+ }
1649
+ function splitDirectSubBlocks(inner, allowedTags, nestedScopeTags) {
1650
+ const targetSet = new Set(allowedTags.map((t) => t.toLowerCase()));
1651
+ const scopeSet = new Set(nestedScopeTags.map((t) => t.toLowerCase()));
1652
+ const subBlocks = scanBlocks(inner, targetSet, scopeSet);
1653
+ if (subBlocks.length === 0) {
1654
+ return { body: inner, subBlocks: [] };
1655
+ }
1656
+ let body = "";
1657
+ let cursor = 0;
1658
+ for (const block of subBlocks) {
1659
+ body += inner.slice(cursor, block.start);
1660
+ cursor = block.end;
1661
+ }
1662
+ body += inner.slice(cursor);
1663
+ return { body, subBlocks };
1664
+ }
1488
1665
 
1489
1666
  // src/template/css-graph.ts
1490
1667
  import { basename as basename4, dirname as dirname6, resolve as resolve4, relative as relative3, join as join11 } from "path";
@@ -2464,6 +2641,157 @@ function loadPublicEnv(projectRoot) {
2464
2641
  return publicEnv;
2465
2642
  }
2466
2643
 
2644
+ // src/template/errors.ts
2645
+ import { relative as relative5 } from "path";
2646
+ function formatTemplatePath(filePath, projectRoot) {
2647
+ if (!filePath)
2648
+ return "";
2649
+ if (projectRoot) {
2650
+ const rel = relative5(projectRoot, filePath).replace(/\\/g, "/");
2651
+ if (rel && !rel.startsWith("..")) {
2652
+ return rel;
2653
+ }
2654
+ }
2655
+ return filePath.replace(/\\/g, "/");
2656
+ }
2657
+ function offsetToLineColumn(source, offset) {
2658
+ const clamped = Math.max(0, Math.min(offset, source.length));
2659
+ let line = 1;
2660
+ let lastNewline = -1;
2661
+ for (let i = 0;i < clamped; i++) {
2662
+ if (source.charCodeAt(i) === 10) {
2663
+ line++;
2664
+ lastNewline = i;
2665
+ }
2666
+ }
2667
+ return {
2668
+ line,
2669
+ column: clamped - lastNewline
2670
+ };
2671
+ }
2672
+ function formatCodeFrame(source, line, column = 1, endColumn, contextLines = 2) {
2673
+ const lines = source.split(/\r?\n/);
2674
+ if (lines.length === 0)
2675
+ return "";
2676
+ const targetLine = Math.max(1, Math.min(line, lines.length));
2677
+ const startLine = Math.max(1, targetLine - contextLines);
2678
+ const endLine = Math.min(lines.length, targetLine + contextLines);
2679
+ const gutterWidth = String(endLine).length;
2680
+ const output = [];
2681
+ for (let i = startLine;i <= endLine; i++) {
2682
+ const lineText = lines[i - 1] ?? "";
2683
+ const marker = i === targetLine ? ">" : " ";
2684
+ const numStr = String(i).padStart(gutterWidth, " ");
2685
+ output.push(` ${marker} ${numStr} | ${lineText}`);
2686
+ if (i === targetLine) {
2687
+ const colStart = Math.max(1, column);
2688
+ const rawPrefix = lineText.slice(0, colStart - 1);
2689
+ const caretPrefix = rawPrefix.replace(/[^\t]/g, " ");
2690
+ const maxRemaining = Math.max(1, lineText.length - (colStart - 1));
2691
+ const requestedSpan = endColumn && endColumn > colStart ? endColumn - colStart : 1;
2692
+ const caretCount = Math.max(1, Math.min(requestedSpan, maxRemaining));
2693
+ const blankNum = " ".repeat(gutterWidth);
2694
+ output.push(` ${blankNum} | ${caretPrefix}${"^".repeat(caretCount)}`);
2695
+ }
2696
+ }
2697
+ return output.join(`
2698
+ `);
2699
+ }
2700
+ function findSnippetLocation(options) {
2701
+ const { source, snippet, openTag, fallbackHtml, fallbackOffset, filePath } = options;
2702
+ const highlightTarget = openTag || snippet;
2703
+ const firstLineLength = Math.max(1, highlightTarget.split(/\r?\n/)[0].length);
2704
+ if (source) {
2705
+ let idx = snippet ? source.indexOf(snippet) : -1;
2706
+ if (idx === -1 && openTag) {
2707
+ idx = source.indexOf(openTag);
2708
+ }
2709
+ if (idx !== -1) {
2710
+ const { line, column } = offsetToLineColumn(source, idx);
2711
+ return {
2712
+ filePath,
2713
+ line,
2714
+ column,
2715
+ endColumn: column + firstLineLength,
2716
+ source
2717
+ };
2718
+ }
2719
+ }
2720
+ if (fallbackHtml) {
2721
+ let idx = fallbackOffset !== undefined && fallbackOffset >= 0 ? fallbackOffset : snippet ? fallbackHtml.indexOf(snippet) : -1;
2722
+ if (idx === -1 && openTag) {
2723
+ idx = fallbackHtml.indexOf(openTag);
2724
+ }
2725
+ if (idx !== -1) {
2726
+ const { line, column } = offsetToLineColumn(fallbackHtml, idx);
2727
+ return {
2728
+ filePath,
2729
+ line,
2730
+ column,
2731
+ endColumn: column + firstLineLength,
2732
+ source: fallbackHtml
2733
+ };
2734
+ }
2735
+ }
2736
+ return { filePath };
2737
+ }
2738
+
2739
+ class BunticTemplateError extends Error {
2740
+ summary;
2741
+ filePath;
2742
+ line;
2743
+ column;
2744
+ endColumn;
2745
+ codeFrame;
2746
+ resolvedTarget;
2747
+ causeMessage;
2748
+ hint;
2749
+ constructor(options) {
2750
+ const { message, location, projectRoot, resolvedTarget, hint, cause } = options;
2751
+ const displayFile = location?.filePath ? formatTemplatePath(location.filePath, projectRoot) : undefined;
2752
+ const displayResolved = resolvedTarget ? formatTemplatePath(resolvedTarget, projectRoot) : undefined;
2753
+ const causeMsg = cause !== undefined ? getErrorMessage(cause) : undefined;
2754
+ const codeFrame = location?.source && location.line ? formatCodeFrame(location.source, location.line, location.column, location.endColumn) : undefined;
2755
+ const parts = [message];
2756
+ if (displayFile) {
2757
+ const coords = location?.line ? `:${location.line}${location.column ? `:${location.column}` : ""}` : "";
2758
+ parts.push(` File: ${displayFile}${coords}`);
2759
+ } else if (location?.line) {
2760
+ const colPart = location.column ? `, column ${location.column}` : "";
2761
+ parts.push(` Location: line ${location.line}${colPart}`);
2762
+ }
2763
+ if (displayResolved) {
2764
+ parts.push(` Resolved: ${displayResolved}`);
2765
+ }
2766
+ if (causeMsg) {
2767
+ parts.push(` Cause: ${causeMsg}`);
2768
+ }
2769
+ if (codeFrame) {
2770
+ parts.push("");
2771
+ parts.push(codeFrame);
2772
+ }
2773
+ if (hint) {
2774
+ const formattedHint = hint.split(`
2775
+ `).join(`
2776
+ `);
2777
+ parts.push("");
2778
+ parts.push(` Hint: ${formattedHint}`);
2779
+ }
2780
+ super(parts.join(`
2781
+ `));
2782
+ this.name = "BunticTemplateError";
2783
+ this.summary = message;
2784
+ this.filePath = displayFile;
2785
+ this.line = location?.line;
2786
+ this.column = location?.column;
2787
+ this.endColumn = location?.endColumn;
2788
+ this.codeFrame = codeFrame;
2789
+ this.resolvedTarget = displayResolved;
2790
+ this.causeMessage = causeMsg;
2791
+ this.hint = hint;
2792
+ }
2793
+ }
2794
+
2467
2795
  // src/template/data-loader.ts
2468
2796
  async function loadGlobalData(config, vfs) {
2469
2797
  const data = {};
@@ -2497,8 +2825,15 @@ async function loadGlobalData(config, vfs) {
2497
2825
  if (isJson) {
2498
2826
  try {
2499
2827
  data[key] = await vfs.readJson(fullPath);
2500
- } catch {
2501
- data[key] = await Bun.file(fullPath).json();
2828
+ } catch (err) {
2829
+ const relPath = formatTemplatePath(fullPath, config.root);
2830
+ throw new BunticTemplateError({
2831
+ message: `[Buntic Error] Failed to parse global JSON data file "${relPath}"`,
2832
+ location: { filePath: fullPath },
2833
+ projectRoot: config.root,
2834
+ cause: err,
2835
+ hint: `Check that "${relPath}" contains valid JSON syntax.`
2836
+ });
2502
2837
  }
2503
2838
  } else if (isModule) {
2504
2839
  try {
@@ -2518,20 +2853,30 @@ async function loadGlobalData(config, vfs) {
2518
2853
  }
2519
2854
  }
2520
2855
  } catch (err) {
2521
- if (err instanceof Error && err.message.includes("[Buntic Error]")) {
2856
+ if (err instanceof BunticTemplateError || err instanceof Error && err.message.includes("[Buntic Error]")) {
2522
2857
  throw err;
2523
2858
  }
2524
2859
  }
2525
2860
  return data;
2526
2861
  }
2527
2862
 
2528
- // src/template/directives.ts
2863
+ // src/template/expressions.ts
2864
+ var FORBIDDEN_PATH_KEYS = new Set(["__proto__", "constructor", "prototype"]);
2865
+
2866
+ class ExpressionSyntaxError extends Error {
2867
+ hint;
2868
+ constructor(message, hint) {
2869
+ super(message);
2870
+ this.name = "ExpressionSyntaxError";
2871
+ this.hint = hint;
2872
+ }
2873
+ }
2529
2874
  function isTruthy(val) {
2530
2875
  if (val === undefined || val === null || val === false || val === "")
2531
2876
  return false;
2532
2877
  if (Array.isArray(val) && val.length === 0)
2533
2878
  return false;
2534
- if (typeof val === "number" && isNaN(val))
2879
+ if (typeof val === "number" && Number.isNaN(val))
2535
2880
  return false;
2536
2881
  return true;
2537
2882
  }
@@ -2541,36 +2886,602 @@ function getNestedValue(obj, path) {
2541
2886
  const parts = path.split(".");
2542
2887
  let cur = obj;
2543
2888
  for (const part of parts) {
2544
- if (cur == null || typeof cur !== "object")
2889
+ if (!part || FORBIDDEN_PATH_KEYS.has(part))
2890
+ return;
2891
+ if (cur == null)
2892
+ return;
2893
+ if (typeof cur === "string") {
2894
+ if (part === "length") {
2895
+ cur = cur.length;
2896
+ continue;
2897
+ }
2898
+ return;
2899
+ }
2900
+ if (typeof cur !== "object")
2545
2901
  return;
2902
+ if (Array.isArray(cur)) {
2903
+ if (part === "length") {
2904
+ cur = cur.length;
2905
+ continue;
2906
+ }
2907
+ if (Object.prototype.hasOwnProperty.call(cur, part)) {
2908
+ cur = cur[part];
2909
+ continue;
2910
+ }
2911
+ return;
2912
+ }
2913
+ if (!Object.prototype.hasOwnProperty.call(cur, part)) {
2914
+ return;
2915
+ }
2546
2916
  cur = cur[part];
2547
2917
  }
2548
2918
  return cur;
2549
2919
  }
2550
- function resolveConditionals(html, context) {
2551
- let res = html.replace(/<if\s+is=["']([^"']+)["'][^>]*>([\s\S]*?)<\/if>/gi, (_match, expr, inner) => {
2552
- const val = getNestedValue(context, expr.trim());
2553
- let thenContent = inner;
2554
- let elseContent = "";
2555
- const elseMatch = inner.match(/([\s\S]*?)<else>([\s\S]*?)<\/else>/i);
2556
- if (elseMatch) {
2557
- thenContent = elseMatch[1];
2558
- elseContent = elseMatch[2];
2559
- }
2560
- return isTruthy(val) ? thenContent.trim() : elseContent.trim();
2920
+ function tokenize(input) {
2921
+ const tokens = [];
2922
+ let i = 0;
2923
+ const len = input.length;
2924
+ while (i < len) {
2925
+ const ch = input[i];
2926
+ if (/\s/.test(ch)) {
2927
+ i++;
2928
+ continue;
2929
+ }
2930
+ if (ch === "{" && input[i + 1] === "{") {
2931
+ throw new ExpressionSyntaxError(`Unexpected "{{" in expression "${input}".`, `Do not wrap expressions in "{{ }}" inside is="...". Write the expression directly, e.g. is="age >= 18".`);
2932
+ }
2933
+ if (ch === "(") {
2934
+ tokens.push({ type: "lparen", value: "(", pos: i });
2935
+ i++;
2936
+ continue;
2937
+ }
2938
+ if (ch === ")") {
2939
+ tokens.push({ type: "rparen", value: ")", pos: i });
2940
+ i++;
2941
+ continue;
2942
+ }
2943
+ const three = input.slice(i, i + 3);
2944
+ if (three === "===" || three === "!==") {
2945
+ tokens.push({ type: "op", value: three, pos: i });
2946
+ i += 3;
2947
+ continue;
2948
+ }
2949
+ const two = input.slice(i, i + 2);
2950
+ if (two === "==" || two === "!=" || two === "<=" || two === ">=" || two === "&&" || two === "||") {
2951
+ tokens.push({ type: "op", value: two, pos: i });
2952
+ i += 2;
2953
+ continue;
2954
+ }
2955
+ if (ch === "=") {
2956
+ throw new ExpressionSyntaxError(`Unexpected assignment operator "=" at position ${i + 1} in expression "${input}".`, `Use "==" or "===" to compare values.`);
2957
+ }
2958
+ if (ch === "&" || ch === "|") {
2959
+ throw new ExpressionSyntaxError(`Unexpected operator "${ch}" at position ${i + 1} in expression "${input}".`, `Use "${ch}${ch}" for logical ${ch === "&" ? "AND" : "OR"}.`);
2960
+ }
2961
+ if (ch === "<" || ch === ">" || ch === "!" || ch === "-") {
2962
+ tokens.push({ type: "op", value: ch, pos: i });
2963
+ i++;
2964
+ continue;
2965
+ }
2966
+ if (ch === "'" || ch === '"') {
2967
+ const quote = ch;
2968
+ const start = i;
2969
+ i++;
2970
+ let str = "";
2971
+ let closed = false;
2972
+ while (i < len) {
2973
+ const c = input[i];
2974
+ if (c === "\\" && i + 1 < len) {
2975
+ const next = input[i + 1];
2976
+ if (next === "n")
2977
+ str += `
2978
+ `;
2979
+ else if (next === "t")
2980
+ str += "\t";
2981
+ else if (next === "r")
2982
+ str += "\r";
2983
+ else
2984
+ str += next;
2985
+ i += 2;
2986
+ continue;
2987
+ }
2988
+ if (c === quote) {
2989
+ closed = true;
2990
+ i++;
2991
+ break;
2992
+ }
2993
+ str += c;
2994
+ i++;
2995
+ }
2996
+ if (!closed) {
2997
+ throw new ExpressionSyntaxError(`Unterminated string literal starting at position ${start + 1} in expression "${input}".`);
2998
+ }
2999
+ tokens.push({ type: "string", value: str, pos: start });
3000
+ continue;
3001
+ }
3002
+ if (/[0-9]/.test(ch)) {
3003
+ const start = i;
3004
+ let hasDot = false;
3005
+ while (i < len) {
3006
+ const c = input[i];
3007
+ if (/[0-9]/.test(c)) {
3008
+ i++;
3009
+ } else if (c === "." && !hasDot && i + 1 < len && /[0-9]/.test(input[i + 1])) {
3010
+ hasDot = true;
3011
+ i++;
3012
+ } else {
3013
+ break;
3014
+ }
3015
+ }
3016
+ const raw = input.slice(start, i);
3017
+ tokens.push({ type: "number", value: raw, numValue: Number(raw), pos: start });
3018
+ continue;
3019
+ }
3020
+ if (/[a-zA-Z_$]/.test(ch)) {
3021
+ const start = i;
3022
+ while (i < len && /[a-zA-Z0-9_$.]/.test(input[i])) {
3023
+ i++;
3024
+ }
3025
+ const raw = input.slice(start, i);
3026
+ if (raw.startsWith(".") || raw.endsWith(".") || raw.includes("..")) {
3027
+ throw new ExpressionSyntaxError(`Invalid property path "${raw}" in expression "${input}".`);
3028
+ }
3029
+ if (raw === "true" || raw === "false") {
3030
+ tokens.push({ type: "boolean", value: raw, boolValue: raw === "true", pos: start });
3031
+ } else if (raw === "null") {
3032
+ tokens.push({ type: "null", value: raw, pos: start });
3033
+ } else if (raw === "undefined") {
3034
+ tokens.push({ type: "undefined", value: raw, pos: start });
3035
+ } else {
3036
+ tokens.push({ type: "path", value: raw, pos: start });
3037
+ }
3038
+ continue;
3039
+ }
3040
+ throw new ExpressionSyntaxError(`Unexpected character "${ch}" at position ${i + 1} in expression "${input}".`);
3041
+ }
3042
+ tokens.push({ type: "eof", value: "", pos: len });
3043
+ return tokens;
3044
+ }
3045
+
3046
+ class ExpressionParser {
3047
+ tokens;
3048
+ pos = 0;
3049
+ rawInput;
3050
+ constructor(tokens, rawInput) {
3051
+ this.tokens = tokens;
3052
+ this.rawInput = rawInput;
3053
+ }
3054
+ peek() {
3055
+ return this.tokens[this.pos];
3056
+ }
3057
+ consume() {
3058
+ return this.tokens[this.pos++];
3059
+ }
3060
+ parse() {
3061
+ const node = this.parseOr();
3062
+ const trailing = this.peek();
3063
+ if (trailing.type !== "eof") {
3064
+ throw new ExpressionSyntaxError(`Unexpected token "${trailing.value}" at position ${trailing.pos + 1} in expression "${this.rawInput}".`);
3065
+ }
3066
+ return node;
3067
+ }
3068
+ parseOr() {
3069
+ let left = this.parseAnd();
3070
+ while (this.peek().type === "op" && this.peek().value === "||") {
3071
+ this.consume();
3072
+ const right = this.parseAnd();
3073
+ left = { kind: "binary", op: "||", left, right };
3074
+ }
3075
+ return left;
3076
+ }
3077
+ parseAnd() {
3078
+ let left = this.parseEquality();
3079
+ while (this.peek().type === "op" && this.peek().value === "&&") {
3080
+ this.consume();
3081
+ const right = this.parseEquality();
3082
+ left = { kind: "binary", op: "&&", left, right };
3083
+ }
3084
+ return left;
3085
+ }
3086
+ parseEquality() {
3087
+ let left = this.parseRelational();
3088
+ while (this.peek().type === "op" && (this.peek().value === "===" || this.peek().value === "!==" || this.peek().value === "==" || this.peek().value === "!=")) {
3089
+ const op = this.consume().value;
3090
+ const right = this.parseRelational();
3091
+ left = { kind: "binary", op, left, right };
3092
+ }
3093
+ return left;
3094
+ }
3095
+ parseRelational() {
3096
+ let left = this.parseUnary();
3097
+ while (this.peek().type === "op" && (this.peek().value === "<" || this.peek().value === "<=" || this.peek().value === ">" || this.peek().value === ">=")) {
3098
+ const op = this.consume().value;
3099
+ const right = this.parseUnary();
3100
+ left = { kind: "binary", op, left, right };
3101
+ }
3102
+ return left;
3103
+ }
3104
+ parseUnary() {
3105
+ const tok = this.peek();
3106
+ if (tok.type === "op" && (tok.value === "!" || tok.value === "-")) {
3107
+ this.consume();
3108
+ const operand = this.parseUnary();
3109
+ return { kind: "unary", op: tok.value, operand };
3110
+ }
3111
+ return this.parsePrimary();
3112
+ }
3113
+ parsePrimary() {
3114
+ const tok = this.peek();
3115
+ if (tok.type === "number") {
3116
+ this.consume();
3117
+ return { kind: "literal", value: tok.numValue };
3118
+ }
3119
+ if (tok.type === "string") {
3120
+ this.consume();
3121
+ return { kind: "literal", value: tok.value };
3122
+ }
3123
+ if (tok.type === "boolean") {
3124
+ this.consume();
3125
+ return { kind: "literal", value: tok.boolValue };
3126
+ }
3127
+ if (tok.type === "null") {
3128
+ this.consume();
3129
+ return { kind: "literal", value: null };
3130
+ }
3131
+ if (tok.type === "undefined") {
3132
+ this.consume();
3133
+ return { kind: "literal", value: undefined };
3134
+ }
3135
+ if (tok.type === "path") {
3136
+ this.consume();
3137
+ return { kind: "path", path: tok.value };
3138
+ }
3139
+ if (tok.type === "lparen") {
3140
+ this.consume();
3141
+ const inner = this.parseOr();
3142
+ if (this.peek().type !== "rparen") {
3143
+ throw new ExpressionSyntaxError(`Expected closing ")" in expression "${this.rawInput}".`);
3144
+ }
3145
+ this.consume();
3146
+ return inner;
3147
+ }
3148
+ throw new ExpressionSyntaxError(`Unexpected ${tok.type === "eof" ? "end of expression" : `token "${tok.value}"`} in expression "${this.rawInput}".`);
3149
+ }
3150
+ }
3151
+ function evalAst(node, context) {
3152
+ switch (node.kind) {
3153
+ case "literal":
3154
+ return node.value;
3155
+ case "path":
3156
+ return getNestedValue(context, node.path);
3157
+ case "unary": {
3158
+ const operand = evalAst(node.operand, context);
3159
+ if (node.op === "!") {
3160
+ return !isTruthy(operand);
3161
+ }
3162
+ return -Number(operand);
3163
+ }
3164
+ case "binary": {
3165
+ if (node.op === "||") {
3166
+ const left = evalAst(node.left, context);
3167
+ return isTruthy(left) ? left : evalAst(node.right, context);
3168
+ }
3169
+ if (node.op === "&&") {
3170
+ const left = evalAst(node.left, context);
3171
+ return isTruthy(left) ? evalAst(node.right, context) : left;
3172
+ }
3173
+ const left = evalAst(node.left, context);
3174
+ const right = evalAst(node.right, context);
3175
+ switch (node.op) {
3176
+ case "===":
3177
+ return left === right;
3178
+ case "!==":
3179
+ return left !== right;
3180
+ case "==":
3181
+ return left == right;
3182
+ case "!=":
3183
+ return left != right;
3184
+ case "<":
3185
+ return left < right;
3186
+ case "<=":
3187
+ return left <= right;
3188
+ case ">":
3189
+ return left > right;
3190
+ case ">=":
3191
+ return left >= right;
3192
+ default:
3193
+ return false;
3194
+ }
3195
+ }
3196
+ }
3197
+ }
3198
+ function evaluateExpression(expr, context) {
3199
+ const trimmed = expr.trim();
3200
+ if (!trimmed) {
3201
+ throw new ExpressionSyntaxError("Condition expression cannot be empty.");
3202
+ }
3203
+ const tokens = tokenize(trimmed);
3204
+ const parser = new ExpressionParser(tokens, trimmed);
3205
+ const ast = parser.parse();
3206
+ return evalAst(ast, context);
3207
+ }
3208
+
3209
+ // src/template/directives.ts
3210
+ var NESTED_DIRECTIVE_SCOPES = ["if", "unless", "match", "each"];
3211
+ function buildError(options) {
3212
+ const { message, hint, cause, snippet, openTag, fallbackHtml, fallbackOffset, diag } = options;
3213
+ const location = findSnippetLocation({
3214
+ source: diag?.source,
3215
+ snippet,
3216
+ openTag,
3217
+ fallbackHtml,
3218
+ fallbackOffset,
3219
+ filePath: diag?.filePath
3220
+ });
3221
+ return new BunticTemplateError({
3222
+ message,
3223
+ location,
3224
+ projectRoot: diag?.projectRoot,
3225
+ cause,
3226
+ hint
2561
3227
  });
2562
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)\s*\/>/gi, (_m, tag, before, expr, after) => {
2563
- const val = getNestedValue(context, expr.trim());
3228
+ }
3229
+ function parseFiniteNumber(raw) {
3230
+ const trimmed = raw.trim();
3231
+ if (trimmed === "")
3232
+ return null;
3233
+ const parsed = Number(trimmed);
3234
+ return Number.isFinite(parsed) ? parsed : null;
3235
+ }
3236
+ function parseAndValidateMatchers(attrs, block, fallbackHtml, diag) {
3237
+ const hasString = "string" in attrs;
3238
+ const hasNumber = "number" in attrs;
3239
+ const hasBoolean = "boolean" in attrs;
3240
+ const hasMin = "min" in attrs;
3241
+ const hasMax = "max" in attrs;
3242
+ const hasRange = hasMin || hasMax;
3243
+ const activeCategories = [hasString, hasNumber, hasBoolean, hasRange].filter(Boolean).length;
3244
+ if (activeCategories === 0) {
3245
+ return { hasMatcher: false };
3246
+ }
3247
+ if (activeCategories > 1) {
3248
+ throw buildError({
3249
+ message: `[Buntic] Conflicting value matcher attributes on <${block.tag}>.`,
3250
+ hint: `Use a single matcher type ("string", "number", "boolean") or a numeric range ("min" / "max"), not a mix of incompatible attributes.`,
3251
+ snippet: block.fullMatch,
3252
+ openTag: block.openTag,
3253
+ fallbackHtml,
3254
+ fallbackOffset: block.start,
3255
+ diag
3256
+ });
3257
+ }
3258
+ if (hasString) {
3259
+ return { hasMatcher: true, stringVal: attrs.string };
3260
+ }
3261
+ if (hasNumber) {
3262
+ const parsed = parseFiniteNumber(attrs.number);
3263
+ if (parsed === null) {
3264
+ throw buildError({
3265
+ message: `[Buntic] Invalid numeric literal "${attrs.number}" in number="..." attribute on <${block.tag}>.`,
3266
+ hint: `The "number" attribute expects a finite numeric literal (e.g. number="0" or number="42"). To compare against another variable, use an expression in is="..." (e.g. is="age === config.target").`,
3267
+ snippet: block.fullMatch,
3268
+ openTag: block.openTag,
3269
+ fallbackHtml,
3270
+ fallbackOffset: block.start,
3271
+ diag
3272
+ });
3273
+ }
3274
+ return { hasMatcher: true, numberVal: parsed };
3275
+ }
3276
+ if (hasBoolean) {
3277
+ const raw = attrs.boolean.trim();
3278
+ if (raw !== "true" && raw !== "false") {
3279
+ throw buildError({
3280
+ message: `[Buntic] Invalid boolean literal "${attrs.boolean}" in boolean="..." attribute on <${block.tag}>.`,
3281
+ hint: `The "boolean" attribute only accepts "true" or "false".`,
3282
+ snippet: block.fullMatch,
3283
+ openTag: block.openTag,
3284
+ fallbackHtml,
3285
+ fallbackOffset: block.start,
3286
+ diag
3287
+ });
3288
+ }
3289
+ return { hasMatcher: true, booleanVal: raw === "true" };
3290
+ }
3291
+ let minVal;
3292
+ let maxVal;
3293
+ if (hasMin) {
3294
+ const parsed = parseFiniteNumber(attrs.min);
3295
+ if (parsed === null) {
3296
+ throw buildError({
3297
+ message: `[Buntic] Invalid numeric literal "${attrs.min}" in min="..." attribute on <${block.tag}>.`,
3298
+ hint: `The "min" attribute expects a finite numeric literal (e.g. min="18"). To compare against another variable, use is="age >= config.minAge".`,
3299
+ snippet: block.fullMatch,
3300
+ openTag: block.openTag,
3301
+ fallbackHtml,
3302
+ fallbackOffset: block.start,
3303
+ diag
3304
+ });
3305
+ }
3306
+ minVal = parsed;
3307
+ }
3308
+ if (hasMax) {
3309
+ const parsed = parseFiniteNumber(attrs.max);
3310
+ if (parsed === null) {
3311
+ throw buildError({
3312
+ message: `[Buntic] Invalid numeric literal "${attrs.max}" in max="..." attribute on <${block.tag}>.`,
3313
+ hint: `The "max" attribute expects a finite numeric literal (e.g. max="30"). To compare against another variable, use is="age <= config.maxAge".`,
3314
+ snippet: block.fullMatch,
3315
+ openTag: block.openTag,
3316
+ fallbackHtml,
3317
+ fallbackOffset: block.start,
3318
+ diag
3319
+ });
3320
+ }
3321
+ maxVal = parsed;
3322
+ }
3323
+ if (minVal !== undefined && maxVal !== undefined && minVal > maxVal) {
3324
+ throw buildError({
3325
+ message: `[Buntic] Invalid range on <${block.tag}>: min="${minVal}" cannot be greater than max="${maxVal}".`,
3326
+ hint: `Ensure min <= max (e.g. min="${maxVal}" max="${minVal}").`,
3327
+ snippet: block.fullMatch,
3328
+ openTag: block.openTag,
3329
+ fallbackHtml,
3330
+ fallbackOffset: block.start,
3331
+ diag
3332
+ });
3333
+ }
3334
+ return { hasMatcher: true, minVal, maxVal };
3335
+ }
3336
+ function matchesValue(val, matchers) {
3337
+ if (matchers.stringVal !== undefined) {
3338
+ return typeof val === "string" && val === matchers.stringVal;
3339
+ }
3340
+ if (matchers.numberVal !== undefined) {
3341
+ return typeof val === "number" && !Number.isNaN(val) && val === matchers.numberVal;
3342
+ }
3343
+ if (matchers.booleanVal !== undefined) {
3344
+ return typeof val === "boolean" && val === matchers.booleanVal;
3345
+ }
3346
+ if (matchers.minVal !== undefined || matchers.maxVal !== undefined) {
3347
+ if (typeof val !== "number" || Number.isNaN(val)) {
3348
+ return false;
3349
+ }
3350
+ if (matchers.minVal !== undefined && val < matchers.minVal)
3351
+ return false;
3352
+ if (matchers.maxVal !== undefined && val > matchers.maxVal)
3353
+ return false;
3354
+ return true;
3355
+ }
3356
+ return false;
3357
+ }
3358
+ function evalDirectiveExpr(expr, context, snippet, openTag, fallbackHtml, fallbackOffset, diag) {
3359
+ try {
3360
+ return evaluateExpression(expr, context);
3361
+ } catch (err) {
3362
+ const hint = err instanceof ExpressionSyntaxError ? err.hint : undefined;
3363
+ throw buildError({
3364
+ message: `[Buntic] Invalid condition expression "${expr}".`,
3365
+ cause: err,
3366
+ hint: hint || `Check expression syntax (supported: paths like "a.b", literals, !, ===, !==, ==, !=, <, <=, >, >=, &&, ||, parentheses).`,
3367
+ snippet,
3368
+ openTag,
3369
+ fallbackHtml,
3370
+ fallbackOffset,
3371
+ diag
3372
+ });
3373
+ }
3374
+ }
3375
+ function evaluateDecisionBlock(block, context, fallbackHtml, diag) {
3376
+ const attrs = parseHtmlAttributes(block.attrString, "");
3377
+ if (!attrs.is || !attrs.is.trim()) {
3378
+ throw buildError({
3379
+ message: `[Buntic] <${block.tag}> tag requires an "is" attribute.`,
3380
+ hint: `Example: <${block.tag} is="condition">...</${block.tag}>.`,
3381
+ snippet: block.fullMatch,
3382
+ openTag: block.openTag,
3383
+ fallbackHtml,
3384
+ fallbackOffset: block.start,
3385
+ diag
3386
+ });
3387
+ }
3388
+ if (block.tag === "if") {
3389
+ const matchers = parseAndValidateMatchers(attrs, block, fallbackHtml, diag);
3390
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
3391
+ const passed = matchers.hasMatcher ? matchesValue(val, matchers) : isTruthy(val);
3392
+ const { body, subBlocks } = splitDirectSubBlocks(block.inner, ["else"], NESTED_DIRECTIVE_SCOPES);
3393
+ const elseBlock = subBlocks[0];
3394
+ const chosen = passed ? body.trim() : elseBlock ? elseBlock.inner.trim() : "";
3395
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
3396
+ }
3397
+ if (block.tag === "unless") {
3398
+ const matchers = parseAndValidateMatchers(attrs, block, fallbackHtml, diag);
3399
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
3400
+ const condition = matchers.hasMatcher ? matchesValue(val, matchers) : isTruthy(val);
3401
+ const chosen = !condition ? block.inner.trim() : "";
3402
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
3403
+ }
3404
+ const { subBlocks } = splitDirectSubBlocks(block.inner, ["case", "else", "none", "default"], NESTED_DIRECTIVE_SCOPES);
3405
+ const cases = [];
3406
+ let elseBlock;
3407
+ let noneBlock;
3408
+ let defaultBlock;
3409
+ for (const sub of subBlocks) {
3410
+ if (sub.tag === "case") {
3411
+ const caseAttrs = parseHtmlAttributes(sub.attrString, "");
3412
+ const matchers = parseAndValidateMatchers(caseAttrs, sub, block.inner, diag);
3413
+ if (!matchers.hasMatcher) {
3414
+ throw buildError({
3415
+ message: `[Buntic] <case> tag inside <match> requires a value matcher attribute.`,
3416
+ hint: `Specify one of: string="...", number="...", boolean="true|false", or min="..." / max="...".`,
3417
+ snippet: sub.fullMatch,
3418
+ openTag: sub.openTag,
3419
+ fallbackHtml: block.inner,
3420
+ fallbackOffset: sub.start,
3421
+ diag
3422
+ });
3423
+ }
3424
+ cases.push({ block: sub, matchers });
3425
+ } else if (sub.tag === "else" && !elseBlock) {
3426
+ elseBlock = sub;
3427
+ } else if (sub.tag === "none" && !noneBlock) {
3428
+ noneBlock = sub;
3429
+ } else if (sub.tag === "default" && !defaultBlock) {
3430
+ defaultBlock = sub;
3431
+ }
3432
+ }
3433
+ const val = evalDirectiveExpr(attrs.is, context, block.fullMatch, block.openTag, fallbackHtml, block.start, diag);
3434
+ let chosen = "";
3435
+ if (val === undefined || val === null) {
3436
+ const fallback = elseBlock ?? defaultBlock;
3437
+ chosen = fallback ? fallback.inner.trim() : "";
3438
+ } else {
3439
+ let matched;
3440
+ for (const c of cases) {
3441
+ if (matchesValue(val, c.matchers)) {
3442
+ matched = c.block;
3443
+ break;
3444
+ }
3445
+ }
3446
+ if (matched) {
3447
+ chosen = matched.inner.trim();
3448
+ } else {
3449
+ const fallback = noneBlock ?? defaultBlock;
3450
+ chosen = fallback ? fallback.inner.trim() : "";
3451
+ }
3452
+ }
3453
+ return chosen ? resolveConditionals(chosen, context, diag) : "";
3454
+ }
3455
+ function resolveConditionals(html, context, diag) {
3456
+ const topBlocks = findTopLevelBlocks(html, ["if", "unless", "match"]);
3457
+ let res = html;
3458
+ if (topBlocks.length > 0) {
3459
+ let rebuilt = "";
3460
+ let cursor = 0;
3461
+ for (const block of topBlocks) {
3462
+ rebuilt += html.slice(cursor, block.start);
3463
+ rebuilt += evaluateDecisionBlock(block, context, html, diag);
3464
+ cursor = block.end;
3465
+ }
3466
+ rebuilt += html.slice(cursor);
3467
+ res = rebuilt;
3468
+ }
3469
+ res = res.replace(/<([a-zA-Z0-9_-]+)((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?)\s+if=(?:"([^"]+)"|'([^']+)')((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*)?)\s*\/>/gi, (fullMatch, tag, before, exprDouble, exprSingle, after, offset) => {
3470
+ const expr = (exprDouble ?? exprSingle ?? "").trim();
3471
+ const val = evalDirectiveExpr(expr, context, fullMatch, fullMatch, res, offset, diag);
2564
3472
  if (!isTruthy(val))
2565
3473
  return "";
2566
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
3474
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
2567
3475
  return attrs ? `<${tag} ${attrs} />` : `<${tag} />`;
2568
3476
  });
2569
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)>([\s\S]*?)<\/\1>/gi, (_m, tag, before, expr, after, content) => {
2570
- const val = getNestedValue(context, expr.trim());
3477
+ res = res.replace(/<([a-zA-Z0-9_-]+)((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?)\s+if=(?:"([^"]+)"|'([^']+)')((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*)?)>([\s\S]*?)<\/\1>/gi, (fullMatch, tag, before, exprDouble, exprSingle, after, content, offset) => {
3478
+ const expr = (exprDouble ?? exprSingle ?? "").trim();
3479
+ const closeLen = tag.length + 3;
3480
+ const openTag = fullMatch.slice(0, fullMatch.length - content.length - closeLen);
3481
+ const val = evalDirectiveExpr(expr, context, fullMatch, openTag, res, offset, diag);
2571
3482
  if (!isTruthy(val))
2572
3483
  return "";
2573
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
3484
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
2574
3485
  return attrs ? `<${tag} ${attrs}>${content}</${tag}>` : `<${tag}>${content}</${tag}>`;
2575
3486
  });
2576
3487
  return res;
@@ -2588,7 +3499,7 @@ function interpolateTemplate(html, context) {
2588
3499
  }
2589
3500
 
2590
3501
  // src/template/dsd-renderer.ts
2591
- import { relative as relative5 } from "path";
3502
+ import { relative as relative6 } from "path";
2592
3503
  function hasScriptWithSrc(html, srcPath) {
2593
3504
  const cleanSrc = srcPath.replace(/^\/+/, "");
2594
3505
  const scriptRegex = /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi;
@@ -2649,7 +3560,7 @@ ${globalCss.trim()}
2649
3560
  continue;
2650
3561
  }
2651
3562
  vfs.registry.markTagUsed(tag);
2652
- const rel = relative5(config.root, scriptPath).replace(/\\/g, "/");
3563
+ const rel = relative6(config.root, scriptPath).replace(/\\/g, "/");
2653
3564
  const publicSrc = rel.startsWith("/") ? rel : `/${rel}`;
2654
3565
  if (!injectedPaths.has(publicSrc) && !hasScriptWithSrc(result, publicSrc)) {
2655
3566
  injectedPaths.add(publicSrc);
@@ -2693,8 +3604,13 @@ ${siblingCss.trim()}
2693
3604
  } catch {
2694
3605
  rawHtml = await Bun.file(triad.htmlPath).text();
2695
3606
  }
3607
+ const originalRawHtml = rawHtml;
2696
3608
  rawHtml = await resolveComponentsFn(rawHtml, context, triad.htmlPath);
2697
- rawHtml = resolveConditionals(rawHtml, context);
3609
+ rawHtml = resolveConditionals(rawHtml, context, {
3610
+ filePath: triad.htmlPath,
3611
+ source: originalRawHtml,
3612
+ projectRoot: config.root
3613
+ });
2698
3614
  rawHtml = interpolateTemplate(rawHtml, context);
2699
3615
  if (rawHtml.includes("<style") && rawHtml.includes("scoped")) {
2700
3616
  const extracted = extractScopedStyles(rawHtml, scopeRegistry);
@@ -2749,7 +3665,7 @@ ${templateTag}`;
2749
3665
  }
2750
3666
 
2751
3667
  // src/template/svg-component.ts
2752
- import { relative as relative6 } from "path";
3668
+ import { relative as relative7 } from "path";
2753
3669
  async function attachSiblingCssIfPresent(options) {
2754
3670
  const { templateHtml, templatePath, siblingCssPath, kindLabel, config, vfs, cssGraph } = options;
2755
3671
  if (!vfs.hasFile(siblingCssPath)) {
@@ -2768,8 +3684,8 @@ async function attachSiblingCssIfPresent(options) {
2768
3684
  if (withScopedCss !== null) {
2769
3685
  return withScopedCss;
2770
3686
  }
2771
- const relTarget = relative6(config.root, templatePath);
2772
- const relCss = relative6(config.root, siblingCssPath);
3687
+ const relTarget = relative7(config.root, templatePath);
3688
+ const relCss = relative7(config.root, siblingCssPath);
2773
3689
  logWarn(`${kindLabel} "${relTarget}" has a sibling CSS file ("${relCss}"), but does not have a single root element. Scoped styles were not applied.`);
2774
3690
  return templateHtml;
2775
3691
  }
@@ -3086,7 +4002,7 @@ class TemplateEngine {
3086
4002
  await this.cssGraph.analyze(this.vfs);
3087
4003
  const globalRoot = this.cssGraph.getGlobalRoot();
3088
4004
  if (globalRoot.conflicts.length > 1) {
3089
- const relConflicts = globalRoot.conflicts.map((c) => relative7(this.config.root, c));
4005
+ const relConflicts = globalRoot.conflicts.map((c) => relative8(this.config.root, c));
3090
4006
  logWarn(`Multiple orphan global CSS roots detected: ${relConflicts.map((c) => `"${c}"`).join(", ")}. Please link them via @import in a single root file or co-locate them with a component/page.`, "Buntic Conflict Warning");
3091
4007
  }
3092
4008
  let processedHtml = pageHtml;
@@ -3104,7 +4020,7 @@ class TemplateEngine {
3104
4020
  let composed = await this.resolveLayout(processedHtml, context, currentFile);
3105
4021
  composed = await this.resolveEach(composed, context, currentFile);
3106
4022
  composed = await this.resolveComponents(composed, context, currentFile);
3107
- composed = this.resolveConditionals(composed, context);
4023
+ composed = this.resolveConditionals(composed, context, currentFile, pageHtml);
3108
4024
  composed = this.interpolate(composed, context);
3109
4025
  composed = await this.resolveWebComponents(composed, context);
3110
4026
  composed = await this.resolveCss(composed, currentFile);
@@ -3146,6 +4062,16 @@ class TemplateEngine {
3146
4062
  resolveFilePath(rawSrc, currentFile, defaultDir) {
3147
4063
  return this.vfs.resolvePath(rawSrc, currentFile, defaultDir);
3148
4064
  }
4065
+ async getOriginalSource(filePath, fallbackHtml) {
4066
+ if (filePath && (this.vfs.hasFile(filePath) || existsSync16(filePath))) {
4067
+ try {
4068
+ return await this.vfs.readText(filePath);
4069
+ } catch {
4070
+ return fallbackHtml;
4071
+ }
4072
+ }
4073
+ return fallbackHtml;
4074
+ }
3149
4075
  async resolveLayout(html, context, currentFile) {
3150
4076
  const layoutMatch = html.match(/<layout\s+src=["']([^"']+)["'][^>]*>([\s\S]*?)<\/layout>/i);
3151
4077
  if (!layoutMatch) {
@@ -3155,7 +4081,24 @@ class TemplateEngine {
3155
4081
  const innerContent = layoutMatch[2];
3156
4082
  const layoutFilePath = this.resolveFilePath(layoutRawSrc, currentFile, this.config.layoutsDir);
3157
4083
  if (!this.vfs.hasFile(layoutFilePath) && !existsSync16(layoutFilePath)) {
3158
- throw new Error(`[Buntic] Layout not found: "${layoutRawSrc}" at ${layoutFilePath}`);
4084
+ const originalSource = await this.getOriginalSource(currentFile, html);
4085
+ const openTag = layoutMatch[0].slice(0, layoutMatch[0].indexOf(">") + 1);
4086
+ const location = findSnippetLocation({
4087
+ source: originalSource,
4088
+ snippet: layoutMatch[0],
4089
+ openTag,
4090
+ fallbackHtml: html,
4091
+ fallbackOffset: layoutMatch.index,
4092
+ filePath: currentFile || undefined
4093
+ });
4094
+ const layoutsDirDisplay = formatTemplatePath(this.config.layoutsDir, this.config.root);
4095
+ throw new BunticTemplateError({
4096
+ message: `[Buntic] Layout not found: "${layoutRawSrc}" at ${layoutFilePath}`,
4097
+ location,
4098
+ projectRoot: this.config.root,
4099
+ resolvedTarget: layoutFilePath,
4100
+ hint: `Check that "${layoutRawSrc}" exists in "${layoutsDirDisplay}" or verify the relative path in <layout src="${layoutRawSrc}">.`
4101
+ });
3159
4102
  }
3160
4103
  const layoutTemplate = await this.vfs.readText(layoutFilePath);
3161
4104
  let resolvedInner = await this.resolveEach(innerContent, context, currentFile);
@@ -3194,31 +4137,140 @@ class TemplateEngine {
3194
4137
  console.warn("[Buntic] Maximum <each> recursion depth (10) reached.");
3195
4138
  return html;
3196
4139
  }
3197
- const eachRegex = /<each\s+([^>]+?)>([\s\S]*?)<\/each>/gis;
3198
- let match;
3199
- const matches = [];
3200
- while ((match = eachRegex.exec(html)) !== null) {
3201
- matches.push({ fullMatch: match[0], attrString: match[1], inner: match[2] });
3202
- }
4140
+ const matches = findTopLevelBlocks(html, ["each"]);
3203
4141
  if (matches.length === 0)
3204
4142
  return html;
4143
+ const locateEachItem = async (item) => {
4144
+ const originalSource = await this.getOriginalSource(currentFile, html);
4145
+ return findSnippetLocation({
4146
+ source: originalSource,
4147
+ snippet: item.fullMatch,
4148
+ openTag: item.openTag,
4149
+ fallbackHtml: html,
4150
+ fallbackOffset: item.start,
4151
+ filePath: currentFile || undefined
4152
+ });
4153
+ };
4154
+ const originalSourceForFile = currentFile && (this.vfs.hasFile(currentFile) || existsSync16(currentFile)) ? await this.getOriginalSource(currentFile, html) : undefined;
4155
+ const renderFallbackBlock = async (content) => {
4156
+ const trimmed = content.trim();
4157
+ if (!trimmed)
4158
+ return "";
4159
+ let rendered = await this.resolveEach(trimmed, context, currentFile, depth + 1);
4160
+ rendered = await this.resolveComponents(rendered, context, currentFile, depth + 1);
4161
+ rendered = this.resolveConditionals(rendered, context, currentFile, originalSourceForFile);
4162
+ rendered = this.interpolate(rendered, context);
4163
+ return rendered;
4164
+ };
3205
4165
  let result = html;
3206
4166
  for (const item of matches) {
3207
4167
  const attrs = parseHtmlAttributes(item.attrString);
4168
+ const { body: loopTemplate, subBlocks } = splitDirectSubBlocks(item.inner, ["else", "none", "default"], ["each", "if", "unless", "match"]);
4169
+ let elseBlock;
4170
+ let noneBlock;
4171
+ let defaultBlock;
4172
+ for (const sub of subBlocks) {
4173
+ if (sub.tag === "else" && !elseBlock)
4174
+ elseBlock = sub;
4175
+ else if (sub.tag === "none" && !noneBlock)
4176
+ noneBlock = sub;
4177
+ else if (sub.tag === "default" && !defaultBlock)
4178
+ defaultBlock = sub;
4179
+ }
3208
4180
  let items;
4181
+ let resolvedFilePath;
3209
4182
  if (attrs.src) {
3210
4183
  const filePath = this.resolveFilePath(attrs.src, currentFile, this.config.dataDir);
4184
+ resolvedFilePath = filePath;
3211
4185
  if (!this.vfs.hasFile(filePath) && !existsSync16(filePath)) {
3212
- throw new Error(`[Buntic] <each> data file not found: "${attrs.src}" at ${filePath}`);
4186
+ const location = await locateEachItem(item);
4187
+ const existsInContext = getNestedValue(context, attrs.src) !== undefined;
4188
+ const dataDirDisplay = formatTemplatePath(this.config.dataDir, this.config.root);
4189
+ let hint;
4190
+ if (existsInContext) {
4191
+ hint = `"${attrs.src}" is available in the template context. ` + `Use <each in="${attrs.src}"> to iterate context data, or provide a valid JSON file path (e.g. "${attrs.src}.json").`;
4192
+ } else if (!attrs.src.endsWith(".json")) {
4193
+ hint = `Use <each in="${attrs.src}"> to iterate data from context, ` + `or include the ".json" extension if loading a file from "${dataDirDisplay}" (e.g. <each src="${attrs.src}.json">).`;
4194
+ } else {
4195
+ hint = `Verify that "${attrs.src}" exists in "${dataDirDisplay}" or check the relative path.`;
4196
+ }
4197
+ throw new BunticTemplateError({
4198
+ message: `[Buntic] <each> data file not found: "${attrs.src}" at ${filePath}`,
4199
+ location,
4200
+ projectRoot: this.config.root,
4201
+ resolvedTarget: filePath,
4202
+ hint
4203
+ });
4204
+ }
4205
+ try {
4206
+ items = await this.vfs.readJson(filePath);
4207
+ } catch (err) {
4208
+ const location = await locateEachItem(item);
4209
+ const ext = extname4(filePath).toLowerCase();
4210
+ const relResolved = formatTemplatePath(filePath, this.config.root);
4211
+ const existsInContext = getNestedValue(context, attrs.src) !== undefined;
4212
+ let hint;
4213
+ if (ext && ext !== ".json") {
4214
+ if (existsInContext) {
4215
+ hint = `Resolved file "${relResolved}" has extension "${ext}", not ".json".
4216
+ ` + `"${attrs.src}" is available in template context \u2014 use <each in="${attrs.src}"> or point "src" to a .json file (e.g. <each src="${attrs.src}.json">).`;
4217
+ } else {
4218
+ hint = `Resolved file "${relResolved}" has extension "${ext}", not ".json".
4219
+ ` + `Use <each in="${attrs.src}"> to iterate data from context, or point "src" to a .json file (e.g. <each src="${attrs.src}.json">).`;
4220
+ }
4221
+ } else {
4222
+ hint = `Check that "${relResolved}" contains valid JSON syntax.`;
4223
+ }
4224
+ throw new BunticTemplateError({
4225
+ message: `[Buntic] Failed to parse JSON data file for <each src="${attrs.src}">`,
4226
+ location,
4227
+ projectRoot: this.config.root,
4228
+ resolvedTarget: filePath,
4229
+ cause: err,
4230
+ hint
4231
+ });
3213
4232
  }
3214
- items = await this.vfs.readJson(filePath);
3215
4233
  } else if (attrs.in) {
3216
4234
  items = getNestedValue(context, attrs.in);
3217
4235
  } else {
3218
- throw new Error(`[Buntic] <each> tag requires either a "src" or "in" attribute.`);
4236
+ const location = await locateEachItem(item);
4237
+ throw new BunticTemplateError({
4238
+ message: `[Buntic] <each> tag requires either a "src" or "in" attribute.`,
4239
+ location,
4240
+ projectRoot: this.config.root,
4241
+ hint: `Use <each src="data.json"> for a JSON file or <each in="items"> for a context variable.`
4242
+ });
4243
+ }
4244
+ if ((items === undefined || items === null) && (elseBlock || defaultBlock)) {
4245
+ const fallbackContent = (elseBlock ?? defaultBlock).inner;
4246
+ const renderedFallback = await renderFallbackBlock(fallbackContent);
4247
+ result = replaceLiteral(result, item.fullMatch, renderedFallback);
4248
+ continue;
3219
4249
  }
3220
4250
  if (!Array.isArray(items)) {
3221
- throw new Error(`[Buntic] <each> source "${attrs.src || attrs.in}" did not resolve to an array.`);
4251
+ const location = await locateEachItem(item);
4252
+ const receivedType = items === null ? "null" : typeof items;
4253
+ let hint;
4254
+ if (attrs.in && items === undefined) {
4255
+ const availableKeys = Object.keys(context).filter((k) => k !== "env");
4256
+ const keysNote = availableKeys.length > 0 ? ` Available top-level keys: ${availableKeys.join(", ")}.` : "";
4257
+ hint = `Context path "${attrs.in}" is undefined. Check the variable name (page loader data lives under "props.*") or add an <else> / <default> fallback inside <each>.${keysNote}`;
4258
+ } else {
4259
+ hint = `<each> expects an array, but "${attrs.src || attrs.in}" resolved to ${receivedType}.`;
4260
+ }
4261
+ throw new BunticTemplateError({
4262
+ message: `[Buntic] <each> source "${attrs.src || attrs.in}" did not resolve to an array (received ${receivedType}).`,
4263
+ location,
4264
+ projectRoot: this.config.root,
4265
+ resolvedTarget: resolvedFilePath,
4266
+ hint
4267
+ });
4268
+ }
4269
+ if (items.length === 0) {
4270
+ const fallback = noneBlock ?? defaultBlock;
4271
+ const renderedFallback = fallback ? await renderFallbackBlock(fallback.inner) : "";
4272
+ result = replaceLiteral(result, item.fullMatch, renderedFallback);
4273
+ continue;
3222
4274
  }
3223
4275
  const renderedItems = [];
3224
4276
  for (const entry of items) {
@@ -3235,9 +4287,9 @@ class TemplateEngine {
3235
4287
  itemContext.item = entry;
3236
4288
  itemContext.this = entry;
3237
4289
  }
3238
- let rendered = await this.resolveEach(item.inner, itemContext, currentFile, depth + 1);
4290
+ let rendered = await this.resolveEach(loopTemplate, itemContext, currentFile, depth + 1);
3239
4291
  rendered = await this.resolveComponents(rendered, itemContext, currentFile, depth + 1);
3240
- rendered = this.resolveConditionals(rendered, itemContext);
4292
+ rendered = this.resolveConditionals(rendered, itemContext, currentFile, originalSourceForFile);
3241
4293
  rendered = this.interpolate(rendered, itemContext);
3242
4294
  renderedItems.push(rendered);
3243
4295
  }
@@ -3257,11 +4309,15 @@ class TemplateEngine {
3257
4309
  while ((match = componentRegex.exec(html)) !== null) {
3258
4310
  const props = parseHtmlAttributes(match[1]);
3259
4311
  if (props.src) {
4312
+ const fullMatch = match[0];
4313
+ const openTagEnd = fullMatch.indexOf(">");
3260
4314
  matches.push({
3261
- fullMatch: match[0],
4315
+ fullMatch,
4316
+ openTag: openTagEnd !== -1 ? fullMatch.slice(0, openTagEnd + 1) : fullMatch,
3262
4317
  children: match[2] ? match[2].trim() : "",
3263
4318
  src: props.src,
3264
- props
4319
+ props,
4320
+ index: match.index
3265
4321
  });
3266
4322
  }
3267
4323
  }
@@ -3271,7 +4327,23 @@ class TemplateEngine {
3271
4327
  for (const item of matches) {
3272
4328
  const compPath = this.resolveFilePath(item.src, currentFile, this.config.componentsDir);
3273
4329
  if (!this.vfs.hasFile(compPath) && !existsSync16(compPath)) {
3274
- throw new Error(`[Buntic] Component not found: "${item.src}" at ${compPath}`);
4330
+ const originalSource = await this.getOriginalSource(currentFile, html);
4331
+ const location = findSnippetLocation({
4332
+ source: originalSource,
4333
+ snippet: item.fullMatch,
4334
+ openTag: item.openTag,
4335
+ fallbackHtml: html,
4336
+ fallbackOffset: item.index,
4337
+ filePath: currentFile || undefined
4338
+ });
4339
+ const compDirDisplay = formatTemplatePath(this.config.componentsDir, this.config.root);
4340
+ throw new BunticTemplateError({
4341
+ message: `[Buntic] Component not found: "${item.src}" at ${compPath}`,
4342
+ location,
4343
+ projectRoot: this.config.root,
4344
+ resolvedTarget: compPath,
4345
+ hint: `Check that "${item.src}" exists in "${compDirDisplay}" or verify the relative path in <component src="${item.src}">.`
4346
+ });
3275
4347
  }
3276
4348
  const ext = extname4(compPath).toLowerCase();
3277
4349
  if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
@@ -3282,7 +4354,11 @@ class TemplateEngine {
3282
4354
  children: item.children,
3283
4355
  context,
3284
4356
  currentFile,
3285
- depth
4357
+ depth,
4358
+ snippet: item.fullMatch,
4359
+ openTag: item.openTag,
4360
+ offset: item.index,
4361
+ sourceHtml: html
3286
4362
  });
3287
4363
  result = replaceLiteral(result, item.fullMatch, replacement);
3288
4364
  continue;
@@ -3298,9 +4374,9 @@ class TemplateEngine {
3298
4374
  result = replaceLiteral(result, item.fullMatch, svgContent);
3299
4375
  continue;
3300
4376
  }
3301
- let compTemplate = await this.vfs.readText(compPath);
3302
- compTemplate = await attachSiblingCssIfPresent({
3303
- templateHtml: compTemplate,
4377
+ const rawCompTemplate = await this.vfs.readText(compPath);
4378
+ let compTemplate = await attachSiblingCssIfPresent({
4379
+ templateHtml: rawCompTemplate,
3304
4380
  templatePath: compPath,
3305
4381
  siblingCssPath: compPath.replace(/\.html$/, ".css"),
3306
4382
  kindLabel: "Component",
@@ -3311,7 +4387,7 @@ class TemplateEngine {
3311
4387
  const compContext = { ...context, ...item.props };
3312
4388
  compTemplate = compTemplate.replace(/<slot\s*>\s*<\/slot>/gi, () => item.children);
3313
4389
  compTemplate = compTemplate.replace(/<slot\s*\/>/gi, () => item.children);
3314
- compTemplate = this.resolveConditionals(compTemplate, compContext);
4390
+ compTemplate = this.resolveConditionals(compTemplate, compContext, compPath, rawCompTemplate);
3315
4391
  compTemplate = this.interpolate(compTemplate, compContext);
3316
4392
  compTemplate = await this.resolveComponents(compTemplate, compContext, compPath, depth + 1);
3317
4393
  result = replaceLiteral(result, item.fullMatch, compTemplate);
@@ -3319,7 +4395,19 @@ class TemplateEngine {
3319
4395
  return result;
3320
4396
  }
3321
4397
  async renderWebComponentAlias(options) {
3322
- const { compPath, rawSrc, props, children, context, currentFile, depth } = options;
4398
+ const {
4399
+ compPath,
4400
+ rawSrc,
4401
+ props,
4402
+ children,
4403
+ context,
4404
+ currentFile,
4405
+ depth,
4406
+ snippet,
4407
+ openTag,
4408
+ offset,
4409
+ sourceHtml
4410
+ } = options;
3323
4411
  let tag = this.vfs.registry.getTagsForFile(compPath)[0];
3324
4412
  if (!tag) {
3325
4413
  let code;
@@ -3335,20 +4423,38 @@ class TemplateEngine {
3335
4423
  tag = filenameToTagName(compPath) || undefined;
3336
4424
  }
3337
4425
  if (!tag) {
3338
- throw new Error(`[Buntic] Could not determine Custom Element tag name for Web Component file "${rawSrc}". ` + `Ensure the filename follows kebab-case (e.g. "my-element.ts") or PascalCase (e.g. "MyElement.ts").`);
4426
+ const originalSource = await this.getOriginalSource(currentFile, sourceHtml || "");
4427
+ const location = findSnippetLocation({
4428
+ source: originalSource,
4429
+ snippet: snippet || "",
4430
+ openTag,
4431
+ fallbackHtml: sourceHtml,
4432
+ fallbackOffset: offset,
4433
+ filePath: currentFile || undefined
4434
+ });
4435
+ throw new BunticTemplateError({
4436
+ message: `[Buntic] Could not determine Custom Element tag name for Web Component file "${rawSrc}". ` + `Ensure the filename follows kebab-case (e.g. "my-element.ts") or PascalCase (e.g. "MyElement.ts").`,
4437
+ location,
4438
+ projectRoot: this.config.root,
4439
+ resolvedTarget: compPath
4440
+ });
3339
4441
  }
3340
4442
  const attrEntries = Object.entries(props).filter(([k]) => k !== "src");
3341
4443
  const attrString = attrEntries.length > 0 ? " " + attrEntries.map(([k, v]) => `${k}="${v}"`).join(" ") : "";
3342
4444
  let innerChildren = children;
3343
4445
  if (innerChildren) {
3344
4446
  innerChildren = await this.resolveComponents(innerChildren, context, currentFile, depth + 1);
3345
- innerChildren = this.resolveConditionals(innerChildren, context);
4447
+ innerChildren = this.resolveConditionals(innerChildren, context, currentFile, sourceHtml);
3346
4448
  innerChildren = this.interpolate(innerChildren, context);
3347
4449
  }
3348
4450
  return innerChildren ? `<${tag}${attrString}>${innerChildren}</${tag}>` : `<${tag}${attrString}></${tag}>`;
3349
4451
  }
3350
- resolveConditionals(html, context) {
3351
- return resolveConditionals(html, context);
4452
+ resolveConditionals(html, context, currentFile = "", originalSource) {
4453
+ return resolveConditionals(html, context, {
4454
+ filePath: currentFile || undefined,
4455
+ source: originalSource,
4456
+ projectRoot: this.config.root
4457
+ });
3352
4458
  }
3353
4459
  interpolate(html, context) {
3354
4460
  return interpolateTemplate(html, context);
@@ -3357,7 +4463,7 @@ class TemplateEngine {
3357
4463
 
3358
4464
  // src/builder/collisions.ts
3359
4465
  import { existsSync as existsSync17 } from "fs";
3360
- import { join as join16, relative as relative8 } from "path";
4466
+ import { join as join16, relative as relative9 } from "path";
3361
4467
  function getDirectoryFiles(dir, baseDir = dir) {
3362
4468
  return walkFiles(dir, {
3363
4469
  baseDir,
@@ -3372,7 +4478,7 @@ function detectPublicCollisions(config, routes) {
3372
4478
  const collisions = [];
3373
4479
  const routeOutputMap = new Map;
3374
4480
  for (const route of routes) {
3375
- const relOut = relative8(config.outDir, route.outputFilePath).replace(/\\/g, "/");
4481
+ const relOut = relative9(config.outDir, route.outputFilePath).replace(/\\/g, "/");
3376
4482
  routeOutputMap.set(relOut, route);
3377
4483
  }
3378
4484
  for (const relFile of publicFiles) {
@@ -3380,22 +4486,22 @@ function detectPublicCollisions(config, routes) {
3380
4486
  const route = routeOutputMap.get(relFile);
3381
4487
  collisions.push({
3382
4488
  type: "route",
3383
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
3384
- conflictWith: relative8(config.root, route.templateFilePath),
4489
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
4490
+ conflictWith: relative9(config.root, route.templateFilePath),
3385
4491
  outputPath: relFile
3386
4492
  });
3387
4493
  }
3388
4494
  if (relFile.startsWith("assets/images/") || relFile === "assets/images") {
3389
4495
  collisions.push({
3390
4496
  type: "reserved-dir",
3391
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
4497
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
3392
4498
  conflictWith: "assets/images/ (Reserved for Buntic <photo> image optimization)",
3393
4499
  outputPath: relFile
3394
4500
  });
3395
4501
  } else if (relFile.startsWith("assets/seo/") || relFile === "assets/seo") {
3396
4502
  collisions.push({
3397
4503
  type: "reserved-dir",
3398
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
4504
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
3399
4505
  conflictWith: "assets/seo/ (Reserved for Buntic <seo> social cards)",
3400
4506
  outputPath: relFile
3401
4507
  });
@@ -3497,7 +4603,7 @@ class Builder {
3497
4603
  }
3498
4604
  }
3499
4605
  }
3500
- const relStagedPath = relative9(this.config.outDir, route.outputFilePath);
4606
+ const relStagedPath = relative10(this.config.outDir, route.outputFilePath);
3501
4607
  const stagedPath = join17(stagingDir, relStagedPath);
3502
4608
  mkdirSync3(dirname9(stagedPath), { recursive: true });
3503
4609
  rendered = this.normalizeRootPaths(rendered, stagedPath, stagingDir);
@@ -3575,7 +4681,7 @@ class Builder {
3575
4681
  warnUnusedWebComponents() {
3576
4682
  const unused = this.engine.getUnusedWebComponents();
3577
4683
  for (const item of unused) {
3578
- logWarn(`Web Component "<${item.tag}>" (${relative9(this.config.root, item.file)}) is registered but not used in any page.`);
4684
+ logWarn(`Web Component "<${item.tag}>" (${relative10(this.config.root, item.file)}) is registered but not used in any page.`);
3579
4685
  }
3580
4686
  }
3581
4687
  normalizeRootPaths(html, stagedFilePath, stagingDir) {
@@ -3586,14 +4692,14 @@ class Builder {
3586
4692
  }
3587
4693
  const targetInRoot = join17(this.config.root, path);
3588
4694
  if (existsSync18(targetInRoot)) {
3589
- let rel = relative9(fromDir, targetInRoot);
4695
+ let rel = relative10(fromDir, targetInRoot);
3590
4696
  if (!rel.startsWith("."))
3591
4697
  rel = "./" + rel;
3592
4698
  return `${attr}="${rel}"`;
3593
4699
  }
3594
4700
  const targetInSrc = join17(this.config.root, "src", path);
3595
4701
  if (existsSync18(targetInSrc)) {
3596
- let rel = relative9(fromDir, targetInSrc);
4702
+ let rel = relative10(fromDir, targetInSrc);
3597
4703
  if (!rel.startsWith("."))
3598
4704
  rel = "./" + rel;
3599
4705
  return `${attr}="${rel}"`;
@@ -3601,7 +4707,7 @@ class Builder {
3601
4707
  if (stagingDir) {
3602
4708
  const targetInStaging = join17(stagingDir, path);
3603
4709
  if (existsSync18(targetInStaging)) {
3604
- let rel = relative9(fromDir, targetInStaging);
4710
+ let rel = relative10(fromDir, targetInStaging);
3605
4711
  if (!rel.startsWith("."))
3606
4712
  rel = "./" + rel;
3607
4713
  return `${attr}="${rel}"`;
@@ -3754,10 +4860,82 @@ function getMimeType(path) {
3754
4860
  return "text/plain; charset=utf-8";
3755
4861
  return "application/octet-stream";
3756
4862
  }
4863
+ function formatCodeFrameHtml(codeFrame) {
4864
+ return codeFrame.split(`
4865
+ `).map((line) => {
4866
+ const escaped = escapeHtml(line);
4867
+ if (line.startsWith(" > ")) {
4868
+ return `<span class="error-line">${escaped}</span>`;
4869
+ }
4870
+ if (/^\s+\|\s+\^+$/.test(line)) {
4871
+ return `<span class="error-caret">${escaped}</span>`;
4872
+ }
4873
+ return escaped;
4874
+ }).join(`
4875
+ `);
4876
+ }
3757
4877
  function renderErrorResponse(title, err) {
3758
4878
  const safeTitle = escapeHtml(title);
3759
4879
  const safeMsg = escapeHtml(getErrorMessage(err));
3760
- return new Response(`<h1>${safeTitle}</h1><pre>${safeMsg}</pre>`, {
4880
+ let bodyContent;
4881
+ if (err instanceof BunticTemplateError) {
4882
+ const metaRows = [];
4883
+ if (err.filePath) {
4884
+ const coords = err.line ? `:${err.line}${err.column ? `:${err.column}` : ""}` : "";
4885
+ metaRows.push(`<div class="meta-row"><span class="meta-label">File</span><code>${escapeHtml(err.filePath + coords)}</code></div>`);
4886
+ } else if (err.line) {
4887
+ const colText = err.column ? `, column ${err.column}` : "";
4888
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Location</span><code>line ${err.line}${colText}</code></div>`);
4889
+ }
4890
+ if (err.resolvedTarget) {
4891
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Resolved</span><code>${escapeHtml(err.resolvedTarget)}</code></div>`);
4892
+ }
4893
+ if (err.causeMessage) {
4894
+ metaRows.push(`<div class="meta-row"><span class="meta-label">Cause</span><span class="cause-text">${escapeHtml(err.causeMessage)}</span></div>`);
4895
+ }
4896
+ const metaBlock = metaRows.length > 0 ? `<div class="meta">${metaRows.join("")}</div>` : "";
4897
+ const frameBlock = err.codeFrame ? `<pre class="code-frame">${formatCodeFrameHtml(err.codeFrame)}</pre>` : "";
4898
+ const hintBlock = err.hint ? `<div class="hint"><strong>Hint:</strong> ${escapeHtml(err.hint).replace(/\n/g, "<br>")}</div>` : "";
4899
+ bodyContent = `
4900
+ <p class="summary">${escapeHtml(err.summary)}</p>
4901
+ ${metaBlock}
4902
+ ${frameBlock}
4903
+ ${hintBlock}
4904
+ `;
4905
+ } else {
4906
+ bodyContent = `<pre class="code-frame">${safeMsg}</pre>`;
4907
+ }
4908
+ const errorHtml = `<!doctype html>
4909
+ <html>
4910
+ <head>
4911
+ <meta charset="utf-8">
4912
+ <title>${safeTitle} | Buntic Dev</title>
4913
+ <style>
4914
+ body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; padding: 2.5rem 1.5rem; margin: 0; }
4915
+ .card { max-width: 820px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 20px 40px rgba(0,0,0,0.35); }
4916
+ h1 { color: #f43f5e; margin: 0 0 1rem; font-size: 1.5rem; }
4917
+ .summary { font-size: 1.05rem; color: #fecdd3; margin: 0 0 1.25rem; line-height: 1.5; font-weight: 500; }
4918
+ .meta { display: flex; flex-direction: column; gap: 0.45rem; margin-bottom: 1.25rem; padding: 0.9rem 1rem; background: #0f172a; border-radius: 8px; border: 1px solid #334155; }
4919
+ .meta-row { display: flex; align-items: baseline; gap: 0.75rem; font-size: 0.92rem; flex-wrap: wrap; }
4920
+ .meta-label { color: #94a3b8; min-width: 72px; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.04em; }
4921
+ code { color: #38bdf8; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; word-break: break-all; }
4922
+ .cause-text { color: #fda4af; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; }
4923
+ pre.code-frame { background: #020617; color: #e2e8f0; padding: 1rem 1.1rem; border-radius: 8px; border: 1px solid #334155; overflow-x: auto; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 0.9rem; line-height: 1.6; margin: 0 0 1.25rem; }
4924
+ .error-line { display: inline-block; min-width: 100%; background: rgba(244, 63, 94, 0.18); color: #fff1f2; font-weight: 600; }
4925
+ .error-caret { color: #f43f5e; font-weight: 700; }
4926
+ .hint { background: rgba(56, 189, 248, 0.1); border-left: 3px solid #38bdf8; padding: 0.85rem 1rem; border-radius: 0 8px 8px 0; color: #e0f2fe; font-size: 0.92rem; line-height: 1.55; }
4927
+ .hint strong { color: #38bdf8; }
4928
+ </style>
4929
+ </head>
4930
+ <body>
4931
+ <div class="card">
4932
+ <h1>${safeTitle}</h1>
4933
+ ${bodyContent}
4934
+ </div>
4935
+ ${LIVE_RELOAD_SCRIPT}
4936
+ </body>
4937
+ </html>`;
4938
+ return new Response(errorHtml, {
3761
4939
  status: 500,
3762
4940
  headers: { "Content-Type": "text/html; charset=utf-8" }
3763
4941
  });
@@ -4092,7 +5270,7 @@ async function runCLI(args) {
4092
5270
  includeSkills,
4093
5271
  force
4094
5272
  });
4095
- const relTarget = relative10(process.cwd(), result.targetDir) || ".";
5273
+ const relTarget = relative11(process.cwd(), result.targetDir) || ".";
4096
5274
  console.log(`
4097
5275
  \u26A1 \x1B[36m[Buntic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
4098
5276
  console.log(` \u2714 Created ${result.filesCopied} file(s) (no package.json required)`);