buntic 0.3.0 → 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.
Files changed (34) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +39 -39
  3. package/dist/cli.js +1362 -189
  4. package/dist/config.d.ts +5 -5
  5. package/dist/index.d.ts +6 -5
  6. package/dist/index.js +1389 -201
  7. package/dist/router/routes.d.ts +1 -1
  8. package/dist/runtime.d.ts +8 -9
  9. package/dist/server/dev-helpers.d.ts +1 -1
  10. package/dist/storage/oras/adapter.d.ts +2 -2
  11. package/dist/template/block-scanner.d.ts +28 -0
  12. package/dist/template/directives.d.ts +17 -8
  13. package/dist/template/engine.d.ts +2 -1
  14. package/dist/template/errors.d.ts +58 -0
  15. package/dist/template/expressions.d.ts +16 -0
  16. package/dist/template/scoped-css.d.ts +1 -1
  17. package/dist/types.d.ts +1 -1
  18. package/dist/utils/html.d.ts +1 -1
  19. package/dist/utils/logger.d.ts +1 -1
  20. package/package.json +7 -7
  21. package/templates/blank/_gitignore +2 -2
  22. package/templates/blank/{bustatic.config.ts → buntic.config.ts} +2 -2
  23. package/templates/blank/src/pages/index.html +2 -2
  24. package/templates/blank/tsconfig.json +4 -9
  25. package/templates/simple/README.md +6 -6
  26. package/templates/simple/_gitignore +2 -2
  27. package/templates/simple/{bustatic.config.ts → buntic.config.ts} +2 -2
  28. package/templates/simple/src/components/footer.html +1 -1
  29. package/templates/simple/src/data/site.json +3 -3
  30. package/templates/simple/src/pages/about.html +1 -1
  31. package/templates/simple/src/pages/contact.html +1 -1
  32. package/templates/simple/tsconfig.json +4 -9
  33. package/templates/skills/{bustatic → buntic}/SKILL.md +83 -43
  34. package/templates/skills/{bustatic → buntic}/examples/README.md +4 -4
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";
@@ -14,7 +14,6 @@ import { existsSync, mkdirSync, readdirSync, cpSync, rmSync, readFileSync, write
14
14
  import { dirname, join, resolve } from "path";
15
15
  import { fileURLToPath } from "url";
16
16
  var resolverRegistered = false;
17
- var PACKAGE_NAMES = new Set(["buntic", "bun-bustatic", "bustatic"]);
18
17
  function getPackageRoot() {
19
18
  let current = dirname(fileURLToPath(import.meta.url));
20
19
  while (true) {
@@ -22,7 +21,7 @@ function getPackageRoot() {
22
21
  if (existsSync(pkgPath)) {
23
22
  try {
24
23
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
25
- if (typeof pkg?.name === "string" && PACKAGE_NAMES.has(pkg.name)) {
24
+ if (pkg?.name === "buntic") {
26
25
  return current;
27
26
  }
28
27
  } catch {}
@@ -48,10 +47,10 @@ function getSelfEntryPath() {
48
47
  }
49
48
  return distEntry;
50
49
  }
51
- function hasLocalBustaticPackage(startDir) {
50
+ function hasLocalBunticPackage(startDir) {
52
51
  let current = resolve(startDir);
53
52
  while (true) {
54
- if (existsSync(join(current, "node_modules", "bun-bustatic", "package.json")) || existsSync(join(current, "node_modules", "bustatic", "package.json"))) {
53
+ if (existsSync(join(current, "node_modules", "buntic", "package.json"))) {
55
54
  return true;
56
55
  }
57
56
  const parent = dirname(current);
@@ -61,27 +60,23 @@ function hasLocalBustaticPackage(startDir) {
61
60
  current = parent;
62
61
  }
63
62
  }
64
- function registerBustaticModuleResolver(projectDir) {
63
+ function registerBunticModuleResolver(projectDir) {
65
64
  if (resolverRegistered)
66
65
  return;
67
- if (projectDir && hasLocalBustaticPackage(projectDir))
66
+ if (projectDir && hasLocalBunticPackage(projectDir))
68
67
  return;
69
68
  resolverRegistered = true;
70
69
  const selfEntry = getSelfEntryPath();
71
70
  Bun.plugin({
72
- name: "bustatic-global-self-resolver",
71
+ name: "buntic-global-self-resolver",
73
72
  setup(build) {
74
- const registerAlias = (specifier) => {
75
- build.module(specifier, async () => {
76
- const mod = await import(selfEntry);
77
- return {
78
- exports: { ...mod },
79
- loader: "object"
80
- };
81
- });
82
- };
83
- registerAlias("bun-bustatic");
84
- registerAlias("bustatic");
73
+ build.module("buntic", async () => {
74
+ const mod = await import(selfEntry);
75
+ return {
76
+ exports: { ...mod },
77
+ loader: "object"
78
+ };
79
+ });
85
80
  }
86
81
  });
87
82
  }
@@ -102,7 +97,7 @@ function copyDeclarationFiles(srcDir, destDir) {
102
97
  }
103
98
  function syncProjectTypes(projectRoot) {
104
99
  const absRoot = resolve(projectRoot);
105
- if (hasLocalBustaticPackage(absRoot)) {
100
+ if (hasLocalBunticPackage(absRoot)) {
106
101
  return false;
107
102
  }
108
103
  const pkgRoot = getPackageRoot();
@@ -112,17 +107,17 @@ function syncProjectTypes(projectRoot) {
112
107
  if (pkg?.version)
113
108
  version = pkg.version;
114
109
  } catch {}
115
- const bustaticDir = join(absRoot, ".bustatic");
116
- const typesDir = join(bustaticDir, "types");
110
+ const bunticDir = join(absRoot, ".buntic");
111
+ const typesDir = join(bunticDir, "types");
117
112
  const typesEntry = join(typesDir, "index.d.ts");
118
- const versionMarkerPath = join(bustaticDir, ".types-version");
113
+ const versionMarkerPath = join(bunticDir, ".types-version");
119
114
  const distDir = join(pkgRoot, "dist");
120
115
  const hasBuiltTypes = existsSync(join(distDir, "index.d.ts"));
121
116
  const expectedMarker = `${version}:${hasBuiltTypes ? "dist" : "src"}`;
122
117
  if (existsSync(typesEntry) && existsSync(versionMarkerPath) && readFileSync(versionMarkerPath, "utf8").trim() === expectedMarker) {
123
118
  return false;
124
119
  }
125
- mkdirSync(bustaticDir, { recursive: true });
120
+ mkdirSync(bunticDir, { recursive: true });
126
121
  if (existsSync(typesDir)) {
127
122
  rmSync(typesDir, { recursive: true, force: true });
128
123
  }
@@ -131,7 +126,7 @@ function syncProjectTypes(projectRoot) {
131
126
  copyDeclarationFiles(distDir, typesDir);
132
127
  } else {
133
128
  const srcIndex = join(pkgRoot, "src", "index.ts").replace(/\\/g, "/");
134
- writeFileSync(typesEntry, `// Auto-generated by Bustatic (source dev fallback).
129
+ writeFileSync(typesEntry, `// Auto-generated by Buntic (source dev fallback).
135
130
  export * from "${srcIndex}";
136
131
  `, "utf8");
137
132
  }
@@ -145,13 +140,13 @@ function findProjectRoot(cliTarget, startCwd = process.cwd()) {
145
140
  if (cliTarget && cliTarget !== ".") {
146
141
  const target = resolve2(startCwd, cliTarget);
147
142
  if (!existsSync2(target)) {
148
- throw new Error(`[Bustatic] Specified project directory does not exist: "${target}"`);
143
+ throw new Error(`[Buntic] Specified project directory does not exist: "${target}"`);
149
144
  }
150
145
  return target;
151
146
  }
152
147
  let current = resolve2(startCwd);
153
148
  while (true) {
154
- const hasConfig = existsSync2(join2(current, "bustatic.config.ts")) || existsSync2(join2(current, "bustatic.config.js")) || existsSync2(join2(current, "bustatic.config.json"));
149
+ const hasConfig = existsSync2(join2(current, "buntic.config.ts")) || existsSync2(join2(current, "buntic.config.js")) || existsSync2(join2(current, "buntic.config.json"));
155
150
  if (hasConfig) {
156
151
  return current;
157
152
  }
@@ -172,27 +167,27 @@ function findProjectRoot(cliTarget, startCwd = process.cwd()) {
172
167
  }
173
168
  current = parent;
174
169
  }
175
- throw new Error(`[Bustatic Error]: Could not find a Bustatic project root.
170
+ throw new Error(`[Buntic Error]: Could not find a Buntic project root.
176
171
  ` + ` Searched in: ${startCwd} (and parent directories)
177
172
 
178
173
  ` + `\uD83D\uDC49 How to fix this:
179
174
  ` + ` 1. Ensure you have a "pages/" or "src/pages/" directory with at least one .html file.
180
175
  ` + ` 2. Or pass the project path explicitly:
181
- ` + ` $ bustatic dev <directory> (e.g. bustatic dev examples/simple)
182
- ` + ` 3. Or create a "bustatic.config.ts" / "bustatic.config.json" configuration file (or run "bustatic init").`);
176
+ ` + ` $ buntic dev <directory> (e.g. buntic dev examples/simple)
177
+ ` + ` 3. Or create a "buntic.config.ts" / "buntic.config.json" configuration file (or run "buntic init").`);
183
178
  }
184
179
  async function resolveConfig(cliRootDir = ".", overrides = {}) {
185
180
  const root = findProjectRoot(cliRootDir);
186
181
  let userConfig = {};
187
- const tsConfigPath = join2(root, "bustatic.config.ts");
188
- const jsConfigPath = join2(root, "bustatic.config.js");
189
- const jsonConfigPath = join2(root, "bustatic.config.json");
182
+ const tsConfigPath = join2(root, "buntic.config.ts");
183
+ const jsConfigPath = join2(root, "buntic.config.js");
184
+ const jsonConfigPath = join2(root, "buntic.config.json");
190
185
  if (existsSync2(tsConfigPath)) {
191
- registerBustaticModuleResolver(root);
186
+ registerBunticModuleResolver(root);
192
187
  const mod = await import(tsConfigPath);
193
188
  userConfig = mod.default || mod;
194
189
  } else if (existsSync2(jsConfigPath)) {
195
- registerBustaticModuleResolver(root);
190
+ registerBunticModuleResolver(root);
196
191
  const mod = await import(jsConfigPath);
197
192
  userConfig = mod.default || mod;
198
193
  } else if (existsSync2(jsonConfigPath)) {
@@ -225,7 +220,7 @@ async function resolveConfig(cliRootDir = ".", overrides = {}) {
225
220
  dataDir: resolve2(root, merged.dataDir ?? pickDir("data")),
226
221
  publicDir: resolve2(root, merged.publicDir ?? pickDir("public", true)),
227
222
  storageDir: resolve2(root, merged.storageDir ?? pickDir("storage")),
228
- cacheDir: resolve2(root, merged.cacheDir ?? ".bustatic/cache/images"),
223
+ cacheDir: resolve2(root, merged.cacheDir ?? ".buntic/cache/images"),
229
224
  outDir: resolve2(root, merged.outDir ?? "dist"),
230
225
  port: merged.port ?? 3000,
231
226
  minify: merged.minify ?? true,
@@ -239,7 +234,7 @@ async function resolveConfig(cliRootDir = ".", overrides = {}) {
239
234
 
240
235
  // src/builder/builder.ts
241
236
  import { cpSync as cpSync2, existsSync as existsSync18, mkdirSync as mkdirSync3, rmSync as rmSync3 } from "fs";
242
- 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";
243
238
 
244
239
  // src/assets/photo-tag.ts
245
240
  import { existsSync as existsSync6, statSync as statSync4 } from "fs";
@@ -450,10 +445,10 @@ function getErrorMessage(err) {
450
445
  return String(err);
451
446
  }
452
447
  }
453
- function logWarn(message, label = "Bustatic Warning") {
448
+ function logWarn(message, label = "Buntic Warning") {
454
449
  console.warn(`\x1B[33m\u26A0 [${label}]\x1B[0m ${message}`);
455
450
  }
456
- function logError(message, err, label = "Bustatic Error") {
451
+ function logError(message, err, label = "Buntic Error") {
457
452
  if (err !== undefined) {
458
453
  console.error(`\x1B[31m[${label}]\x1B[0m ${message}:`, getErrorMessage(err));
459
454
  } else {
@@ -528,15 +523,15 @@ class StorageManager {
528
523
  const available = this.getAvailableStorages();
529
524
  if (!targetStorage) {
530
525
  if (available.length === 0) {
531
- throw new Error(`[Bustatic Error] No storage loaders found in "${this.config.storageDir}".
526
+ throw new Error(`[Buntic Error] No storage loaders found in "${this.config.storageDir}".
532
527
  ` + `\uD83D\uDC49 Create a storage loader (e.g. "${join4(this.config.storageDir, "s3.ts")}") to handle key "${key}".`);
533
528
  }
534
- throw new Error(`[Bustatic Error] Multiple storage loaders detected ([${available.join(", ")}]), but no storage name was specified for key "${key}".
535
- ` + `\uD83D\uDC49 Specify storage="..." in your tag or set "defaultStorage" in bustatic.config.ts.`);
529
+ throw new Error(`[Buntic Error] Multiple storage loaders detected ([${available.join(", ")}]), but no storage name was specified for key "${key}".
530
+ ` + `\uD83D\uDC49 Specify storage="..." in your tag or set "defaultStorage" in buntic.config.ts.`);
536
531
  }
537
532
  const storage = this.storages.get(targetStorage);
538
533
  if (!storage) {
539
- throw new Error(`[Bustatic Error] Storage loader "${targetStorage}" not found in "${this.config.storageDir}".
534
+ throw new Error(`[Buntic Error] Storage loader "${targetStorage}" not found in "${this.config.storageDir}".
540
535
  Available storages: [${available.join(", ")}]`);
541
536
  }
542
537
  try {
@@ -550,7 +545,7 @@ class StorageManager {
550
545
  }
551
546
  async function normalizeStorageResult(result, key, storageName) {
552
547
  if (!result) {
553
- throw new Error(`[Bustatic Error] Storage loader "${storageName}" returned null/undefined for key "${key}".`);
548
+ throw new Error(`[Buntic Error] Storage loader "${storageName}" returned null/undefined for key "${key}".`);
554
549
  }
555
550
  if (result instanceof Response) {
556
551
  const arrayBuf = await result.arrayBuffer();
@@ -604,7 +599,7 @@ async function normalizeStorageResult(result, key, storageName) {
604
599
  bytes: new Uint8Array(result)
605
600
  };
606
601
  }
607
- throw new Error(`[Bustatic Error] Unsupported return type from storage loader "${storageName}" for key "${key}".
602
+ throw new Error(`[Buntic Error] Unsupported return type from storage loader "${storageName}" for key "${key}".
608
603
  Expected Uint8Array, ArrayBuffer, Response, BunFile or { bytes, etag?, contentType? }. Received: ${typeof result}`);
609
604
  }
610
605
 
@@ -761,7 +756,7 @@ class PhotoProcessor {
761
756
  const key = attrs.key;
762
757
  const storage = attrs.storage;
763
758
  if (!src && !key) {
764
- throw new Error(`[Bustatic Error] <photo> tag must have a "src" (for local files) or a "key" (for remote storage) in "${templatePath}".
759
+ throw new Error(`[Buntic Error] <photo> tag must have a "src" (for local files) or a "key" (for remote storage) in "${templatePath}".
765
760
  ` + ` Found: ${match.fullMatch}`);
766
761
  }
767
762
  const widths = attrs.widths ? attrs.widths.split(",").map((w) => parseInt(w.trim(), 10)).filter((w) => !isNaN(w) && w > 0) : undefined;
@@ -801,7 +796,7 @@ class PhotoProcessor {
801
796
  }
802
797
  const localPath = resolveLocalAssetPath(this.config, src, templatePath);
803
798
  if (!existsSync6(localPath)) {
804
- throw new Error(`[Bustatic Error] Local image file "${src}" referenced in <photo> not found.
799
+ throw new Error(`[Buntic Error] Local image file "${src}" referenced in <photo> not found.
805
800
  ` + ` Looked in: "${localPath}"
806
801
  ` + ` Referenced in: "${templatePath}"`);
807
802
  }
@@ -936,15 +931,15 @@ function validateRouteParams(requiredTokens, params, loaderPath) {
936
931
  for (const token of requiredTokens) {
937
932
  const rawVal = params[token];
938
933
  if (rawVal === undefined || rawVal === null) {
939
- throw new Error(`[Bustatic Error]: Missing required route parameter "${token}" in loader "${loaderPath}".
934
+ throw new Error(`[Buntic Error]: Missing required route parameter "${token}" in loader "${loaderPath}".
940
935
  Provided parameters: ${JSON.stringify(params)}`);
941
936
  }
942
937
  const strVal = String(rawVal).trim();
943
938
  if (strVal === "") {
944
- throw new Error(`[Bustatic Error]: Route parameter "${token}" in loader "${loaderPath}" cannot be an empty string.`);
939
+ throw new Error(`[Buntic Error]: Route parameter "${token}" in loader "${loaderPath}" cannot be an empty string.`);
945
940
  }
946
941
  if (/[\/\\?#\0]/.test(strVal)) {
947
- throw new Error(`[Bustatic Error]: Route parameter "${token}" with value "${strVal}" in "${loaderPath}" contains invalid characters (/ \\ ? #).`);
942
+ throw new Error(`[Buntic Error]: Route parameter "${token}" with value "${strVal}" in "${loaderPath}" contains invalid characters (/ \\ ? #).`);
948
943
  }
949
944
  cleanParams[token] = strVal;
950
945
  }
@@ -991,7 +986,7 @@ function buildCleanUrl(patternRelPath, params) {
991
986
  }
992
987
  function registerRouteOrThrow(urlRegistry, urlPath, sourceDesc) {
993
988
  if (urlRegistry.has(urlPath)) {
994
- throw new Error(`[Bustatic Collision Error]: Duplicate route generated for "${urlPath}".
989
+ throw new Error(`[Buntic Collision Error]: Duplicate route generated for "${urlPath}".
995
990
  - First generated by: ${urlRegistry.get(urlPath)}
996
991
  - Conflicting with: ${sourceDesc}`);
997
992
  }
@@ -1035,7 +1030,7 @@ async function resolveDynamicRoutes(options) {
1035
1030
  } = options;
1036
1031
  if (!loaderPath) {
1037
1032
  const expected = relPattern.replace(/\.html$/, ".data.ts");
1038
- throw new Error(`[Bustatic Error]: Dynamic page "${relPattern}" contains parameter(s) [${tokens.join(", ")}], but no co-located loader was found.
1033
+ throw new Error(`[Buntic Error]: Dynamic page "${relPattern}" contains parameter(s) [${tokens.join(", ")}], but no co-located loader was found.
1039
1034
  ` + `\uD83D\uDC49 Create "${expected}" exporting a default async function or getStaticPaths().`);
1040
1035
  }
1041
1036
  const relLoader = relative2(config.root, loaderPath);
@@ -1049,7 +1044,7 @@ async function resolveDynamicRoutes(options) {
1049
1044
  }
1050
1045
  const handler = mod.default ?? mod.getStaticPaths;
1051
1046
  if (typeof handler !== "function") {
1052
- throw new Error(`[Bustatic Error]: Loader "${relLoader}" must export a default function ("export default async function") or "getStaticPaths".`);
1047
+ throw new Error(`[Buntic Error]: Loader "${relLoader}" must export a default function ("export default async function") or "getStaticPaths".`);
1053
1048
  }
1054
1049
  const basePattern = relPattern.split(sep2).join("/").replace(/\.html$/, "");
1055
1050
  const lastSlash = basePattern.lastIndexOf("/");
@@ -1066,7 +1061,7 @@ async function resolveDynamicRoutes(options) {
1066
1061
  throw err;
1067
1062
  }
1068
1063
  if (!Array.isArray(pathsResult)) {
1069
- throw new Error(`[Bustatic Error]: Dynamic loader "${relLoader}" must return an Array of path objects ({ params, props }). Received: ${typeof pathsResult}.`);
1064
+ throw new Error(`[Buntic Error]: Dynamic loader "${relLoader}" must return an Array of path objects ({ params, props }). Received: ${typeof pathsResult}.`);
1070
1065
  }
1071
1066
  if (pathsResult.length === 0) {
1072
1067
  logWarn(`Dynamic loader "${relLoader}" returned 0 paths. No pages generated for "${relPattern}".`);
@@ -1076,7 +1071,7 @@ async function resolveDynamicRoutes(options) {
1076
1071
  for (let i = 0;i < pathsResult.length; i++) {
1077
1072
  const item = pathsResult[i];
1078
1073
  if (!item || typeof item !== "object" || !item.params || typeof item.params !== "object") {
1079
- throw new Error(`[Bustatic Error]: Item at index ${i} in loader "${relLoader}" must be an object with a "params" property.
1074
+ throw new Error(`[Buntic Error]: Item at index ${i} in loader "${relLoader}" must be an object with a "params" property.
1080
1075
  Received: ${JSON.stringify(item)}`);
1081
1076
  }
1082
1077
  const cleanParams = validateRouteParams(tokens, item.params, relLoader);
@@ -1310,7 +1305,7 @@ class SeoMetadataEngine {
1310
1305
  imgHeight = processed.height;
1311
1306
  }
1312
1307
  } catch (err) {
1313
- logWarn(`Failed to process social image in "${templatePath}": ${getErrorMessage(err)}`, "Bustatic SEO Warning");
1308
+ logWarn(`Failed to process social image in "${templatePath}": ${getErrorMessage(err)}`, "Buntic SEO Warning");
1314
1309
  }
1315
1310
  }
1316
1311
  const metaTags = this.generateMetaTagsHtml({
@@ -1489,7 +1484,184 @@ ${urlsXml.join(`
1489
1484
 
1490
1485
  // src/template/engine.ts
1491
1486
  import { existsSync as existsSync16 } from "fs";
1492
- 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
+ }
1493
1665
 
1494
1666
  // src/template/css-graph.ts
1495
1667
  import { basename as basename4, dirname as dirname6, resolve as resolve4, relative as relative3, join as join11 } from "path";
@@ -1549,13 +1721,13 @@ class WebComponentRegistry {
1549
1721
  const expectedTag = filenameToTagName(filePath);
1550
1722
  if (!expectedTag) {
1551
1723
  if (content && /(?:customElements\.define|@customElement)\s*\(\s*["']([a-z0-9-]+)["']/i.test(content)) {
1552
- console.warn(`\x1B[33m\u26A0 [Bustatic Warning]\x1B[0m Web Component file "${filePath}" does not match naming convention (must be hyphenated kebab-case like "my-button.ts" or PascalCase like "MyButton.ts"). Registration skipped.`);
1724
+ console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Web Component file "${filePath}" does not match naming convention (must be hyphenated kebab-case like "my-button.ts" or PascalCase like "MyButton.ts"). Registration skipped.`);
1553
1725
  }
1554
1726
  return [];
1555
1727
  }
1556
1728
  const validation = this.validateTagName(expectedTag);
1557
1729
  if (!validation.valid) {
1558
- console.warn(`\x1B[33m\u26A0 [Bustatic Warning]\x1B[0m Skipping invalid Custom Element tag "${expectedTag}" in ${filePath}: ${validation.reason}`);
1730
+ console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Skipping invalid Custom Element tag "${expectedTag}" in ${filePath}: ${validation.reason}`);
1559
1731
  return [];
1560
1732
  }
1561
1733
  if (content) {
@@ -1566,13 +1738,13 @@ class WebComponentRegistry {
1566
1738
  declaredTags.add(match[1].toLowerCase());
1567
1739
  }
1568
1740
  if (declaredTags.size > 1) {
1569
- console.warn(`\x1B[33m\u26A0 [Bustatic Warning]\x1B[0m File "${filePath}" declares multiple Custom Elements (${Array.from(declaredTags).map((t) => `<${t}>`).join(", ")}). Bustatic strictly enforces 1 Web Component per file. File skipped.`);
1741
+ console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m File "${filePath}" declares multiple Custom Elements (${Array.from(declaredTags).map((t) => `<${t}>`).join(", ")}). Buntic strictly enforces 1 Web Component per file. File skipped.`);
1570
1742
  return [];
1571
1743
  }
1572
1744
  if (declaredTags.size === 1) {
1573
1745
  const declaredTag = Array.from(declaredTags)[0];
1574
1746
  if (declaredTag !== expectedTag) {
1575
- console.warn(`\x1B[33m\u26A0 [Bustatic Warning]\x1B[0m Tag "<${declaredTag}>" in "${filePath}" does not match filename. Expected tag "<${expectedTag}>" for file "${basename3(filePath)}". Registration skipped.`);
1747
+ console.warn(`\x1B[33m\u26A0 [Buntic Warning]\x1B[0m Tag "<${declaredTag}>" in "${filePath}" does not match filename. Expected tag "<${expectedTag}>" for file "${basename3(filePath)}". Registration skipped.`);
1576
1748
  return [];
1577
1749
  }
1578
1750
  }
@@ -1584,7 +1756,7 @@ class WebComponentRegistry {
1584
1756
  conflictFiles.push(filePath);
1585
1757
  }
1586
1758
  this.conflicts.set(expectedTag, conflictFiles);
1587
- console.warn(`\x1B[33m\u26A0 [Bustatic Collision Warning]\x1B[0m Tag "<${expectedTag}>" in ${filePath} conflicts with definition in ${existingFile}.`);
1759
+ console.warn(`\x1B[33m\u26A0 [Buntic Collision Warning]\x1B[0m Tag "<${expectedTag}>" in ${filePath} conflicts with definition in ${existingFile}.`);
1588
1760
  return [];
1589
1761
  }
1590
1762
  this.tagToFile.set(expectedTag, filePath);
@@ -1641,7 +1813,7 @@ ${c.files.map((f) => ` - ${f}`).join(`
1641
1813
  `)}`).join(`
1642
1814
 
1643
1815
  `);
1644
- throw new Error(`[Bustatic Conflict Error]: Tag collision detected between Web Components:
1816
+ throw new Error(`[Buntic Conflict Error]: Tag collision detected between Web Components:
1645
1817
  ${details}
1646
1818
 
1647
1819
  ` + `\uD83D\uDC49 Each Custom Element tag must be uniquely defined.`);
@@ -2371,7 +2543,7 @@ async function resolvePageCss(options) {
2371
2543
  } catch {
2372
2544
  cssContent = await Bun.file(cssFilePath).text();
2373
2545
  }
2374
- const styleBlock = `<style id="__bustatic_global">
2546
+ const styleBlock = `<style id="__buntic_global">
2375
2547
  ${cssContent}
2376
2548
  </style>`;
2377
2549
  result = replaceLiteral(result, fullTag, styleBlock);
@@ -2379,15 +2551,15 @@ ${cssContent}
2379
2551
  }
2380
2552
  }
2381
2553
  const headMatch = result.match(/<head[\s\S]*?<\/head>/i);
2382
- const headHasGlobalStyle = headMatch ? headMatch[0].includes('id="__bustatic_global"') : false;
2554
+ const headHasGlobalStyle = headMatch ? headMatch[0].includes('id="__buntic_global"') : false;
2383
2555
  if (!hadManualGlobalLink && !headHasGlobalStyle && globalCssContent) {
2384
- const globalTag = ` <style id="__bustatic_global">
2556
+ const globalTag = ` <style id="__buntic_global">
2385
2557
  ${globalCssContent}
2386
2558
  </style>`;
2387
2559
  result = injectIntoHead(result, globalTag, "prepend");
2388
2560
  }
2389
2561
  if (hasScopedRules) {
2390
- const scopedTag = ` <style id="__bustatic_scoped">
2562
+ const scopedTag = ` <style id="__buntic_scoped">
2391
2563
  ${scopedCssText}
2392
2564
  </style>`;
2393
2565
  result = injectIntoHead(result, scopedTag, "append");
@@ -2469,6 +2641,157 @@ function loadPublicEnv(projectRoot) {
2469
2641
  return publicEnv;
2470
2642
  }
2471
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
+
2472
2795
  // src/template/data-loader.ts
2473
2796
  async function loadGlobalData(config, vfs) {
2474
2797
  const data = {};
@@ -2502,8 +2825,15 @@ async function loadGlobalData(config, vfs) {
2502
2825
  if (isJson) {
2503
2826
  try {
2504
2827
  data[key] = await vfs.readJson(fullPath);
2505
- } catch {
2506
- 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
+ });
2507
2837
  }
2508
2838
  } else if (isModule) {
2509
2839
  try {
@@ -2523,20 +2853,30 @@ async function loadGlobalData(config, vfs) {
2523
2853
  }
2524
2854
  }
2525
2855
  } catch (err) {
2526
- if (err instanceof Error && err.message.includes("[Bustatic Error]")) {
2856
+ if (err instanceof BunticTemplateError || err instanceof Error && err.message.includes("[Buntic Error]")) {
2527
2857
  throw err;
2528
2858
  }
2529
2859
  }
2530
2860
  return data;
2531
2861
  }
2532
2862
 
2533
- // 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
+ }
2534
2874
  function isTruthy(val) {
2535
2875
  if (val === undefined || val === null || val === false || val === "")
2536
2876
  return false;
2537
2877
  if (Array.isArray(val) && val.length === 0)
2538
2878
  return false;
2539
- if (typeof val === "number" && isNaN(val))
2879
+ if (typeof val === "number" && Number.isNaN(val))
2540
2880
  return false;
2541
2881
  return true;
2542
2882
  }
@@ -2546,36 +2886,602 @@ function getNestedValue(obj, path) {
2546
2886
  const parts = path.split(".");
2547
2887
  let cur = obj;
2548
2888
  for (const part of parts) {
2549
- 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")
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
+ }
2550
2911
  return;
2912
+ }
2913
+ if (!Object.prototype.hasOwnProperty.call(cur, part)) {
2914
+ return;
2915
+ }
2551
2916
  cur = cur[part];
2552
2917
  }
2553
2918
  return cur;
2554
2919
  }
2555
- function resolveConditionals(html, context) {
2556
- let res = html.replace(/<if\s+is=["']([^"']+)["'][^>]*>([\s\S]*?)<\/if>/gi, (_match, expr, inner) => {
2557
- const val = getNestedValue(context, expr.trim());
2558
- let thenContent = inner;
2559
- let elseContent = "";
2560
- const elseMatch = inner.match(/([\s\S]*?)<else>([\s\S]*?)<\/else>/i);
2561
- if (elseMatch) {
2562
- thenContent = elseMatch[1];
2563
- elseContent = elseMatch[2];
2564
- }
2565
- 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
2566
3227
  });
2567
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)\s*\/>/gi, (_m, tag, before, expr, after) => {
2568
- 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);
2569
3472
  if (!isTruthy(val))
2570
3473
  return "";
2571
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
3474
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
2572
3475
  return attrs ? `<${tag} ${attrs} />` : `<${tag} />`;
2573
3476
  });
2574
- res = res.replace(/<([a-zA-Z0-9_-]+)\s+([^>]*?)if=["']([^"']+)["']([^>]*?)>([\s\S]*?)<\/\1>/gi, (_m, tag, before, expr, after, content) => {
2575
- 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);
2576
3482
  if (!isTruthy(val))
2577
3483
  return "";
2578
- const attrs = `${before} ${after}`.trim().replace(/\s+/g, " ");
3484
+ const attrs = `${before ?? ""} ${after ?? ""}`.trim().replace(/\s+/g, " ");
2579
3485
  return attrs ? `<${tag} ${attrs}>${content}</${tag}>` : `<${tag}>${content}</${tag}>`;
2580
3486
  });
2581
3487
  return res;
@@ -2593,7 +3499,7 @@ function interpolateTemplate(html, context) {
2593
3499
  }
2594
3500
 
2595
3501
  // src/template/dsd-renderer.ts
2596
- import { relative as relative5 } from "path";
3502
+ import { relative as relative6 } from "path";
2597
3503
  function hasScriptWithSrc(html, srcPath) {
2598
3504
  const cleanSrc = srcPath.replace(/^\/+/, "");
2599
3505
  const scriptRegex = /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi;
@@ -2625,7 +3531,7 @@ async function resolveWebComponentsInHtml(options) {
2625
3531
  if (globalRoot.root) {
2626
3532
  if (config.cssStrategy === "inline") {
2627
3533
  const globalCss = await cssGraph.flattenCss(globalRoot.root, vfs);
2628
- globalCssBlock = `<style data-bustatic="global">
3534
+ globalCssBlock = `<style data-buntic="global">
2629
3535
  ${globalCss.trim()}
2630
3536
  </style>`;
2631
3537
  } else if (globalRoot.relativeRoot) {
@@ -2654,7 +3560,7 @@ ${globalCss.trim()}
2654
3560
  continue;
2655
3561
  }
2656
3562
  vfs.registry.markTagUsed(tag);
2657
- const rel = relative5(config.root, scriptPath).replace(/\\/g, "/");
3563
+ const rel = relative6(config.root, scriptPath).replace(/\\/g, "/");
2658
3564
  const publicSrc = rel.startsWith("/") ? rel : `/${rel}`;
2659
3565
  if (!injectedPaths.has(publicSrc) && !hasScriptWithSrc(result, publicSrc)) {
2660
3566
  injectedPaths.add(publicSrc);
@@ -2698,14 +3604,19 @@ ${siblingCss.trim()}
2698
3604
  } catch {
2699
3605
  rawHtml = await Bun.file(triad.htmlPath).text();
2700
3606
  }
3607
+ const originalRawHtml = rawHtml;
2701
3608
  rawHtml = await resolveComponentsFn(rawHtml, context, triad.htmlPath);
2702
- rawHtml = resolveConditionals(rawHtml, context);
3609
+ rawHtml = resolveConditionals(rawHtml, context, {
3610
+ filePath: triad.htmlPath,
3611
+ source: originalRawHtml,
3612
+ projectRoot: config.root
3613
+ });
2703
3614
  rawHtml = interpolateTemplate(rawHtml, context);
2704
3615
  if (rawHtml.includes("<style") && rawHtml.includes("scoped")) {
2705
3616
  const extracted = extractScopedStyles(rawHtml, scopeRegistry);
2706
3617
  rawHtml = extracted.html;
2707
3618
  if (extracted.scopedRules.length > 0) {
2708
- scopedDsdCssBlock = `<style data-bustatic="dsd-scoped">
3619
+ scopedDsdCssBlock = `<style data-buntic="dsd-scoped">
2709
3620
  ${extracted.scopedRules.join(`
2710
3621
 
2711
3622
  `)}
@@ -2754,7 +3665,7 @@ ${templateTag}`;
2754
3665
  }
2755
3666
 
2756
3667
  // src/template/svg-component.ts
2757
- import { relative as relative6 } from "path";
3668
+ import { relative as relative7 } from "path";
2758
3669
  async function attachSiblingCssIfPresent(options) {
2759
3670
  const { templateHtml, templatePath, siblingCssPath, kindLabel, config, vfs, cssGraph } = options;
2760
3671
  if (!vfs.hasFile(siblingCssPath)) {
@@ -2773,8 +3684,8 @@ async function attachSiblingCssIfPresent(options) {
2773
3684
  if (withScopedCss !== null) {
2774
3685
  return withScopedCss;
2775
3686
  }
2776
- const relTarget = relative6(config.root, templatePath);
2777
- const relCss = relative6(config.root, siblingCssPath);
3687
+ const relTarget = relative7(config.root, templatePath);
3688
+ const relCss = relative7(config.root, siblingCssPath);
2778
3689
  logWarn(`${kindLabel} "${relTarget}" has a sibling CSS file ("${relCss}"), but does not have a single root element. Scoped styles were not applied.`);
2779
3690
  return templateHtml;
2780
3691
  }
@@ -2837,7 +3748,7 @@ function isIgnoredPath(filePathOrName) {
2837
3748
  const normalized = filePathOrName.replace(/\\/g, "/");
2838
3749
  const segments = normalized.split("/");
2839
3750
  for (const seg of segments) {
2840
- if (seg === "node_modules" || seg === ".git" || seg === ".agents" || seg === "dist" || seg.startsWith(".bustatic")) {
3751
+ if (seg === "node_modules" || seg === ".git" || seg === ".agents" || seg === "dist" || seg.startsWith(".buntic")) {
2841
3752
  return true;
2842
3753
  }
2843
3754
  }
@@ -3091,8 +4002,8 @@ class TemplateEngine {
3091
4002
  await this.cssGraph.analyze(this.vfs);
3092
4003
  const globalRoot = this.cssGraph.getGlobalRoot();
3093
4004
  if (globalRoot.conflicts.length > 1) {
3094
- const relConflicts = globalRoot.conflicts.map((c) => relative7(this.config.root, c));
3095
- 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.`, "Bustatic Conflict Warning");
4005
+ const relConflicts = globalRoot.conflicts.map((c) => relative8(this.config.root, c));
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");
3096
4007
  }
3097
4008
  let processedHtml = pageHtml;
3098
4009
  if (currentFile && currentFile.endsWith(".html")) {
@@ -3109,7 +4020,7 @@ class TemplateEngine {
3109
4020
  let composed = await this.resolveLayout(processedHtml, context, currentFile);
3110
4021
  composed = await this.resolveEach(composed, context, currentFile);
3111
4022
  composed = await this.resolveComponents(composed, context, currentFile);
3112
- composed = this.resolveConditionals(composed, context);
4023
+ composed = this.resolveConditionals(composed, context, currentFile, pageHtml);
3113
4024
  composed = this.interpolate(composed, context);
3114
4025
  composed = await this.resolveWebComponents(composed, context);
3115
4026
  composed = await this.resolveCss(composed, currentFile);
@@ -3151,6 +4062,16 @@ class TemplateEngine {
3151
4062
  resolveFilePath(rawSrc, currentFile, defaultDir) {
3152
4063
  return this.vfs.resolvePath(rawSrc, currentFile, defaultDir);
3153
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
+ }
3154
4075
  async resolveLayout(html, context, currentFile) {
3155
4076
  const layoutMatch = html.match(/<layout\s+src=["']([^"']+)["'][^>]*>([\s\S]*?)<\/layout>/i);
3156
4077
  if (!layoutMatch) {
@@ -3160,7 +4081,24 @@ class TemplateEngine {
3160
4081
  const innerContent = layoutMatch[2];
3161
4082
  const layoutFilePath = this.resolveFilePath(layoutRawSrc, currentFile, this.config.layoutsDir);
3162
4083
  if (!this.vfs.hasFile(layoutFilePath) && !existsSync16(layoutFilePath)) {
3163
- throw new Error(`[Bustatic] 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
+ });
3164
4102
  }
3165
4103
  const layoutTemplate = await this.vfs.readText(layoutFilePath);
3166
4104
  let resolvedInner = await this.resolveEach(innerContent, context, currentFile);
@@ -3196,34 +4134,143 @@ class TemplateEngine {
3196
4134
  }
3197
4135
  async resolveEach(html, context, currentFile, depth = 0) {
3198
4136
  if (depth > 10) {
3199
- console.warn("[Bustatic] Maximum <each> recursion depth (10) reached.");
4137
+ console.warn("[Buntic] Maximum <each> recursion depth (10) reached.");
3200
4138
  return html;
3201
4139
  }
3202
- const eachRegex = /<each\s+([^>]+?)>([\s\S]*?)<\/each>/gis;
3203
- let match;
3204
- const matches = [];
3205
- while ((match = eachRegex.exec(html)) !== null) {
3206
- matches.push({ fullMatch: match[0], attrString: match[1], inner: match[2] });
3207
- }
4140
+ const matches = findTopLevelBlocks(html, ["each"]);
3208
4141
  if (matches.length === 0)
3209
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
+ };
3210
4165
  let result = html;
3211
4166
  for (const item of matches) {
3212
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
+ }
3213
4180
  let items;
4181
+ let resolvedFilePath;
3214
4182
  if (attrs.src) {
3215
4183
  const filePath = this.resolveFilePath(attrs.src, currentFile, this.config.dataDir);
4184
+ resolvedFilePath = filePath;
3216
4185
  if (!this.vfs.hasFile(filePath) && !existsSync16(filePath)) {
3217
- throw new Error(`[Bustatic] <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
+ });
3218
4232
  }
3219
- items = await this.vfs.readJson(filePath);
3220
4233
  } else if (attrs.in) {
3221
4234
  items = getNestedValue(context, attrs.in);
3222
4235
  } else {
3223
- throw new Error(`[Bustatic] <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;
3224
4249
  }
3225
4250
  if (!Array.isArray(items)) {
3226
- throw new Error(`[Bustatic] <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;
3227
4274
  }
3228
4275
  const renderedItems = [];
3229
4276
  for (const entry of items) {
@@ -3240,9 +4287,9 @@ class TemplateEngine {
3240
4287
  itemContext.item = entry;
3241
4288
  itemContext.this = entry;
3242
4289
  }
3243
- let rendered = await this.resolveEach(item.inner, itemContext, currentFile, depth + 1);
4290
+ let rendered = await this.resolveEach(loopTemplate, itemContext, currentFile, depth + 1);
3244
4291
  rendered = await this.resolveComponents(rendered, itemContext, currentFile, depth + 1);
3245
- rendered = this.resolveConditionals(rendered, itemContext);
4292
+ rendered = this.resolveConditionals(rendered, itemContext, currentFile, originalSourceForFile);
3246
4293
  rendered = this.interpolate(rendered, itemContext);
3247
4294
  renderedItems.push(rendered);
3248
4295
  }
@@ -3253,7 +4300,7 @@ class TemplateEngine {
3253
4300
  }
3254
4301
  async resolveComponents(html, context, currentFile, depth = 0) {
3255
4302
  if (depth > 10) {
3256
- console.warn("[Bustatic] Maximum component recursion depth (10) reached. Check for circular component includes.");
4303
+ console.warn("[Buntic] Maximum component recursion depth (10) reached. Check for circular component includes.");
3257
4304
  return html;
3258
4305
  }
3259
4306
  const componentRegex = /<component\s+([^>]+?)(?:\s*\/>|>(.*?)<\/component>)/gis;
@@ -3262,11 +4309,15 @@ class TemplateEngine {
3262
4309
  while ((match = componentRegex.exec(html)) !== null) {
3263
4310
  const props = parseHtmlAttributes(match[1]);
3264
4311
  if (props.src) {
4312
+ const fullMatch = match[0];
4313
+ const openTagEnd = fullMatch.indexOf(">");
3265
4314
  matches.push({
3266
- fullMatch: match[0],
4315
+ fullMatch,
4316
+ openTag: openTagEnd !== -1 ? fullMatch.slice(0, openTagEnd + 1) : fullMatch,
3267
4317
  children: match[2] ? match[2].trim() : "",
3268
4318
  src: props.src,
3269
- props
4319
+ props,
4320
+ index: match.index
3270
4321
  });
3271
4322
  }
3272
4323
  }
@@ -3276,7 +4327,23 @@ class TemplateEngine {
3276
4327
  for (const item of matches) {
3277
4328
  const compPath = this.resolveFilePath(item.src, currentFile, this.config.componentsDir);
3278
4329
  if (!this.vfs.hasFile(compPath) && !existsSync16(compPath)) {
3279
- throw new Error(`[Bustatic] 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
+ });
3280
4347
  }
3281
4348
  const ext = extname4(compPath).toLowerCase();
3282
4349
  if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
@@ -3287,7 +4354,11 @@ class TemplateEngine {
3287
4354
  children: item.children,
3288
4355
  context,
3289
4356
  currentFile,
3290
- depth
4357
+ depth,
4358
+ snippet: item.fullMatch,
4359
+ openTag: item.openTag,
4360
+ offset: item.index,
4361
+ sourceHtml: html
3291
4362
  });
3292
4363
  result = replaceLiteral(result, item.fullMatch, replacement);
3293
4364
  continue;
@@ -3303,9 +4374,9 @@ class TemplateEngine {
3303
4374
  result = replaceLiteral(result, item.fullMatch, svgContent);
3304
4375
  continue;
3305
4376
  }
3306
- let compTemplate = await this.vfs.readText(compPath);
3307
- compTemplate = await attachSiblingCssIfPresent({
3308
- templateHtml: compTemplate,
4377
+ const rawCompTemplate = await this.vfs.readText(compPath);
4378
+ let compTemplate = await attachSiblingCssIfPresent({
4379
+ templateHtml: rawCompTemplate,
3309
4380
  templatePath: compPath,
3310
4381
  siblingCssPath: compPath.replace(/\.html$/, ".css"),
3311
4382
  kindLabel: "Component",
@@ -3316,7 +4387,7 @@ class TemplateEngine {
3316
4387
  const compContext = { ...context, ...item.props };
3317
4388
  compTemplate = compTemplate.replace(/<slot\s*>\s*<\/slot>/gi, () => item.children);
3318
4389
  compTemplate = compTemplate.replace(/<slot\s*\/>/gi, () => item.children);
3319
- compTemplate = this.resolveConditionals(compTemplate, compContext);
4390
+ compTemplate = this.resolveConditionals(compTemplate, compContext, compPath, rawCompTemplate);
3320
4391
  compTemplate = this.interpolate(compTemplate, compContext);
3321
4392
  compTemplate = await this.resolveComponents(compTemplate, compContext, compPath, depth + 1);
3322
4393
  result = replaceLiteral(result, item.fullMatch, compTemplate);
@@ -3324,7 +4395,19 @@ class TemplateEngine {
3324
4395
  return result;
3325
4396
  }
3326
4397
  async renderWebComponentAlias(options) {
3327
- 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;
3328
4411
  let tag = this.vfs.registry.getTagsForFile(compPath)[0];
3329
4412
  if (!tag) {
3330
4413
  let code;
@@ -3340,20 +4423,38 @@ class TemplateEngine {
3340
4423
  tag = filenameToTagName(compPath) || undefined;
3341
4424
  }
3342
4425
  if (!tag) {
3343
- throw new Error(`[Bustatic] 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
+ });
3344
4441
  }
3345
4442
  const attrEntries = Object.entries(props).filter(([k]) => k !== "src");
3346
4443
  const attrString = attrEntries.length > 0 ? " " + attrEntries.map(([k, v]) => `${k}="${v}"`).join(" ") : "";
3347
4444
  let innerChildren = children;
3348
4445
  if (innerChildren) {
3349
4446
  innerChildren = await this.resolveComponents(innerChildren, context, currentFile, depth + 1);
3350
- innerChildren = this.resolveConditionals(innerChildren, context);
4447
+ innerChildren = this.resolveConditionals(innerChildren, context, currentFile, sourceHtml);
3351
4448
  innerChildren = this.interpolate(innerChildren, context);
3352
4449
  }
3353
4450
  return innerChildren ? `<${tag}${attrString}>${innerChildren}</${tag}>` : `<${tag}${attrString}></${tag}>`;
3354
4451
  }
3355
- resolveConditionals(html, context) {
3356
- 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
+ });
3357
4458
  }
3358
4459
  interpolate(html, context) {
3359
4460
  return interpolateTemplate(html, context);
@@ -3362,7 +4463,7 @@ class TemplateEngine {
3362
4463
 
3363
4464
  // src/builder/collisions.ts
3364
4465
  import { existsSync as existsSync17 } from "fs";
3365
- import { join as join16, relative as relative8 } from "path";
4466
+ import { join as join16, relative as relative9 } from "path";
3366
4467
  function getDirectoryFiles(dir, baseDir = dir) {
3367
4468
  return walkFiles(dir, {
3368
4469
  baseDir,
@@ -3377,7 +4478,7 @@ function detectPublicCollisions(config, routes) {
3377
4478
  const collisions = [];
3378
4479
  const routeOutputMap = new Map;
3379
4480
  for (const route of routes) {
3380
- const relOut = relative8(config.outDir, route.outputFilePath).replace(/\\/g, "/");
4481
+ const relOut = relative9(config.outDir, route.outputFilePath).replace(/\\/g, "/");
3381
4482
  routeOutputMap.set(relOut, route);
3382
4483
  }
3383
4484
  for (const relFile of publicFiles) {
@@ -3385,23 +4486,23 @@ function detectPublicCollisions(config, routes) {
3385
4486
  const route = routeOutputMap.get(relFile);
3386
4487
  collisions.push({
3387
4488
  type: "route",
3388
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
3389
- conflictWith: relative8(config.root, route.templateFilePath),
4489
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
4490
+ conflictWith: relative9(config.root, route.templateFilePath),
3390
4491
  outputPath: relFile
3391
4492
  });
3392
4493
  }
3393
4494
  if (relFile.startsWith("assets/images/") || relFile === "assets/images") {
3394
4495
  collisions.push({
3395
4496
  type: "reserved-dir",
3396
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
3397
- conflictWith: "assets/images/ (Reserved for Bustatic <photo> image optimization)",
4497
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
4498
+ conflictWith: "assets/images/ (Reserved for Buntic <photo> image optimization)",
3398
4499
  outputPath: relFile
3399
4500
  });
3400
4501
  } else if (relFile.startsWith("assets/seo/") || relFile === "assets/seo") {
3401
4502
  collisions.push({
3402
4503
  type: "reserved-dir",
3403
- publicPath: relative8(config.root, join16(config.publicDir, relFile)),
3404
- conflictWith: "assets/seo/ (Reserved for Bustatic <seo> social cards)",
4504
+ publicPath: relative9(config.root, join16(config.publicDir, relFile)),
4505
+ conflictWith: "assets/seo/ (Reserved for Buntic <seo> social cards)",
3405
4506
  outputPath: relFile
3406
4507
  });
3407
4508
  }
@@ -3419,7 +4520,7 @@ function assertNoPublicCollisions(config, routes) {
3419
4520
  return ` - Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`;
3420
4521
  }).join(`
3421
4522
  `);
3422
- throw new Error(`[Bustatic Collision Error]: Conflict detected between public/ files and build output:
4523
+ throw new Error(`[Buntic Collision Error]: Conflict detected between public/ files and build output:
3423
4524
  ` + details + `
3424
4525
 
3425
4526
  \uD83D\uDC49 Action: Remove or rename conflicting files in "public/" or adjust page routes in "pages/".`);
@@ -3445,17 +4546,17 @@ class Builder {
3445
4546
  this.engine.assertNoWebComponentConflicts();
3446
4547
  this.engine.clearUsedWebComponents();
3447
4548
  if (!existsSync18(this.config.pagesDir)) {
3448
- throw new Error(`[Bustatic] Pages directory not found at: ${this.config.pagesDir}`);
4549
+ throw new Error(`[Buntic] Pages directory not found at: ${this.config.pagesDir}`);
3449
4550
  }
3450
4551
  const globalData = await this.engine.loadData();
3451
4552
  const routes = await resolveAllRoutes(this.config, globalData);
3452
4553
  if (routes.length === 0) {
3453
- console.warn(`[Bustatic] No HTML pages found in: ${this.config.pagesDir}`);
4554
+ console.warn(`[Buntic] No HTML pages found in: ${this.config.pagesDir}`);
3454
4555
  return { success: true, pagesCount: 0, outputFiles: [], durationMs: 0 };
3455
4556
  }
3456
4557
  assertNoPublicCollisions(this.config, routes);
3457
4558
  this.prepareEmptyDir(this.config.outDir);
3458
- const stagingDir = join17(this.config.root, ".bustatic-staging");
4559
+ const stagingDir = join17(this.config.root, ".buntic-staging");
3459
4560
  this.prepareEmptyDir(stagingDir);
3460
4561
  try {
3461
4562
  const stagedEntrypoints = await this.stagePages(routes, stagingDir);
@@ -3502,7 +4603,7 @@ class Builder {
3502
4603
  }
3503
4604
  }
3504
4605
  }
3505
- const relStagedPath = relative9(this.config.outDir, route.outputFilePath);
4606
+ const relStagedPath = relative10(this.config.outDir, route.outputFilePath);
3506
4607
  const stagedPath = join17(stagingDir, relStagedPath);
3507
4608
  mkdirSync3(dirname9(stagedPath), { recursive: true });
3508
4609
  rendered = this.normalizeRootPaths(rendered, stagedPath, stagingDir);
@@ -3528,7 +4629,7 @@ class Builder {
3528
4629
  for (const log of buildResult.logs) {
3529
4630
  console.error(log);
3530
4631
  }
3531
- throw new Error("[Bustatic] Bun.build bundling failed.");
4632
+ throw new Error("[Buntic] Bun.build bundling failed.");
3532
4633
  }
3533
4634
  return buildResult.outputs.map((o) => o.path);
3534
4635
  }
@@ -3580,25 +4681,25 @@ class Builder {
3580
4681
  warnUnusedWebComponents() {
3581
4682
  const unused = this.engine.getUnusedWebComponents();
3582
4683
  for (const item of unused) {
3583
- 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.`);
3584
4685
  }
3585
4686
  }
3586
4687
  normalizeRootPaths(html, stagedFilePath, stagingDir) {
3587
4688
  const fromDir = dirname9(stagedFilePath);
3588
4689
  return html.replace(/(href|src)=["']\/([^"']+)["']/gi, (match, attr, path) => {
3589
- if (path.startsWith("/") || path.startsWith("http:") || path.startsWith("https:") || path.startsWith("_bustatic") || path.startsWith("assets/images/") || path.startsWith("assets/seo/")) {
4690
+ if (path.startsWith("/") || path.startsWith("http:") || path.startsWith("https:") || path.startsWith("_buntic") || path.startsWith("assets/images/") || path.startsWith("assets/seo/")) {
3590
4691
  return match;
3591
4692
  }
3592
4693
  const targetInRoot = join17(this.config.root, path);
3593
4694
  if (existsSync18(targetInRoot)) {
3594
- let rel = relative9(fromDir, targetInRoot);
4695
+ let rel = relative10(fromDir, targetInRoot);
3595
4696
  if (!rel.startsWith("."))
3596
4697
  rel = "./" + rel;
3597
4698
  return `${attr}="${rel}"`;
3598
4699
  }
3599
4700
  const targetInSrc = join17(this.config.root, "src", path);
3600
4701
  if (existsSync18(targetInSrc)) {
3601
- let rel = relative9(fromDir, targetInSrc);
4702
+ let rel = relative10(fromDir, targetInSrc);
3602
4703
  if (!rel.startsWith("."))
3603
4704
  rel = "./" + rel;
3604
4705
  return `${attr}="${rel}"`;
@@ -3606,7 +4707,7 @@ class Builder {
3606
4707
  if (stagingDir) {
3607
4708
  const targetInStaging = join17(stagingDir, path);
3608
4709
  if (existsSync18(targetInStaging)) {
3609
- let rel = relative9(fromDir, targetInStaging);
4710
+ let rel = relative10(fromDir, targetInStaging);
3610
4711
  if (!rel.startsWith("."))
3611
4712
  rel = "./" + rel;
3612
4713
  return `${attr}="${rel}"`;
@@ -3625,13 +4726,13 @@ import { join as join19, resolve as resolve7 } from "path";
3625
4726
  import { existsSync as existsSync19, statSync as statSync7 } from "fs";
3626
4727
  import { join as join18 } from "path";
3627
4728
  var LIVE_RELOAD_SCRIPT = `
3628
- <script id="__bustatic_live_reload">
4729
+ <script id="__buntic_live_reload">
3629
4730
  (() => {
3630
4731
  const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
3631
- const ws = new WebSocket(\`\${protocol}//\${location.host}/_bustatic/ws\`);
4732
+ const ws = new WebSocket(\`\${protocol}//\${location.host}/_buntic/ws\`);
3632
4733
  ws.onmessage = (event) => {
3633
4734
  if (event.data === 'reload') {
3634
- console.log('[bustatic] Change detected. Reloading...');
4735
+ console.log('[buntic] Change detected. Reloading...');
3635
4736
  location.reload();
3636
4737
  }
3637
4738
  };
@@ -3759,10 +4860,82 @@ function getMimeType(path) {
3759
4860
  return "text/plain; charset=utf-8";
3760
4861
  return "application/octet-stream";
3761
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
+ }
3762
4877
  function renderErrorResponse(title, err) {
3763
4878
  const safeTitle = escapeHtml(title);
3764
4879
  const safeMsg = escapeHtml(getErrorMessage(err));
3765
- 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, {
3766
4939
  status: 500,
3767
4940
  headers: { "Content-Type": "text/html; charset=utf-8" }
3768
4941
  });
@@ -3779,7 +4952,7 @@ function renderNotFoundResponse(pathname, routes) {
3779
4952
  <!doctype html>
3780
4953
  <html>
3781
4954
  <head>
3782
- <title>404 - Not Found | Bustatic Dev</title>
4955
+ <title>404 - Not Found | Buntic Dev</title>
3783
4956
  <style>
3784
4957
  body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; padding: 3rem; }
3785
4958
  .card { max-width: 650px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 12px; border: 1px solid #334155; }
@@ -3818,9 +4991,9 @@ function startDevServer(config) {
3818
4991
  const collisions = detectPublicCollisions(config, routes);
3819
4992
  for (const c of collisions) {
3820
4993
  if (c.type === "route") {
3821
- logWarn(`Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both resolve to "${c.outputPath}").`, "Bustatic Collision Warning");
4994
+ logWarn(`Public file "${c.publicPath}" conflicts with page template "${c.conflictWith}" (both resolve to "${c.outputPath}").`, "Buntic Collision Warning");
3822
4995
  } else {
3823
- logWarn(`Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`, "Bustatic Collision Warning");
4996
+ logWarn(`Public file "${c.publicPath}" conflicts with reserved internal path "${c.conflictWith}".`, "Buntic Collision Warning");
3824
4997
  }
3825
4998
  }
3826
4999
  } catch {}
@@ -3867,7 +5040,7 @@ function startDevServer(config) {
3867
5040
  } catch {
3868
5041
  return new Response("Bad Request", { status: 400 });
3869
5042
  }
3870
- if (pathname === "/_bustatic/ws") {
5043
+ if (pathname === "/_buntic/ws") {
3871
5044
  if (srv.upgrade(req))
3872
5045
  return;
3873
5046
  return new Response("WebSocket upgrade failed", { status: 400 });
@@ -3913,7 +5086,7 @@ function startDevServer(config) {
3913
5086
  seoEngine
3914
5087
  });
3915
5088
  } catch (err) {
3916
- return renderErrorResponse("[Bustatic Template Error]", err);
5089
+ return renderErrorResponse("[Buntic Template Error]", err);
3917
5090
  }
3918
5091
  }
3919
5092
  try {
@@ -3934,7 +5107,7 @@ function startDevServer(config) {
3934
5107
  });
3935
5108
  }
3936
5109
  } catch (err) {
3937
- return renderErrorResponse("[Bustatic Dynamic Route Error]", err);
5110
+ return renderErrorResponse("[Buntic Dynamic Route Error]", err);
3938
5111
  }
3939
5112
  if (engine.generatedPageStyles.has(pathname)) {
3940
5113
  const css = engine.generatedPageStyles.get(pathname);
@@ -3999,7 +5172,7 @@ function copyTemplateDirectory(srcDir, destDir) {
3999
5172
  function initProject(options = {}) {
4000
5173
  const templateName = options.template || "blank";
4001
5174
  if (!AVAILABLE_TEMPLATES.includes(templateName)) {
4002
- throw new Error(`[Bustatic] Unknown template "${options.template}". Available templates: ${AVAILABLE_TEMPLATES.join(", ")}.`);
5175
+ throw new Error(`[Buntic] Unknown template "${options.template}". Available templates: ${AVAILABLE_TEMPLATES.join(", ")}.`);
4003
5176
  }
4004
5177
  const targetDir = resolve8(process.cwd(), options.targetDir || ".");
4005
5178
  const includeSkills = options.includeSkills ?? true;
@@ -4007,22 +5180,22 @@ function initProject(options = {}) {
4007
5180
  const pkgRoot = getPackageRoot();
4008
5181
  const templateDir = join20(pkgRoot, "templates", templateName);
4009
5182
  if (!existsSync21(templateDir)) {
4010
- throw new Error(`[Bustatic] Template directory not found: "${templateDir}"`);
5183
+ throw new Error(`[Buntic] Template directory not found: "${templateDir}"`);
4011
5184
  }
4012
5185
  if (existsSync21(targetDir) && !force) {
4013
5186
  const existingEntries = readdirSync6(targetDir).filter((name) => name !== ".git" && name !== ".DS_Store");
4014
5187
  if (existingEntries.length > 0) {
4015
- throw new Error(`[Bustatic] Target directory "${targetDir}" is not empty.
4016
- ` + ` Pass a new directory name (e.g. "bustatic init my-site") or use --force to initialize anyway.`);
5188
+ throw new Error(`[Buntic] Target directory "${targetDir}" is not empty.
5189
+ ` + ` Pass a new directory name (e.g. "buntic init my-site") or use --force to initialize anyway.`);
4017
5190
  }
4018
5191
  }
4019
5192
  mkdirSync4(targetDir, { recursive: true });
4020
5193
  let filesCopied = copyTemplateDirectory(templateDir, targetDir);
4021
5194
  let skillsDir = null;
4022
5195
  if (includeSkills) {
4023
- const srcSkillsDir = join20(pkgRoot, "templates", "skills", "bustatic");
5196
+ const srcSkillsDir = join20(pkgRoot, "templates", "skills", "buntic");
4024
5197
  if (existsSync21(srcSkillsDir)) {
4025
- skillsDir = join20(targetDir, ".agents", "skills", "bustatic");
5198
+ skillsDir = join20(targetDir, ".agents", "skills", "buntic");
4026
5199
  filesCopied += copyTemplateDirectory(srcSkillsDir, skillsDir);
4027
5200
  }
4028
5201
  }
@@ -4037,11 +5210,11 @@ function initProject(options = {}) {
4037
5210
 
4038
5211
  // src/cli.ts
4039
5212
  async function runCLI(args) {
4040
- registerBustaticModuleResolver();
5213
+ registerBunticModuleResolver();
4041
5214
  const command = args[0] || "help";
4042
5215
  if (command === "--version" || command === "-v") {
4043
5216
  const pkg = await Bun.file(`${getPackageRoot()}/package.json`).json();
4044
- console.log(`bustatic v${pkg.version}`);
5217
+ console.log(`buntic v${pkg.version}`);
4045
5218
  return;
4046
5219
  }
4047
5220
  if (command === "help" || command === "--help" || command === "-h") {
@@ -4097,27 +5270,27 @@ async function runCLI(args) {
4097
5270
  includeSkills,
4098
5271
  force
4099
5272
  });
4100
- const relTarget = relative10(process.cwd(), result.targetDir) || ".";
5273
+ const relTarget = relative11(process.cwd(), result.targetDir) || ".";
4101
5274
  console.log(`
4102
- \u26A1 \x1B[36m[Bustatic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
5275
+ \u26A1 \x1B[36m[Buntic]\x1B[0m Initialized new project (\x1B[33m${result.template}\x1B[0m) in: \x1B[32m${result.targetDir}\x1B[0m`);
4103
5276
  console.log(` \u2714 Created ${result.filesCopied} file(s) (no package.json required)`);
4104
5277
  if (result.skillsDir) {
4105
- console.log(` \u2714 Installed Bustatic agent skill in .agents/skills/bustatic`);
5278
+ console.log(` \u2714 Installed Buntic agent skill in .agents/skills/buntic`);
4106
5279
  }
4107
- console.log(` \u2714 Generated TypeScript definitions in .bustatic/types/`);
5280
+ console.log(` \u2714 Generated TypeScript definitions in .buntic/types/`);
4108
5281
  console.log(`
4109
5282
  \x1B[1mNext steps:\x1B[0m`);
4110
5283
  if (relTarget !== ".") {
4111
5284
  console.log(` cd ${relTarget}`);
4112
5285
  }
4113
- console.log(` bustatic dev
5286
+ console.log(` buntic dev
4114
5287
  `);
4115
5288
  return;
4116
5289
  }
4117
5290
  if (command === "clean") {
4118
5291
  const config = await resolveConfig(targetDir);
4119
5292
  console.log(`
4120
- \uD83E\uDDF9 \x1B[36m[Bustatic]\x1B[0m Cleaning build and cache directories for: \x1B[33m${config.root}\x1B[0m`);
5293
+ \uD83E\uDDF9 \x1B[36m[Buntic]\x1B[0m Cleaning build and cache directories for: \x1B[33m${config.root}\x1B[0m`);
4121
5294
  if (existsSync22(config.outDir)) {
4122
5295
  rmSync4(config.outDir, { recursive: true, force: true });
4123
5296
  console.log(` \u2714 Removed ${config.outDir}`);
@@ -4138,14 +5311,14 @@ async function runCLI(args) {
4138
5311
  console.log(`\x1B[32m\u2714\x1B[0m Cache cleaned.`);
4139
5312
  }
4140
5313
  console.log(`
4141
- \uD83D\uDE80 \x1B[36m[Bustatic]\x1B[0m Starting dev server for: \x1B[33m${config.root}\x1B[0m`);
5314
+ \uD83D\uDE80 \x1B[36m[Buntic]\x1B[0m Starting dev server for: \x1B[33m${config.root}\x1B[0m`);
4142
5315
  const devInstance = startDevServer(config);
4143
5316
  console.log(` \u279C Local: \x1B[32mhttp://localhost:${devInstance.port}/\x1B[0m`);
4144
5317
  console.log(` \u279C Live reload enabled via WebSockets.
4145
5318
  `);
4146
5319
  process.on("SIGINT", () => {
4147
5320
  console.log(`
4148
- \x1B[33m[Bustatic]\x1B[0m Shutting down server...`);
5321
+ \x1B[33m[Buntic]\x1B[0m Shutting down server...`);
4149
5322
  devInstance.stop();
4150
5323
  process.exit(0);
4151
5324
  });
@@ -4153,7 +5326,7 @@ async function runCLI(args) {
4153
5326
  const config = await resolveConfig(targetDir, { outDir });
4154
5327
  syncProjectTypes(config.root);
4155
5328
  console.log(`
4156
- \uD83D\uDCE6 \x1B[36m[Bustatic]\x1B[0m Building static site for: \x1B[33m${config.root}\x1B[0m`);
5329
+ \uD83D\uDCE6 \x1B[36m[Buntic]\x1B[0m Building static site for: \x1B[33m${config.root}\x1B[0m`);
4157
5330
  const builder = new Builder(config);
4158
5331
  const result = await builder.build({ cleanCache });
4159
5332
  console.log(`\x1B[32m\u2714\x1B[0m Successfully built ${result.pagesCount} page(s) in ${result.durationMs}ms`);
@@ -4173,21 +5346,21 @@ async function runCLI(args) {
4173
5346
  }
4174
5347
  function printHelp() {
4175
5348
  console.log(`
4176
- \x1B[1mBustatic\x1B[0m - Lightweight zero-dependency static site generator for Bun
5349
+ \x1B[1mBuntic\x1B[0m - Lightweight zero-dependency static site generator for Bun
4177
5350
 
4178
5351
  \x1B[1mUSAGE:\x1B[0m
4179
- bustatic <command> [directory] [options]
5352
+ buntic <command> [directory] [options]
4180
5353
 
4181
5354
  \x1B[1mCOMMANDS:\x1B[0m
4182
- init [dir] Initialize a new Bustatic project (zero package.json)
5355
+ init [dir] Initialize a new Buntic project (zero package.json)
4183
5356
  dev [dir] Start the development server with live reload
4184
5357
  build [dir] Build the static site for production into dist/
4185
- clean [dir] Remove dist/ and .bustatic/cache/ directories
5358
+ clean [dir] Remove dist/ and .buntic/cache/ directories
4186
5359
  help Show this help message
4187
5360
 
4188
5361
  \x1B[1mOPTIONS:\x1B[0m
4189
5362
  -t, --template <name> Template for init: ${AVAILABLE_TEMPLATES.join(", ")} (default: blank)
4190
- --no-skills Skip installing agent skills in .agents/skills/bustatic
5363
+ --no-skills Skip installing agent skills in .agents/skills/buntic
4191
5364
  -f, --force Allow init in a non-empty directory
4192
5365
  -p, --port <port> Port to run dev server on (default: 3000)
4193
5366
  -o, --outdir <dir> Output directory for build (default: dist)
@@ -4196,15 +5369,15 @@ function printHelp() {
4196
5369
  -h, --help Show help
4197
5370
 
4198
5371
  \x1B[1mEXAMPLES:\x1B[0m
4199
- $ bustatic init mi-sitio
4200
- $ bustatic init mi-sitio --template simple
4201
- $ bustatic dev
4202
- $ bustatic dev my-site --port 8080
4203
- $ bustatic build
4204
- $ bustatic build my-site --outdir ./public_html --clean-cache
4205
- $ bustatic clean
5372
+ $ buntic init mi-sitio
5373
+ $ buntic init mi-sitio --template simple
5374
+ $ buntic dev
5375
+ $ buntic dev my-site --port 8080
5376
+ $ buntic build
5377
+ $ buntic build my-site --outdir ./public_html --clean-cache
5378
+ $ buntic clean
4206
5379
  `);
4207
5380
  }
4208
5381
 
4209
- // bin/bustatic.ts
5382
+ // bin/buntic.ts
4210
5383
  await runCLI(process.argv.slice(2));