@stacksjs/stx 0.2.711 → 0.2.714

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 (225) hide show
  1. package/dist/chunk-00bf81ep.js +2 -0
  2. package/dist/chunk-04bhg3nn.js +2 -0
  3. package/dist/{chunk-vstvadc2.js → chunk-05qf3e2p.js} +3 -3
  4. package/dist/{chunk-nxmrbz95.js → chunk-0babpwqd.js} +22 -22
  5. package/dist/chunk-0g9a1kks.js +2 -0
  6. package/dist/{chunk-xt85pfwm.js → chunk-0k1nwbch.js} +9 -9
  7. package/dist/{chunk-twrkqpfm.js → chunk-142z94rk.js} +4 -4
  8. package/dist/chunk-19vshytp.js +2 -0
  9. package/dist/{chunk-qzbvxq1f.js → chunk-1kpfkjy7.js} +18 -18
  10. package/dist/{chunk-9n0rkv8n.js → chunk-1ncmrzk1.js} +2 -2
  11. package/dist/chunk-2fmn23mb.js +2 -0
  12. package/dist/{chunk-3ps07041.js → chunk-2mqzpzy7.js} +4 -4
  13. package/dist/{chunk-wbfg7p3k.js → chunk-2t00wxz0.js} +1 -1
  14. package/dist/chunk-336t7zzz.js +2 -0
  15. package/dist/{chunk-467r9gpt.js → chunk-35br675g.js} +4 -4
  16. package/dist/chunk-362sjw8c.js +2 -0
  17. package/dist/{chunk-dxqvv686.js → chunk-39nkd53v.js} +2 -2
  18. package/dist/{chunk-yw66yks2.js → chunk-3e40sm05.js} +4 -4
  19. package/dist/{chunk-zjw6j2x0.js → chunk-3fwdxxh1.js} +4 -4
  20. package/dist/chunk-3j8x8mhx.js +2 -0
  21. package/dist/chunk-3nbvr34s.js +2 -0
  22. package/dist/chunk-3r0zha0y.js +2 -0
  23. package/dist/{chunk-zav8yrtp.js → chunk-3xyvc3g1.js} +5 -5
  24. package/dist/{chunk-stvw8y3c.js → chunk-4c86wr9a.js} +2 -2
  25. package/dist/chunk-4ee5msma.js +2 -0
  26. package/dist/chunk-54a60nh2.js +2 -0
  27. package/dist/chunk-5d1c504j.js +2 -0
  28. package/dist/chunk-5wpgbwap.js +2 -0
  29. package/dist/{chunk-d06q5k8r.js → chunk-5zg56hwd.js} +5 -5
  30. package/dist/{chunk-qa9t9k6z.js → chunk-62awa752.js} +1 -1
  31. package/dist/{chunk-mr3r8crk.js → chunk-630yrhzv.js} +2 -2
  32. package/dist/{chunk-kxf8z7vp.js → chunk-6fx89gvg.js} +2 -2
  33. package/dist/chunk-6h1qa3hw.js +2 -0
  34. package/dist/chunk-6jn0p1a9.js +2 -0
  35. package/dist/chunk-6vj7vx7z.js +2 -0
  36. package/dist/{chunk-ckrmrdjp.js → chunk-72hfqwvk.js} +5 -5
  37. package/dist/{chunk-hh7wx4pv.js → chunk-7407ac26.js} +5 -5
  38. package/dist/{chunk-cwhzk2n3.js → chunk-74fepz6h.js} +2 -2
  39. package/dist/{chunk-ahjeegyv.js → chunk-77rjnavp.js} +13 -13
  40. package/dist/{chunk-42w6snem.js → chunk-78x8qfvt.js} +4 -4
  41. package/dist/chunk-79sjdpfy.js +2 -0
  42. package/dist/{chunk-8k139g1q.js → chunk-7nmrycrz.js} +4 -4
  43. package/dist/{chunk-jvbzeeqr.js → chunk-87zvjhp9.js} +10 -10
  44. package/dist/{chunk-zecgd1wz.js → chunk-88rftjjk.js} +4 -4
  45. package/dist/chunk-8dfq934n.js +2 -0
  46. package/dist/{chunk-t6ayy0t5.js → chunk-8fazd6fr.js} +2 -2
  47. package/dist/chunk-8w1ep4w3.js +2 -0
  48. package/dist/chunk-918xy0ra.js +2 -0
  49. package/dist/{chunk-tvcr9sct.js → chunk-9chqvq23.js} +3 -3
  50. package/dist/chunk-a0r5011d.js +2 -0
  51. package/dist/chunk-a49at1ah.js +2 -0
  52. package/dist/{chunk-q82n06dy.js → chunk-a9kxcdkz.js} +2 -2
  53. package/dist/chunk-agjysd2b.js +2 -0
  54. package/dist/chunk-ajcb0z8k.js +2 -0
  55. package/dist/chunk-ak04tgvw.js +2 -0
  56. package/dist/chunk-anew18ct.js +2 -0
  57. package/dist/chunk-azatpcm0.js +2 -0
  58. package/dist/chunk-c1481efw.js +2 -0
  59. package/dist/chunk-c510b95e.js +2 -0
  60. package/dist/chunk-c8yrvpr7.js +2 -0
  61. package/dist/chunk-cbbjepfk.js +2 -0
  62. package/dist/{chunk-kbc92p7a.js → chunk-cgpf1fva.js} +2 -2
  63. package/dist/{chunk-6cz1sbb1.js → chunk-d9hw6n2d.js} +3 -3
  64. package/dist/{chunk-zjaw79zp.js → chunk-dhy6n39n.js} +2 -2
  65. package/dist/{chunk-edka95zp.js → chunk-dmnncw90.js} +3 -3
  66. package/dist/chunk-dn8x6c98.js +2 -0
  67. package/dist/{chunk-b7j48bq9.js → chunk-dnqzrktd.js} +2 -2
  68. package/dist/chunk-dph9dzzs.js +2 -0
  69. package/dist/{chunk-hr3emvsh.js → chunk-dxzs589r.js} +3 -3
  70. package/dist/chunk-ez35607j.js +3 -0
  71. package/dist/{chunk-768evhvm.js → chunk-f2c3t1ky.js} +2 -2
  72. package/dist/{chunk-x2gxx8eg.js → chunk-f4gqzg1y.js} +2 -2
  73. package/dist/chunk-f9smbpkp.js +2 -0
  74. package/dist/chunk-fb8sw7fc.js +2 -0
  75. package/dist/{chunk-029qng4p.js → chunk-fsz9k5k0.js} +5 -5
  76. package/dist/chunk-g8fg3kq8.js +2 -0
  77. package/dist/{chunk-fnk16531.js → chunk-g8ve8pag.js} +6 -6
  78. package/dist/{chunk-0b77b7e0.js → chunk-gjfgmhpw.js} +1 -1
  79. package/dist/chunk-gw4pycg0.js +2 -0
  80. package/dist/{chunk-an387127.js → chunk-h16qbyjd.js} +2 -2
  81. package/dist/chunk-h5srt1gz.js +2 -0
  82. package/dist/{chunk-t63f15yh.js → chunk-hez09ssh.js} +2 -2
  83. package/dist/{chunk-2aarvd3a.js → chunk-hnqpqtk2.js} +6 -6
  84. package/dist/chunk-hrb9fmq0.js +2 -0
  85. package/dist/{chunk-q4t69m06.js → chunk-hx2s1j09.js} +8 -8
  86. package/dist/{chunk-zcs0nh8b.js → chunk-j0sj81bg.js} +6 -6
  87. package/dist/{chunk-fcbd7kwj.js → chunk-j28r2d0q.js} +2 -2
  88. package/dist/chunk-jb5najk3.js +1101 -0
  89. package/dist/chunk-jc7823qy.js +2 -0
  90. package/dist/chunk-jresy8fn.js +2 -0
  91. package/dist/{chunk-pdz9xm5s.js → chunk-jtgb1s62.js} +2 -2
  92. package/dist/{chunk-netw39rp.js → chunk-k3j8kd19.js} +5 -5
  93. package/dist/{chunk-34hsn8tn.js → chunk-k93mp66m.js} +144 -136
  94. package/dist/{chunk-791gt3mj.js → chunk-m1n9re2p.js} +6 -6
  95. package/dist/{chunk-8v2vbc4y.js → chunk-m5nzpjej.js} +1 -1
  96. package/dist/chunk-m6d2bq3y.js +2 -0
  97. package/dist/chunk-m8r7v1js.js +2 -0
  98. package/dist/{chunk-64hrtvvq.js → chunk-mpphyb4g.js} +1 -1
  99. package/dist/{chunk-s9b6abkb.js → chunk-mwxbdpb1.js} +2 -2
  100. package/dist/chunk-mymb85q5.js +3 -0
  101. package/dist/{chunk-83p5k4eb.js → chunk-narz7105.js} +2 -2
  102. package/dist/chunk-ngahc72q.js +2 -0
  103. package/dist/{chunk-khrckvwn.js → chunk-nqfpvejh.js} +1 -1
  104. package/dist/chunk-nvtp22qp.js +2 -0
  105. package/dist/{chunk-3y0bmmgq.js → chunk-ny5j5jhm.js} +3 -3
  106. package/dist/{chunk-4ckxs446.js → chunk-pd89jnqk.js} +3 -3
  107. package/dist/{chunk-9gdb9a7z.js → chunk-q73xkgn0.js} +76 -76
  108. package/dist/{chunk-3t3p2c1t.js → chunk-q7fh1xka.js} +6 -6
  109. package/dist/{chunk-5n4qg8za.js → chunk-qc93ce5h.js} +2 -2
  110. package/dist/{chunk-3457kk19.js → chunk-qf2aa8qe.js} +6 -6
  111. package/dist/{chunk-jb5sftzz.js → chunk-r3hden6p.js} +2 -2
  112. package/dist/{chunk-7dc3n69c.js → chunk-r3j4m04w.js} +2 -2
  113. package/dist/chunk-r5re2zj0.js +2 -0
  114. package/dist/{chunk-wp6q0geg.js → chunk-rbmt5w9v.js} +2 -2
  115. package/dist/chunk-rgv7rjrs.js +2 -0
  116. package/dist/{chunk-67abad76.js → chunk-rj4j7qcj.js} +1 -1
  117. package/dist/chunk-s9hw4vcx.js +2 -0
  118. package/dist/{chunk-g1tq4xdb.js → chunk-serrx31a.js} +2 -2
  119. package/dist/{chunk-tr33tzts.js → chunk-sfkexejc.js} +2 -2
  120. package/dist/{chunk-0eym6mhw.js → chunk-snxzvyz3.js} +1 -1
  121. package/dist/chunk-sx1aer4p.js +2 -0
  122. package/dist/{chunk-p3dkhz9v.js → chunk-tdrcn1mn.js} +30 -30
  123. package/dist/chunk-tdvmf3ge.js +2 -0
  124. package/dist/{chunk-2t85t7zc.js → chunk-tz4wh90e.js} +5 -5
  125. package/dist/chunk-tzhm09xq.js +2 -0
  126. package/dist/{chunk-vx14d8zm.js → chunk-tzk4cmvm.js} +5 -5
  127. package/dist/{chunk-9dg5ja4w.js → chunk-v402swbm.js} +1 -1
  128. package/dist/chunk-vf9s563f.js +2 -0
  129. package/dist/chunk-vpmk1w2t.js +2 -0
  130. package/dist/chunk-wj5j2ekg.js +2 -0
  131. package/dist/{chunk-b6318vv3.js → chunk-wk50m71x.js} +1 -1
  132. package/dist/{chunk-nvmdwrz4.js → chunk-wv412s1h.js} +7 -7
  133. package/dist/{chunk-rb2a1qxb.js → chunk-x5dc06p5.js} +6 -6
  134. package/dist/chunk-x7z2s532.js +2 -0
  135. package/dist/{chunk-ap30qs8p.js → chunk-x9wwd2ee.js} +2 -2
  136. package/dist/{chunk-ncs2j5kc.js → chunk-xaddgvkx.js} +2 -2
  137. package/dist/{chunk-6n11z33h.js → chunk-y3w2rc1y.js} +5 -5
  138. package/dist/chunk-ye3yyq6n.js +12 -0
  139. package/dist/{chunk-d9pxe492.js → chunk-yen9xzzg.js} +6 -6
  140. package/dist/chunk-yg1wcsbj.js +2 -0
  141. package/dist/{chunk-hf4hsdep.js → chunk-z4dpz6dh.js} +3 -3
  142. package/dist/{chunk-9qqzxd5y.js → chunk-z5pm69w1.js} +39 -39
  143. package/dist/{chunk-xyyt8v1r.js → chunk-zkx2m308.js} +12 -12
  144. package/dist/cli.js +19 -19
  145. package/dist/client/signals-public-api-runtime.js +1 -0
  146. package/dist/composables/use-broadcast-stream.d.ts +1 -1
  147. package/dist/craft-bridge.d.ts +0 -18
  148. package/dist/craft-bridge.js +12 -7
  149. package/dist/craft-components.d.ts +0 -20
  150. package/dist/craft-components.js +5 -13
  151. package/dist/craft-entry.js +2 -2
  152. package/dist/craft.js +2 -2
  153. package/dist/document-injection.d.ts +2 -0
  154. package/dist/document-injection.js +8 -0
  155. package/dist/native-build.js +2 -1
  156. package/dist/pwa.js +3 -3
  157. package/dist/runtime-globals.js +1 -0
  158. package/dist/signals.js +3 -0
  159. package/dist/ssg.js +15 -15
  160. package/dist/stx-module.d.ts +1 -0
  161. package/dist/unresolved-identifiers.js +0 -1
  162. package/package.json +5 -5
  163. package/stx-module.d.ts +1 -0
  164. package/stx.d.ts +1 -0
  165. package/dist/chunk-12vjp2gr.js +0 -2
  166. package/dist/chunk-18fr730w.js +0 -2
  167. package/dist/chunk-29sapda2.js +0 -2
  168. package/dist/chunk-2qf6kd9r.js +0 -2
  169. package/dist/chunk-2snfd93r.js +0 -2
  170. package/dist/chunk-2zd7v9xw.js +0 -2
  171. package/dist/chunk-48ye65g0.js +0 -2
  172. package/dist/chunk-4c1fbthr.js +0 -2
  173. package/dist/chunk-4fxg20je.js +0 -2
  174. package/dist/chunk-58v34kba.js +0 -2
  175. package/dist/chunk-5z8bc75p.js +0 -2
  176. package/dist/chunk-8s4rxgs8.js +0 -2
  177. package/dist/chunk-8ssryq8y.js +0 -2
  178. package/dist/chunk-9736003n.js +0 -2
  179. package/dist/chunk-97r557ws.js +0 -2
  180. package/dist/chunk-9kxykbg7.js +0 -2
  181. package/dist/chunk-bcr8sq50.js +0 -2
  182. package/dist/chunk-cn692w5v.js +0 -2
  183. package/dist/chunk-d6anxge7.js +0 -2
  184. package/dist/chunk-dhdt7e54.js +0 -2
  185. package/dist/chunk-e8n0x8dt.js +0 -2
  186. package/dist/chunk-ew7sdykm.js +0 -3033
  187. package/dist/chunk-fn4a8fja.js +0 -2
  188. package/dist/chunk-fvk1xr5a.js +0 -2
  189. package/dist/chunk-fxvxkb55.js +0 -2
  190. package/dist/chunk-g6wd49b5.js +0 -2
  191. package/dist/chunk-gk0nq2ky.js +0 -2
  192. package/dist/chunk-h8kbcz9t.js +0 -2
  193. package/dist/chunk-hj72xfv9.js +0 -2
  194. package/dist/chunk-hvytbft6.js +0 -2
  195. package/dist/chunk-hw70h16g.js +0 -2
  196. package/dist/chunk-j1f39jyb.js +0 -12
  197. package/dist/chunk-jjwfksv0.js +0 -2
  198. package/dist/chunk-kk8y8yba.js +0 -2
  199. package/dist/chunk-mfp4563h.js +0 -2
  200. package/dist/chunk-mzwa2478.js +0 -2
  201. package/dist/chunk-nq13s6sd.js +0 -2
  202. package/dist/chunk-pwaby9gk.js +0 -2
  203. package/dist/chunk-pxh3x1m6.js +0 -2
  204. package/dist/chunk-r6bc2q44.js +0 -2
  205. package/dist/chunk-rdj74dqc.js +0 -2
  206. package/dist/chunk-rn7s8h5j.js +0 -2
  207. package/dist/chunk-rtbkjq0y.js +0 -2
  208. package/dist/chunk-rwjgpmrw.js +0 -2
  209. package/dist/chunk-rwxtmr96.js +0 -2
  210. package/dist/chunk-sy1btryy.js +0 -2
  211. package/dist/chunk-t3m5bkqq.js +0 -2
  212. package/dist/chunk-t7mbaf69.js +0 -2
  213. package/dist/chunk-tjstkc0v.js +0 -2
  214. package/dist/chunk-vcssgx5z.js +0 -2
  215. package/dist/chunk-w2h6nn70.js +0 -2
  216. package/dist/chunk-w8b2jt4q.js +0 -2
  217. package/dist/chunk-wan4x3sg.js +0 -2
  218. package/dist/chunk-wjvhhy95.js +0 -2
  219. package/dist/chunk-wt18wv6x.js +0 -3
  220. package/dist/chunk-x5h95nnq.js +0 -2
  221. package/dist/chunk-ykmcnk3x.js +0 -2
  222. package/dist/chunk-z05dbey1.js +0 -2
  223. package/dist/chunk-z3anq3t4.js +0 -2
  224. package/dist/chunk-zgnfah3n.js +0 -2
  225. package/dist/chunk-zqhcdzby.js +0 -3
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{oe,de,pn,Pt,It,m,r,fe,p}from"./chunk-9gdb9a7z.js";import{mt,Re,Fa,Xr,vo,wo,i}from"./chunk-9qqzxd5y.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-3ps07041.js";import{cs,a,P}from"./chunk-nxmrbz95.js";import{dt,Tn,_e,M,qi,eo,Br,Ue,Ki,Ce}from"./chunk-nvmdwrz4.js";import{ir,ar}from"./chunk-q82n06dy.js";import{Cn}from"./chunk-9n0rkv8n.js";import{e,sn,tr,y}from"./chunk-fnk16531.js";import{Ge}from"./chunk-jvbzeeqr.js";import{$e}from"./chunk-1xjv71dw.js";import{K,ye,be}from"./chunk-d9pxe492.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(`
2
+ import{oe,de,pn,Pt,It,m,r,fe,p}from"./chunk-q73xkgn0.js";import{mt,Re,za,Jr,wo,xo,i}from"./chunk-z5pm69w1.js";import{ae,xr,Se,B,wn}from"./chunk-zkx2m308.js";import{wt,lr,hs,ys,bs,xt,St,kt,_t,Ct,Et,Ze}from"./chunk-2mqzpzy7.js";import{ls,a,P}from"./chunk-0babpwqd.js";import{dt,Tn,_e,M,Ki,to,Br,Ue,Gi,Ce}from"./chunk-wv412s1h.js";import{ir,ar}from"./chunk-a9kxcdkz.js";import{Cn}from"./chunk-1ncmrzk1.js";import{e,sn,tr,y}from"./chunk-g8ve8pag.js";import{Ge}from"./chunk-87zvjhp9.js";import{$e}from"./chunk-1xjv71dw.js";import{G,ye,be}from"./chunk-yen9xzzg.js";import{l}from"./chunk-qc93ce5h.js";import{K}from"./chunk-xaddgvkx.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
3
  `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
4
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(`
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 Di(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
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
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 {};
@@ -410,7 +410,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
410
410
  }
