@stacksjs/stx 0.2.705 → 0.2.707

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 (263) hide show
  1. package/dist/app-shell.d.ts +2 -1
  2. package/dist/app-shell.js +5 -2
  3. package/dist/{chunk-e3yhx053.js → chunk-029qng4p.js} +5 -5
  4. package/dist/chunk-0dve54ne.js +3 -0
  5. package/dist/chunk-0f12mv0z.js +2 -0
  6. package/dist/{chunk-m4j9gedb.js → chunk-0myrwz84.js} +48 -8
  7. package/dist/{chunk-613reww3.js → chunk-0v5nfhwg.js} +3 -3
  8. package/dist/chunk-12vjp2gr.js +2 -0
  9. package/dist/chunk-18fr730w.js +2 -0
  10. package/dist/{chunk-k59yexav.js → chunk-1f4e06c2.js} +2 -2
  11. package/dist/{chunk-n2ema4wf.js → chunk-1xjv71dw.js} +2 -2
  12. package/dist/chunk-29sapda2.js +2 -0
  13. package/dist/{chunk-d597d0dp.js → chunk-2aarvd3a.js} +6 -6
  14. package/dist/chunk-2dgbme86.js +2 -0
  15. package/dist/{chunk-ah5ch04j.js → chunk-2gny5jdt.js} +2 -2
  16. package/dist/chunk-2qf6kd9r.js +2 -0
  17. package/dist/chunk-2snfd93r.js +2 -0
  18. package/dist/chunk-2tqekz3d.js +3 -0
  19. package/dist/{chunk-y91rz3rq.js → chunk-3457kk19.js} +7 -7
  20. package/dist/chunk-3hhcea1p.js +54 -0
  21. package/dist/chunk-3t3p2c1t.js +65 -0
  22. package/dist/{chunk-3850m7ab.js → chunk-3wkgd883.js} +1 -1
  23. package/dist/chunk-42t97n9v.js +2 -0
  24. package/dist/{chunk-t27fecet.js → chunk-42w6snem.js} +4 -4
  25. package/dist/chunk-46s9ma3t.js +2 -0
  26. package/dist/chunk-4c1fbthr.js +2 -0
  27. package/dist/{chunk-zggdhtmn.js → chunk-4ckxs446.js} +3 -3
  28. package/dist/chunk-4fxg20je.js +2 -0
  29. package/dist/chunk-4m9qn8ps.js +4 -0
  30. package/dist/chunk-4y73c35z.js +33 -0
  31. package/dist/{chunk-jkywbfb0.js → chunk-533g1b9b.js} +2 -2
  32. package/dist/chunk-58v34kba.js +2 -0
  33. package/dist/{chunk-rpfzk6yg.js → chunk-59g266vc.js} +114 -114
  34. package/dist/{chunk-2gzrx4ma.js → chunk-59k5ntkt.js} +56 -56
  35. package/dist/chunk-5n4qg8za.js +3 -0
  36. package/dist/{chunk-1kr1mpft.js → chunk-67abad76.js} +1 -1
  37. package/dist/{chunk-7smgebdq.js → chunk-6cz1sbb1.js} +3 -3
  38. package/dist/{chunk-x0espnry.js → chunk-6ms7rtqt.js} +1 -1
  39. package/dist/{chunk-4sesw88b.js → chunk-6n11z33h.js} +5 -5
  40. package/dist/chunk-6ndeycxk.js +2 -0
  41. package/dist/{chunk-tp4eqfxq.js → chunk-6ts3sthp.js} +2 -2
  42. package/dist/{chunk-8w4y3dx3.js → chunk-768evhvm.js} +2 -2
  43. package/dist/{chunk-1d2xbwhm.js → chunk-79p5580k.js} +4 -4
  44. package/dist/chunk-79vj1txq.js +4 -0
  45. package/dist/chunk-7c7jnph2.js +20 -0
  46. package/dist/chunk-7dc3n69c.js +3 -0
  47. package/dist/chunk-7hpwcwwh.js +2 -0
  48. package/dist/chunk-7ppbv5bc.js +14 -0
  49. package/dist/{chunk-ccqe741j.js → chunk-83p5k4eb.js} +2 -2
  50. package/dist/{chunk-w71189qh.js → chunk-89s38bat.js} +2 -2
  51. package/dist/chunk-8s4rxgs8.js +2 -0
  52. package/dist/chunk-8ss2v7sw.js +2 -0
  53. package/dist/chunk-8t9em8md.js +2 -0
  54. package/dist/{chunk-vfjenjez.js → chunk-8v2vbc4y.js} +1 -1
  55. package/dist/chunk-921gb49g.js +2 -0
  56. package/dist/chunk-9736003n.js +2 -0
  57. package/dist/chunk-97r557ws.js +2 -0
  58. package/dist/{chunk-x7rtrdqq.js → chunk-998zvkzr.js} +3 -3
  59. package/dist/{chunk-5w1erc2m.js → chunk-9dg5ja4w.js} +1 -1
  60. package/dist/chunk-9frqh3bj.js +2 -0
  61. package/dist/{chunk-w7j88qkc.js → chunk-9v1t47d2.js} +2 -2
  62. package/dist/chunk-a35m0g7z.js +2 -0
  63. package/dist/{chunk-3hxd5td3.js → chunk-am4wadh7.js} +2 -2
  64. package/dist/{chunk-wqe98032.js → chunk-an387127.js} +2 -2
  65. package/dist/{chunk-bsr9wnq4.js → chunk-ap30qs8p.js} +2 -2
  66. package/dist/chunk-avr65xra.js +2 -0
  67. package/dist/chunk-b2ajtmvk.js +2 -0
  68. package/dist/chunk-b6318vv3.js +2 -0
  69. package/dist/{chunk-7kn0d1f1.js → chunk-b7j48bq9.js} +2 -2
  70. package/dist/chunk-bcr8sq50.js +2 -0
  71. package/dist/chunk-bd9p1xmr.js +2 -0
  72. package/dist/chunk-c5tky2vf.js +32 -0
  73. package/dist/{chunk-gj95952w.js → chunk-cam9je83.js} +105 -105
  74. package/dist/{chunk-njhd845r.js → chunk-ckrmrdjp.js} +5 -5
  75. package/dist/{chunk-9g0hyvhv.js → chunk-cm8m2ygc.js} +11 -11
  76. package/dist/{chunk-k296qq0p.js → chunk-cwhzk2n3.js} +2 -2
  77. package/dist/{chunk-g92jvafk.js → chunk-czy6hs6g.js} +5 -5
  78. package/dist/{chunk-rabmqfzr.js → chunk-d21twmm2.js} +1 -1
  79. package/dist/chunk-d22sgyg2.js +3 -0
  80. package/dist/chunk-dhdt7e54.js +2 -0
  81. package/dist/chunk-dmcjap96.js +20 -0
  82. package/dist/chunk-dxqvv686.js +3 -0
  83. package/dist/chunk-dzkg6cy5.js +3 -0
  84. package/dist/{chunk-b3sw5ykg.js → chunk-edka95zp.js} +3 -3
  85. package/dist/chunk-enssxcpa.js +2 -0
  86. package/dist/chunk-eqz0g5c5.js +25 -0
  87. package/dist/chunk-f7a6nzx6.js +2 -0
  88. package/dist/{chunk-44c1mbye.js → chunk-fcbd7kwj.js} +3 -3
  89. package/dist/chunk-fen5nnc4.js +2 -0
  90. package/dist/chunk-fvk1xr5a.js +2 -0
  91. package/dist/chunk-g03tkxds.js +2 -0
  92. package/dist/{chunk-b2j7s1a2.js → chunk-g1tq4xdb.js} +2 -2
  93. package/dist/chunk-g6wd49b5.js +2 -0
  94. package/dist/chunk-gbkcc96c.js +2 -0
  95. package/dist/chunk-gk0nq2ky.js +2 -0
  96. package/dist/chunk-h8kbcz9t.js +2 -0
  97. package/dist/chunk-hs2sbkvk.js +2 -0
  98. package/dist/{chunk-yn9kvsk1.js → chunk-j2mpqa4p.js} +2 -2
  99. package/dist/chunk-j3emvkjb.js +2 -0
  100. package/dist/{chunk-5gkxpcex.js → chunk-j9mpwt71.js} +3 -3
  101. package/dist/{chunk-gp9k0t3g.js → chunk-jb5sftzz.js} +2 -2
  102. package/dist/chunk-jef9mn1h.js +2 -0
  103. package/dist/chunk-jx7q5cnv.js +11 -0
  104. package/dist/chunk-jztsks2y.js +2 -0
  105. package/dist/{chunk-t8d33x9w.js → chunk-khrckvwn.js} +4 -4
  106. package/dist/{chunk-n5wgst66.js → chunk-km5dpg5v.js} +171 -171
  107. package/dist/chunk-kqdzjgm6.js +421 -0
  108. package/dist/chunk-ktf42hmd.js +2 -0
  109. package/dist/{chunk-4x2gnvz1.js → chunk-kxf8z7vp.js} +2 -2
  110. package/dist/chunk-mzwa2478.js +2 -0
  111. package/dist/chunk-n6carvxa.js +2 -0
  112. package/dist/chunk-ncs2j5kc.js +3 -0
  113. package/dist/chunk-nzyr320e.js +2 -0
  114. package/dist/{chunk-z9csfarm.js → chunk-p4s8hq38.js} +11 -11
  115. package/dist/chunk-pank9g6n.js +2 -0
  116. package/dist/chunk-pf427myt.js +2 -0
  117. package/dist/chunk-pfjsyvmj.js +21 -0
  118. package/dist/chunk-pgjqx3kg.js +42 -0
  119. package/dist/{chunk-3ys3sa08.js → chunk-qa9t9k6z.js} +1 -1
  120. package/dist/chunk-qf0bs4a5.js +2 -0
  121. package/dist/chunk-qprjkz11.js +18 -0
  122. package/dist/{chunk-j76w5rnm.js → chunk-qy1ss1en.js} +2 -2
  123. package/dist/chunk-r6bc2q44.js +2 -0
  124. package/dist/{chunk-bymqr1bt.js → chunk-r96wcqs6.js} +2 -2
  125. package/dist/{chunk-sxf17xfc.js → chunk-rb2a1qxb.js} +6 -6
  126. package/dist/chunk-rwjgpmrw.js +2 -0
  127. package/dist/{chunk-416jy1m5.js → chunk-s9b6abkb.js} +2 -2
  128. package/dist/chunk-sdpzaase.js +2 -0
  129. package/dist/{chunk-2p34qf9c.js → chunk-stvw8y3c.js} +2 -2
  130. package/dist/chunk-sy1btryy.js +2 -0
  131. package/dist/{chunk-d635e7b5.js → chunk-t21ae4rx.js} +5 -5
  132. package/dist/{chunk-9ra3ne11.js → chunk-t63f15yh.js} +3 -3
  133. package/dist/{chunk-2v7t87n8.js → chunk-t6ayy0t5.js} +2 -2
  134. package/dist/{chunk-gxd737m5.js → chunk-t7ezw8cj.js} +45 -45
  135. package/dist/chunk-t7mbaf69.js +2 -0
  136. package/dist/chunk-taste5sr.js +2 -0
  137. package/dist/chunk-txjx2xd6.js +2 -0
  138. package/dist/chunk-txr51pkd.js +2 -0
  139. package/dist/chunk-vjyrwvz0.js +24 -0
  140. package/dist/chunk-vstvadc2.js +12 -0
  141. package/dist/chunk-w2h6nn70.js +2 -0
  142. package/dist/chunk-w4vxhedk.js +2 -0
  143. package/dist/{chunk-ktkmv1j8.js → chunk-wbfg7p3k.js} +4 -4
  144. package/dist/{chunk-4afwn4yj.js → chunk-wevcmbn6.js} +10 -10
  145. package/dist/chunk-wj235n59.js +130 -0
  146. package/dist/{chunk-3392k9vm.js → chunk-wp6q0geg.js} +2 -2
  147. package/dist/chunk-x8zekavj.js +2 -0
  148. package/dist/{chunk-xc03cdet.js → chunk-xyyt8v1r.js} +28 -28
  149. package/dist/chunk-ykmcnk3x.js +2 -0
  150. package/dist/chunk-yw66yks2.js +43 -0
  151. package/dist/chunk-z05dbey1.js +2 -0
  152. package/dist/{chunk-w7e28p74.js → chunk-zav8yrtp.js} +9 -9
  153. package/dist/{chunk-2nqt1m3m.js → chunk-zdpd29xd.js} +2 -2
  154. package/dist/{chunk-ywzh979k.js → chunk-zecgd1wz.js} +4 -4
  155. package/dist/{chunk-c3hr5mm2.js → chunk-zjaw79zp.js} +2 -2
  156. package/dist/{chunk-fgr56q3w.js → chunk-zjw6j2x0.js} +4 -4
  157. package/dist/{chunk-k7pmzreg.js → chunk-zn3c0ew5.js} +3 -3
  158. package/dist/cli.js +46 -46
  159. package/dist/craft-entry.js +2 -2
  160. package/dist/craft.js +2 -2
  161. package/dist/dev-server/serve-app.js +1 -1
  162. package/dist/expressions.js +6 -2
  163. package/dist/index.d.ts +1 -0
  164. package/dist/index.js +1 -0
  165. package/dist/island-chunking.js +5 -1
  166. package/dist/native/compiler/icons.d.ts +8 -0
  167. package/dist/native/compiler/icons.js +8 -0
  168. package/dist/page-head.d.ts +2 -0
  169. package/dist/page-head.js +35 -0
  170. package/dist/production-builder.js +1 -1
  171. package/dist/production-server.js +2 -2
  172. package/dist/pwa.js +3 -3
  173. package/dist/site-builder/i18n.js +1 -1
  174. package/dist/ssg.js +36 -36
  175. package/dist/template-compiler.js +2 -1
  176. package/package.json +5 -5
  177. package/dist/chunk-0mzbm86d.js +0 -2
  178. package/dist/chunk-11dpedh5.js +0 -2
  179. package/dist/chunk-1e79xcc8.js +0 -2
  180. package/dist/chunk-2fg2es95.js +0 -4
  181. package/dist/chunk-2r7j8q2q.js +0 -2
  182. package/dist/chunk-2whqx2c0.js +0 -2
  183. package/dist/chunk-2xtzzx00.js +0 -2
  184. package/dist/chunk-44efrzry.js +0 -2
  185. package/dist/chunk-4t9cggwf.js +0 -2
  186. package/dist/chunk-5h1ahj7m.js +0 -2
  187. package/dist/chunk-5zqxzyxk.js +0 -2
  188. package/dist/chunk-62q6f4vy.js +0 -2
  189. package/dist/chunk-68wezwr7.js +0 -2
  190. package/dist/chunk-7gw96jpj.js +0 -2
  191. package/dist/chunk-7w2mrg3s.js +0 -2
  192. package/dist/chunk-8hhyp9p6.js +0 -2
  193. package/dist/chunk-905azzfg.js +0 -2
  194. package/dist/chunk-926fs6g7.js +0 -2
  195. package/dist/chunk-93ft5jea.js +0 -3
  196. package/dist/chunk-983zpa57.js +0 -3
  197. package/dist/chunk-98yf0aq9.js +0 -4
  198. package/dist/chunk-99k1wbcw.js +0 -2
  199. package/dist/chunk-b378jpbp.js +0 -2
  200. package/dist/chunk-b7e07ybq.js +0 -3
  201. package/dist/chunk-bfhks7zf.js +0 -43
  202. package/dist/chunk-cbdyns7r.js +0 -3
  203. package/dist/chunk-csx3zne1.js +0 -3
  204. package/dist/chunk-d499mwtq.js +0 -3
  205. package/dist/chunk-d7vmzkjy.js +0 -2
  206. package/dist/chunk-d7whccsw.js +0 -2
  207. package/dist/chunk-djwat8vn.js +0 -2
  208. package/dist/chunk-dpjs0ajs.js +0 -2
  209. package/dist/chunk-ezna88p6.js +0 -2
  210. package/dist/chunk-fazw6sxz.js +0 -2
  211. package/dist/chunk-ffmtqtkf.js +0 -2
  212. package/dist/chunk-fhhx61qk.js +0 -18
  213. package/dist/chunk-g1bed7se.js +0 -2
  214. package/dist/chunk-g7mbb5kc.js +0 -2
  215. package/dist/chunk-gbgbhpms.js +0 -2
  216. package/dist/chunk-gcgvac2h.js +0 -2
  217. package/dist/chunk-gsj7yve0.js +0 -130
  218. package/dist/chunk-gvf7akv0.js +0 -2
  219. package/dist/chunk-gvggrhpq.js +0 -2
  220. package/dist/chunk-ha4vb9a6.js +0 -2
  221. package/dist/chunk-hadbgke6.js +0 -2
  222. package/dist/chunk-hkmewh5h.js +0 -12
  223. package/dist/chunk-hrc3wj8r.js +0 -421
  224. package/dist/chunk-hzszdz02.js +0 -2
  225. package/dist/chunk-j6rgdnkg.js +0 -2
  226. package/dist/chunk-jkpcrf4z.js +0 -11
  227. package/dist/chunk-jv7gdt4t.js +0 -2
  228. package/dist/chunk-jxwnk094.js +0 -2
  229. package/dist/chunk-k3yw4tha.js +0 -2
  230. package/dist/chunk-khhx6m7x.js +0 -2
  231. package/dist/chunk-kjc1f6af.js +0 -2
  232. package/dist/chunk-mv4wfsc5.js +0 -2
  233. package/dist/chunk-nhv3jt0d.js +0 -2
  234. package/dist/chunk-nmcgyxcg.js +0 -2
  235. package/dist/chunk-p4e7x4f6.js +0 -2
  236. package/dist/chunk-p6sdrq1y.js +0 -2
  237. package/dist/chunk-p78v88ng.js +0 -65
  238. package/dist/chunk-ptkr6m3a.js +0 -2
  239. package/dist/chunk-qdw0y8gw.js +0 -33
  240. package/dist/chunk-rb8g9nnc.js +0 -2
  241. package/dist/chunk-rhm7wg6p.js +0 -2
  242. package/dist/chunk-rkk14e9h.js +0 -14
  243. package/dist/chunk-t5qsaq1q.js +0 -21
  244. package/dist/chunk-tg5m9xn3.js +0 -31
  245. package/dist/chunk-tmzp0ght.js +0 -20
  246. package/dist/chunk-tqavwhja.js +0 -25
  247. package/dist/chunk-twcb0wp6.js +0 -42
  248. package/dist/chunk-v4x3ckcr.js +0 -54
  249. package/dist/chunk-w9kak6aj.js +0 -2
  250. package/dist/chunk-wta3e3q2.js +0 -2
  251. package/dist/chunk-xbn2p5m8.js +0 -2
  252. package/dist/chunk-xf7b2s2z.js +0 -2
  253. package/dist/chunk-xhzqswq2.js +0 -2
  254. package/dist/chunk-xj5e6nbn.js +0 -24
  255. package/dist/chunk-xvz9b1ht.js +0 -20
  256. package/dist/chunk-yfppczrm.js +0 -2
  257. package/dist/chunk-yr6qxp88.js +0 -2
  258. package/dist/chunk-yyx89zxs.js +0 -2
  259. package/dist/chunk-z0x54ynx.js +0 -3
  260. package/dist/chunk-z9e2a3mv.js +0 -2
  261. package/dist/chunk-za6teyn1.js +0 -2
  262. package/dist/chunk-zgyw04pj.js +0 -2
  263. package/dist/chunk-zw924mfr.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{se,ue,dn,At,Pt,g,n,pe,d}from"./chunk-hrc3wj8r.js";import{gt,$e,ja,qr,ho,yo,o}from"./chunk-gj95952w.js";import{ie,br,xe,D,vn}from"./chunk-xc03cdet.js";import{vt,ir,ds,ps,gs,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-m4j9gedb.js";import{os,i,R}from"./chunk-rpfzk6yg.js";import{ut,Vi,ke,O,Ui,Ys,Mr,Ve,Wi,_e}from"./chunk-tg5m9xn3.js";import{rr,sr}from"./chunk-d499mwtq.js";import{_n}from"./chunk-bymqr1bt.js";import{e,rn,Zn,h}from"./chunk-9g0hyvhv.js";import{Ge}from"./chunk-v4x3ckcr.js";import{Te}from"./chunk-n2ema4wf.js";import{q,he,ye}from"./chunk-rkk14e9h.js";import{c}from"./chunk-93ft5jea.js";import{W}from"./chunk-csx3zne1.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
3
- `),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(s?s[1]:"").split(`
4
- `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let s=[],p=Kt(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=Kt(t,"foreach","endforeach");if(a>0)s.push({type:"error",category:"syntax",message:`Found ${a} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)s.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
- `).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)s.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function Un(t,r){let s=[];if(r.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)s.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(r.directives.total===0&&r.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function Wn(t,r){let s=1;if(s+=r.directives.conditionals*0.1,s+=r.directives.loops*0.5,s+=r.directives.includes*2,s+=r.expressions*0.05,s+=r.components*1,r.scriptLines>10)s+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(s>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function Kt(t,r,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function Pi(t=["**/*.stx"],r){let s=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);s.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=Vn(s);return{results:s,summary:a}}function Vn(t){let r=t.length,s=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as qn,readFile as Kn,readdir as Xn,stat as Xt,writeFile as Gn}from"fs/promises";import Re from"path";function en(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Jn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Yn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Qn(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function er(t){let r=[];async function s(p){let a=await Xn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=Re.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await s(t),r}function tr(t,r){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function nr(t,r){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(tn.has(y))throw Error(`${r}: client ${en(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return s}function or(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Gt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
2
+ import{oe,de,pn,Pt,It,m,r,fe,p}from"./chunk-kqdzjgm6.js";import{mt,Re,Fa,Xr,vo,wo,i}from"./chunk-cam9je83.js";import{ae,xr,Se,j,wn}from"./chunk-xyyt8v1r.js";import{wt,lr,ms,hs,ys,xt,St,kt,_t,Ct,Et,Ze}from"./chunk-0myrwz84.js";import{cs,a,P}from"./chunk-59g266vc.js";import{dt,Tn,_e,M,qi,eo,Br,Ue,Gi,Ce}from"./chunk-c5tky2vf.js";import{ir,ar}from"./chunk-dzkg6cy5.js";import{Cn}from"./chunk-r96wcqs6.js";import{e,sn,tr,y}from"./chunk-cm8m2ygc.js";import{Ke}from"./chunk-3hhcea1p.js";import{$e}from"./chunk-1xjv71dw.js";import{G,ye,be}from"./chunk-7ppbv5bc.js";import{l}from"./chunk-5n4qg8za.js";import{q}from"./chunk-ncs2j5kc.js";async function zn(t){try{let n=await Bun.file(t).text(),o=Nn(n),d=Un(n,t),s=Wn(n,o),c=Vn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:c}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Nn(t){let n=t.split(`
3
+ `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
4
+ `).length,c={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};c.total=c.conditionals+c.loops+c.includes+c.custom;let f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=f+u+h,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(c.total*0.5+g*0.1+b*0.3+(s>10?s*0.05:0)+v));return{lines:n.length,characters:t.length,directives:c,expressions:g,components:b,layouts:w,scriptLines:s,complexity:x}}function Un(t,n){let o=[],d=Kt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let s=Kt(t,"foreach","endforeach");if(s>0)o.push({type:"error",category:"syntax",message:`Found ${s} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let c=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(c&&c.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)o.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
5
+ `).filter((b)=>b.length>120);if(h.length>0)o.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)o.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Wn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Vn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Kt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,c=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-c)}async function Ni(t=["**/*.stx"],n){let o=[],d=[];for(let c of t){let f=await Array.fromAsync(new Bun.Glob(c).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...f.filter((u)=>u.endsWith(".stx")))}for(let c of d)try{let f=await zn(c);o.push(f)}catch(f){console.warn(`Failed to analyze ${c}:`,f)}let s=qn(o);return{results:o,summary:s}}function qn(t){let n=t.length,o=t.reduce((g,b)=>g+b.metrics.lines,0),d=n>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/n:0,s=t.reduce((g,b)=>g+b.issues.length,0),c={};t.forEach((g)=>{g.issues.forEach((b)=>{c[b.category]=(c[b.category]||0)+1})});let f=n>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/n:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(s>n*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(c.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:s,issuesByCategory:c,performanceScore:u,recommendations:h}}import{mkdir as Kn,readFile as Xn,readdir as Gn,stat as Xt,writeFile as Jn}from"fs/promises";import Te from"path";function en(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Qn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Zn(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function er(t){let n=[];async function o(d){let s=await Gn(d,{withFileTypes:!0});s.sort((c,f)=>c.name.localeCompare(f.name));for(let c of s){let f=Te.join(d,c.name);if(c.isDirectory()){if(!c.name.startsWith(".")&&c.name!=="node_modules")await o(f)}else if(c.isFile()&&c.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(c.name))n.push(f)}}return await o(t),n}function nr(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(s){throw Error(`${n}: <script component> must contain JSON metadata (${s.message})`)}}function rr(t,n){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let s of d){if(!/\bclient\b/i.test(s[1])||/\bcomponent\b|\bstx:component\b/i.test(s[1]))continue;let c;try{c=new Bun.Transpiler({loader:"ts"}).transformSync(s[2])}catch(h){throw Error(`${n}: failed to transpile <script client> (${h.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(c)){let h=u[1];if(tn.has(h))throw Error(`${n}: client ${en(h)}`);let g=f.lastIndex,b=1,w="",S=!1,C=g;for(;C<c.length&&b>0;C++){let x=c[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${n}: unterminated client function "${h}"`);let v=u[0].includes("async")?"async ":"";o[h]=`${v}${h}(${u[2]}) {${c.slice(g,C-1)}}`,f.lastIndex=C}}return o}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Gt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
6
6
 
7
- `)}function ar(t){if(!t)return null;let r=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(r))return"string";if(/^number$/.test(r))return"number";if(/^boolean$/.test(r))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(r))return"string";return"object"}function cr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function lr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function dr(t){let r=[],s=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),a=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,f=(y)=>{if(p[y]!=="(")return null;let m=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")m++;else if(S===")"){if(m--,m===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let m=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>m)r.push(`out += ${JSON.stringify(y.slice(m,w.index))};`);r.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),m=w.index+w[0].length}if(m<y.length)r.push(`out += ${JSON.stringify(y.slice(m))};`)};while(l=a.exec(p)){u(p.slice(s,l.index)),s=l.index+l[0].length;let m=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?f(s):null;if(m)s=m.end,a.lastIndex=m.end;let b=m?.expression;switch(l[1]){case"if":r.push(`if (${b}) {`);break;case"elseif":r.push(`} else if (${b}) {`);break;case"else":r.push("} else {");break;case"endif":case"endforeach":r.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){r.push(`out += ${JSON.stringify(l[0]+(m?`(${b})`:""))};`);break}let[,S,C,v]=w;r.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(s)),r.join(`
8
- `)}function ct(t,r,s,p){if(t[r]!==s)return-1;let a=0,l=null;for(let f=r;f<t.length;f++){let u=t[f];if(l){if(u==="\\"){f++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===s)a++;else if(u===p){if(p===">"&&t[f-1]==="=")continue;if(a--,a===0)return f+1}}return-1}function Lt(t,r,s){let p=s?"([{<":"([{",a=s?")]}>":")]}",l=[],f=0,u=null,y="";for(let m=0;m<t.length;m++){let b=t[m];if(u){if(y+=b,b==="\\"){y+=t[++m]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))f++;else if(a.includes(b))f--;if(f===0&&r.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((m)=>m.trim()).filter(Boolean)}function pr(t){let r=0,s=null;for(let p=0;p<t.length;p++){let a=t[p];if(s){if(a==="\\"){p++;continue}if(a===s)s=null;continue}if(a==="'"||a==='"'||a==="`"){s=a;continue}if("([{".includes(a))r++;else if(")]}".includes(a))r--;if(r!==0||a!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Jt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function ur(t){let r=/\bdefineProps\b/.exec(t);if(!r)return null;let s=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=s.exec(t);k&&k.index<r.index;k=s.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let a={},l={},f=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},m;if(t[u]==="{"){let k=ct(t,u,"{","}");if(k===-1)return null;m=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;m=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(y(),t[u]==="<"){let k=ct(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=ct(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=ct(t,u,"{","}");if(k===-1)return null;for(let[I,A]of It(t.slice(u,k)))l[I]=A;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of Lt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let I=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(I)a[I[1]]=I[2].trim()}if(x.startsWith("{"))for(let[k,I]of It(x)){if(f.push(k),!I.startsWith("{")){let A=Jt(I);if(A)a[k]=A;continue}for(let[A,M]of It(I))if(A==="default")l[k]=M;else if(A==="type"){let E=Jt(M);if(E)a[k]=E}}else if(x.startsWith("["))for(let k of Lt(x.slice(1,-1),",",!1))f.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(m.startsWith("{")){f.length=0;for(let k of Lt(m.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let I=pr(k),M=(I===-1?k:k.slice(0,I)).split(":")[0].trim().replace(/^\.\.\./,"");if(!M)continue;if(f.push(M),I!==-1)l[M]=k.slice(I+1).trim()}}else if(f.length===0)f.push(...Object.keys(a));return{text:t.slice(p,u),propNames:f,defaults:l,declared:a,typeName:T}}function It(t){let r=t.trim().replace(/^\{/,"").replace(/\}$/,""),s=[],p=0;while(p<r.length){let a=/\s*([A-Za-z_$][\w$]*)\s*:/y;a.lastIndex=p;let l=a.exec(r);if(!l)break;p=a.lastIndex;let f=0,u="",y=p;while(p<r.length){let b=r[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")f++;else if(b==="}"||b==="]"||b===")")f--;else if(b===","&&f===0)break;p++}let m=r.slice(y,p).trim();if(m)s.push([l[1],m]);p++}return s}function fr(t,r,s){let a=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!a)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=a[2],f=[],u=[],y={},m={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return f.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Re.resolve(Re.dirname(r),x),I=Re.relative(s,k);return`${v}${I.startsWith(".")?I:`./${I}`}${T}`})),""});let b=ur(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(m,b.declared),l=l.replace(b.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))m[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:f,body:l.trim(),propNames:u,defaults:y,declared:m}}function mr(t){let r=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,a,l,f,u)=>{let y=a.toLowerCase();r.add(y);let m=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${m?` data-stx-mod-${y}="${m}"`:""}`}),eventTypes:[...r].sort()}}function gr(t){let r=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,a,l,f)=>{let u=r.length;return r.push({id:u,name:a,expression:f}),` data-stx-bind-${u}=""`}),bindings:r}}function hr(t){let r=new Set;for(let s of t.matchAll(/<slot\b([^>]*)>/gi))r.add(s[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...r].map((s)=>({name:s}))}function yr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((r)=>r[1]))].sort().map((r)=>({name:r}))}function Yt(t,r){if(!r||!new Set(["string","number","boolean","object","array"]).has(r.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...r,reflect:r.reflect??r.attribute!==!1}}async function xr(t,r,s){let p=Re.isAbsolute(r.file)?r.file:Re.resolve(t,r.file),a=await Kn(p,"utf8"),l=tr(a,p),f=Re.basename(p,".stx"),u=r.name||l.name||Jn(f),y=`${jt(s.prefix||"stx")}-${jt(f)}`,m=r.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!Yn(m))throw Error(`${p}: invalid custom-element tag "${m}"; tags must be lowercase and contain a hyphen`);let b=r.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([A,M])=>[A,Yt(A,M)])),S=mr(or(a)),C=gr(S.template),v=fr(a,p,Re.resolve(s.outputDir)),x=dr(C.template);for(let A of v.propNames){if(w[A])continue;let M=v.defaults[A];w[A]=Yt(A,{type:ar(v.declared[A])??cr(M),...M===void 0?{}:{default:lr(M)}})}let T=l.methods||{},k=r.methods||{},I=nr(a,p);return{file:Re.relative(t,p),sourcePath:p,name:u,tag:m,description:r.description||l.description||"",template:C.template,styles:Gt(a),shadowMode:Qn(r.shadowDOM??l.shadowDOM??s.shadowDOM),progressive:r.progressive??l.progressive??s.progressive??!0,properties:w,events:r.events||l.events||{},methods:{...T,...k,...I},eventTypes:S.eventTypes,bindings:C.bindings,slots:hr(C.template),cssProperties:yr(Gt(a)),scope:v,render:x}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
7
+ `)}function sr(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function cr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function dr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function pr(t){let n=[],o=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),s=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,c,f=(h)=>{if(d[h]!=="(")return null;let g=0,b="";for(let w=h;w<d.length;w++){let S=d[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:d.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(h)){if(w.index>g)n.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);n.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)n.push(`out += ${JSON.stringify(h.slice(g))};`)};while(c=s.exec(d)){u(d.slice(o,c.index)),o=c.index+c[0].length;let g=c[1]==="if"||c[1]==="elseif"||c[1]==="foreach"?f(o):null;if(g)o=g.end,s.lastIndex=g.end;let b=g?.expression;switch(c[1]){case"if":n.push(`if (${b}) {`);break;case"elseif":n.push(`} else if (${b}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){n.push(`out += ${JSON.stringify(c[0]+(g?`(${b})`:""))};`);break}let[,S,C,v]=w;n.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(d.slice(o)),n.join(`
8
+ `)}function ct(t,n,o,d){if(t[n]!==o)return-1;let s=0,c=null;for(let f=n;f<t.length;f++){let u=t[f];if(c){if(u==="\\"){f++;continue}if(u===c)c=null;continue}if(u==="'"||u==='"'||u==="`"){c=u;continue}if(u===o)s++;else if(u===d){if(d===">"&&t[f-1]==="=")continue;if(s--,s===0)return f+1}}return-1}function Mt(t,n,o){let d=o?"([{<":"([{",s=o?")]}>":")]}",c=[],f=0,u=null,h="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(h+=b,b==="\\"){h+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,h+=b;continue}if(d.includes(b))f++;else if(s.includes(b))f--;if(f===0&&n.includes(b)){c.push(h),h="";continue}h+=b}return c.push(h),c.map((g)=>g.trim()).filter(Boolean)}function ur(t){let n=0,o=null;for(let d=0;d<t.length;d++){let s=t[d];if(o){if(s==="\\"){d++;continue}if(s===o)o=null;continue}if(s==="'"||s==='"'||s==="`"){o=s;continue}if("([{".includes(s))n++;else if(")]}".includes(s))n--;if(n!==0||s!=="=")continue;let c=t[d-1];if(t[d+1]==="="||c==="="||c==="!"||c==="<"||c===">")continue;return d}return-1}function Jt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function fr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let o=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=o.exec(t);k&&k.index<n.index;k=o.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let s={},c={},f=[],u=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=ct(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(h(),t[u]==="<"){let k=ct(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=ct(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=ct(t,u,"{","}");if(k===-1)return null;for(let[L,O]of Lt(t.slice(u,k)))c[L]=O;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of Mt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let L=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(L)s[L[1]]=L[2].trim()}if(x.startsWith("{"))for(let[k,L]of Lt(x)){if(f.push(k),!L.startsWith("{")){let O=Jt(L);if(O)s[k]=O;continue}for(let[O,A]of Lt(L))if(O==="default")c[k]=A;else if(O==="type"){let R=Jt(A);if(R)s[k]=R}}else if(x.startsWith("["))for(let k of Mt(x.slice(1,-1),",",!1))f.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){f.length=0;for(let k of Mt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let L=ur(k),A=(L===-1?k:k.slice(0,L)).split(":")[0].trim().replace(/^\.\.\./,"");if(!A)continue;if(f.push(A),L!==-1)c[A]=k.slice(L+1).trim()}}else if(f.length===0)f.push(...Object.keys(s));return{text:t.slice(d,u),propNames:f,defaults:c,declared:s,typeName:T}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),o=[],d=0;while(d<n.length){let s=/\s*([A-Za-z_$][\w$]*)\s*:/y;s.lastIndex=d;let c=s.exec(n);if(!c)break;d=s.lastIndex;let f=0,u="",h=d;while(d<n.length){let b=n[d];if(u){if(b==="\\")d++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")f++;else if(b==="}"||b==="]"||b===")")f--;else if(b===","&&f===0)break;d++}let g=n.slice(h,d).trim();if(g)o.push([c[1],g]);d++}return o}function mr(t,n,o){let s=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!s)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let c=s[2],f=[],u=[],h={},g={};c=c.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return f.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Te.resolve(Te.dirname(n),x),L=Te.relative(o,k);return`${v}${L.startsWith(".")?L:`./${L}`}${T}`})),""});let b=fr(c);if(b)u.push(...b.propNames),Object.assign(h,b.defaults),Object.assign(g,b.declared),c=c.replace(b.text,"");let w={};for(let S of c.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return c=c.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:f,body:c.trim(),propNames:u,defaults:h,declared:g}}function gr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,s,c,f,u)=>{let h=s.toLowerCase();n.add(h);let g=(c||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...n].sort()}}function hr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,s,c,f)=>{let u=n.length;return n.push({id:u,name:s,expression:f}),` data-stx-bind-${u}=""`}),bindings:n}}function yr(t){let n=new Set;for(let o of t.matchAll(/<slot\b([^>]*)>/gi))n.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((o)=>({name:o}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Yt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function vr(t,n,o){let d=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),s=await Xn(d,"utf8"),c=nr(s,d),f=Te.basename(d,".stx"),u=n.name||c.name||Yn(f),h=`${jt(o.prefix||"stx")}-${jt(f)}`,g=n.tag||c.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${d}: invalid component class name "${u}"`);if(!Qn(g))throw Error(`${d}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=n.properties||c.properties||c.props||{},w=Object.fromEntries(Object.entries(b).map(([O,A])=>[O,Yt(O,A)])),S=gr(or(s)),C=hr(S.template),v=mr(s,d,Te.resolve(o.outputDir)),x=pr(C.template);for(let O of v.propNames){if(w[O])continue;let A=v.defaults[O];w[O]=Yt(O,{type:sr(v.declared[O])??cr(A),...A===void 0?{}:{default:dr(A)}})}let T=c.methods||{},k=n.methods||{},L=rr(s,d);return{file:Te.relative(t,d),sourcePath:d,name:u,tag:g,description:n.description||c.description||"",template:C.template,styles:Gt(s),shadowMode:Zn(n.shadowDOM??c.shadowDOM??o.shadowDOM),progressive:n.progressive??c.progressive??o.progressive??!0,properties:w,events:n.events||c.events||{},methods:{...T,...k,...L},eventTypes:S.eventTypes,bindings:C.bindings,slots:yr(C.template),cssProperties:br(Gt(s)),scope:v,render:x}}function wr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -212,7 +212,7 @@ export class StxElement extends HTMLElementBase {
212
212
  ? this.render(RENDER_HELPERS)
213
213
  : definition.template
214
214
  .replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
215
- .replace(new RegExp(${r}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
215
+ .replace(new RegExp(${n}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
216
216
  if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
217
217
  root.innerHTML = html;
218
218
  this._applyBindings();
@@ -303,46 +303,46 @@ export function defineComponent(Component, definition) {
303
303
  }
304
304
  return Component;
305
305
  }
306
- `}function wr(t){let r=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),s=Object.entries(t.methods).map(([u,y])=>{if(tn.has(u))throw Error(`${t.sourcePath}: ${en(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
307
- ${y}
306
+ `}function Sr(t){let n=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),o=Object.entries(t.methods).map(([u,h])=>{if(tn.has(u))throw Error(`${t.sourcePath}: ${en(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${u}($event) {
307
+ ${h}
308
308
  }`}).join(`
309
309
 
310
- `),p=t.scope,a=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
311
- `).map((y)=>y.trim()===""?y:` ${y}`).join(`
312
- `),f="";if(t.render.trim()!==""||p.body!==""||a!==""){let u=[a?`const { ${a} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
313
- `),y;try{let m=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
310
+ `),d=t.scope,s=[...new Set([...Object.keys(t.properties),...d.propNames])].map((u)=>d.defaults[u]===void 0?u:`${u} = ${d.defaults[u]}`).join(", "),c=(u)=>u.split(`
311
+ `).map((h)=>h.trim()===""?h:` ${h}`).join(`
312
+ `),f="";if(t.render.trim()!==""||d.body!==""||s!==""){let u=[s?`const { ${s} } = this._props();`:"",d.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
313
+ `),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
314
314
  ${u}
315
- }`),b=m.indexOf("{"),w=m.lastIndexOf("}");y=m.slice(b+1,w).trim()}catch(m){throw Error(`${t.sourcePath}: failed to compile render (${m.message})`)}f=`
315
+ }`),b=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(b+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}f=`
316
316
  render(__helpers) {
317
317
  const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
318
- ${l(y.trim())}
318
+ ${c(h.trim())}
319
319
  }
320
320
  `}return`import { StxElement, defineComponent } from './runtime.js';
321
- ${p.imports.length?`${p.imports.join(`
321
+ ${d.imports.length?`${d.imports.join(`
322
322
  `)}
323
323
  `:""}
324
324
  /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
325
325
  export class ${t.name} extends StxElement {
326
- ${s}${f}
326
+ ${o}${f}
327
327
  }
328
328
 
329
- defineComponent(${t.name}, ${r});
329
+ defineComponent(${t.name}, ${n});
330
330
  export default ${t.name};
331
- `}function lt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Sr(t){let r=Object.entries(t.properties).map(([l,f])=>` ${l}${f.required?"":"?"}: ${lt(f)}`).join(`
332
- `),s=Object.entries(t.properties).map(([l,f])=>` ${l}: ${lt(f)}`).join(`
333
- `),p=Object.entries(t.events).map(([l,f])=>` ${JSON.stringify(l)}: CustomEvent<${f.detailType||"unknown"}>`).join(`
334
- `),a=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
331
+ `}function lt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function kr(t){let n=Object.entries(t.properties).map(([c,f])=>` ${c}${f.required?"":"?"}: ${lt(f)}`).join(`
332
+ `),o=Object.entries(t.properties).map(([c,f])=>` ${c}: ${lt(f)}`).join(`
333
+ `),d=Object.entries(t.events).map(([c,f])=>` ${JSON.stringify(c)}: CustomEvent<${f.detailType||"unknown"}>`).join(`
334
+ `),s=Object.keys(t.methods).map((c)=>` ${c}($event?: Event): unknown`).join(`
335
335
  `);return`export interface ${t.name}Props {
336
- ${r}
336
+ ${n}
337
337
  }
338
338
 
339
339
  export interface ${t.name}EventMap {
340
- ${p}
340
+ ${d}
341
341
  }
342
342
 
343
343
  export declare class ${t.name} extends HTMLElement {
344
+ ${o}
344
345
  ${s}
345
- ${a}
346
346
  readonly updateComplete: Promise<void>
347
347
  requestUpdate(): Promise<void>
348
348
  emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
@@ -355,14 +355,14 @@ declare global {
355
355
  }
356
356
 
357
357
  export default ${t.name}
358
- `}function kr(t){return`declare global {
358
+ `}function Tr(t){return`declare global {
359
359
  namespace JSX {
360
360
  interface IntrinsicElements {
361
- ${t.map((s)=>{let p=Object.entries(s.properties).map(([l,f])=>` ${JSON.stringify(l)}?: ${lt(f)}`).join(`
362
- `),a=Object.keys(s.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${s.events[l].detailType||"unknown"}>) => void`).join(`
363
- `);return` ${JSON.stringify(s.tag)}: {
364
- ${p}
365
- ${a}
361
+ ${t.map((o)=>{let d=Object.entries(o.properties).map(([c,f])=>` ${JSON.stringify(c)}?: ${lt(f)}`).join(`
362
+ `),s=Object.keys(o.events).map((c)=>` ${`on${c.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${o.events[c].detailType||"unknown"}>) => void`).join(`
363
+ `);return` ${JSON.stringify(o.tag)}: {
364
+ ${d}
365
+ ${s}
366
366
  children?: unknown
367
367
  slot?: string
368
368
  class?: string
@@ -374,10 +374,10 @@ ${a}
374
374
  }
375
375
 
376
376
  export {}
377
- `}function Tr(t){return{schemaVersion:"1.0.0",modules:t.map((r)=>({kind:"javascript-module",path:`./${r.tag}.js`,declarations:[{kind:"class",name:r.name,description:r.description||void 0,customElement:!0,tagName:r.tag,members:Object.entries(r.properties).map(([s,p])=>({kind:"field",name:s,description:p.description,type:{text:lt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||jt(s),reflects:p.reflect})),events:Object.entries(r.events).map(([s,p])=>({name:s,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:r.slots,cssProperties:r.cssProperties}],exports:[{kind:"js",name:r.name,declaration:{name:r.name,module:`./${r.tag}.js`}}]}))}}function Qt(t){if(!t.styles)return"";let r=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(r))return r;return`@scope (${t.tag}) {
378
- ${r}
379
- }`}function Zt(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function $r(t){let r=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),a=Object.fromEntries(t.map((f)=>[f.tag,{template:f.template,styles:f.styles,shadowMode:f.shadowMode,properties:f.properties}])),l=t.map((f)=>`export const render${f.name} = (props = {}, slots = {}) => renderComponent('${f.tag}', props, slots);`).join(`
380
- `);return`const definitions = ${JSON.stringify(a,null,2)};
377
+ `}function $r(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([o,d])=>({kind:"field",name:o,description:d.description,type:{text:lt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||jt(o),reflects:d.reflect})),events:Object.entries(n.events).map(([o,d])=>({name:o,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function Qt(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
378
+ ${n}
379
+ }`}function Zt(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Cr(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),o=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),s=Object.fromEntries(t.map((f)=>[f.tag,{template:f.template,styles:f.styles,shadowMode:f.shadowMode,properties:f.properties}])),c=t.map((f)=>`export const render${f.name} = (props = {}, slots = {}) => renderComponent('${f.tag}', props, slots);`).join(`
380
+ `);return`const definitions = ${JSON.stringify(s,null,2)};
381
381
  const escapeHTML = (value) => String(value ?? '')
382
382
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
383
383
  .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
@@ -389,9 +389,9 @@ export function renderComponent(tag, props = {}, slots = {}) {
389
389
  const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
390
390
  Object.assign(values, props);
391
391
  let template = definition.template
392
- .replace(new RegExp(${r}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
- .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
- .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
392
+ .replace(new RegExp(${n}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
+ .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
+ .replace(new RegExp(${d}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
395
395
  const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
396
396
  if (property.attribute === false || !(name in props)) return [];
397
397
  const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
@@ -409,22 +409,22 @@ export function renderComponent(tag, props = {}, slots = {}) {
409
409
  return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
410
410
  }
411
411
 
412
- ${l}
413
- `}async function Ii(t){let r=Re.resolve(t.inputDir),s=Re.resolve(t.outputDir);if(!(await Xt(r).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${r}`);let a=t.components?.length?t.components:(await er(r)).map((x)=>({file:x}));if(!a.length)throw Error(`No .stx components found in ${r}`);let l=await Promise.all(a.map((x)=>xr(r,x,t)));l.sort((x,T)=>x.tag.localeCompare(T.tag));let f=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(f.length)throw Error(`Duplicate custom-element tag: ${f[0].tag}`);let u=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await qn(s,{recursive:!0});let y=[],m=async(x,T)=>{let k=Re.join(s,x);return await Gn(k,T.endsWith(`
412
+ ${c}
413
+ `}async function Di(t){let n=Te.resolve(t.inputDir),o=Te.resolve(t.outputDir);if(!(await Xt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let s=t.components?.length?t.components:(await er(n)).map((x)=>({file:x}));if(!s.length)throw Error(`No .stx components found in ${n}`);let c=await Promise.all(s.map((x)=>vr(n,x,t)));c.sort((x,T)=>x.tag.localeCompare(T.tag));let f=c.filter((x,T)=>c.findIndex((k)=>k.tag===x.tag)!==T);if(f.length)throw Error(`Duplicate custom-element tag: ${f[0].tag}`);let u=c.filter((x,T)=>c.findIndex((k)=>k.name===x.name)!==T);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await Kn(o,{recursive:!0});let h=[],g=async(x,T)=>{let k=Te.join(o,x);return await Jn(k,T.endsWith(`
414
414
  `)?T:`${T}
415
- `,"utf8"),y.push(k),k};await m("runtime.js",vr());for(let x of l){if(await m(`${x.tag}.js`,wr(x)),t.declarations!==!1)await m(`${x.tag}.d.ts`,Sr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:Qt(x);await m(`${x.tag}.css`,t.minify?Zt(T):T)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
- `);if(await m("index.js",b),await m("ssr.js",$r(l)),t.declarations!==!1)await m("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
- `)),await m("custom-elements.d.ts",kr(l)),await m("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
415
+ `,"utf8"),h.push(k),k};await g("runtime.js",wr());for(let x of c){if(await g(`${x.tag}.js`,Sr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,kr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:Qt(x);await g(`${x.tag}.css`,t.minify?Zt(T):T)}}let b=c.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
+ `);if(await g("index.js",b),await g("ssr.js",Cr(c)),t.declarations!==!1)await g("index.d.ts",c.map((x)=>`export * from './${x.tag}.js'`).join(`
417
+ `)),await g("custom-elements.d.ts",Tr(c)),await g("ssr.d.ts",`${c.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
418
418
  `)}
419
419
  export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
420
- ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
421
- `)}`);let w;if(t.manifest!==!1)w=await m("custom-elements.json",JSON.stringify(Tr(l),null,2));let S;if(t.css!==!1){let x=l.filter((T)=>!T.shadowMode&&T.styles).map(Qt).join(`
420
+ ${c.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
421
+ `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify($r(c),null,2));let S;if(t.css!==!1){let x=c.filter((T)=>!T.shadowMode&&T.styles).map(Qt).join(`
422
422
 
423
- `);if(x)S=await m("bundle.css",t.minify?Zt(x):x)}let C;if(t.bundle!==!1){C=Re.join(s,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Re.join(s,"index.js")],outdir:s,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],I=k.map((A)=>String(A).trim()).filter(Boolean).join(`
424
- `);throw AggregateError(k,`Failed to bundle component library${I?`
425
- ${I}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
423
+ `);if(x)S=await g("bundle.css",t.minify?Zt(x):x)}let C;if(t.bundle!==!1){C=Te.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Te.join(o,"index.js")],outdir:o,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],L=k.map((O)=>String(O).trim()).filter(Boolean).join(`
424
+ `);throw AggregateError(k,`Failed to bundle component library${L?`
425
+ ${L}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
426
  `);throw AggregateError(x.logs,`Failed to bundle component library${T?`
427
- ${T}`:""}`)}if(y.push(C),t.sourcemap==="external")y.push(`${C}.map`)}let v=await Promise.all(y.map(async(x)=>(await Xt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Re.join(s,`${x.tag}.js`)})),files:y,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}var{serve:Hr}=globalThis.Bun;import Bt from"fs";import et from"path";function dt(){return`
427
+ ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await Promise.all(h.map(async(x)=>(await Xt(x)).size));return{components:c.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Te.join(o,`${x.tag}.js`)})),files:h,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}var{serve:jr}=globalThis.Bun;import Bt from"fs";import et from"path";function pt(){return`
428
428
  /* Theme selector for code blocks */
429
429
  .theme-selector {
430
430
  margin: 1rem 0;
@@ -474,7 +474,7 @@ ${T}`:""}`)}if(y.push(C),t.sourcemap==="external")y.push(`${C}.map`)}let v=await
474
474
 
475
475
  body.dark-mode a {
476
476
  color: #58a6ff;
477
- }`}function pt(t){return`
477
+ }`}function ut(t){return`
478
478
  <div class="theme-selector">
479
479
  Theme:
480
480
  <select id="themeSelector" onchange="changeTheme()">
@@ -496,27 +496,27 @@ else {
496
496
  }
497
497
 
498
498
  // Initialize theme on page load
499
- document.addEventListener('DOMContentLoaded', changeTheme);`}function mt(t){if(Object.keys(t).length===0)return"";return`
499
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function gt(t){if(Object.keys(t).length===0)return"";return`
500
500
  <div class="frontmatter">
501
501
  <h3>Frontmatter</h3>
502
- ${Object.entries(t).map(([r,s])=>`
502
+ ${Object.entries(t).map(([n,o])=>`
503
503
  <div class="frontmatter-item">
504
- <span class="frontmatter-label">${r}:</span>
505
- <span>${Array.isArray(s)?s.join(", "):String(s)}</span>
504
+ <span class="frontmatter-label">${n}:</span>
505
+ <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
506
506
  </div>`).join("")}
507
- </div>`}import nn from"net";async function Cr(t){return new Promise((r)=>{let s=nn.createServer();s.once("error",()=>r(!1)),s.once("listening",()=>{s.close(()=>r(!0))}),s.listen(t,"0.0.0.0")})}async function Rr(t){return new Promise((r)=>{let s=nn.createServer();s.once("error",()=>r(!1)),s.once("listening",()=>{s.close(()=>r(!0))}),s.listen(t,"::")})}async function Er(t){if(!await Cr(t))return!1;return await Rr(t)}async function We(t,r=20){t=Number(t);for(let s=0;s<r;s++){let p=t+s;if(await Er(p))return p}throw Error(`Could not find an available port between ${t} and ${t+r-1}`)}var Or={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Dr(){try{let t=await import("./chunk-2xtzzx00.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,r={}){let s={...Or,...r},p=await Dr();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let a=await p.openDevWindow(t,{title:s.title,width:s.width,height:s.height,darkMode:s.darkMode,hotReload:s.hotReload,titlebarHidden:s.titlebarHidden,nativeSidebar:s.nativeSidebar,sidebarWidth:s.sidebarWidth,sidebarConfig:s.sidebarConfig});if(a&&s.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return a}catch(a){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,a),!1}}function ht(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let a=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(a){let l=a[1];try{let f=`
508
- ${l}
507
+ </div>`}import nn from"net";async function Rr(t){return new Promise((n)=>{let o=nn.createServer();o.once("error",()=>n(!1)),o.once("listening",()=>{o.close(()=>n(!0))}),o.listen(t,"0.0.0.0")})}async function Er(t){return new Promise((n)=>{let o=nn.createServer();o.once("error",()=>n(!1)),o.once("listening",()=>{o.close(()=>n(!0))}),o.listen(t,"::")})}async function Pr(t){if(!await Rr(t))return!1;return await Er(t)}async function Ve(t,n=20){t=Number(t);for(let o=0;o<n;o++){let d=t+o;if(await Pr(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Ar={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Mr(){try{let t=await import("./chunk-sdpzaase.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Qe(t,n={}){let o={...Ar,...n},d=await Mr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let s=await d.openDevWindow(t,{title:o.title,width:o.width,height:o.height,darkMode:o.darkMode,hotReload:o.hotReload,titlebarHidden:o.titlebarHidden,nativeSidebar:o.nativeSidebar,sidebarWidth:o.sidebarWidth,sidebarConfig:o.sidebarConfig});if(s&&o.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return s}catch(s){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,s),!1}}function ht(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let s=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(s){let c=s[1];try{let f=`
508
+ ${c}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
- `,y=Function(f)();if(y)return y}catch(f){console.warn("Invalid sidebarConfig:",f)}}return{sections:[]}}let s=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(s)try{return JSON.parse(s[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let a=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(a)return Function(`return ${a[1]}`)()}catch(a){console.warn("Invalid native-sidebar script configuration:",a)}return}function Ht(){console.log(`
511
- Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function _r(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function Lr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function qe(t,r,s){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let p="";process.stdin.on("data",(a)=>{if(a==="\x03"){if(s?.onQuit)s.onQuit();r(),process.exit(0)}if(p+=a,p.endsWith("\r")||p.endsWith(`
512
- `)){let l=p.trim().toLowerCase();p="",jr(l,t,r,s)}})}function jr(t,r,s,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Lr(r);break;case"c":if(p?.onClear)p.onClear();else console.clear(),_r(r);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),s(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=et.resolve(t);if(!Bt.existsSync(a))return console.error(`${e.red}Error: File not found: ${e.bright}${a}${e.reset}`),!1;if(!a.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${a}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,f=async()=>{try{let{content:w,data:S}=await $e(a,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],I=[...new Set([...x,...T])].map((A)=>`<option value="${A}"${A===v?" selected":""}>${A}</option>`).join(`
513
- `);return l=`
510
+ `,h=Function(f)();if(h)return h}catch(f){console.warn("Invalid sidebarConfig:",f)}}return{sections:[]}}let o=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(o)try{return JSON.parse(o[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let s=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(s)return Function(`return ${s[1]}`)()}catch(s){console.warn("Invalid native-sidebar script configuration:",s)}return}function Ht(){console.log(`
511
+ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function _r(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function Lr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function qe(t,n,o){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let d="";process.stdin.on("data",(s)=>{if(s==="\x03"){if(o?.onQuit)o.onQuit();n(),process.exit(0)}if(d+=s,d.endsWith("\r")||d.endsWith(`
512
+ `)){let c=d.trim().toLowerCase();d="",Ir(c,t,n,o)}})}function Ir(t,n,o,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Lr(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),_r(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),o(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Ht();break;default:break}}async function Ft(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=et.resolve(t);if(!Bt.existsSync(s))return console.error(`${e.red}Error: File not found: ${e.bright}${s}${e.reset}`),!1;if(!s.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${s}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let c=null,f=async()=>{try{let{content:w,data:S}=await Re(s,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=n.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],L=[...new Set([...x,...T])].map((O)=>`<option value="${O}"${O===v?" selected":""}>${O}</option>`).join(`
513
+ `);return c=`
514
514
  <!DOCTYPE html>
515
515
  <html lang="en">
516
516
  <head>
517
517
  <meta charset="UTF-8">
518
518
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
519
- <title>${Br(S.title||et.basename(a))}</title>
519
+ <title>${Hr(S.title||et.basename(s))}</title>
520
520
  <!-- Syntax highlighting styles -->
521
521
  <style id="syntax-theme">
522
522
  :root {
@@ -658,12 +658,12 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
658
658
  min-width: 100px;
659
659
  color: #555;
660
660
  }
661
- ${dt()}
661
+ ${pt()}
662
662
  </style>
663
663
  </head>
664
664
  <body>
665
- ${mt(S)}
666
- ${pt(I)}
665
+ ${gt(S)}
666
+ ${ut(L)}
667
667
 
668
668
  ${w}
669
669
 
@@ -672,24 +672,24 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
672
672
  </script>
673
673
  </body>
674
674
  </html>
675
- `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await f())return!1;let y=s;try{if(y=await We(s),y!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let m=Hr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
675
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await f())return!1;let h=o;try{if(h=await Ve(o),h!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${h} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${h}/${e.reset}...`);let g=jr({port:h,fetch(w){if(new URL(w.url).pathname==="/")return new Response(c,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
676
676
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
677
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
678
- ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
679
- ${e.yellow}Routes:${e.reset}`);let b=et.relative(process.cwd(),a);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${b}${e.reset}`),console.log(`
680
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(m.url.toString(),()=>{if(p)Bt.watch(et.dirname(a),{recursive:!0}).close();m.stop()}),r.native)await Ze(y,{title:et.basename(a,".md")});if(p){let w=et.dirname(a);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(C,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await f()});process.on("SIGINT",()=>{S.close(),m.stop(),process.exit(0)})}return!0}function Br(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zr}=globalThis.Bun;import Be from"fs";import ge from"path";class on{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let r=t??this.options.wsPort,s=20;for(let p=0;p<s;p++)try{if(this.server=Bun.serve({port:r,fetch(a,l){if(l.upgrade(a,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(a)=>{if(this.clients.add(a),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);a.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(a)=>{if(this.clients.delete(a),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(a,l)=>{let f=typeof l==="string"?l:l.toString();if(f==="ping")return;try{let u=JSON.parse(f);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${r}`);return r}catch(a){if(a?.code==="EADDRINUSE"){r++;continue}throw a}throw Error(`Could not find an available port after ${s} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let r=JSON.stringify(t),s=0;for(let p of this.clients)try{if(p.readyState===1)p.send(r),s++}catch{this.clients.delete(p)}if(this.options.verbose&&s>0)console.log(`[HMR] Broadcast ${t.type} to ${s} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,r){this.broadcast({type:"css-update",path:t,content:r,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Fr(t,r={}){let{showOverlay:s=!0,reconnectInterval:p=1000,maxReconnectAttempts:a=10}=r;return`
678
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
679
+ ${e.yellow}Routes:${e.reset}`);let b=et.relative(process.cwd(),s);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${b}${e.reset}`),console.log(`
680
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(g.url.toString(),()=>{if(d)Bt.watch(et.dirname(s),{recursive:!0}).close();g.stop()}),n.native)await Qe(h,{title:et.basename(s,".md")});if(d){let w=et.dirname(s);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(C,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await f()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function Hr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zr}=globalThis.Bun;import Be from"fs";import ge from"path";class rn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,o=20;for(let d=0;d<o;d++)try{if(this.server=Bun.serve({port:n,fetch(s,c){if(c.upgrade(s,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(s)=>{if(this.clients.add(s),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);s.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(s)=>{if(this.clients.delete(s),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(s,c)=>{let f=typeof c==="string"?c:c.toString();if(f==="ping")return;try{let u=JSON.parse(f);if(u.type==="console"&&Array.isArray(u.args)){let h=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(s){if(s?.code==="EADDRINUSE"){n++;continue}throw s}throw Error(`Could not find an available port after ${o} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),o=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),o++}catch{this.clients.delete(d)}if(this.options.verbose&&o>0)console.log(`[HMR] Broadcast ${t.type} to ${o} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Fr(t,n={}){let{showOverlay:o=!0,reconnectInterval:d=1000,maxReconnectAttempts:s=10}=n;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
684
684
  var wsUrl = 'ws://' + window.location.hostname + ':${t}';
685
685
  var reconnectAttempts = 0;
686
- var maxAttempts = ${a};
687
- var reconnectInterval = ${p};
686
+ var maxAttempts = ${s};
687
+ var reconnectInterval = ${d};
688
688
  var socket = null;
689
689
  var overlay = null;
690
690
  var wasConnected = false; // Track if we ever connected successfully
691
691
 
692
- ${s?`
692
+ ${o?`
693
693
  // Create connection status overlay
694
694
  function createOverlay() {
695
695
  overlay = document.createElement('div');
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function Ne(t,r,s={}){let p=Fr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await os(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await rr(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new br(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new br(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-d7whccsw.js"),T=x(w.join(`
879
+ `}function Ne(t,n,o={}){let d=Fr(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function yt(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function vt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var tt=null;function Tt(t){if(!tt)tt=new rn(t);return tt}function st(){if(tt)tt.stop(),tt=null}import $t from"path";var nt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${$t.relative($t.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let f=await cs(o,d);if(c.push(...f),o.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(o.cache&&o.cachePath){let x=await ir(f,o);if(x){if(o.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let h=await Se(()=>Bun.file(f).text(),"",(x)=>{throw new xr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new xr(`stx file is empty: ${f}`,f);let{scriptContent:g,templateContent:b,allScripts:w}=oe.time("script-extraction",()=>{let x=h,T=de(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],L="",O=[];for(let R of k){let D=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=R.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))L=D;else O.push(R)}let A=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:L,templateContent:A,allScripts:O}}),S={__filename:f,__dirname:$t.dirname(f),__stx:{webComponentsPath:s,builtComponents:c}};await Se(()=>m(g,S,f),void 0,(x)=>{let T=new ae(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,g.substring(0,100));if(j.log(T,{filePath:f,scriptContent:g}),o.debug)throw T});let v=await oe.timeAsync("directive-processing",async()=>await i(b,S,f,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-b2ajtmvk.js"),T=x(w.join(`
880
880
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
881
881
  `+v.slice(k);else v+=`
882
- ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await sr(f,v,u,s),s.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new ie(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),vn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:s.debug||W()?`<!DOCTYPE html>
882
+ ${T}`}if(v=await be(v),u.forEach((x)=>d.add(x)),o.cache&&o.cachePath){if(await ar(f,v,u,o),o.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new ae(`Plugin processing failed: ${String(u)}`,f);if(j.log(h,{filePath:f,buildConfig:t.config}),wn.logDetailedError(h,{filePath:f,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",h);let g=h,b=g.line||null,w=g.context||null;return{contents:o.debug||q()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -902,16 +902,16 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await s
902
902
 
903
903
  <div class="error-details">
904
904
  <h3>Error Details</h3>
905
- <p><strong>File:</strong> <span class="file-path">${d(f)}</span></p>
906
- <p><strong>Error:</strong> ${d(y.message)}</p>
907
- ${b?`<p><strong>Line:</strong> ${d(String(b))}</p>`:""}
908
- ${w?`<p><strong>Context:</strong> ${d(String(w))}</p>`:""}
905
+ <p><strong>File:</strong> <span class="file-path">${p(f)}</span></p>
906
+ <p><strong>Error:</strong> ${p(h.message)}</p>
907
+ ${b?`<p><strong>Line:</strong> ${p(String(b))}</p>`:""}
908
+ ${w?`<p><strong>Context:</strong> ${p(String(w))}</p>`:""}
909
909
  </div>
910
910
 
911
- ${y.stack?`
911
+ ${h.stack?`
912
912
  <div class="error-details">
913
913
  <h3>Stack Trace</h3>
914
- <pre class="error-code">${d(y.stack)}</pre>
914
+ <pre class="error-code">${p(h.stack)}</pre>
915
915
  </div>`:""}
916
916
 
917
917
  <div class="help-section">
@@ -920,7 +920,7 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await s
920
920
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
921
921
  <li>Verify that all variables used in the template are properly defined</li>
922
922
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
923
- <li>Run <code>stx debug ${d(Rt.basename(f))}</code> for detailed analysis</li>
923
+ <li>Run <code>stx debug ${p($t.basename(f))}</code> for detailed analysis</li>
924
924
  <li>Enable debug mode in your stx config for more detailed error messages</li>
925
925
  </ul>
926
926
  </div>
@@ -939,12 +939,12 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await s
939
939
  <h1>Something went wrong</h1>
940
940
  <p>An internal error occurred. Please try again later.</p>
941
941
  </body>
942
- </html>`,loader:"html"}}})}};async function Ar(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await rn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-905azzfg.js"),j=await _();if(T=r.stxOptions?.serverApi??j.serverApi,j?.apiRouter)x=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){v=j.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-5h1ahj7m.js"),we=j.broadcasting;await K(we);let le=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:I}=await import("./chunk-gvggrhpq.js"),A=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let M=zr({port:C,async fetch(_){return _n(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>I(ge.join(ne,j.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[j.pathname])try{return await v[j.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await A(_);if(K)return K;if(j.pathname==="/")return(async()=>{let F=await h(m||"");if(a)F=Ne(F,f);if(r.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(r.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(y,j.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let we=ge.dirname(u),le=ge.join(we,j.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Pe=ge.join(process.cwd(),"public",j.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),L="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
943
- ${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
942
+ </html>`,loader:"html"}}})}};async function Or(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,f=n.hmrPort||o+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,n);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=l(process.cwd(),"output");Be.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let D={name:"public-assets",setup(ve){ve.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[u],outdir:h,plugins:[D,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await b())return!1;let S=ge.dirname(u);await sn(S);let C=o;try{if(C=await Ve(o),C!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let D=n.hmrPort||C+1;c=Tt({wsPort:D,verbose:!1}),f=c.start(D)}let v={},x=null,T;try{let{loadStxConfig:D}=await import("./chunk-fen5nnc4.js"),I=await D();if(T=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)x=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){v=I.apiRoutes;let V=Object.keys(v).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-gk0nq2ky.js"),ve=I.broadcasting;await V(ve);let le=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:L}=await import("./chunk-ktf42hmd.js"),O=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let A=zr({port:C,async fetch(D){return Cn(D,await(async()=>{let I=new URL(D.url);if([h,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>L(ge.join(ne,I.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(D);if(ne.status!==404)return ne}catch{}if(v[I.pathname])try{return await v[I.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await O(D);if(V)return V;if(I.pathname==="/")return(async()=>{let F=await y(g||"");if(s)F=Ne(F,f);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(h,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let ve=ge.dirname(u),le=ge.join(ve,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let Pe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
943
+ ${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
944
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
945
945
  ${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
946
- ${e.yellow}Routes:${e.reset}`);let E=ge.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
947
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(M.url.toString(),()=>{if(p)Be.watch(ge.dirname(u),{recursive:!0}).close();M.stop()}),r.native){let _=await Bun.file(u).text(),j=ht(_);await Ze(C,{title:ge.basename(u,".stx"),titlebarHidden:r.titlebarHidden===!0,nativeSidebar:!!j,sidebarConfig:j})}if(p){let _=ge.dirname(u);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let j=Be.watch(_,{recursive:!0},async(K,Y)=>{if(!Y||Tt(Y))return;if(bt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ge.clear(),pe();let we=await b();if(await Zn(S),a&&l)if(we)l.reload(Y);else l.error("Build failed - check console for details")}else if(yt(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),a&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(j.close(),l)st();M.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Ke from"fs";import Ee from"path";var sn=`
946
+ ${e.yellow}Routes:${e.reset}`);let R=ge.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${R}${e.reset}`),console.log(`
947
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(A.url.toString(),()=>{if(d)Be.watch(ge.dirname(u),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(u).text(),I=ht(D);await Qe(C,{title:ge.basename(u,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!I,sidebarConfig:I})}if(d){let D=ge.dirname(u);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let I=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||vt(Y))return;if(bt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),fe();let ve=await b();if(await tr(S),s&&c)if(ve)c.reload(Y);else c.error("Build failed - check console for details")}else if(yt(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),s&&c)c.updateCss(Y)}});process.on("SIGINT",()=>{if(I.close(),c)st();A.stop(),process.exit(0)})}return!0}var{serve:Ur}=globalThis.Bun;import Xe from"fs";import Ee from"path";var on=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,14 +1255,14 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function cn(t){if(t.length===0)return"";if(t.length===1)return t[0];let r=t.map((p)=>p.split(Ee.sep)),s=[];for(let p=0;p<r[0].length;p++){let a=r[0][p];if(r.every((l)=>l[p]===a))s.push(a);else break}return s.join(Ee.sep)}async function Pr(t,r={}){let s=r.port||3000,p=r.watch!==!1;for(let v of t){let x=Ee.resolve(v);if(!Ke.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let a=c(process.cwd(),"output");Ke.mkdirSync(a,{recursive:!0});let l=cn(t.map((v)=>Ee.dirname(Ee.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let f={},u=[],y=async()=>{try{for(let v of t){let x=Ee.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:I}=await $e(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),A=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,M=A?.defaultTheme||"github-dark",E=["github-dark"],_=A?.additionalThemes||[],K=[...new Set([...E,..._])].map((Pe)=>`<option value="${Pe}"${Pe===M?" selected":""}>${Pe}</option>`).join(`
1258
+ `;function cn(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split(Ee.sep)),o=[];for(let d=0;d<n[0].length;d++){let s=n[0][d];if(n.every((c)=>c[d]===s))o.push(s);else break}return o.join(Ee.sep)}async function Nr(t,n={}){let o=n.port||3000,d=n.watch!==!1;for(let v of t){let x=Ee.resolve(v);if(!Xe.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let s=l(process.cwd(),"output");Xe.mkdirSync(s,{recursive:!0});let c=cn(t.map((v)=>Ee.dirname(Ee.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let f={},u=[],h=async()=>{try{for(let v of t){let x=Ee.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:L}=await Re(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),O=n.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,A=O?.defaultTheme||"github-dark",R=["github-dark"],D=O?.additionalThemes||[],V=[...new Set([...R,...D])].map((Pe)=>`<option value="${Pe}"${Pe===A?" selected":""}>${Pe}</option>`).join(`
1259
1259
  `),Y=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
1262
1262
  <head>
1263
1263
  <meta charset="UTF-8">
1264
1264
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
- <title>${an(I.title||Ee.basename(x))}</title>
1265
+ <title>${an(L.title||Ee.basename(x))}</title>
1266
1266
  <!-- Syntax highlighting styles -->
1267
1267
  <style id="syntax-theme">
1268
1268
  :root {
@@ -1404,12 +1404,12 @@ else {
1404
1404
  min-width: 100px;
1405
1405
  color: #555;
1406
1406
  }
1407
- ${dt()}
1407
+ ${pt()}
1408
1408
  </style>
1409
1409
  </head>
1410
1410
  <body>
1411
- ${mt(I)}
1412
- ${pt(K)}
1411
+ ${gt(L)}
1412
+ ${ut(V)}
1413
1413
 
1414
1414
  ${k}
1415
1415
 
@@ -1418,26 +1418,26 @@ else {
1418
1418
  </script>
1419
1419
  </body>
1420
1420
  </html>
1421
- `,le=`/${Ee.relative(l,x).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";f[le||"/"]={filePath:x,content:Y,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(_)=>({path:_.path,external:!0}))}},I;try{let E=await Bun.build({entrypoints:[x],outdir:a,plugins:[k,nt],define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Te(E.logs,x));continue}let _=E.outputs.find((j)=>j.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}I=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
- ${Te(E,x)}`);continue}let M=`/${Ee.relative(l,x).replace(/\.stx$/,"")}`;if(M.endsWith("/index"))M=M.slice(0,-6)||"/";if(M.includes("[")){let{regex:E,params:_}=ds(M,{page:!0});u.push({pattern:E,paramNames:_,filePath:x,routeTemplate:M,fileType:"stx"}),f[M]={filePath:x,content:I,fileType:"stx"}}else f[M||"/"]={filePath:x,content:I,fileType:"stx"}}}if(Object.keys(f).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,Te(v)),!1}};if(!await y())return!1;let b=s;try{if(b=await We(s),b!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Nr({port:b,async fetch(v){let x=new URL(v.url),T=Ee.join(process.cwd(),"public",x.pathname);if(Ke.existsSync(T)&&Ke.statSync(T).isFile()){let A=Bun.file(T),M=Ee.extname(T).toLowerCase(),E="application/octet-stream";if(M===".ts"||M===".tsx"){let _=new Bun.Transpiler({loader:M===".tsx"?"tsx":"ts"}),j=await A.text(),K=_.transformSync(j);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(M){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(A,{headers:{"Content-Type":E}})}let k=f[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=f[`${x.pathname}/`];if(!k)for(let A of u){let M=x.pathname.match(A.pattern);if(M){let E=f[A.routeTemplate];if(E){let _={};for(let Y=0;Y<A.paramNames.length;Y++)_[A.paramNames[Y]]=decodeURIComponent(M[Y+1]);let j=E.content,K=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(j.includes("</head>"))j=j.replace("</head>",`${K}
1423
- </head>`);else j=K+j;k={...E,content:j}}break}}if(k)return h(k.content).then((A)=>{if(A.includes("</head>"))A=A.replace("</head>",`${sn}
1424
- </head>`);return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let I=Ee.join(a,x.pathname);if(Ke.existsSync(I)&&Ke.statSync(I).isFile()){let A=Bun.file(I),M=Ee.extname(I).toLowerCase(),E="text/plain";if(M===".ts"||M===".tsx"){let _=new Bun.Transpiler({loader:M===".tsx"?"tsx":"ts"}),j=await A.text(),K=_.transformSync(j);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(M){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(A,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&f["/"]){let A=ke(v);return h(f["/"].content).then((M)=>{if(A){let E=M.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=M.match(/<title[^>]*>([\s\S]*?)<\/title>/i),j=_?_[1]:"",K=`<!DOCTYPE html><html><head><title>${an(j)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...O(),"Cache-Control":ut,Pragma:"no-cache",Expires:"0"}})}}return new Response(M,{headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1421
+ `,le=`/${Ee.relative(c,x).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";f[le||"/"]={filePath:x,content:Y,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(R){R.onResolve({filter:/^\/(images|fonts|assets|public)\//},(D)=>({path:D.path,external:!0}))}},L;try{let R=await Bun.build({entrypoints:[x],outdir:s,plugins:[k,nt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!R.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,$e(R.logs,x));continue}let D=R.outputs.find((I)=>I.path.endsWith(".html"));if(!D){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}L=await Bun.file(D.path).text()}catch(R){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${$e(R,x)}`);continue}let A=`/${Ee.relative(c,x).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:R,params:D}=ms(A,{page:!0});u.push({pattern:R,paramNames:D,filePath:x,routeTemplate:A,fileType:"stx"}),f[A]={filePath:x,content:L,fileType:"stx"}}else f[A||"/"]={filePath:x,content:L,fileType:"stx"}}}if(Object.keys(f).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,$e(v)),!1}};if(!await h())return!1;let b=o;try{if(b=await Ve(o),b!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Ur({port:b,async fetch(v){let x=new URL(v.url),T=Ee.join(process.cwd(),"public",x.pathname);if(Xe.existsSync(T)&&Xe.statSync(T).isFile()){let O=Bun.file(T),A=Ee.extname(T).toLowerCase(),R="application/octet-stream";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),I=await O.text(),V=D.transformSync(I);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(O,{headers:{"Content-Type":R}})}let k=f[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=f[`${x.pathname}/`];if(!k)for(let O of u){let A=x.pathname.match(O.pattern);if(A){let R=f[O.routeTemplate];if(R){let D={};for(let Y=0;Y<O.paramNames.length;Y++)D[O.paramNames[Y]]=decodeURIComponent(A[Y+1]);let I=R.content,V=`<script>window.__routeParams = ${JSON.stringify(D)};</script>`;if(I.includes("</head>"))I=I.replace("</head>",`${V}
1423
+ </head>`);else I=V+I;k={...R,content:I}}break}}if(k)return y(k.content).then((O)=>{if(O.includes("</head>"))O=O.replace("</head>",`${on}
1424
+ </head>`);return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let L=Ee.join(s,x.pathname);if(Xe.existsSync(L)&&Xe.statSync(L).isFile()){let O=Bun.file(L),A=Ee.extname(L).toLowerCase(),R="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),I=await O.text(),V=D.transformSync(I);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(O,{headers:{"Content-Type":R}})}if(x.pathname!=="/"&&f["/"]){let O=_e(v);return y(f["/"].content).then((A)=>{if(O){let R=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(R){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),I=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${an(I)}</title></head><body><main>${R[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...M(),"Cache-Control":dt,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...M(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1425
1425
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1426
1426
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1427
1427
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1428
- ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",I=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${I}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Ke.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ke.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ge.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return dn(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Ir(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-905azzfg.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-gvggrhpq.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ui(u,r.stxOptions?.shell),_){if(E=await Ys(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-905azzfg.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-5h1ahj7m.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=ps(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-905azzfg.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-xbn2p5m8.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=dn(Z),{classifyAllScripts:fe}=await import("./chunk-905azzfg.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-d7whccsw.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-ezna88p6.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await rn(u);let Xe=s;try{if(Xe=await We(s),Xe!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Xe+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Ur({port:Xe,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===ho&&z?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:yo(z,qr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-fazw6sxz.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=ir(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Wi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Vi(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[ja]:qr(),...O(),"Cache-Control":ut}})}if(E)U=Mr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-ezna88p6.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=ir(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Mr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Mr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1430
- ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1428
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",L=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${L}`)}),console.log(`
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(c,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),fe(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return pn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Dr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,f=n.hmrPort||o+1,u=te.resolve(t),{loadStxConfig:h}=await import("./chunk-fen5nnc4.js"),g=await h(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-ktf42hmd.js"),S=n.stxOptions?.serverApi??g.serverApi,C=await b(u,S),v=g.root&&g.root!=="."?te.join(u,g.root):u,x=n.pagesDir||g.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!g._layerPageDirs?.some((E)=>me.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=G(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let L=g?._pluginPageDirs||[],O=[];for(let{dir:E,prefix:H}of L)if(me.existsSync(E)){let z=G(te.dirname(E),{pagesDir:te.basename(E)});for(let Q of z){let K=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;O.push({route:{...Q,pattern:K},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let A=new Map,R=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await qi(u,n.stxOptions?.shell),D){if(R=await eo(D,n.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}xt(),await kt(u);let I=St();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:E}=await import("./chunk-fen5nnc4.js"),H=await E(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){V=H.apiRoutes;let z=Object.keys(V).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-gk0nq2ky.js"),K=H.broadcasting;await z(K);let Oe=K.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let we=te.join(process.cwd(),"channels.ts");if(me.existsSync(we))try{let N=await Q(we);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let ve=l(u,"output");me.mkdirSync(ve,{recursive:!0});let le=new Map,Pe=new Set,ne=async(E)=>{let H=hs(T,E);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:ve,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!z.success)return null;let Q=z.outputs.find((K)=>K.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(E,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:K,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-fen5nnc4.js"),{checkCache:N,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-7hpwcwwh.js"),X=await Oe(u),We=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(u,ie)},ce={...K,...X,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=We(ce.partialsDir),ce.componentsDir=We(ce.componentsDir),ce.layoutsDir=We(ce.layoutsDir),ce.storesDir=We(ce.storesDir||"stores"),ce.cachePath=We(ce.cachePath)??l(u,"cache");let B=!H&&!n.profile,re=ce.cache!==!1;if(re&&B){let ie=pe.get(E.filePath);if(ie)try{if((await me.promises.stat(E.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let ke of ie.dependencies){if(!me.existsSync(ke)){He=!1;break}if((await me.promises.stat(ke)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let ke=ie.output;if(R)ke=Ue(ke,{preserveHead:!0});let ot=F.get(E.filePath);return{route:E,content:ke,status:ot?.status??await ln(E.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(E.filePath,ce);if(Ie){let je=Ie;if(R)je=Ue(je,{preserveHead:!0});let He=F.get(E.filePath);return{route:E,content:je,status:He?.status??await ln(E.filePath),headers:He?.headers}}}let Z=re?await W(E.filePath):await Bun.file(E.filePath).text(),se=pn(Z),{classifyAllScripts:ue}=await import("./chunk-fen5nnc4.js"),U=ue(Z),Le=U.server.map((ie)=>ie.content),De=Z;for(let ie of U.server)De=De.replace(ie.fullTag,"");let ee={__filename:E.filePath,__dirname:te.dirname(E.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,E.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ae=new Set,he;if(n.profile){let ie=performance.now();he=await z(De,ee,E.filePath,ce,Ae);let Ie=performance.now()-ie,je=te.relative(u,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await z(De,ee,E.filePath,ce,Ae);if(!R)he=await we(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-b2ajtmvk.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(R)he=Ue(he,{preserveHead:!0});if(re&&B)await J(E.filePath,he,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-pf427myt.js"),Ye=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((ke)=>({id:ke,render:async()=>{let ot=typeof ie[ke]==="function"?await ie[ke]():void 0;return z(rt[ke],{...ee,$boundary:ot},E.filePath,Ie,new Set)}})),He=new Set(je.map((ke)=>ke.id));Ye=[...(Ye||[]).filter((ke)=>!He.has(ke.id)),...je]}if(Ye&&Ye.length>0)Pe.add(E.pattern);else Ye=void 0;let Wt=Pt(ee),Vt=It(ee);if(B)F.set(E.filePath,{status:Wt,headers:Vt});return{route:E,content:he,status:Wt??se,headers:Vt,boundaries:Ye}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let E=new Set(le.keys()),H=new Set(A.keys());le.clear(),A.clear();let z=n.prebuild===!1?k.filter((K)=>E.has(K.pattern)):k,Q=n.prebuild===!1?O.filter(({route:K})=>H.has(K.pattern)):O;for(let K=0;K<z.length;K+=Fe){let Oe=z.slice(K,K+Fe),we=await Promise.all(Oe.map((N)=>_(N)));for(let N of we)if(N)le.set(N.route.pattern,N)}for(let K=0;K<Q.length;K+=Fe){let Oe=Q.slice(K,K+Fe),we=await Promise.all(Oe.map(({route:N})=>_(N)));for(let N of we)if(N)A.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?k.length+O.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await sn(u);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let E=n.hmrPort||Ge+1;c=Tt({wsPort:E,verbose:!1}),f=c.start(E)}let Ot=(E,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(E.includes("</head>"))return E.replace("</head>",`${Q}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+E};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(E){let H=new URL(E.url),z=n.stxOptions?.offline??g.offline;if(H.pathname===vo&&z?.enabled){if(!["GET","HEAD"].includes(E.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(E.method==="HEAD"?null:wo(z,Xr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=g?.publicDir||"public",K=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),we=te.join(ve,H.pathname);if([K,Oe,we].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,W]=await Promise.all([me.promises.stat(K).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(we).catch(()=>null)]);if(N?.isFile()&&!w(K,u,S))return zt(K);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(W?.isFile()&&!w(we,u,S))return zt(we);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-mzwa2478.js"),re=await B(E,{publicDir:te.join(u,Q),cacheDir:l(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(E);if(B.status!==404)return B}catch{}if(V[H.pathname])try{return await V[H.pathname](E)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await C(E);if(pe)return pe;let X=lr(H.pathname,k);if(X){let B=le.get(X.route.pattern),re=Pe.has(X.route.pattern);if(!B||X.route.isDynamic&&Object.keys(X.params).length>0||re){let Z=await _(X.route,X.params);if(Z){if(B=Z,!X.route.isDynamic&&!re)le.set(X.route.pattern,Z)}}if(B){let Z=B.status??200,se=B.headers??{},ue=(X.route.filePath?mt(await Bun.file(X.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:X.params})){let De=await ne(404);if(De){let ee=De;if(ee=await y(ee,u),s)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=_t(H.pathname,X.params,ue,H.search),De=Ct(Le,null,E,{isServer:!0}),ee=await Et(ue.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,he=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:he,headers:at})}if(ee.abort){let{statusCode:Ae,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${he}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(R&&Gi(E)){let Le=Ze(U),De=ye(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Tn(ee[1].trim()):"";if(Object.keys(X.params).length>0)U=Ot(U,X.params);U=await y(U,u);let he=g?.router?.container||"main";return U=Ce(U,he,!0),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[Fa]:Xr(),...M(),"Cache-Control":dt}})}if(R)U=Br(R,U);if(Object.keys(X.params).length>0)U=Ot(U,X.params);if(U=await y(U,u),s)U=Ne(U,f);if(n.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(n.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-pf427myt.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...M(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(O.length>0){let B=O.map((Z)=>Z.route),re=lr(H.pathname,B);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await _(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(R)se=Br(R,se);if(Object.keys(re.params).length>0)se=Ot(se,re.params);if(se=await y(se,u),s)se=Ne(se,f);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of L)if(Z!=="/"&&H.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=O.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(ue){let U=await _(ue.route);if(U)se=U,A.set(ue.route.pattern,U)}}if(se){let ue=se.content;if(R)ue=Br(R,ue);if(ue=await y(ue,u),s)ue=Ne(ue,f);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(wt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=le.get("/");if(We){let B=We.content;if(B=await y(B,u),s)B=Ne(B,f);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await y(B,u),s)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
1430
+ ${E.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1431
1431
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1432
- ${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
1433
- ${e.yellow}Routes:${e.reset}`);let Mt=[...gs(k,u)];for(let{route:P}of A)Mt.push(`${P.pattern}`);if(Mt.forEach((P,H)=>{let Q=H===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Xe,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ge.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-xbn2p5m8.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(_&&V){if(te.resolve(N,V)===_||te.basename(_)===V){let G=await Ys(_,r.stxOptions||{});if(G)E=G}}if(await ze(),await Zn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ge.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-xbn2p5m8.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await ze(),a&&l)l.reload(V)}}else if(yt(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(l)st();Dt.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Wr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
1435
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function Vr(t){try{let r=await Bun.file(t).text(),s=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
1436
- `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,r=!1,s){let p=it.basename(t,".stx"),a=await Wr(t),l=await Vr(t),f="";if(r&&s)f=`<${s}></${s}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
- `);f=`<${p}
1432
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),s)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
1433
+ ${e.yellow}Routes:${e.reset}`);let Dt=[...ys(k,u)];for(let{route:E}of O)Dt.push(`${E.pattern}`);if(Dt.forEach((E,H)=>{let Q=H===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${E}`)}),console.log(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(At.url.toString(),()=>{if(c)st();At.stop()}),n.native){let E,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();E=ht(Q)}let z=g?.app?.window??{};await Qe(Ge,{title:g?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!E,sidebarConfig:E})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...g._layerGraph?.layers.map((J)=>J.root)??[],...g._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of g._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...N].some((X)=>pe===X||pe.startsWith(`${X}${te.sep}`)))N.add(pe)}for(let[J,W]of z)if(!N.has(J))W.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Oe(J,W,pe).catch((X)=>console.error("[stx] Layer rebuild failed:",X))}))},K=Promise.resolve(),Oe=(N,J,W)=>(K=K.catch(()=>{}).then(()=>we(N,J,W)),K),we=async(N,J,W)=>{if(!W||vt(W))return;if(bt(W)){if(g._layerGraph){let pe=await h(u);Object.assign(g,pe),k.splice(0,k.length,...G(v,{pagesDir:x,pagesDirs:pe._layerPageDirs?[T,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(E(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(H(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ke.clear(),fe();try{let{invalidateFileCache:pe,templateCache:X}=await import("./chunk-7hpwcwwh.js");pe(te.resolve(N,W)),X.delete(te.resolve(N,W))}catch{}if(D&&W){if(te.resolve(N,W)===D||te.basename(D)===W){let X=await eo(D,n.stxOptions||{});if(X)R=X}}if(await ze(),await tr(u),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ke.clear(),fe();try{let{invalidateFileCache:pe,templateCache:X}=await import("./chunk-7hpwcwwh.js");pe(te.resolve(N,W)),X.delete(te.resolve(N,W))}catch{}if(await ze(),s&&c)c.reload(W)}}else if(yt(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&c)c.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(c)st();At.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Vr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],c=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=c.exec(d))!==null){let u=f[1],h=f[2]||f[3]||f[4];if(!h)continue;let g={name:h},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let C=u.split(`
1435
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=C.join(" ").trim(),s.push(g)}if(s.length===0){let u=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.split(":").map((S)=>S.trim());if(w)s.push({name:w})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function qr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
1436
+ `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,n=!1,o){let d=it.basename(t,".stx"),s=await Vr(t),c=await qr(t),f="";if(n&&o)f=`<${o}></${o}>`;else{let u=s.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
1437
+ `);f=`<${d}
1438
1438
  ${u}
1439
- />`}return{name:p,path:t,description:l,props:a,example:f,isWebComponent:r,tag:s}}async function pn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let r=await Nt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of r){let a=it.join(t,p.name);if(p.isDirectory()){let l=await pn(a);s.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))s.push(a)}return s}catch(r){return console.error(`Error finding component files in ${t}:`,r),[]}}async function Xr(t,r){try{if(!await n(t))return[];let s=await pn(t),p=[],a=new Map;if(r?.components?.length)for(let l of r.components)a.set(l.file,l);for(let l of s){let f=a.get(l),u=!!f,y=f?.tag,m=await Kr(l,u,y);p.push(m)}return p}catch(s){return console.error("Error generating component docs:",s),[]}}async function Gr(t){try{if(!await n(t))return[];let r=await Nt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of r){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let a=it.join(t,p.name),l=await Bun.file(a).text(),f=it.basename(a,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
1440
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",m=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=m.exec(l))!==null)w.add(S[1]);while((S=b.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let C=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=C.exec(l))!==null)v.add(S[1]);s.push({name:f,path:a,description:y,components:[...w],directives:[...v]})}return s}catch(r){return console.error("Error generating template docs:",r),[]}}async function Jr(t=[]){try{let r=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1439
+ />`}return{name:d,path:t,description:c,props:s,example:f,isWebComponent:n,tag:o}}async function dn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Nt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of n){let s=it.join(t,d.name);if(d.isDirectory()){let c=await dn(s);o.push(...c)}else if(d.isFile()&&d.name.endsWith(".stx"))o.push(s)}return o}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Gr(t,n){try{if(!await r(t))return[];let o=await dn(t),d=[],s=new Map;if(n?.components?.length)for(let c of n.components)s.set(c.file,c);for(let c of o){let f=s.get(c),u=!!f,h=f?.tag,g=await Kr(c,u,h);d.push(g)}return d}catch(o){return console.error("Error generating component docs:",o),[]}}async function Jr(t){try{if(!await r(t))return[];let n=await Nt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let s=it.join(t,d.name),c=await Bun.file(s).text(),f=it.basename(s,".stx"),u=c.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||c.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=u?u[1].split(`
1440
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(c))!==null)w.add(S[1]);while((S=b.exec(c))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let C=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=C.exec(c))!==null)v.add(S[1]);o.push({name:f,path:s,description:h,components:[...w],directives:[...v]})}return o}catch(n){return console.error("Error generating template docs:",n),[]}}async function Yr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1441
1441
  <p>Welcome, {{ user.name }}!</p>
1442
1442
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1443
1443
  <p>Welcome back!</p>
@@ -1457,49 +1457,49 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.
1457
1457
  <p>Page {{ page }}</p>
1458
1458
  @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
1459
1459
  {{ This will be displayed as-is }}
1460
- @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let s of t)r.push({name:s.name,description:s.description||"",hasEndTag:s.hasEndTag||!1,example:""});return r}catch(r){return console.error("Error generating directive docs:",r),[]}}function Yr(t=[],r=[],s=[],p){let a=`# stx Documentation
1460
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let o of t)n.push({name:o.name,description:o.description||"",hasEndTag:o.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function Qr(t=[],n=[],o=[],d){let s=`# stx Documentation
1461
1461
 
1462
- `;if(p)a+=`${p}
1462
+ `;if(d)s+=`${d}
1463
1463
 
1464
- `;if(t.length>0){a+=`## Components
1464
+ `;if(t.length>0){s+=`## Components
1465
1465
 
1466
- `;for(let l of t){if(a+=`### ${l.name}
1466
+ `;for(let c of t){if(s+=`### ${c.name}
1467
1467
 
1468
- `,l.description)a+=`${l.description}
1468
+ `,c.description)s+=`${c.description}
1469
1469
 
1470
- `;if(l.isWebComponent)a+=`**Web Component Tag:** \`${l.tag}\`
1470
+ `;if(c.isWebComponent)s+=`**Web Component Tag:** \`${c.tag}\`
1471
1471
 
1472
- `;if(l.props.length>0){a+=`#### Properties
1472
+ `;if(c.props.length>0){s+=`#### Properties
1473
1473
 
1474
- `,a+=`| Name | Type | Required | Default | Description |
1475
- `,a+=`| ---- | ---- | -------- | ------- | ----------- |
1476
- `;for(let f of l.props)a+=`| ${f.name} | ${f.type||"any"} | ${f.required?"Yes":"No"} | ${f.default||"-"} | ${f.description||"-"} |
1477
- `;a+=`
1478
- `}if(l.example)a+=`#### Example
1474
+ `,s+=`| Name | Type | Required | Default | Description |
1475
+ `,s+=`| ---- | ---- | -------- | ------- | ----------- |
1476
+ `;for(let f of c.props)s+=`| ${f.name} | ${f.type||"any"} | ${f.required?"Yes":"No"} | ${f.default||"-"} | ${f.description||"-"} |
1477
+ `;s+=`
1478
+ `}if(c.example)s+=`#### Example
1479
1479
 
1480
- `,a+="```html\n",a+=l.example,a+="\n```\n\n"}}if(r.length>0){a+=`## Templates
1480
+ `,s+="```html\n",s+=c.example,s+="\n```\n\n"}}if(n.length>0){s+=`## Templates
1481
1481
 
1482
- `;for(let l of r){if(a+=`### ${l.name}
1482
+ `;for(let c of n){if(s+=`### ${c.name}
1483
1483
 
1484
- `,l.description)a+=`${l.description}
1484
+ `,c.description)s+=`${c.description}
1485
1485
 
1486
- `;if(l.components&&l.components.length>0)a+=`**Components Used:** ${l.components.join(", ")}
1486
+ `;if(c.components&&c.components.length>0)s+=`**Components Used:** ${c.components.join(", ")}
1487
1487
 
1488
- `;if(l.directives&&l.directives.length>0)a+=`**Directives Used:** ${l.directives.join(", ")}
1488
+ `;if(c.directives&&c.directives.length>0)s+=`**Directives Used:** ${c.directives.join(", ")}
1489
1489
 
1490
- `}}if(s.length>0){a+=`## Directives
1490
+ `}}if(o.length>0){s+=`## Directives
1491
1491
 
1492
- `,a+=`| Directive | Description | Has End Tag |
1493
- `,a+=`| --------- | ----------- | ----------- |
1494
- `;for(let l of s)a+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
- `;a+=`
1496
- `;for(let l of s)if(l.example)a+=`### @${l.name}
1492
+ `,s+=`| Directive | Description | Has End Tag |
1493
+ `,s+=`| --------- | ----------- | ----------- |
1494
+ `;for(let c of o)s+=`| @${c.name} | ${c.description||"-"} | ${c.hasEndTag?"Yes":"No"} |
1495
+ `;s+=`
1496
+ `;for(let c of o)if(c.example)s+=`### @${c.name}
1497
1497
 
1498
- `,a+=`${l.description||""}
1498
+ `,s+=`${c.description||""}
1499
1499
 
1500
- `,a+=`#### Example
1500
+ `,s+=`#### Example
1501
1501
 
1502
- `,a+="```html\n",a+=l.example,a+="\n```\n\n"}return a}function Qr(t=[],r=[],s=[],p){let a=`<!DOCTYPE html>
1502
+ `,s+="```html\n",s+=c.example,s+="\n```\n\n"}return s}function Zr(t=[],n=[],o=[],d){let s=`<!DOCTYPE html>
1503
1503
  <html lang="en">
1504
1504
  <head>
1505
1505
  <meta charset="UTF-8">
@@ -1542,7 +1542,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.
1542
1542
  </head>
1543
1543
  <body>
1544
1544
  <h1>stx Documentation</h1>
1545
- `;if(p)a+=`<div>${p}</div>`;if(t.length>0){a+="<h2>Components</h2>";for(let l of t){if(a+=`<h3>${l.name}</h3>`,l.description)a+=`<p>${l.description}</p>`;if(l.isWebComponent)a+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){a+="<h4>Properties</h4>",a+=`<table>
1545
+ `;if(d)s+=`<div>${d}</div>`;if(t.length>0){s+="<h2>Components</h2>";for(let c of t){if(s+=`<h3>${c.name}</h3>`,c.description)s+=`<p>${c.description}</p>`;if(c.isWebComponent)s+=`<p><strong>Web Component Tag:</strong> <code>${c.tag}</code></p>`;if(c.props.length>0){s+="<h4>Properties</h4>",s+=`<table>
1546
1546
  <thead>
1547
1547
  <tr>
1548
1548
  <th>Name</th>
@@ -1552,13 +1552,13 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.
1552
1552
  <th>Description</th>
1553
1553
  </tr>
1554
1554
  </thead>
1555
- <tbody>`;for(let f of l.props)a+=`<tr>
1555
+ <tbody>`;for(let f of c.props)s+=`<tr>
1556
1556
  <td>${f.name}</td>
1557
1557
  <td>${f.type||"any"}</td>
1558
1558
  <td>${f.required?"Yes":"No"}</td>
1559
1559
  <td>${f.default||"-"}</td>
1560
1560
  <td>${f.description||"-"}</td>
1561
- </tr>`;a+="</tbody></table>"}if(l.example)a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(r.length>0){a+="<h2>Templates</h2>";for(let l of r){if(a+=`<h3>${l.name}</h3>`,l.description)a+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)a+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)a+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(s.length>0){a+="<h2>Directives</h2>",a+=`<table>
1561
+ </tr>`;s+="</tbody></table>"}if(c.example)s+="<h4>Example</h4>",s+=`<pre><code>${c.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(n.length>0){s+="<h2>Templates</h2>";for(let c of n){if(s+=`<h3>${c.name}</h3>`,c.description)s+=`<p>${c.description}</p>`;if(c.components&&c.components.length>0)s+=`<p><strong>Components Used:</strong> ${c.components.join(", ")}</p>`;if(c.directives&&c.directives.length>0)s+=`<p><strong>Directives Used:</strong> ${c.directives.join(", ")}</p>`}}if(o.length>0){s+="<h2>Directives</h2>",s+=`<table>
1562
1562
  <thead>
1563
1563
  <tr>
1564
1564
  <th>Directive</th>
@@ -1566,44 +1566,44 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.
1566
1566
  <th>Has End Tag</th>
1567
1567
  </tr>
1568
1568
  </thead>
1569
- <tbody>`;for(let l of s)a+=`<tr>
1570
- <td>@${l.name}</td>
1571
- <td>${l.description||"-"}</td>
1572
- <td>${l.hasEndTag?"Yes":"No"}</td>
1573
- </tr>`;a+="</tbody></table>";for(let l of s)if(l.example)a+=`<h3>@${l.name}</h3>`,a+=`<p>${l.description||""}</p>`,a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return a+="</body></html>",a}function Zr(t=[],r=[],s=[],p){return JSON.stringify({components:t,templates:r,directives:s,extraContent:p||""},null,2)}async function eo(t){try{let{componentsDir:r,templatesDir:s,webComponentsConfig:p,customDirectives:a,config:l}=t;if(!l.enabled)return!1;let f=l.outputDir||"docs";if(await Nt.promises.mkdir(f,{recursive:!0}),console.log("Generating documentation..."),r)console.log(`Components directory: ${r}`);if(s)console.log(`Templates directory: ${s}`);console.log(`Output directory: ${f}`);let u=[];if(l.components!==!1&&r)console.log("Generating component documentation..."),u=await Xr(r,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&s)console.log("Generating template documentation..."),y=await Gr(s),console.log(`Found ${y.length} templates`);let m=[];if(l.directives!==!1)console.log("Generating directive documentation..."),m=await Jr(a),console.log(`Found ${m.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",C="";switch(b){case"markdown":S=Yr(u,y,m,w),C="md";break;case"html":S=Qr(u,y,m,w),C="html";break;case"json":S=Zr(u,y,m,w),C="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=it.join(f,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(r){return console.error("Error generating documentation:",r),!1}}async function Oi(t){let r={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},s=t.componentsDir||R.componentsDir,p=t.templatesDir||".";return eo({componentsDir:s,templatesDir:p,webComponentsConfig:R.webComponents,customDirectives:R.customDirectives,config:r})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Vs(t,r={}){let s={...fn,...r};if(t.trim()==="")return`
1574
- `;let p=t;if(s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=ro(p,s),p=ao(p,s),p=oo(p,s),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1569
+ <tbody>`;for(let c of o)s+=`<tr>
1570
+ <td>@${c.name}</td>
1571
+ <td>${c.description||"-"}</td>
1572
+ <td>${c.hasEndTag?"Yes":"No"}</td>
1573
+ </tr>`;s+="</tbody></table>";for(let c of o)if(c.example)s+=`<h3>@${c.name}</h3>`,s+=`<p>${c.description||""}</p>`,s+="<h4>Example</h4>",s+=`<pre><code>${c.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return s+="</body></html>",s}function to(t=[],n=[],o=[],d){return JSON.stringify({components:t,templates:n,directives:o,extraContent:d||""},null,2)}async function no(t){try{let{componentsDir:n,templatesDir:o,webComponentsConfig:d,customDirectives:s,config:c}=t;if(!c.enabled)return!1;let f=c.outputDir||"docs";if(await Nt.promises.mkdir(f,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(o)console.log(`Templates directory: ${o}`);console.log(`Output directory: ${f}`);let u=[];if(c.components!==!1&&n)console.log("Generating component documentation..."),u=await Gr(n,d),console.log(`Found ${u.length} components`);let h=[];if(c.templates!==!1&&o)console.log("Generating template documentation..."),h=await Jr(o),console.log(`Found ${h.length} templates`);let g=[];if(c.directives!==!1)console.log("Generating directive documentation..."),g=await Yr(s),console.log(`Found ${g.length} directives`);let b=c.format||"markdown",w=c.extraContent,S="",C="";switch(b){case"markdown":S=Qr(u,h,g,w),C="md";break;case"html":S=Zr(u,h,g,w),C="html";break;case"json":S=to(u,h,g,w),C="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=it.join(f,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function Mi(t){let n={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},o=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return no({componentsDir:o,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:n})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function qs(t,n={}){let o={...fn,...n};if(t.trim()==="")return`
1574
+ `;let d=t;if(o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=so(d,o),d=lo(d,o),d=io(d,o),o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1575
1575
  `).replace(/\r/g,`
1576
- `),!p.endsWith(`
1577
- `))p+=`
1578
- `;return p}function Ni(t,r={}){let s={...fn,...r};if(t.trim()==="")return`
1579
- `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(a,l,f,u,y)=>{let m=u.split(`
1580
- `),b=m.filter((x)=>x.trim().length>0);if(b.length===0)return a;let w=Math.min(...b.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=m.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
- `),v=Vs(S,s).trimEnd().split(`
1582
- `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
- `);return`${l}\`\`\`${f}
1576
+ `),!d.endsWith(`
1577
+ `))d+=`
1578
+ `;return d}function Li(t,n={}){let o={...fn,...n};if(t.trim()==="")return`
1579
+ `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(s,c,f,u,h)=>{let g=u.split(`
1580
+ `),b=g.filter((x)=>x.trim().length>0);if(b.length===0)return s;let w=Math.min(...b.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
+ `),v=qs(S,o).trimEnd().split(`
1582
+ `).map((x)=>{if(x.trim().length===0)return"";return c+x}).join(`
1583
+ `);return`${c}\`\`\`${f}
1584
1584
  ${v}
1585
- ${l}\`\`\``}),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1585
+ ${c}\`\`\``}),o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
- `),!p.endsWith(`
1588
- `))p+=`
1589
- `;return p}function no(t){let r=t,s=[],p="__PROTECTED_BLOCK_";return r=r.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(a)=>{let l=s.length;return s.push(a),`${p}${l}__`}),r=r.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1587
+ `),!d.endsWith(`
1588
+ `))d+=`
1589
+ `;return d}function oo(t){let n=t,o=[],d="__PROTECTED_BLOCK_";return n=n.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(s)=>{let c=o.length;return o.push(s),`${d}${c}__`}),n=n.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1590
1590
  $1
1591
- `),r=r.replace(/(@end\w+)/g,`
1591
+ `),n=n.replace(/(@end\w+)/g,`
1592
1592
  $1
1593
- `),r=r.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1593
+ `),n=n.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1594
1594
  $1
1595
- `),r=r.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1595
+ `),n=n.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1596
1596
  $1
1597
- `),r=r.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(a,l,f,u)=>{let y=u.substring(f+a.length,Math.min(u.length,f+a.length+20)),m=a.match(/<(\w+)/)?.[1];if(m&&y.match(new RegExp(`^</${m}>`)))return a;return`
1598
- ${a}`}),r=r.replace(/(>)(<\/)/g,(a,l,f,u,y)=>{let m=y.substring(Math.max(0,u-50),u),w=y.substring(u+a.length,Math.min(y.length,u+a.length+20)).match(/^(\w+)>/)?.[1],S=m.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return a;return`${l}
1599
- ${f}`}),r=r.replace(/(<\/[^>]+>)(?=<|$)/g,(a,l,f,u)=>{let y=u.substring(Math.max(0,f-20),f),m=a.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${m}[^>]*>$`);if(m&&y.match(b))return a;return`${a}
1600
- `}),r=r.replace(new RegExp(`${p}(\\d+)__`,"g"),(a,l)=>s[Number.parseInt(l,10)]),r=r.replace(/\n{2,}/g,`
1601
- `),r=r.split(`
1602
- `).map((a)=>a.trim()).join(`
1603
- `),r=r.replace(/^\n+/,"").replace(/\n+$/,""),r}function ro(t,r){let p=no(t).split(`
1604
- `),a=[],l=0,f=!1,u=r.useTabs?"\t":" ".repeat(r.indentSize);for(let y=0;y<p.length;y++){let m=p[y],b=m.trim();if(b===""){a.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(f&&!S){a.push(m);continue}let C=b===">";if(un(b)&&!b.startsWith("<")&&!b.startsWith("@")){a.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),T=b.startsWith("@")&&io(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),I=b.startsWith("<!--"),A=b.startsWith("</"),M=b.startsWith("<")&&!A&&!I&&!k,E=b.includes("/>")||so(b),_=un(b);if(A||v)l=Math.max(0,l-1);let j=x?Math.max(0,l-1):l;if(C)a.push(m);else a.push(u.repeat(j)+b);if(M&&!E&&!_&&!C||T)l++;if(w)f=!0;if(S)f=!1}return a.join(`
1605
- `)}function oo(t,r){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(s,p,a)=>{let l=a.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(s,p,a)=>{if(a.trim()==="")return`@${p}`;return`@${p}(${a.trim()})`}),r.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(s,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(s,p)=>`{!! ${p.trim()} !!}`);return t}function so(t){let r=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let s=t.match(/<(\w+)/);if(s){let p=s[1];return r.includes(p.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function io(t){let r=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let s of r)if(t.startsWith(`@${s}`))return!t.includes(`@end${s}`);return!1}function ao(t,r){if(!r.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(s,p,a)=>{if(!a.trim())return s;if(a.includes("<")||a.includes(`
1606
- `)||a.includes("@"))return s;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,f=[],u;while((u=l.exec(a))!==null)f.push({name:u[1],value:u[2]});f.sort((m,b)=>{if(m.name==="id")return-1;if(b.name==="id")return 1;if(m.name==="class")return-1;if(b.name==="class")return 1;return m.name.localeCompare(b.name)});let y=f.map((m)=>m.value?`${m.name}=${m.value}`:m.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import mn from"fs";import Ut from"path";async function Di(t="index.stx",r={}){try{let s=r.force||!1,p=Ut.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!s)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let a=Ut.dirname(p);if(!mn.existsSync(a))mn.mkdirSync(a,{recursive:!0});let l;if(r.template){let f=Ut.resolve(process.cwd(),r.template);if(!await Bun.file(f).exists())throw Error(`Template file ${r.template} does not exist.`);if(!f.endsWith(".stx"))console.warn(`Warning: Template file ${r.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(f).text(),console.warn(`Using template from ${r.template}`)}else if(r.preset)l=gn(r.preset),console.warn(`Using '${r.preset}' preset template`);else l=gn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(s){return console.error(`Error creating file: ${s instanceof Error?s.message:String(s)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return co();case"layout":return lo();case"blog":return po();case"api":return uo();case"app":return fo();default:return hn()}}function hn(){return`<script>
1597
+ `),n=n.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(s,c,f,u)=>{let h=u.substring(f+s.length,Math.min(u.length,f+s.length+20)),g=s.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return s;return`
1598
+ ${s}`}),n=n.replace(/(>)(<\/)/g,(s,c,f,u,h)=>{let g=h.substring(Math.max(0,u-50),u),w=h.substring(u+s.length,Math.min(h.length,u+s.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return s;return`${c}
1599
+ ${f}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(s,c,f,u)=>{let h=u.substring(Math.max(0,f-20),f),g=s.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(b))return s;return`${s}
1600
+ `}),n=n.replace(new RegExp(`${d}(\\d+)__`,"g"),(s,c)=>o[Number.parseInt(c,10)]),n=n.replace(/\n{2,}/g,`
1601
+ `),n=n.split(`
1602
+ `).map((s)=>s.trim()).join(`
1603
+ `),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function so(t,n){let d=oo(t).split(`
1604
+ `),s=[],c=0,f=!1,u=n.useTabs?"\t":" ".repeat(n.indentSize);for(let h=0;h<d.length;h++){let g=d[h],b=g.trim();if(b===""){s.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(f&&!S){s.push(g);continue}let C=b===">";if(un(b)&&!b.startsWith("<")&&!b.startsWith("@")){s.push(u.repeat(c)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),T=b.startsWith("@")&&co(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),L=b.startsWith("<!--"),O=b.startsWith("</"),A=b.startsWith("<")&&!O&&!L&&!k,R=b.includes("/>")||ao(b),D=un(b);if(O||v)c=Math.max(0,c-1);let I=x?Math.max(0,c-1):c;if(C)s.push(g);else s.push(u.repeat(I)+b);if(A&&!R&&!D&&!C||T)c++;if(w)f=!0;if(S)f=!1}return s.join(`
1605
+ `)}function io(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,d,s)=>{let c=s.trim().replace(/\s+/g," ");return`@${d}(${c})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,d,s)=>{if(s.trim()==="")return`@${d}`;return`@${d}(${s.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,d)=>`{!! ${d.trim()} !!}`);return t}function ao(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let o=t.match(/<(\w+)/);if(o){let d=o[1];return n.includes(d.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function co(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let o of n)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function lo(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,d,s)=>{if(!s.trim())return o;if(s.includes("<")||s.includes(`
1606
+ `)||s.includes("@"))return o;let c=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,f=[],u;while((u=c.exec(s))!==null)f.push({name:u[1],value:u[2]});f.sort((g,b)=>{if(g.name==="id")return-1;if(b.name==="id")return 1;if(g.name==="class")return-1;if(b.name==="class")return 1;return g.name.localeCompare(b.name)});let h=f.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${h?` ${h}`:""}>`})}import mn from"fs";import Ut from"path";async function ji(t="index.stx",n={}){try{let o=n.force||!1,d=Ut.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!o)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let s=Ut.dirname(d);if(!mn.existsSync(s))mn.mkdirSync(s,{recursive:!0});let c;if(n.template){let f=Ut.resolve(process.cwd(),n.template);if(!await Bun.file(f).exists())throw Error(`Template file ${n.template} does not exist.`);if(!f.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);c=await Bun.file(f).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)c=gn(n.preset),console.warn(`Using '${n.preset}' preset template`);else c=gn("basic");return await Bun.write(d,c),console.warn(`Created new stx file: ${t}`),!0}catch(o){return console.error(`Error creating file: ${o instanceof Error?o.message:String(o)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return po();case"layout":return uo();case"blog":return fo();case"api":return mo();case"app":return go();default:return hn()}}function hn(){return`<script>
1607
1607
  const title = "My stx Page"
1608
1608
  const description = "A page built with stx"
1609
1609
  const features = [
@@ -1628,7 +1628,7 @@ const features = [
1628
1628
  </div>
1629
1629
  @endforeach
1630
1630
  </main>
1631
- @endsection`}function co(){return`{{-- Component: Card --}}
1631
+ @endsection`}function po(){return`{{-- Component: Card --}}
1632
1632
  {{-- Props: title, variant, collapsible --}}
1633
1633
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1634
1634
  <script>
@@ -1673,7 +1673,7 @@ const features = [
1673
1673
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
1674
1674
  .card__body { padding: 1rem; }
1675
1675
  .card.collapsed .card__body { display: none; }
1676
- </style>`}function lo(){return`<!DOCTYPE html>
1676
+ </style>`}function uo(){return`<!DOCTYPE html>
1677
1677
  <html lang="en">
1678
1678
  <head>
1679
1679
  <meta charset="UTF-8">
@@ -1724,7 +1724,7 @@ const features = [
1724
1724
 
1725
1725
  @yield('scripts')
1726
1726
  </body>
1727
- </html>`}function po(){return`<script>
1727
+ </html>`}function fo(){return`<script>
1728
1728
  // Article metadata
1729
1729
  const title = "My Blog Post"
1730
1730
  const author = "Your Name"
@@ -1769,7 +1769,7 @@ const features = [
1769
1769
  <p>Wrap up your thoughts here.</p>
1770
1770
  </div>
1771
1771
  </article>
1772
- @endsection`}function uo(){return`<script>
1772
+ @endsection`}function mo(){return`<script>
1773
1773
  // API endpoint configuration
1774
1774
  const endpoint = "/api/data"
1775
1775
  const method = "GET"
@@ -1804,7 +1804,7 @@ const features = [
1804
1804
  }
1805
1805
  @else
1806
1806
  {{ JSON.stringify(data, null, 2) }}
1807
- @endif`}function fo(){return`<!DOCTYPE html>
1807
+ @endif`}function go(){return`<!DOCTYPE html>
1808
1808
  <html lang="en">
1809
1809
  <head>
1810
1810
  <meta charset="UTF-8">
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
2032
- </html>`}var Mi="f9c3713";function ol(t){return t}function il(t){return t}function Ai(t,r){let s=[],p=`${r}=`;for(let a=0;a<t.length;a++){let l=t[a];if(l.startsWith(p)){let f=l.slice(p.length);if(f)s.push(f);continue}if(l===r){let f=t[a+1];if(f!==void 0&&!f.startsWith("-"))s.push(f),a++}}return s}import Me from"fs";import ve from"path";function $n(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Et(t,r){let s=Math.max(0,Math.round((r-t)/1000));if(s<60)return`${s}s ago`;if(s<3600)return`${Math.round(s/60)}m ago`;return`${Math.round(s/3600)}h ago`}function ki(t,r){try{return globalThis.Bun?.resolveSync(t,r)??null}catch{return null}}function Cn(t,r="stx"){let s=ve.resolve(t);for(let p=0;p<10;p++){let a=ve.join(s,"pantry","@stacksjs",r);if(Me.existsSync(a))return a;let l=ve.dirname(s);if(l===s)break;s=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function Ti(t){try{let r=Me.readFileSync(ve.join(t,"package.json"),"utf8"),s=JSON.parse(r)?.version;return typeof s==="string"?s:null}catch{return null}}function $i(t,r=6){let s=ve.resolve(t),p=[],a=new Set;function l(u,y){if(y>r)return;let m;try{m=Me.realpathSync(u)}catch{return}if(a.has(m))return;a.add(m);for(let w of Rn){let S=ve.join(u,w),C=Ti(S);if(C!==null)p.push({name:w,version:C,dir:ve.relative(s,S)||S,nested:y>0})}let b;try{b=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ve.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=ve.join(S,x.name,"node_modules");if(Me.existsSync(T))l(T,y+1)}continue}let C=ve.join(S,"node_modules");if(Me.existsSync(C))l(C,y+1)}}let f=ve.join(s,"node_modules");if(Me.existsSync(f))l(f,0);return p}function Ci(t){let r=[];for(let s of Rn){let p=t.filter((f)=>f.name===s);if(p.length<=1)continue;let a=[...new Set(p.map((f)=>f.version))],l=p.map((f)=>`${f.version} at ${f.dir}`).join("; ");if(a.length===1){r.push({name:`${s} copies`,status:"info",detail:`${p.length} copies, all ${a[0]} \u2014 duplicated but in agreement`});continue}r.push({name:`${s} copies disagree`,status:"error",detail:`${a.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${s}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${s}/package.json' -exec grep -H '"version"' {} +`})}return r}async function Us(t={}){let r=t.cwd?ve.resolve(t.cwd):process.cwd(),s=t.resolve??ki,p=Date.now(),a=[],l=s("@stacksjs/stx",r);a.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let f=s("bun-plugin-stx",r);if(f)a.push({name:"bun-plugin-stx resolves to",status:"ok",detail:f});for(let y of Ci($i(r)))a.push(y);let u=Cn(r,"stx");if(!u)a.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ve.join(u,"src/signals.ts"),m=[ve.join(u,"dist/index.js"),ve.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,b=$n(y),w=m?$n(m):null;if(b==null)a.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)a.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);a.push({name:"pantry dist freshness",status:"error",detail:`dist (${Et(w,p)}) is OLDER than src/signals.ts (${Et(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else a.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Et(b,p)}, dist ${Et(w,p)})`});let S=ve.join(r,"node_modules/@stacksjs/stx"),C=null;try{C=Me.lstatSync(S)}catch{C=null}if(!C)a.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();a.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else a.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(a.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let m=t.generateRuntime().length;a.push(m>1000?{name:"signals runtime",status:"ok",detail:`generated ${m.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${m} chars \u2014 suspiciously short`})}catch(y){a.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:a,ok:!a.some((y)=>y.status==="error")}}function Ws(t){let r={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},s=["stx runtime resolution:"];for(let p of t.checks)if(s.push(` ${r[p.status]} ${p.name}: ${p.detail}`),p.fix)s.push(` \u2192 ${p.fix}`);return s.push(""),s.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),s.join(`
2033
- `)}export{Ai,Pi,Ii,Oi,Vs,Ni,Di,Mi,ol,il,Us,Ws,Ar,Pr,Ir};
2032
+ </html>`}var Bi="f9c3713";function al(t){return t}function cl(t){return t}function Oi(t,n){let o=[],d=`${n}=`;for(let s=0;s<t.length;s++){let c=t[s];if(c.startsWith(d)){let f=c.slice(d.length);if(f)o.push(f);continue}if(c===n){let f=t[s+1];if(f!==void 0&&!f.startsWith("-"))o.push(f),s++}}return o}import Me from"fs";import xe from"path";function Rn(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Rt(t,n){let o=Math.max(0,Math.round((n-t)/1000));if(o<60)return`${o}s ago`;if(o<3600)return`${Math.round(o/60)}m ago`;return`${Math.round(o/3600)}h ago`}function Ti(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function En(t,n="stx"){let o=xe.resolve(t);for(let d=0;d<10;d++){let s=xe.join(o,"pantry","@stacksjs",n);if(Me.existsSync(s))return s;let c=xe.dirname(o);if(c===o)break;o=c}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function $i(t){try{let n=Me.readFileSync(xe.join(t,"package.json"),"utf8"),o=JSON.parse(n)?.version;return typeof o==="string"?o:null}catch{return null}}function Ci(t,n=6){let o=xe.resolve(t),d=[],s=new Set;function c(u,h){if(h>n)return;let g;try{g=Me.realpathSync(u)}catch{return}if(s.has(g))return;s.add(g);for(let w of Pn){let S=xe.join(u,w),C=$i(S);if(C!==null)d.push({name:w,version:C,dir:xe.relative(o,S)||S,nested:h>0})}let b;try{b=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=xe.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=xe.join(S,x.name,"node_modules");if(Me.existsSync(T))c(T,h+1)}continue}let C=xe.join(S,"node_modules");if(Me.existsSync(C))c(C,h+1)}}let f=xe.join(o,"node_modules");if(Me.existsSync(f))c(f,0);return d}function Ri(t){let n=[];for(let o of Pn){let d=t.filter((f)=>f.name===o);if(d.length<=1)continue;let s=[...new Set(d.map((f)=>f.version))],c=d.map((f)=>`${f.version} at ${f.dir}`).join("; ");if(s.length===1){n.push({name:`${o} copies`,status:"info",detail:`${d.length} copies, all ${s[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${o} copies disagree`,status:"error",detail:`${s.length} versions installed, so which one runs depends on who imports it: ${c}`,fix:`remove the nested copies, or add an overrides entry pinning ${o}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${o}/package.json' -exec grep -H '"version"' {} +`})}return n}async function Gs(t={}){let n=t.cwd?xe.resolve(t.cwd):process.cwd(),o=t.resolve??Ti,d=Date.now(),s=[],c=o("@stacksjs/stx",n);s.push(c?{name:"@stacksjs/stx resolves to",status:"ok",detail:c}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let f=o("bun-plugin-stx",n);if(f)s.push({name:"bun-plugin-stx resolves to",status:"ok",detail:f});for(let h of Ri(Ci(n)))s.push(h);let u=En(n,"stx");if(!u)s.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=xe.join(u,"src/signals.ts"),g=[xe.join(u,"dist/index.js"),xe.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,b=Rn(h),w=g?Rn(g):null;if(b==null)s.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)s.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);s.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(w,d)}) is OLDER than src/signals.ts (${Rt(b,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else s.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(b,d)}, dist ${Rt(w,d)})`});let S=xe.join(n,"node_modules/@stacksjs/stx"),C=null;try{C=Me.lstatSync(S)}catch{C=null}if(!C)s.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();s.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else s.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(s.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;s.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){s.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:s,ok:!s.some((h)=>h.status==="error")}}function Ks(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let d of t.checks)if(o.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)o.push(` \u2192 ${d.fix}`);return o.push(""),o.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),o.join(`
2033
+ `)}export{Oi,Ni,Di,Mi,qs,Li,ji,Bi,al,cl,Gs,Ks,Or,Nr,Dr};