411
411
 
412
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(`
413
+ `}async function Mi(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
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
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(`
@@ -504,7 +504,7 @@ else {
504
504
  <span class="frontmatter-label">${n}:</span>
505
505
  <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
506
506
  </div>`).join("")}
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-rdj74dqc.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=`
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-cbbjepfk.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
508
  ${c}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
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(`
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
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-z3anq3t4.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 ls(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(B.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-fb8sw7fc.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 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>
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(B.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||K()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -939,7 +939,7 @@ ${T}`}if(v=await be(v),u.forEach((x)=>d.add(x)),o.cache&&o.cachePath){if(await a
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 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-nq13s6sd.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-wan4x3sg.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}
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-vpmk1w2t.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-79sjdpfy.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-g8fg3kq8.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
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(`
@@ -1419,24 +1419,24 @@ else {
1419
1419
  </body>
1420
1420
  </html>
1421
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(Ke.existsSync(T)&&Ke.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}
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}=hs(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(Ke.existsSync(T)&&Ke.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
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
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(Ke.existsSync(L)&&Ke.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
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)Ke.watch(c,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ke.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}`),Ge.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-nq13s6sd.js"),g=await h(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-wan4x3sg.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=K(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=K(te.dirname(E),{pagesDir:te.basename(E)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;O.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 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-nq13s6sd.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"),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 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((X)=>X.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:X,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-nq13s6sd.js"),{checkCache:N,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-w8b2jt4q.js"),G=await Oe(u),We=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(u,ie)},ce={...X,...G,...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-nq13s6sd.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-z3anq3t4.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-fn4a8fja.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((X)=>E.has(X.pattern)):k,Q=n.prebuild===!1?O.filter(({route:X})=>H.has(X.pattern)):O;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),we=await Promise.all(Oe.map((N)=>_(N)));for(let N of we)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+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 Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let E=n.hmrPort||Xe+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:Xe,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",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),we=te.join(ve,H.pathname);if([X,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(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(we).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);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 G=lr(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 _(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,se=B.headers??{},ue=(G.route.filePath?mt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.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,G.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&&Ki(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(G.params).length>0)U=Ot(U,G.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(G.params).length>0)U=Ot(U,G.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-fn4a8fja.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}
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(d)Ke.watch(c,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ke.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}`),Ge.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-vpmk1w2t.js"),g=await h(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-g8fg3kq8.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:j}of L)if(me.existsSync(E)){let z=G(te.dirname(E),{pagesDir:te.basename(E)});for(let Q of z){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;O.push({route:{...Q,pattern:q},prefix:j})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,R=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await Ki(u,n.stxOptions?.shell),D){if(R=await to(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-vpmk1w2t.js"),j=await E(u);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.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(j?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-79sjdpfy.js"),q=j.broadcasting;await z(q);let Oe=q.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 j=ys(T,E);if(!j)return null;try{let z=await Bun.build({entrypoints:[j],outdir:ve,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!z.success)return null;let Q=z.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(E,j)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:q,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-vpmk1w2t.js"),{checkCache:N,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-yg1wcsbj.js"),X=await Oe(u),We=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(u,ie)},ce={...q,...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 H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){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-vpmk1w2t.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:j??{},__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-fb8sw7fc.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&&H)await J(E.filePath,he,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-h5srt1gz.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(H)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()),j=new Set(A.keys());le.clear(),A.clear();let z=n.prebuild===!1?k.filter((q)=>E.has(q.pattern)):k,Q=n.prebuild===!1?O.filter(({route:q})=>j.has(q.pattern)):O;for(let q=0;q<z.length;q+=Fe){let Oe=z.slice(q,q+Fe),we=await Promise.all(Oe.map((N)=>_(N)));for(let N of we)if(N)le.set(N.route.pattern,N)}for(let q=0;q<Q.length;q+=Fe){let Oe=Q.slice(q,q+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 Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let E=n.hmrPort||Xe+1;c=Tt({wsPort:E,verbose:!1}),f=c.start(E)}let Ot=(E,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).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:Xe,hostname:n.hostname,async fetch(E){let j=new URL(E.url),z=n.stxOptions?.offline??g.offline;if(j.pathname===wo&&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:xo(z,Jr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=g?.publicDir||"public",q=te.join(u,Q,j.pathname),Oe=te.join(u,j.pathname),we=te.join(ve,j.pathname);if([q,Oe,we].some((H)=>w(H,u,S)))return new Response("Not Found",{status:404});let[N,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(we).catch(()=>null)]);if(N?.isFile()&&!w(q,u,S))return zt(q);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(W?.isFile()&&!w(we,u,S))return zt(we);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(u,"components",`${H}.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(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-ak04tgvw.js"),re=await H(E,{publicDir:te.join(u,Q),cacheDir:l(u,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(E);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](E)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await C(E);if(pe)return pe;let X=lr(j.pathname,k);if(X){let H=le.get(X.route.pattern),re=Pe.has(X.route.pattern);if(!H||X.route.isDynamic&&Object.keys(X.params).length>0||re){let Z=await _(X.route,X.params);if(Z){if(H=Z,!X.route.isDynamic&&!re)le.set(X.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.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(j.pathname,X.params,ue,j.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>`;H.content=H.content.replace("</head>",`${Ae}</head>`)}}let U=H.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)},[za]:Jr(),...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(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-h5srt1gz.js");return De(Le(U,H.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 H=O.map((Z)=>Z.route),re=lr(j.pathname,H);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!=="/"&&j.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(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=le.get("/");if(We){let H=We.content;if(H=await y(H,u),s)H=Ne(H,f);if(n.native)if(H.includes("<head>"))H=H.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 H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{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 H=ce;if(H=await y(H,u),s)H=Ne(H,f);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
1430
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
1432
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${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(Xe,{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((G)=>pe===G||pe.startsWith(`${G}${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((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,W)=>(X=X.catch(()=>{}).then(()=>we(N,J,W)),X),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,...K(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}`),Ge.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-w8b2jt4q.js");pe(te.resolve(N,W)),G.delete(te.resolve(N,W))}catch{}if(D&&W){if(te.resolve(N,W)===D||te.basename(D)===W){let G=await eo(D,n.stxOptions||{});if(G)R=G}}if(await ze(),await tr(u),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ge.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-w8b2jt4q.js");pe(te.resolve(N,W)),G.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(`
1433
+ ${e.yellow}Routes:${e.reset}`);let Dt=[...bs(k,u)];for(let{route:E}of O)Dt.push(`${E.pattern}`);if(Dt.forEach((E,j)=>{let Q=j===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,j=te.join(T,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();E=ht(Q)}let z=g?.app?.window??{};await Qe(Xe,{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\\"),j=(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))}))},q=Promise.resolve(),Oe=(N,J,W)=>(q=q.catch(()=>{}).then(()=>we(N,J,W)),q),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(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ge.clear(),fe();try{let{invalidateFileCache:pe,templateCache:X}=await import("./chunk-yg1wcsbj.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 to(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}`),Ge.clear(),fe();try{let{invalidateFileCache:pe,templateCache:X}=await import("./chunk-yg1wcsbj.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
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
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
1437
  `);f=`<${d}
1438
1438
  ${u}
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(`
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 Xr(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 Gr(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
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)
@@ -1570,15 +1570,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(At.
1570
1570
  <td>@${c.name}</td>
1571
1571
  <td>${c.description||"-"}</td>
1572
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`
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 eo(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 Xr(n,d),console.log(`Found ${u.length} components`);let h=[];if(c.templates!==!1&&o)console.log("Generating template documentation..."),h=await Gr(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=eo(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 Li(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 Ks(t,n={}){let o={...fn,...n};if(t.trim()==="")return`
1574
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
1576
  `),!d.endsWith(`
1577
1577
  `))d+=`
1578
- `;return d}function Li(t,n={}){let o={...fn,...n};if(t.trim()==="")return`
1578
+ `;return d}function ji(t,n={}){let o={...fn,...n};if(t.trim()==="")return`
1579
1579
  `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(s,c,f,u,h)=>{let g=u.split(`
1580
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(`
1581
+ `),v=Ks(S,o).trimEnd().split(`
1582
1582
  `).map((x)=>{if(x.trim().length===0)return"";return c+x}).join(`
1583
1583
  `);return`${c}\`\`\`${f}
1584
1584
  ${v}
@@ -1603,7 +1603,7 @@ ${f}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(s,c,f,u)=>{let h=u.substring(Math.max
1603
1603
  `),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function so(t,n){let d=oo(t).split(`
1604
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
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>
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 Bi(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 = [
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
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 Ks(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 Gs(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,Ks,Gs,Or,Nr,Dr};
2032
+ </html>`}var Fi="f9c3713";function cl(t){return t}function ll(t){return t}function Ni(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 Xs(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{Ni,Di,Mi,Li,Ks,ji,Bi,Fi,cl,ll,Gs,Xs,Or,Nr,Dr};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{V}from"./chunk-9gdb9a7z.js";import{Fe,O,Dt}from"./chunk-wp6q0geg.js";import{dt,_e,M,Ce,Ji,to,Yi,Rn}from"./chunk-nvmdwrz4.js";import{wt,ue,Ze}from"./chunk-3ps07041.js";import{yo}from"./chunk-hh7wx4pv.js";import{An}from"./chunk-b7j48bq9.js";import{ye}from"./chunk-d9pxe492.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import F from"zlib";import{promisify as Q}from"util";var K=Q(F.brotliCompress),ee=Q(F.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((o)=>e.startsWith(o)))return!1;return te.some((o)=>e.startsWith(o))}function oe(t){let e=new Map;for(let o of t.split(",")){let[r,...a]=o.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of a){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),o=e.get("*"),r=(a)=>e.get(a)??o??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,H=new Map,U=0;function ie(t,e){if(e.length>Y/8)return;H.set(t,e),U+=e.length;for(let[o,r]of H){if(U<=Y)break;H.delete(o),U-=r.length}}async function Cn(t,e,o={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let a;try{a=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(a,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(a.length<(o.threshold??re))return f();try{let h=o.quality??5,g=`${r}:${h}:${a.length}:${Bun.hash(a)}`,l=H.get(g);if(!l)l=r==="br"?await K(a,{params:{[F.constants.BROTLI_PARAM_QUALITY]:h,[F.constants.BROTLI_PARAM_SIZE_HINT]:a.length}}):await ee(a),ie(g,l);if(l.length>=a.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),o=e.get("Vary");if(!o)return e.set("Vary","Accept-Encoding"),e;if(!o.split(",").some((a)=>a.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${o}, Accept-Encoding`);return e}class G{now;entries=new V(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,o){let r,a=async()=>{let s=r??await o();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",M(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return a();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${_e(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,_=async()=>{let s=await o();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let E=await s.clone().arrayBuffer();if(E.byteLength>1048576)return null;s.headers.set("Vary",M(s.headers.get("Vary")).Vary);let n={body:E,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return a();x=_().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let A=await x;return A?l(A):a()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function vg(t={}){let e=T.resolve(t.outputDir||".output"),o=t.port??3000,r=Ji(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let a=An(r.routeRules),f=new G,h=yo(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?O(l):void 0,v=new Map,_=new Map,x=new Map,A=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),i=JSON.parse(await Bun.file(y).text());if(m)i.html=Dt(i.html,m);v.set(n.pattern,i),x.set(n.pattern,Ze(i.html)),A.set(n.pattern,ye(i.html));let j=T.join(e,n.fragmentPath);if(await Bun.file(j).exists()){let P=await Bun.file(j).text();_.set(n.pattern,m?Dt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:i}=ue(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:i})}else s.set(n.pattern,n);let E=ce({port:o,async fetch(n){return Cn(n,await Fe(m??O(),async()=>{let i=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[i])return t.apiRoutes[i](n);let j=await h(n);if(j)return j;if((n.method==="GET"||n.method==="HEAD")&&i!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(i)}catch{d=i}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),B=pe[R]||"application/octet-stream",X=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":B,"Cache-Control":X?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=_e(n),C=null,q={};if(C=s.get(i)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let c=i.match(p);if(c){C=d,u.forEach((R,B)=>{q[R]=c[B+1]});break}}if(!C){let p=wt(i)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let N=a(i),W=Object.keys(N).length>0;return f.respond(n,N.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let c=_.get(C.pattern);if(c){let R=x.get(C.pattern);return new Response(c,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...A.has(C.pattern)?{"X-STX-Runtime":A.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...M(),...N.cache?{}:{"Cache-Control":dt}}})}}let d=to(n.method),u=v.get(C.pattern);if(!u){let c=s.get("/500")||null;if(c){let R=v.get(c.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...M(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:B,cookies:X,status:I,headers:D}=await Rn(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(B)return Yi(B,X,D);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:z}=await import("./chunk-fn4a8fja.js"),L=new Headers({...M(),...D,"Cache-Control":"private, no-store"});for(let k of X??[])L.append("Set-Cookie",k);if(P&&!d){let k=Ze(c);L.set("X-STX-Fragment","true"),L.set("X-STX-Runtime",ye(c)?"true":"false"),L.set("X-STX-Layout",k.layout),L.set("X-STX-Layout-Group",k.group)}return z(S(P&&!d?Ce(c,r.routerContainer||"main",!0):c,R,{timeoutMs:30000}),{status:I??u.status??200,headers:L})}let w=new Headers({"Content-Type":"text/html",...M(),...N.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of X??[])w.append("Set-Cookie",S);for(let[S,z]of Object.entries(D??{}))w.set(S,z);if(w.set("Vary",M(w.get("Vary")).Vary),P&&!d){let S=Ze(c);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",ye(c)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(Ce(c,r.routerContainer||"main",!0),{status:I??u.status??200,headers:w})}return new Response(c,{status:I??u.status??200,headers:w})}catch(c){if(console.error(`[stx] Hydration error for ${i}:`,c),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${E.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:E.port,stop:()=>{f.invalidate(),E.stop()},invalidate:(n)=>f.invalidate(n)}}
3
- export{Cn,vg};
2
+ import{U}from"./chunk-q73xkgn0.js";import{Fe,O,Dt}from"./chunk-rbmt5w9v.js";import{dt,_e,M,Ce,Yi,no,Zi,Rn}from"./chunk-wv412s1h.js";import{wt,ue,Ze}from"./chunk-2mqzpzy7.js";import{bo}from"./chunk-7407ac26.js";import{An}from"./chunk-dnqzrktd.js";import{ye}from"./chunk-yen9xzzg.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import H from"zlib";import{promisify as Q}from"util";var K=Q(H.brotliCompress),ee=Q(H.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((o)=>e.startsWith(o)))return!1;return te.some((o)=>e.startsWith(o))}function oe(t){let e=new Map;for(let o of t.split(",")){let[r,...a]=o.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of a){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),o=e.get("*"),r=(a)=>e.get(a)??o??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,V=new Map,z=0;function ie(t,e){if(e.length>Y/8)return;V.set(t,e),z+=e.length;for(let[o,r]of V){if(z<=Y)break;V.delete(o),z-=r.length}}async function Cn(t,e,o={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let a;try{a=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(a,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(a.length<(o.threshold??re))return f();try{let h=o.quality??5,g=`${r}:${h}:${a.length}:${Bun.hash(a)}`,l=V.get(g);if(!l)l=r==="br"?await K(a,{params:{[H.constants.BROTLI_PARAM_QUALITY]:h,[H.constants.BROTLI_PARAM_SIZE_HINT]:a.length}}):await ee(a),ie(g,l);if(l.length>=a.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),o=e.get("Vary");if(!o)return e.set("Vary","Accept-Encoding"),e;if(!o.split(",").some((a)=>a.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${o}, Accept-Encoding`);return e}class G{now;entries=new U(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,o){let r,a=async()=>{let s=r??await o();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",M(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return a();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${_e(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,_=async()=>{let s=await o();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let E=await s.clone().arrayBuffer();if(E.byteLength>1048576)return null;s.headers.set("Vary",M(s.headers.get("Vary")).Vary);let n={body:E,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return a();x=_().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let A=await x;return A?l(A):a()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function xg(t={}){let e=T.resolve(t.outputDir||".output"),o=t.port??3000,r=Yi(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let a=An(r.routeRules),f=new G,h=bo(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?O(l):void 0,v=new Map,_=new Map,x=new Map,A=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),i=JSON.parse(await Bun.file(y).text());if(m)i.html=Dt(i.html,m);v.set(n.pattern,i),x.set(n.pattern,Ze(i.html)),A.set(n.pattern,ye(i.html));let j=T.join(e,n.fragmentPath);if(await Bun.file(j).exists()){let P=await Bun.file(j).text();_.set(n.pattern,m?Dt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:i}=ue(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:i})}else s.set(n.pattern,n);let E=ce({port:o,async fetch(n){return Cn(n,await Fe(m??O(),async()=>{let i=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[i])return t.apiRoutes[i](n);let j=await h(n);if(j)return j;if((n.method==="GET"||n.method==="HEAD")&&i!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(i)}catch{d=i}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),B=pe[R]||"application/octet-stream",X=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":B,"Cache-Control":X?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=_e(n),C=null,q={};if(C=s.get(i)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let c=i.match(p);if(c){C=d,u.forEach((R,B)=>{q[R]=c[B+1]});break}}if(!C){let p=wt(i)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let N=a(i),W=Object.keys(N).length>0;return f.respond(n,N.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let c=_.get(C.pattern);if(c){let R=x.get(C.pattern);return new Response(c,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...A.has(C.pattern)?{"X-STX-Runtime":A.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...M(),...N.cache?{}:{"Cache-Control":dt}}})}}let d=no(n.method),u=v.get(C.pattern);if(!u){let c=s.get("/500")||null;if(c){let R=v.get(c.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...M(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:B,cookies:X,status:F,headers:I}=await Rn(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(B)return Zi(B,X,I);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:D}=await import("./chunk-h5srt1gz.js"),L=new Headers({...M(),...I,"Cache-Control":"private, no-store"});for(let k of X??[])L.append("Set-Cookie",k);if(P&&!d){let k=Ze(c);L.set("X-STX-Fragment","true"),L.set("X-STX-Runtime",ye(c)?"true":"false"),L.set("X-STX-Layout",k.layout),L.set("X-STX-Layout-Group",k.group)}return D(S(P&&!d?Ce(c,r.routerContainer||"main",!0):c,R,{timeoutMs:30000}),{status:F??u.status??200,headers:L})}let w=new Headers({"Content-Type":"text/html",...M(),...N.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of X??[])w.append("Set-Cookie",S);for(let[S,D]of Object.entries(I??{}))w.set(S,D);if(w.set("Vary",M(w.get("Vary")).Vary),P&&!d){let S=Ze(c);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",ye(c)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(Ce(c,r.routerContainer||"main",!0),{status:F??u.status??200,headers:w})}return new Response(c,{status:F??u.status??200,headers:w})}catch(c){if(console.error(`[stx] Hydration error for ${i}:`,c),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${E.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:E.port,stop:()=>{f.invalidate(),E.stop()},invalidate:(n)=>f.invalidate(n)}}
3
+ export{Cn,xg};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{bl,qi,Cg,vl,wl,Eg,Tg}from"./chunk-77rjnavp.js";import"./chunk-hx2s1j09.js";import"./chunk-k3j8kd19.js";import"./chunk-7407ac26.js";import"./chunk-1xjv71dw.js";import"./chunk-0k1nwbch.js";import"./chunk-yen9xzzg.js";import"./chunk-m5nzpjej.js";import"./chunk-0babpwqd.js";import"./chunk-dxzs589r.js";import"./chunk-4c86wr9a.js";import"./chunk-3fwdxxh1.js";import"./chunk-q7fh1xka.js";import"./chunk-2mqzpzy7.js";import{At,Of}from"./chunk-q73xkgn0.js";import"./chunk-jtgb1s62.js";import"./chunk-rbmt5w9v.js";import"./chunk-zkx2m308.js";import"./chunk-zn3c0ew5.js";import"./chunk-ez35607j.js";export{bl as buildVirtualSource,At as extractScriptBlocks,Of as extractTemplateExpressions,vl as findRuntimeTypeDeclarations,wl as findStxModuleDeclarations,Tg as formatTypecheckDiagnostics,Cg as sourcePathFor,Eg as typecheckStxFiles,qi as virtualPathFor};