@stacksjs/stx 0.2.818 → 0.2.820

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 (211) hide show
  1. package/dist/{chunk-4h78zypb.js → chunk-01cwrww2.js} +1 -1
  2. package/dist/{chunk-nsxjt6h3.js → chunk-06hc6rs6.js} +1 -1
  3. package/dist/{chunk-skht06a2.js → chunk-076fj387.js} +1 -1
  4. package/dist/chunk-09285y4b.js +2 -0
  5. package/dist/chunk-0e0z4ab6.js +2 -0
  6. package/dist/{chunk-8gcg9maj.js → chunk-0p797a25.js} +15 -15
  7. package/dist/{chunk-g7mjv276.js → chunk-1f7d1c0y.js} +2 -2
  8. package/dist/{chunk-n4s0se11.js → chunk-2235krey.js} +13 -13
  9. package/dist/{chunk-fmawgk87.js → chunk-2nj9aewf.js} +1 -1
  10. package/dist/{chunk-m7hfcxt3.js → chunk-2vqpz4qv.js} +2 -2
  11. package/dist/{chunk-dq9djbgq.js → chunk-30rpspzt.js} +4 -4
  12. package/dist/{chunk-8wdy7kdq.js → chunk-36sb6j2v.js} +6 -6
  13. package/dist/{chunk-1hg0zb3p.js → chunk-3axb6t08.js} +2 -2
  14. package/dist/chunk-3bf48zrh.js +2 -0
  15. package/dist/chunk-3kaw5zjm.js +2 -0
  16. package/dist/chunk-3na8kkec.js +2 -0
  17. package/dist/{chunk-mr2ke5km.js → chunk-3yh6y00f.js} +6 -6
  18. package/dist/{chunk-k01aftw0.js → chunk-3zhwcckc.js} +5 -5
  19. package/dist/chunk-49hywhze.js +2 -0
  20. package/dist/{chunk-1a8qtvs1.js → chunk-4mj9dem1.js} +2 -2
  21. package/dist/chunk-4qsamkyc.js +2 -0
  22. package/dist/{chunk-9xd85mvm.js → chunk-4t4af1mb.js} +5 -5
  23. package/dist/{chunk-x34me5ar.js → chunk-5e88021j.js} +6 -6
  24. package/dist/{chunk-vmxzktdr.js → chunk-67kbsav0.js} +1 -1
  25. package/dist/chunk-6h1qa3hw.js +2 -0
  26. package/dist/{chunk-xc7nynb9.js → chunk-6qvn1h09.js} +3 -3
  27. package/dist/{chunk-k3t72x38.js → chunk-76eh43e9.js} +2 -2
  28. package/dist/chunk-77s1kvzj.js +2 -0
  29. package/dist/chunk-7ffmz1fb.js +2 -0
  30. package/dist/chunk-7pz76f28.js +2 -0
  31. package/dist/{chunk-6s9bk98p.js → chunk-7yb82rm6.js} +2 -2
  32. package/dist/{chunk-72jt897s.js → chunk-8ttmzcxb.js} +12 -12
  33. package/dist/{chunk-035m9ada.js → chunk-8w9spdbn.js} +4 -4
  34. package/dist/{chunk-zme16hcr.js → chunk-90p175a7.js} +3 -3
  35. package/dist/chunk-91s9c9wa.js +2 -0
  36. package/dist/{chunk-e3t2bqyf.js → chunk-9gmceny5.js} +5 -5
  37. package/dist/chunk-a8fy7jv8.js +2 -0
  38. package/dist/{chunk-4fbg7gq8.js → chunk-akj26p4b.js} +2 -2
  39. package/dist/{chunk-8hfgvs0x.js → chunk-aqh663ef.js} +2 -2
  40. package/dist/{chunk-mm8ak4w2.js → chunk-atszywea.js} +4 -4
  41. package/dist/chunk-b22yj5j5.js +2 -0
  42. package/dist/{chunk-b9d70mgr.js → chunk-b4x5ndt9.js} +3 -3
  43. package/dist/{chunk-qr14xvwb.js → chunk-b89wsq8r.js} +1 -1
  44. package/dist/{chunk-zhvmcj78.js → chunk-bfbh0hfn.js} +5 -5
  45. package/dist/{chunk-9gj702tw.js → chunk-bfztkcfe.js} +4 -4
  46. package/dist/{chunk-casvvt3k.js → chunk-bkdfkm10.js} +3 -3
  47. package/dist/{chunk-0rjcbqk3.js → chunk-brhas9mp.js} +2 -2
  48. package/dist/{chunk-p13wg97w.js → chunk-bsg90smr.js} +4 -4
  49. package/dist/{chunk-1tzqqr0p.js → chunk-bt0amey5.js} +2 -2
  50. package/dist/{chunk-1rvgv1fr.js → chunk-btxnrqxf.js} +5 -5
  51. package/dist/chunk-c1e45rtv.js +2 -0
  52. package/dist/chunk-cckq47hd.js +2 -0
  53. package/dist/{chunk-tj6zvs8f.js → chunk-cxz4cdcn.js} +2 -2
  54. package/dist/{chunk-mbhvf0sv.js → chunk-d6d2s7n6.js} +2 -2
  55. package/dist/chunk-det3z847.js +2 -0
  56. package/dist/{chunk-gcje06er.js → chunk-e4jwhmpb.js} +30 -30
  57. package/dist/chunk-ec2f30f7.js +3 -0
  58. package/dist/{chunk-a67c2xrp.js → chunk-exghjgzk.js} +4 -4
  59. package/dist/{chunk-mjg9cx5a.js → chunk-f0txsdpa.js} +3 -3
  60. package/dist/{chunk-y3zjmv9e.js → chunk-ftfjwjes.js} +3 -3
  61. package/dist/chunk-g8kcg8v2.js +2 -0
  62. package/dist/chunk-g8nqmnb7.js +2 -0
  63. package/dist/{chunk-hwcfgs3e.js → chunk-gjf8cjdt.js} +3 -3
  64. package/dist/{chunk-swbrvrgr.js → chunk-gywyr2x3.js} +2 -2
  65. package/dist/{chunk-2jn0x4sh.js → chunk-h1hm975m.js} +6 -6
  66. package/dist/chunk-h67pm636.js +2 -0
  67. package/dist/{chunk-a1cy78h3.js → chunk-h7fgk4ew.js} +2 -2
  68. package/dist/chunk-hb8jxg45.js +2 -0
  69. package/dist/{chunk-s6mte5vy.js → chunk-hbdzhpy1.js} +4 -4
  70. package/dist/chunk-he6tejhc.js +2 -0
  71. package/dist/chunk-hfgzqapw.js +2 -0
  72. package/dist/chunk-j0hrk24j.js +2 -0
  73. package/dist/chunk-j2fgv2pe.js +2 -0
  74. package/dist/{chunk-ymypc1rp.js → chunk-j4cjn4m1.js} +79 -79
  75. package/dist/{chunk-k3zcadcc.js → chunk-j737tnvt.js} +4 -4
  76. package/dist/chunk-j79bjm48.js +2 -0
  77. package/dist/chunk-jjbdtj4w.js +2 -0
  78. package/dist/{chunk-nqdh7z2d.js → chunk-jzgyrxye.js} +1 -1
  79. package/dist/{chunk-sf4rntqj.js → chunk-k0bztfk3.js} +2 -2
  80. package/dist/chunk-k0xdvegc.js +2 -0
  81. package/dist/{chunk-9gwhs0gk.js → chunk-k81trehg.js} +2 -2
  82. package/dist/chunk-m3wk6b1r.js +2 -0
  83. package/dist/chunk-m7nsk6fb.js +2 -0
  84. package/dist/chunk-m934bzg2.js +2 -0
  85. package/dist/{chunk-znx5m1jv.js → chunk-me6kgvsm.js} +1 -1
  86. package/dist/chunk-mmeck545.js +2 -0
  87. package/dist/{chunk-s9b6abkb.js → chunk-mwxbdpb1.js} +2 -2
  88. package/dist/chunk-mz6qjee1.js +2 -0
  89. package/dist/chunk-mzvccryg.js +2 -0
  90. package/dist/chunk-n4pzq9k7.js +2 -0
  91. package/dist/{chunk-baj6w8ja.js → chunk-n7arptzc.js} +2 -2
  92. package/dist/{chunk-j24psz0z.js → chunk-nb5d00dz.js} +10 -10
  93. package/dist/{chunk-hntm02x0.js → chunk-nype1b17.js} +3 -3
  94. package/dist/{chunk-1ae3megp.js → chunk-p1fpferp.js} +6 -6
  95. package/dist/chunk-p6e3zz9e.js +2 -0
  96. package/dist/{chunk-7ac98ja7.js → chunk-p77cnteg.js} +5 -5
  97. package/dist/chunk-prt4ntb0.js +2 -0
  98. package/dist/{chunk-sxad7x2s.js → chunk-pvj0bpqg.js} +4 -4
  99. package/dist/chunk-q5bct2ks.js +2 -0
  100. package/dist/{chunk-rpen41w3.js → chunk-q7zwv88b.js} +2 -2
  101. package/dist/{chunk-e9w8qav3.js → chunk-qe5h58mx.js} +2 -2
  102. package/dist/{chunk-gtd6qs1r.js → chunk-qj4r08jb.js} +2 -2
  103. package/dist/{chunk-sh1hbhhb.js → chunk-qz3fdmrc.js} +3 -3
  104. package/dist/chunk-r2hjn9ds.js +2 -0
  105. package/dist/{chunk-2bnbcr22.js → chunk-rm1510e0.js} +12 -12
  106. package/dist/chunk-rtk813jv.js +2 -0
  107. package/dist/chunk-s2zsa16d.js +2 -0
  108. package/dist/chunk-s53hy1gs.js +2 -0
  109. package/dist/{chunk-dpn314z2.js → chunk-sb6jph84.js} +1 -1
  110. package/dist/chunk-sddp2398.js +2 -0
  111. package/dist/chunk-sj24g10j.js +2 -0
  112. package/dist/chunk-sv4emtcj.js +2 -0
  113. package/dist/chunk-t6y9ar2j.js +2 -0
  114. package/dist/chunk-t9byym6f.js +2 -0
  115. package/dist/chunk-t9rj27hc.js +2 -0
  116. package/dist/chunk-tcyvwy8p.js +2 -0
  117. package/dist/chunk-tg18j1yf.js +2 -0
  118. package/dist/chunk-tj7dh2dz.js +2 -0
  119. package/dist/{chunk-j8r0am39.js → chunk-tksjakyv.js} +1 -1
  120. package/dist/chunk-vafxrky2.js +2 -0
  121. package/dist/chunk-vyb4sxh9.js +42 -0
  122. package/dist/{chunk-6n11z33h.js → chunk-vzbyn4nh.js} +5 -5
  123. package/dist/chunk-w04h1t4t.js +2 -0
  124. package/dist/{chunk-cf196sv5.js → chunk-wc7dn3mr.js} +2 -2
  125. package/dist/{chunk-f6nk205v.js → chunk-wceg59n0.js} +1 -1
  126. package/dist/{chunk-t2sg2tp2.js → chunk-wf0n9gpj.js} +4 -4
  127. package/dist/{chunk-c5vzr1va.js → chunk-wpendr22.js} +2 -2
  128. package/dist/chunk-wps6y6n5.js +2 -0
  129. package/dist/{chunk-427mhgje.js → chunk-wy0gghvh.js} +1 -1
  130. package/dist/chunk-x30gh7vt.js +2 -0
  131. package/dist/{chunk-zgq8bfaw.js → chunk-xc0kwms2.js} +4 -4
  132. package/dist/{chunk-j65nf7mt.js → chunk-xdbwghty.js} +9 -9
  133. package/dist/{chunk-em2yy1te.js → chunk-xpy9yjyx.js} +6 -6
  134. package/dist/{chunk-9egd7tx3.js → chunk-y8p85kcj.js} +2 -2
  135. package/dist/{chunk-7xs45trj.js → chunk-y9bj3566.js} +2 -2
  136. package/dist/chunk-ybpysahk.js +2 -0
  137. package/dist/{chunk-9487tyfa.js → chunk-ydr5y7va.js} +2 -2
  138. package/dist/chunk-ytyyfvke.js +2 -0
  139. package/dist/{chunk-8dmey36n.js → chunk-z23arg8m.js} +2 -2
  140. package/dist/chunk-z845f18k.js +2 -0
  141. package/dist/{chunk-9tzcvsv0.js → chunk-zbyfxcrr.js} +6 -6
  142. package/dist/{chunk-vtt2dec3.js → chunk-zefkd9t8.js} +4 -4
  143. package/dist/cli.js +19 -19
  144. package/dist/craft-entry.js +2 -2
  145. package/dist/craft.js +2 -2
  146. package/dist/html-masking.d.ts +10 -0
  147. package/dist/html-masking.js +50 -0
  148. package/dist/pwa.js +3 -3
  149. package/dist/server-bindings.js +28 -30
  150. package/dist/ssg.js +4 -4
  151. package/package.json +5 -5
  152. package/dist/chunk-03mtfndv.js +0 -2
  153. package/dist/chunk-18qxd18d.js +0 -2
  154. package/dist/chunk-1cd0w20k.js +0 -2
  155. package/dist/chunk-2kt1gqtq.js +0 -2
  156. package/dist/chunk-2vaap97d.js +0 -2
  157. package/dist/chunk-33ewq978.js +0 -2
  158. package/dist/chunk-3m342maz.js +0 -2
  159. package/dist/chunk-46sej67y.js +0 -2
  160. package/dist/chunk-5zf566bv.js +0 -2
  161. package/dist/chunk-67k5q95t.js +0 -2
  162. package/dist/chunk-6e76tz09.js +0 -2
  163. package/dist/chunk-72w08sh9.js +0 -2
  164. package/dist/chunk-7q79h0j4.js +0 -2
  165. package/dist/chunk-88mhhbqj.js +0 -2
  166. package/dist/chunk-9736003n.js +0 -2
  167. package/dist/chunk-99zwpazg.js +0 -2
  168. package/dist/chunk-9e5gamvs.js +0 -2
  169. package/dist/chunk-9y1dm510.js +0 -2
  170. package/dist/chunk-abzrvxct.js +0 -2
  171. package/dist/chunk-avbvedyx.js +0 -2
  172. package/dist/chunk-bbxzkcsk.js +0 -2
  173. package/dist/chunk-c179xpsq.js +0 -2
  174. package/dist/chunk-cvq4bz8y.js +0 -2
  175. package/dist/chunk-d4pmddb9.js +0 -2
  176. package/dist/chunk-dh1f8ga0.js +0 -2
  177. package/dist/chunk-em7kntfc.js +0 -2
  178. package/dist/chunk-enm79dwe.js +0 -2
  179. package/dist/chunk-fvs15n0s.js +0 -2
  180. package/dist/chunk-gvthmy3a.js +0 -2
  181. package/dist/chunk-h8kbcz9t.js +0 -2
  182. package/dist/chunk-h8x56dq5.js +0 -2
  183. package/dist/chunk-hx575xy8.js +0 -2
  184. package/dist/chunk-j58z3y2g.js +0 -2
  185. package/dist/chunk-j5t40n2g.js +0 -2
  186. package/dist/chunk-kgwdxx75.js +0 -2
  187. package/dist/chunk-m5cdkb11.js +0 -2
  188. package/dist/chunk-n1tbc7da.js +0 -2
  189. package/dist/chunk-n7dm6prj.js +0 -2
  190. package/dist/chunk-nknpr8cy.js +0 -2
  191. package/dist/chunk-pe9npaby.js +0 -2
  192. package/dist/chunk-pyz2jqph.js +0 -2
  193. package/dist/chunk-q51w24br.js +0 -2
  194. package/dist/chunk-qek9bcjt.js +0 -2
  195. package/dist/chunk-qkxx34vt.js +0 -2
  196. package/dist/chunk-r2v042ym.js +0 -2
  197. package/dist/chunk-r8ydxe4z.js +0 -42
  198. package/dist/chunk-rjzp7za8.js +0 -2
  199. package/dist/chunk-s9b49v74.js +0 -3
  200. package/dist/chunk-sata7rh2.js +0 -2
  201. package/dist/chunk-tmcgpf68.js +0 -2
  202. package/dist/chunk-tsb5h4e2.js +0 -2
  203. package/dist/chunk-v8h2kns0.js +0 -2
  204. package/dist/chunk-vpazz8ca.js +0 -2
  205. package/dist/chunk-vyw40ym7.js +0 -2
  206. package/dist/chunk-whq40bdm.js +0 -2
  207. package/dist/chunk-x15hrtmt.js +0 -2
  208. package/dist/chunk-xha2gt0n.js +0 -2
  209. package/dist/chunk-ydt1pbhx.js +0 -2
  210. package/dist/chunk-z8ywxqqg.js +0 -2
  211. package/dist/chunk-zwp7n01x.js +0 -2
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{de,gn,It,Ot,m,s,fe,p}from"./chunk-ymypc1rp.js";import{yt,Re,rc,os,No,Mo,i}from"./chunk-8gcg9maj.js";import{ie,ae,Er,ke,F,Sn}from"./chunk-72jt897s.js";import{St,pr,Ts,$s,Rs,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-gtd6qs1r.js";import{xs,a,I}from"./chunk-j65nf7mt.js";import{ft,An,Ce,L,aa,mo,qr,We,ca,qe,Ee}from"./chunk-k01aftw0.js";import{lr,ur}from"./chunk-swbrvrgr.js";import{$n}from"./chunk-cf196sv5.js";import{e,cn,sr,y}from"./chunk-9tzcvsv0.js";import{Je}from"./chunk-7ac98ja7.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-9xd85mvm.js";import{c}from"./chunk-0rjcbqk3.js";import{K}from"./chunk-c5vzr1va.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
2
+ import{de,gn,It,Ot,m,s,fe,p}from"./chunk-j4cjn4m1.js";import{yt,Re,sc,os,No,Mo,i}from"./chunk-0p797a25.js";import{ie,ae,Er,ke,F,Sn}from"./chunk-8ttmzcxb.js";import{St,pr,Ts,$s,Rs,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-qj4r08jb.js";import{xs,a,I}from"./chunk-xdbwghty.js";import{ft,An,Ce,L,ca,mo,qr,We,la,qe,Ee}from"./chunk-3zhwcckc.js";import{lr,ur}from"./chunk-gywyr2x3.js";import{$n}from"./chunk-wc7dn3mr.js";import{e,cn,sr,y}from"./chunk-zbyfxcrr.js";import{Je}from"./chunk-p77cnteg.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-4t4af1mb.js";import{c}from"./chunk-brhas9mp.js";import{K}from"./chunk-wpendr22.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
3
3
  `),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
4
4
  `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,b=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:b}}function Wn(t,n){let r=[],d=Xt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Xt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
5
- `).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.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)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.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)r.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)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=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 o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Xi(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(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 nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(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 Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=Te.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let b=l[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}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 Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
5
+ `).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.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)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.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)r.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)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=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 o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Gi(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(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 nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(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 Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=Te.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let b=l[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}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 Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
6
6
 
7
7
  `)}function ir(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 ar(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 cr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function dr(t){let n=[],r=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(g)=>{if(d[g]!=="(")return null;let h=0,x="";for(let v=g;v<d.length;v++){let S=d[v];if(x!==""){if(S==="\\")v++;else if(S===x)x="";continue}if(S==="'"||S==='"'||S==="`"){x=S;continue}if(S==="(")h++;else if(S===")"){if(h--,h===0)return{expression:d.slice(g+1,v),end:v+1}}}return null},f=(g)=>{if(g==="")return;let h=0,x=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,v;while(v=x.exec(g)){if(v.index>h)n.push(`out += ${JSON.stringify(g.slice(h,v.index))};`);n.push(v[1]!==void 0?`out += __raw(${v[1]});`:`out += __escape(${v[2]});`),h=v.index+v[0].length}if(h<g.length)n.push(`out += ${JSON.stringify(g.slice(h))};`)};while(l=o.exec(d)){f(d.slice(r,l.index)),r=l.index+l[0].length;let h=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(r):null;if(h)r=h.end,o.lastIndex=h.end;let x=h?.expression;switch(l[1]){case"if":n.push(`if (${x}) {`);break;case"elseif":n.push(`} else if (${x}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let v=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((x||"").trim());if(!v){n.push(`out += ${JSON.stringify(l[0]+(h?`(${x})`:""))};`);break}let[,S,T,w]=v;n.push(T?`for (const [${T}, ${w}] of __entries(${S})) {`:`for (const ${w} of __values(${S})) {`);break}}}return f(d.slice(r)),n.join(`
8
8
  `)}function lt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function Mt(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,g="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(g+=x,x==="\\"){g+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,g+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(g),g="";continue}g+=x}return l.push(g),l.map((h)=>h.trim()).filter(Boolean)}function fr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Yt(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 mr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},g=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(g<t.length&&/\s/.test(t[g]))g++},x;if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;x=t.slice(g,E),g=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(g));if(!E)return null;x=E[0],g+=E[0].length}if(h(),t[g]!=="=")return null;g++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(g)),S=Boolean(v);if(v)g+=v[0].length;let T=/^defineProps\b/.exec(t.slice(g));if(!T)return null;g+=T[0].length;let w="";if(h(),t[g]==="<"){let E=lt(t,g,"<",">");if(E===-1)return null;w=t.slice(g+1,E-1).trim(),g=E}if(h(),t[g]!=="(")return null;let b=lt(t,g,"(",")");if(b===-1)return null;let k=t.slice(g+1,b-1).trim();if(g=b,S){if(h(),t[g]===",")g++,h();if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;for(let[R,O]of Lt(t.slice(g,E)))l[R]=O;g=E}if(h(),t[g]===",")g++,h();if(t[g]===")")g++}if(t[g]===";")g++;let D=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of Mt(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of Lt(k)){if(u.push(E),!R.startsWith("{")){let O=Yt(R);if(O)o[E]=O;continue}for(let[O,C]of Lt(R))if(O==="default")l[E]=C;else if(O==="type"){let A=Yt(C);if(A)o[E]=A}}else if(k.startsWith("["))for(let E of Mt(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of Mt(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=fr(E),O=R===-1?E:E.slice(0,R),C=O.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=O.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,g),propNames:u,propBindings:f,defaults:l,declared:o,typeName:D}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",g=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(g,d).trim();if(h)r.push([l[1],h]);d++}return r}function gr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],g={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,b,k,D)=>{let E=Te.resolve(Te.dirname(n),k),R=Te.relative(r,E);return`${b}${R.startsWith(".")?R:`./${R}`}${D}`})),""});let v=mr(l);if(v)f.push(...v.propNames),Object.assign(g,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let b of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[b[1]]=b[2].trim(),w.push(b[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:g,defaults:h,declared:x}}function hr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let g=o.toLowerCase();n.add(g);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${g}="${f}"${h?` data-stx-mod-${g}="${h}"`:""}`}),eventTypes:[...n].sort()}}function yr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function br(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function xr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Qt(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,r){let d=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),o=await Gn(d,"utf8"),l=nr(o,d),u=Te.basename(d,".stx"),f=n.name||l.name||Qn(u),g=`${jt(r.prefix||"stx")}-${jt(u)}`,h=n.tag||l.tag||g;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Zn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,O])=>[R,Qt(R,O)])),S=hr(or(o)),T=yr(S.template),w=gr(o,d,Te.resolve(r.outputDir)),b=dr(T.template);for(let R of w.propNames){if(v[R])continue;let O=w.defaults[R];v[R]=Qt(R,{type:ir(w.declared[R])??ar(O),...O===void 0?{}:{default:cr(O)}})}let k=l.methods||{},D=n.methods||{},E=rr(o,d);return{file:Te.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Jt(o),shadowMode:er(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...D,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:br(T.template),cssProperties:xr(Jt(o)),scope:w,render:b}}function wr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
@@ -421,7 +421,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
421
421
  }
422
422
 
423
423
  ${l}
424
- `}async function Gi(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Gt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await tr(n)).map((b)=>({file:b}));if(!o.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(o.map((b)=>vr(n,b,t)));l.sort((b,k)=>b.tag.localeCompare(k.tag));let u=l.filter((b,k)=>l.findIndex((D)=>D.tag===b.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((b,k)=>l.findIndex((D)=>D.name===b.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Xn(r,{recursive:!0});let g=[],h=async(b,k)=>{let D=Te.join(r,b);return await Yn(D,k.endsWith(`
424
+ `}async function Ji(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Gt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await tr(n)).map((b)=>({file:b}));if(!o.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(o.map((b)=>vr(n,b,t)));l.sort((b,k)=>b.tag.localeCompare(k.tag));let u=l.filter((b,k)=>l.findIndex((D)=>D.tag===b.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((b,k)=>l.findIndex((D)=>D.name===b.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Xn(r,{recursive:!0});let g=[],h=async(b,k)=>{let D=Te.join(r,b);return await Yn(D,k.endsWith(`
425
425
  `)?k:`${k}
426
426
  `,"utf8"),g.push(D),D};await h("runtime.js",wr());for(let b of l){if(await h(`${b.tag}.js`,Sr(b)),t.declarations!==!1)await h(`${b.tag}.d.ts`,kr(b));if(t.css!==!1&&b.styles){let k=b.shadowMode?b.styles:Zt(b);await h(`${b.tag}.css`,t.minify?en(k):k)}}let x=l.map((b)=>`export { ${b.name}, default as ${b.name}Element } from './${b.tag}.js';`).join(`
427
427
  `);if(await h("index.js",x),await h("ssr.js",Cr(l)),t.declarations!==!1)await h("index.d.ts",l.map((b)=>`export * from './${b.tag}.js'`).join(`
@@ -515,7 +515,7 @@ else {
515
515
  <span class="frontmatter-label">${n}:</span>
516
516
  <span>${Array.isArray(r)?r.join(", "):String(r)}</span>
517
517
  </div>`).join("")}
518
- </div>`}import rn from"net";async function Rr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"0.0.0.0")})}async function Pr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"::")})}async function Or(t){if(!await Rr(t))return!1;return await Pr(t)}async function Ve(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Or(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 Dr(){try{let t=await import("./chunk-nknpr8cy.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let r={...Ar,...n},d=await Dr();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 o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
518
+ </div>`}import rn from"net";async function Rr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"0.0.0.0")})}async function Pr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"::")})}async function Or(t){if(!await Rr(t))return!1;return await Pr(t)}async function Ve(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Or(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 Dr(){try{let t=await import("./chunk-7pz76f28.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let r={...Ar,...n},d=await Dr();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 o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
519
519
  ${l}
520
520
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
521
521
  `,g=Function(u)();if(g)return g}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function Bt(){console.log(`
@@ -887,7 +887,7 @@ else {
887
887
  };
888
888
  })();
889
889
  </script>
890
- `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(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 xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await xs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let b=await lr(u,r);if(b){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ie.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let D=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of D){let A=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",_=C.match(/<script\b([^>]*)>/i),V=_?_[1]:"";if(/\bserver\b/i.test(V))E=A;else R.push(C)}let O=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:O,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(F.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ie.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-c179xpsq.js"),k=b(v.join(`
890
+ `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(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 xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await xs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let b=await lr(u,r);if(b){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ie.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let D=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of D){let A=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",_=C.match(/<script\b([^>]*)>/i),V=_?_[1]:"";if(/\bserver\b/i.test(V))E=A;else R.push(C)}let O=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:O,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(F.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ie.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-m7nsk6fb.js"),k=b(v.join(`
891
891
  `),S),D=w.search(/<\/body>/i);if(D!==-1)w=w.slice(0,D)+k+`
892
892
  `+w.slice(D);else w+=`
893
893
  ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),r.cache&&r.cachePath){if(await ur(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(F.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:r.debug||K()?`<!DOCTYPE html>
@@ -950,7 +950,7 @@ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),r.cache&&r.cachePath){if(await u
950
950
  <h1>Something went wrong</h1>
951
951
  <p>An internal error occurred. Please try again later.</p>
952
952
  </body>
953
- </html>`,loader:"html"}}})}};async function Fr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return zt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let A={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},_=await Bun.build({entrypoints:[f],outdir:g,plugins:[A,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!_.success)return console.error(`${e.red}Build failed:${e.reset}`,_.logs),!1;let V=_.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(A){return console.error(`${e.red}Error building stx file:${e.reset}`,A),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=r;try{if(T=await Ve(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let A=n.hmrPort||T+1;l=vt({wsPort:A,verbose:!1}),u=l.start(A)}let w={},b=null,k;try{let{loadStxConfig:A}=await import("./chunk-vpazz8ca.js"),_=await A();if(k=n.stxOptions?.serverApi??_.serverApi,_?.apiRouter)b=_?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(_?.apiRoutes){w=_.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-vyw40ym7.js"),xe=_.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);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:D,isServerApiSource:E}=await import("./chunk-ydt1pbhx.js"),R=await D(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let O=Nr({port:T,async fetch(A){return $n(A,await(async()=>{let _=new URL(A.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,_.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(A);if(ne.status!==404)return ne}catch{}if(w[_.pathname])try{return await w[_.pathname](A)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(A);if(V)return V;if(_.pathname==="/")return(async()=>{let z=await y(h||"");if(o)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,_.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let xe=ge.dirname(f),le=ge.join(xe,_.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let Oe=ge.join(process.cwd(),"public",_.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),M="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}return new Response("Not Found",{status:404})})())},error(A){return new Response(`<pre>${A}
953
+ </html>`,loader:"html"}}})}};async function Fr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return zt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let A={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},_=await Bun.build({entrypoints:[f],outdir:g,plugins:[A,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!_.success)return console.error(`${e.red}Build failed:${e.reset}`,_.logs),!1;let V=_.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(A){return console.error(`${e.red}Error building stx file:${e.reset}`,A),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=r;try{if(T=await Ve(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let A=n.hmrPort||T+1;l=vt({wsPort:A,verbose:!1}),u=l.start(A)}let w={},b=null,k;try{let{loadStxConfig:A}=await import("./chunk-w04h1t4t.js"),_=await A();if(k=n.stxOptions?.serverApi??_.serverApi,_?.apiRouter)b=_?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(_?.apiRoutes){w=_.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-r2hjn9ds.js"),xe=_.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);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:D,isServerApiSource:E}=await import("./chunk-3na8kkec.js"),R=await D(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let O=Nr({port:T,async fetch(A){return $n(A,await(async()=>{let _=new URL(A.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,_.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(A);if(ne.status!==404)return ne}catch{}if(w[_.pathname])try{return await w[_.pathname](A)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(A);if(V)return V;if(_.pathname==="/")return(async()=>{let z=await y(h||"");if(o)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,_.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let xe=ge.dirname(f),le=ge.join(xe,_.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let Oe=ge.join(process.cwd(),"public",_.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),M="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}return new Response("Not Found",{status:404})})())},error(A){return new Response(`<pre>${A}
954
954
  ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
955
955
  ${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(`
956
956
  ${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
1437
1437
  ${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(`
1438
1438
  ${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
1439
1439
  ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let D=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${D}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.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 dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=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"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Hr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-vpazz8ca.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-ydt1pbhx.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${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 ${b}/index.stx for the homepage.${e.reset}`),!1;let D=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(D.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${D.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:j}of E)if(me.existsSync(P)){let N=X(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let O=new Map,C=null,A=null;if(n.stxOptions?.shell!==!1){if(A=await aa(f,n.stxOptions?.shell),A){if(C=await mo(A,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,A)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let _=_t();if(_.length>0)console.log(`${e.blue}Loaded ${e.bright}${_.length}${e.blue} middleware: ${e.dim}${_.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-vpazz8ca.js"),j=await P(f);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 N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-vyw40ym7.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=c(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(P)=>{let j=$s(k,P);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,M=async(P,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-vpazz8ca.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-67k5q95t.js"),G=await Ae(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let se=pe.get(P.filePath);if(se)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=gn(Z),{classifyAllScripts:ue}=await import("./chunk-vpazz8ca.js"),B=ue(Z),Le=B.server.map((se)=>se.content),Me=Z;for(let se of B.server)Me=Me.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let se=performance.now();he=await N(Me,ee,P.filePath,ce,De);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,P.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:se}=await import("./chunk-c179xpsq.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}>${se(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-pyz2jqph.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(P.pattern);else Qe=void 0;let Vt=It(ee),qt=Ot(ee);if(H)z.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),j=new Set(O.keys());le.clear(),O.clear();let N=n.prebuild===!1?D.filter((q)=>P.has(q.pattern)):D,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>M(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>M(U)));for(let U of ve)if(U)O.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?D.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=r;try{if(Ge=await Ve(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,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(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(P){let j=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Mo(N,os()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Ae,f,S))return Nt(Ae);if(W?.isFile()&&!v(ve,f,S))return Nt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-dh1f8ga0.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(P);if(pe)return pe;let G=pr(j.pathname,D);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await M(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,P,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<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>",`${De}</head>`)}}let B=H.content;if(C&&ca(P)&&qe(B,h?.router?.container||"main")){let Le=et(B),Me=be(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)B=Pt(B,G.params);B=await y(B,f);let he=h?.router?.container||"main";return B=Ee(B,he,!0),new Response(B,{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":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[rc]:os(),...L(),"Cache-Control":ft}})}if(C)B=qr(C,B);if(Object.keys(G.params).length>0)B=Pt(B,G.params);if(B=await y(B,f),o)B=Ne(B,u);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;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-pyz2jqph.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...L(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=O.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await M(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)O.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=qr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await y(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let oe=O.get(Z)||O.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await M(ue.route);if(B)oe=B,O.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),o)H=Ne(H,u);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,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1440
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.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 dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=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"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Hr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-w04h1t4t.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-3na8kkec.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${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 ${b}/index.stx for the homepage.${e.reset}`),!1;let D=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(D.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${D.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:j}of E)if(me.existsSync(P)){let N=X(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let O=new Map,C=null,A=null;if(n.stxOptions?.shell!==!1){if(A=await ca(f,n.stxOptions?.shell),A){if(C=await mo(A,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,A)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let _=_t();if(_.length>0)console.log(`${e.blue}Loaded ${e.bright}${_.length}${e.blue} middleware: ${e.dim}${_.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-w04h1t4t.js"),j=await P(f);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 N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-r2hjn9ds.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=c(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(P)=>{let j=$s(k,P);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,M=async(P,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-w04h1t4t.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-0e0z4ab6.js"),G=await Ae(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let se=pe.get(P.filePath);if(se)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=gn(Z),{classifyAllScripts:ue}=await import("./chunk-w04h1t4t.js"),B=ue(Z),Le=B.server.map((se)=>se.content),Me=Z;for(let se of B.server)Me=Me.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let se=performance.now();he=await N(Me,ee,P.filePath,ce,De);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,P.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:se}=await import("./chunk-m7nsk6fb.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}>${se(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-7ffmz1fb.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(P.pattern);else Qe=void 0;let Vt=It(ee),qt=Ot(ee);if(H)z.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),j=new Set(O.keys());le.clear(),O.clear();let N=n.prebuild===!1?D.filter((q)=>P.has(q.pattern)):D,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>M(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>M(U)));for(let U of ve)if(U)O.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?D.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=r;try{if(Ge=await Ve(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,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(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(P){let j=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Mo(N,os()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Ae,f,S))return Nt(Ae);if(W?.isFile()&&!v(ve,f,S))return Nt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-sddp2398.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(P);if(pe)return pe;let G=pr(j.pathname,D);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await M(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,P,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<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>",`${De}</head>`)}}let B=H.content;if(C&&la(P)&&qe(B,h?.router?.container||"main")){let Le=et(B),Me=be(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)B=Pt(B,G.params);B=await y(B,f);let he=h?.router?.container||"main";return B=Ee(B,he,!0),new Response(B,{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":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[sc]:os(),...L(),"Cache-Control":ft}})}if(C)B=qr(C,B);if(Object.keys(G.params).length>0)B=Pt(B,G.params);if(B=await y(B,f),o)B=Ne(B,u);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;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-7ffmz1fb.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...L(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=O.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await M(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)O.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=qr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await y(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let oe=O.get(Z)||O.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await M(ue.route);if(B)oe=B,O.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),o)H=Ne(H,u);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,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1441
1441
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1442
1442
  ${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(`
1443
1443
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
1444
  ${e.yellow}Routes:${e.reset}`);let Dt=[...Rs(D,f)];for(let{route:P}of R)Dt.push(`${P.pattern}`);if(Dt.forEach((P,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1445
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();P=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),D.splice(0,D.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-67k5q95t.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(A&&W){if(te.resolve(U,W)===A||te.basename(A)===W){let G=await mo(A,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-67k5q95t.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1445
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();P=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),D.splice(0,D.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-0e0z4ab6.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(A&&W){if(te.resolve(U,W)===A||te.basename(A)===W){let G=await mo(A,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-0e0z4ab6.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1446
1446
  `).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Kr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1447
1447
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Vr(t),l=await Kr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
1448
1448
  `);u=`<${d}
@@ -1581,12 +1581,12 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.
1581
1581
  <td>@${l.name}</td>
1582
1582
  <td>${l.description||"-"}</td>
1583
1583
  <td>${l.hasEndTag?"Yes":"No"}</td>
1584
- </tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function eo(t=[],n=[],r=[],d){return JSON.stringify({components:t,templates:n,directives:r,extraContent:d||""},null,2)}async function to(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:d,customDirectives:o,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Gr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&r)console.log("Generating template documentation..."),g=await Jr(r),console.log(`Found ${g.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Yr(o),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Qr(f,g,h,v),T="md";break;case"html":S=Zr(f,g,h,v),T="html";break;case"json":S=eo(f,g,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function Ji(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},r=t.componentsDir||I.componentsDir,d=t.templatesDir||".";return to({componentsDir:r,templatesDir:d,webComponentsConfig:I.webComponents,customDirectives:I.customDirectives,config:n})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function io(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1584
+ </tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function eo(t=[],n=[],r=[],d){return JSON.stringify({components:t,templates:n,directives:r,extraContent:d||""},null,2)}async function to(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:d,customDirectives:o,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Gr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&r)console.log("Generating template documentation..."),g=await Jr(r),console.log(`Found ${g.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Yr(o),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Qr(f,g,h,v),T="md";break;case"html":S=Zr(f,g,h,v),T="html";break;case"json":S=eo(f,g,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function Yi(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},r=t.componentsDir||I.componentsDir,d=t.templatesDir||".";return to({componentsDir:r,templatesDir:d,webComponentsConfig:I.webComponents,customDirectives:I.customDirectives,config:n})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function io(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1585
1585
  `;let d=t;if(r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=oo(d,r),d=uo(d,r),d=so(d,r),r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!d.endsWith(`
1588
1588
  `))d+=`
1589
- `;return d}function Yi(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1589
+ `;return d}function Zi(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1590
1590
  `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(o,l,u,f,g)=>{let h=f.split(`
1591
1591
  `),x=h.filter((b)=>b.trim().length>0);if(x.length===0)return o;let v=Math.min(...x.map((b)=>{let k=b.match(/^( *)/);return k?k[1].length:0})),S=h.map((b)=>{if(b.trim().length===0)return"";return b.substring(v)}).join(`
1592
1592
  `),w=io(S,r).trimEnd().split(`
@@ -1614,7 +1614,7 @@ ${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,l,u,f)=>{let g=f.substring(Math.max
1614
1614
  `),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function oo(t,n){let d=ro(t).split(`
1615
1615
  `),o=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let g=0;g<d.length;g++){let h=d[g],x=h.trim();if(x===""){o.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){o.push(h);continue}let T=x===">";if(un(x)&&!x.startsWith("<")&&!x.startsWith("@")){o.push(f.repeat(l)+x);continue}let w=x.startsWith("@end"),b=x.startsWith("@else")||x.startsWith("@elseif"),k=x.startsWith("@")&&po(x),D=x.startsWith("<!DOCTYPE")||x.startsWith("<!doctype"),E=x.startsWith("<!--"),R=x.startsWith("</"),O=x.startsWith("<")&&!R&&!E&&!D,C=x.includes("/>")||lo(x),A=un(x);if(R||w)l=Math.max(0,l-1);let _=b?Math.max(0,l-1):l;if(T)o.push(h);else o.push(f.repeat(_)+x);if(O&&!C&&!A&&!T||k)l++;if(v)u=!0;if(S)u=!1}return o.join(`
1616
1616
  `)}function so(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,d,o)=>{let l=o.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,d,o)=>{if(o.trim()==="")return`@${d}`;return`@${d}(${o.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,d)=>`{!! ${d.trim()} !!}`);return t}function lo(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let r=t.match(/<(\w+)/);if(r){let d=r[1];return n.includes(d.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function po(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of n)if(t.startsWith(`@${r}`))return!t.includes(`@end${r}`);return!1}function uo(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(r,d,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
1617
- `)||o.includes("@"))return r;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(o))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let g=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${g?` ${g}`:""}>`})}import mn from"fs";import Wt from"path";async function Zi(t="index.stx",n={}){try{let r=n.force||!1,d=Wt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Wt.dirname(d);if(!mn.existsSync(o))mn.mkdirSync(o,{recursive:!0});let l;if(n.template){let u=Wt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)l=hn(n.preset),console.warn(`Using '${n.preset}' preset template`);else l=hn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function hn(t){switch(t){case"basic":return yn();case"component":return fo();case"layout":return go();case"blog":return ho();case"api":return yo();case"app":return bo();default:return yn()}}function yn(){return`<script>
1617
+ `)||o.includes("@"))return r;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(o))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let g=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${g?` ${g}`:""}>`})}import mn from"fs";import Wt from"path";async function Qi(t="index.stx",n={}){try{let r=n.force||!1,d=Wt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Wt.dirname(d);if(!mn.existsSync(o))mn.mkdirSync(o,{recursive:!0});let l;if(n.template){let u=Wt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)l=hn(n.preset),console.warn(`Using '${n.preset}' preset template`);else l=hn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function hn(t){switch(t){case"basic":return yn();case"component":return fo();case"layout":return go();case"blog":return ho();case"api":return yo();case"app":return bo();default:return yn()}}function yn(){return`<script>
1618
1618
  const title = "My stx Page"
1619
1619
  const description = "A page built with stx"
1620
1620
  const features = [
@@ -2040,5 +2040,5 @@ const features = [
2040
2040
  })();
2041
2041
  </script>
2042
2042
  </body>
2043
- </html>`}var Qi="f9c3713";function El(t){return t}function Tl(t){return t}function Ki(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function Rn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Rt(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $i(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function En(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Ci(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ri(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,g){if(g>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Pn){let S=ye.join(f,v),T=Ci(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:g>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let b of w){let k=ye.join(S,b.name,"node_modules");if(_e.existsSync(k))l(k,g+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,g+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ei(t){let n=[];for(let r of Pn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function ao(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??$i,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let g of Ei(Ri(n)))o.push(g);let f=En(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let g=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=Rn(g),v=h?Rn(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.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 ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(v,d)}) is OLDER than src/signals.ts (${Rt(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(x,d)}, dist ${Rt(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let b=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===b?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.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(o.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 h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(g){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${g.message}`})}return{checks:o,ok:!o.some((g)=>g.status==="error")}}function co(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2044
- `)}export{Ki,Xi,Gi,Ji,io,Yi,Zi,Qi,El,Tl,ao,co,Fr,zr,Hr};
2043
+ </html>`}var ea="f9c3713";function Tl(t){return t}function $l(t){return t}function Xi(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function Rn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Rt(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $i(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function En(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Ci(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ri(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,g){if(g>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Pn){let S=ye.join(f,v),T=Ci(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:g>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let b of w){let k=ye.join(S,b.name,"node_modules");if(_e.existsSync(k))l(k,g+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,g+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ei(t){let n=[];for(let r of Pn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function ao(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??$i,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let g of Ei(Ri(n)))o.push(g);let f=En(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let g=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=Rn(g),v=h?Rn(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.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 ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(v,d)}) is OLDER than src/signals.ts (${Rt(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(x,d)}, dist ${Rt(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let b=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===b?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.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(o.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 h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(g){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${g.message}`})}return{checks:o,ok:!o.some((g)=>g.status==="error")}}function co(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2044
+ `)}export{Xi,Gi,Ji,Yi,io,Zi,Qi,ea,Tl,$l,ao,co,Fr,zr,Hr};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{x}from"./chunk-72jt897s.js";function Ze(e,r){let n=y(e,r);return n.ok?{expression:n.expression,endPos:n.endPos}:null}function y(e,r){let n=r;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]!=="(")return{ok:!1,reason:"missing-open-paren",pos:n};let c=x(e,"(",")",n);if(c===-1)return{ok:!1,reason:"unclosed-paren",pos:n};return{ok:!0,expression:e.slice(n+1,c),endPos:c+1}}function k(e,r){let n=e.lastIndexOf("<",r);if(n===-1)return!1;return n>e.lastIndexOf(">",r)}function vt(e,r,n,c){let o=1,i=c,u=new RegExp(`@${r}\\s*\\(`,"g"),a=new RegExp(`@${n}(?![a-z])`,"g");while(i<e.length&&o>0){u.lastIndex=i,a.lastIndex=i;let p=u.exec(e),t=a.exec(e),s=p?p.index:1/0,f=t?t.index:1/0;if(s<f)o++,i=s+p[0].length;else if(f<1/0){if(o--,o===0)return f;i=f+t[0].length}else break}return-1}function v(e,r){let n=e.slice(r).match(/^@if\s*/);if(!n)return null;let c=r+n[0].length,o=Ze(e,c);if(!o)return null;let i=o.endPos,u=vt(e,"if","endif",i);if(u===-1)return null;let a=e.slice(i,u),p=[],t=0,s="if",f=o.expression,l=0,g=0;while(t<a.length){let h=a.indexOf("@",t);if(h===-1)break;t=h;let d=a.substring(h);if(k(a,h)){t++;continue}if(/^@if\s*\(/.test(d)){g++,t++;continue}if(/^@endif(?![a-z])/.test(d)){g--,t+=6;continue}if(g===0){let b=d.match(/^@elseif\s*/);if(b){p.push({type:s,condition:f,content:a.substring(l,t),start:i+l,end:i+t});let E=t+b[0].length,m=Ze(a,E);if(!m){t++;continue}s="elseif",f=m.expression,t=m.endPos,l=t;continue}else if(/^@else(?![a-z])/.test(d)){p.push({type:s,condition:f,content:a.substring(l,t),start:i+l,end:i+t}),s="else",f=void 0,t+=5,l=t;continue}}t++}return p.push({type:s,condition:f,content:a.slice(l),start:i+l,end:i+a.length}),{fullMatch:e.slice(r,u+6),branches:p,start:r,end:u+6}}function ln(e){let r=[],n=/@if\s*\(/g,c=n.exec(e);while(c!==null){if(r.some((u)=>c.index>u.start&&c.index<u.end)){c=n.exec(e);continue}let i=v(e,c.index);if(i)r.push(i),n.lastIndex=i.end;c=n.exec(e)}return r}function bs(e,r,n){let c=[],o=new RegExp(`@${r}\\s*\\(`,"g"),i=o.exec(e);while(i!==null){if(c.some((d)=>i.index>d.start&&i.index<d.end)){i=o.exec(e);continue}let a=i.index,p=a+i[0].length-1,t=x(e,"(",")",p);if(t===-1){i=o.exec(e);continue}let s=e.slice(p+1,t),f=t+1,l=vt(e,r,n,f);if(l===-1){i=o.exec(e);continue}let g=e.slice(f,l),h=l+`@${n}`.length;c.push({fullMatch:e.slice(a,h),name:r,params:s,content:g,start:a,end:h}),o.lastIndex=h,i=o.exec(e)}return c}function Ko(e,r){let n=e.slice(r).match(/^@switch\s*/);if(!n)return null;let c=r+n[0].length,o=Ze(e,c);if(!o)return null;let i=o.endPos,u=vt(e,"switch","endswitch",i);if(u===-1)return null;let a=e.slice(i,u),p=[],t=0,s=null,f=0;while(t<a.length){let l=a.slice(t),g=l.match(/^@switch\s*\(/),h=l.match(/^@endswitch(?![a-z])/);if(g){if(f++,s)s.content+=g[0];t+=g[0].length;continue}if(h){if(f--,s)s.content+=h[0];t+=h[0].length;continue}if(f>0){if(s)s.content+=a[t];t++;continue}let d=l.match(/^@case\s*/),b=l.match(/^@default(?![a-z])/),E=l.match(/^@break(?![a-z])/);if(d&&l.startsWith("@case")){if(s)p.push(s);let m=t+d[0].length,P=Ze(a,m);if(!P){t++;continue}s={type:"case",value:P.expression,content:""},t=P.endPos}else if(b&&l.startsWith("@default")){if(s)p.push(s);s={type:"default",content:""},t+=b[0].length}else if(E&&l.startsWith("@break"))t+=E[0].length;else{if(s)s.content+=a[t];t++}}if(s)p.push(s);return{fullMatch:e.slice(r,u+10),expression:o.expression,cases:p,start:r,end:u+10}}export{Ze,vt,ln,bs,Ko};
2
+ import{x}from"./chunk-8ttmzcxb.js";function Ze(e,r){let n=y(e,r);return n.ok?{expression:n.expression,endPos:n.endPos}:null}function y(e,r){let n=r;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]!=="(")return{ok:!1,reason:"missing-open-paren",pos:n};let c=x(e,"(",")",n);if(c===-1)return{ok:!1,reason:"unclosed-paren",pos:n};return{ok:!0,expression:e.slice(n+1,c),endPos:c+1}}function k(e,r){let n=e.lastIndexOf("<",r);if(n===-1)return!1;return n>e.lastIndexOf(">",r)}function vt(e,r,n,c){let o=1,i=c,u=new RegExp(`@${r}\\s*\\(`,"g"),a=new RegExp(`@${n}(?![a-z])`,"g");while(i<e.length&&o>0){u.lastIndex=i,a.lastIndex=i;let p=u.exec(e),t=a.exec(e),s=p?p.index:1/0,f=t?t.index:1/0;if(s<f)o++,i=s+p[0].length;else if(f<1/0){if(o--,o===0)return f;i=f+t[0].length}else break}return-1}function v(e,r){let n=e.slice(r).match(/^@if\s*/);if(!n)return null;let c=r+n[0].length,o=Ze(e,c);if(!o)return null;let i=o.endPos,u=vt(e,"if","endif",i);if(u===-1)return null;let a=e.slice(i,u),p=[],t=0,s="if",f=o.expression,l=0,g=0;while(t<a.length){let h=a.indexOf("@",t);if(h===-1)break;t=h;let d=a.substring(h);if(k(a,h)){t++;continue}if(/^@if\s*\(/.test(d)){g++,t++;continue}if(/^@endif(?![a-z])/.test(d)){g--,t+=6;continue}if(g===0){let b=d.match(/^@elseif\s*/);if(b){p.push({type:s,condition:f,content:a.substring(l,t),start:i+l,end:i+t});let E=t+b[0].length,m=Ze(a,E);if(!m){t++;continue}s="elseif",f=m.expression,t=m.endPos,l=t;continue}else if(/^@else(?![a-z])/.test(d)){p.push({type:s,condition:f,content:a.substring(l,t),start:i+l,end:i+t}),s="else",f=void 0,t+=5,l=t;continue}}t++}return p.push({type:s,condition:f,content:a.slice(l),start:i+l,end:i+a.length}),{fullMatch:e.slice(r,u+6),branches:p,start:r,end:u+6}}function ln(e){let r=[],n=/@if\s*\(/g,c=n.exec(e);while(c!==null){if(r.some((u)=>c.index>u.start&&c.index<u.end)){c=n.exec(e);continue}let i=v(e,c.index);if(i)r.push(i),n.lastIndex=i.end;c=n.exec(e)}return r}function bs(e,r,n){let c=[],o=new RegExp(`@${r}\\s*\\(`,"g"),i=o.exec(e);while(i!==null){if(c.some((d)=>i.index>d.start&&i.index<d.end)){i=o.exec(e);continue}let a=i.index,p=a+i[0].length-1,t=x(e,"(",")",p);if(t===-1){i=o.exec(e);continue}let s=e.slice(p+1,t),f=t+1,l=vt(e,r,n,f);if(l===-1){i=o.exec(e);continue}let g=e.slice(f,l),h=l+`@${n}`.length;c.push({fullMatch:e.slice(a,h),name:r,params:s,content:g,start:a,end:h}),o.lastIndex=h,i=o.exec(e)}return c}function Ko(e,r){let n=e.slice(r).match(/^@switch\s*/);if(!n)return null;let c=r+n[0].length,o=Ze(e,c);if(!o)return null;let i=o.endPos,u=vt(e,"switch","endswitch",i);if(u===-1)return null;let a=e.slice(i,u),p=[],t=0,s=null,f=0;while(t<a.length){let l=a.slice(t),g=l.match(/^@switch\s*\(/),h=l.match(/^@endswitch(?![a-z])/);if(g){if(f++,s)s.content+=g[0];t+=g[0].length;continue}if(h){if(f--,s)s.content+=h[0];t+=h[0].length;continue}if(f>0){if(s)s.content+=a[t];t++;continue}let d=l.match(/^@case\s*/),b=l.match(/^@default(?![a-z])/),E=l.match(/^@break(?![a-z])/);if(d&&l.startsWith("@case")){if(s)p.push(s);let m=t+d[0].length,P=Ze(a,m);if(!P){t++;continue}s={type:"case",value:P.expression,content:""},t=P.endPos}else if(b&&l.startsWith("@default")){if(s)p.push(s);s={type:"default",content:""},t+=b[0].length}else if(E&&l.startsWith("@break"))t+=E[0].length;else{if(s)s.content+=a[t];t++}}if(s)p.push(s);return{fullMatch:e.slice(r,u+10),expression:o.expression,cases:p,start:r,end:u+10}}export{Ze,vt,ln,bs,Ko};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{AsyncLocalStorage as R}from"async_hooks";var b=Symbol.for("stx.runtime-config.scope"),y=globalThis,m=y[b]??=new R;function ze(n,f){return m.run(n,f)}function xn(){return m.getStore()}function Ws(){let n=m.getStore();if(!n)throw Error("useServerRuntimeConfig requires a server request or template render");return Object.freeze(Object.defineProperty({public:n.public},"private",{value:n.private}))}function xi(){return Ws().public}function N(n={},f=process.env){let s=new Set;function o(e,i){if(i===null)return e===null;if(Array.isArray(i))return Array.isArray(e)&&(!i.length||e.every((r)=>i.some((u)=>o(r,u))));if(typeof i==="object")return e!==null&&typeof e==="object"&&!Array.isArray(e)&&Object.entries(i).every(([r,u])=>Object.hasOwn(e,r)&&o(e[r],u));return typeof e===typeof i}function g(e,i){if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Runtime config ${i.join(".")} must contain JSON values`);let t=Object.create(null);for(let[c,l]of Object.entries(e)){if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(c)||["constructor","prototype","__proto__"].includes(c))throw TypeError(`Invalid runtime config key: ${c}`);t[c]=g(l,[...i,c])}return Object.freeze(t)}let r=`STX_RUNTIME_${i.map((t)=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()).join("__")}`;if(s.has(r))throw TypeError(`Ambiguous runtime config environment key: ${r}`);s.add(r);let u=f[r],a=e;if(u!==void 0){try{a=typeof e==="string"?u:JSON.parse(u)}catch{throw TypeError(`Invalid runtime config override: ${r}`)}if(!o(a,e))throw TypeError(`Wrong runtime config override type: ${r}`)}function p(t){if(t===null||typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;if(Array.isArray(t))return Object.freeze(t.map(p));if(t&&typeof t==="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.freeze(Object.fromEntries(Object.entries(t).map(([c,l])=>[c,p(l)])));throw TypeError(`Runtime config ${i.join(".")} must contain JSON values`)}return p(a)}return Object.freeze({public:g(n.public??{},["public"]),private:g(n.private??{},["private"])})}function C(n){return`<script data-stx-scoped data-stx-runtime-config type="application/json">${JSON.stringify(n.public).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}</script>`}function Dt(n,f){let s=n.replace(/<script\b[^>]*\bdata-stx-runtime-config\b[^>]*>[\s\S]*?<\/script>/gi,""),o=/<head\b[^>]*>/i.exec(s),g=o?o.index+o[0].length:0;return s.slice(0,g)+C(f)+s.slice(g)}
3
- export{ze,xn,Ws,xi,N,Dt};
2
+ import{AsyncLocalStorage as R}from"async_hooks";var b=Symbol.for("stx.runtime-config.scope"),y=globalThis,m=y[b]??=new R;function ze(n,f){return m.run(n,f)}function xn(){return m.getStore()}function Ws(){let n=m.getStore();if(!n)throw Error("useServerRuntimeConfig requires a server request or template render");return Object.freeze(Object.defineProperty({public:n.public},"private",{value:n.private}))}function Si(){return Ws().public}function N(n={},f=process.env){let s=new Set;function o(e,i){if(i===null)return e===null;if(Array.isArray(i))return Array.isArray(e)&&(!i.length||e.every((r)=>i.some((u)=>o(r,u))));if(typeof i==="object")return e!==null&&typeof e==="object"&&!Array.isArray(e)&&Object.entries(i).every(([r,u])=>Object.hasOwn(e,r)&&o(e[r],u));return typeof e===typeof i}function g(e,i){if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Runtime config ${i.join(".")} must contain JSON values`);let t=Object.create(null);for(let[c,l]of Object.entries(e)){if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(c)||["constructor","prototype","__proto__"].includes(c))throw TypeError(`Invalid runtime config key: ${c}`);t[c]=g(l,[...i,c])}return Object.freeze(t)}let r=`STX_RUNTIME_${i.map((t)=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()).join("__")}`;if(s.has(r))throw TypeError(`Ambiguous runtime config environment key: ${r}`);s.add(r);let u=f[r],a=e;if(u!==void 0){try{a=typeof e==="string"?u:JSON.parse(u)}catch{throw TypeError(`Invalid runtime config override: ${r}`)}if(!o(a,e))throw TypeError(`Wrong runtime config override type: ${r}`)}function p(t){if(t===null||typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;if(Array.isArray(t))return Object.freeze(t.map(p));if(t&&typeof t==="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.freeze(Object.fromEntries(Object.entries(t).map(([c,l])=>[c,p(l)])));throw TypeError(`Runtime config ${i.join(".")} must contain JSON values`)}return p(a)}return Object.freeze({public:g(n.public??{},["public"]),private:g(n.private??{},["private"])})}function C(n){return`<script data-stx-scoped data-stx-runtime-config type="application/json">${JSON.stringify(n.public).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}</script>`}function Dt(n,f){let s=n.replace(/<script\b[^>]*\bdata-stx-runtime-config\b[^>]*>[\s\S]*?<\/script>/gi,""),o=/<head\b[^>]*>/i.exec(s),g=o?o.index+o[0].length:0;return s.slice(0,g)+C(f)+s.slice(g)}
3
+ export{ze,xn,Ws,Si,N,Dt};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Q,ee,te,Nn,me,Te,gt,Xt,Mn,Dn,Ln,ne,jn,Bn}from"./chunk-4fbg7gq8.js";import{xt}from"./chunk-mv3yhspn.js";function Rl(s,r={}){let{src:e,alt:t,width:n,height:a,sizes:i="100vw",loading:m="lazy",priority:o=!1,quality:u=te,placeholder:l="none",formats:f=ee,widths:y=Q,decoding:c="async",fetchpriority:h,objectFit:d,objectPosition:g}=s,{class:p,style:v}=s,{processedImage:w,variants:I,optimize:b=!0,isDev:A=!1}=r;if(I&&I.length>0)return K(s,I,w);if(A||!b)return Z(s);return G(s)}function K(s,r,e){let{src:t,alt:n,width:a,height:i,sizes:m="100vw",loading:o="lazy",priority:u=!1,decoding:l="async",fetchpriority:f,objectFit:y,objectPosition:c,placeholder:h="none"}=s,{class:d,style:g}=s,p=Dn(r),v=Mn(r),w=typeof m==="object"?Xt(m):m,I=e?e.aspectRatio:a&&i?Number(a)/Number(i):void 0,b=[];if(I)b.push(`aspect-ratio: ${I}`);if(y)b.push(`object-fit: ${y}`);if(c)b.push(`object-position: ${c}`);if(g)b.push(g);let A=b.length>0?` style="${b.join("; ")}"`:"",S=d?` class="${d}"`:"",F=u?"":` loading="${o}"`,R=` decoding="${l}"`,C=f?` fetchpriority="${f}"`:u?' fetchpriority="high"':"",E=["avif","webp","jpeg","png"],M=[];for(let k of E){let z=p.get(k);if(z&&z.length>0){let O=gt(z),J=ne(k);M.push(` <source type="${J}" srcset="${O}" sizes="${w}" />`)}}let U="",L="",T;if(h!=="none"&&e?.placeholder){let k=`img-${Math.random().toString(36).slice(2,8)}`;if(U=`<div class="stx-image-wrapper" id="${k}">`,L="</div>",h==="blur")T=`
2
+ import{Q,ee,te,Nn,me,Te,gt,Xt,Mn,Dn,Ln,ne,jn,Bn}from"./chunk-akj26p4b.js";import{xt}from"./chunk-mv3yhspn.js";function Al(s,r={}){let{src:e,alt:t,width:n,height:a,sizes:i="100vw",loading:m="lazy",priority:o=!1,quality:u=te,placeholder:l="none",formats:f=ee,widths:y=Q,decoding:c="async",fetchpriority:h,objectFit:d,objectPosition:g}=s,{class:p,style:v}=s,{processedImage:w,variants:I,optimize:b=!0,isDev:A=!1}=r;if(I&&I.length>0)return K(s,I,w);if(A||!b)return Z(s);return G(s)}function K(s,r,e){let{src:t,alt:n,width:a,height:i,sizes:m="100vw",loading:o="lazy",priority:u=!1,decoding:l="async",fetchpriority:f,objectFit:y,objectPosition:c,placeholder:h="none"}=s,{class:d,style:g}=s,p=Dn(r),v=Mn(r),w=typeof m==="object"?Xt(m):m,I=e?e.aspectRatio:a&&i?Number(a)/Number(i):void 0,b=[];if(I)b.push(`aspect-ratio: ${I}`);if(y)b.push(`object-fit: ${y}`);if(c)b.push(`object-position: ${c}`);if(g)b.push(g);let A=b.length>0?` style="${b.join("; ")}"`:"",S=d?` class="${d}"`:"",F=u?"":` loading="${o}"`,R=` decoding="${l}"`,C=f?` fetchpriority="${f}"`:u?' fetchpriority="high"':"",E=["avif","webp","jpeg","png"],M=[];for(let k of E){let z=p.get(k);if(z&&z.length>0){let O=gt(z),J=ne(k);M.push(` <source type="${J}" srcset="${O}" sizes="${w}" />`)}}let U="",L="",T;if(h!=="none"&&e?.placeholder){let k=`img-${Math.random().toString(36).slice(2,8)}`;if(U=`<div class="stx-image-wrapper" id="${k}">`,L="</div>",h==="blur")T=`
3
3
  #${k} {
4
4
  position: relative;
5
5
  background-image: url('${e.placeholder}');
@@ -30,7 +30,7 @@ ${M.join(`
30
30
  data-quality="${o}"
31
31
  data-formats="${u.join(",")}"
32
32
  data-widths="${l.join(",")}"
33
- `.replace(/\s+/g," ").trim();return{html:`<img src="${r}" alt="${B(e)}"${I}${b}${w}${v}${A}${S}${F} ${C} />`}}function na(s){let r=s.match(/<Image\s+([^>]*?)\/?>/);if(!r)return null;let e=r[1],t={},n=/(\w+)(?:=(?:"([^"]*)"|'([^']*)'|(\{[^}]+\})))?/g,a;while((a=n.exec(e))!==null){let[,i,m,o,u]=a,l=m??o??u??!0;switch(i){case"src":t.src=String(l);break;case"alt":t.alt=String(l);break;case"width":t.width=Number(l)||l;break;case"height":t.height=Number(l)||l;break;case"sizes":t.sizes=String(l);break;case"loading":t.loading=l;break;case"priority":t.priority=l===!0||l==="true";break;case"quality":t.quality=Number(l);break;case"placeholder":t.placeholder=l;break;case"class":t.class=String(l);break;case"style":t.style=String(l);break;case"decoding":t.decoding=l;break;case"fetchpriority":t.fetchpriority=l;break;case"objectFit":t.objectFit=l;break;case"objectPosition":t.objectPosition=String(l);break}}if(!t.src||!t.alt)return null;return t}async function Al(s,r){let e=/<Image\s+[^>]*?\/?>/g,t=[],n=[],a=s,i,m=[];while((i=e.exec(s))!==null)m.push({match:i[0],index:i.index});for(let o=m.length-1;o>=0;o--){let{match:u}=m[o],l=na(u);if(l){let f=await r(l);if(a=a.replace(u,f.html),f.preloadLink)t.push(f.preloadLink);if(f.placeholderCss)n.push(f.placeholderCss)}}return{html:a,preloadLinks:t,styles:n}}function B(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var D=new Map;function Pl(){D.clear()}async function X(s,r){let e=`${s}:${JSON.stringify(r)}`;if(D.has(e))return D.get(e);try{let t=await Te(s,r);return D.set(e,t),t}catch{return null}}function ra(){return xt({name:"image",hasEndTag:!1,description:"Render an optimized image with responsive variants",transform:async(s,r,e)=>{let{src:t,alt:n,options:a}=se(s,r,e);if(!t)return console.warn("@image directive: missing src argument"),"<!-- @image: missing src -->";let i={widths:a.widths||(a.width?[a.width]:Q),formats:a.formats||ee,quality:a.quality||te,placeholder:(a.placeholder==="color"?"dominant-color":a.placeholder)||"none"};if(!await me())return q(t,n||"",a);let o=await X(t,i);if(!o)return q(t,n||"",a);return ae(o,n||"",a)}})}function se(s,r,e){if(r.src)return{src:String(r.src),alt:String(r.alt||""),options:r.options||{}};let n=s.trim();if(n.startsWith("@image(")||n.startsWith("("))n=n.replace(/^@image\(/,"").replace(/^\(/,"").replace(/\)$/,"");let a=re(n),i=a[0]||"",m=a[1]||"",o={};if(i&&!i.startsWith("/")&&!i.startsWith(".")&&!i.startsWith("http")){let u=e[i];if(typeof u==="string")i=u}if(a[2])try{if(typeof a[2]==="string")o=JSON.parse(a[2]);else o=a[2]}catch{}return{src:i,alt:m,options:o}}function re(s){let r=[],e="",t=!1,n="",a=0,i=0;for(let m=0;m<s.length;m++){let o=s[m],u=m>0?s[m-1]:"";if((o==='"'||o==="'")&&u!=="\\"){if(!t)t=!0,n=o;else if(o===n)t=!1,n="";else e+=o;continue}if(!t){if(o==="{")a++;if(o==="}")a--;if(o==="[")i++;if(o==="]")i--;if(o===","&&a===0&&i===0){r.push(e.trim()),e="";continue}}e+=o}if(e.trim())r.push(e.trim());return r}function q(s,r,e){let t=[`src="${x(s)}"`];if(r)t.push(`alt="${x(r)}"`);if(e.width)t.push(`width="${e.width}"`);if(e.height)t.push(`height="${e.height}"`);if(e.class)t.push(`class="${x(e.class)}"`);if(e.style)t.push(`style="${x(e.style)}"`);if(e.lazy!==!1)t.push('loading="lazy"');return t.push('decoding="async"'),`<img ${t.join(" ")} />`}function ae(s,r,e){let{variants:t,placeholder:n,width:a,height:i,aspectRatio:m}=s,o=new Map;for(let g of t){let p=o.get(g.format)||[];p.push(g),o.set(g.format,p)}let u=["avif","webp","jpeg","png"],l=[];for(let g of u){let p=o.get(g);if(p&&p.length>0){let v=gt(p),w=ne(g),I=e.sizes||"100vw";l.push(` <source type="${w}" srcset="${x(v)}" sizes="${x(I)}" />`)}}let f=o.get("jpeg")||[],y=f.length>0?f[Math.floor(f.length/2)]:t[Math.floor(t.length/2)],c=[`src="${y?.url||s.src}"`,`alt="${x(r)}"`];if(e.width||a)c.push(`width="${e.width||a}"`);if(e.height||i)c.push(`height="${e.height||i}"`);if(e.class)c.push(`class="${x(e.class)}"`);let h=[];if(m)h.push(`aspect-ratio: ${m.toFixed(4)}`);if(e.style)h.push(e.style);if(h.length>0)c.push(`style="${h.join("; ")}"`);if(e.lazy!==!1&&!e.priority)c.push('loading="lazy"');if(c.push('decoding="async"'),e.priority)c.push('fetchpriority="high"');let d=`<picture>
33
+ `.replace(/\s+/g," ").trim();return{html:`<img src="${r}" alt="${B(e)}"${I}${b}${w}${v}${A}${S}${F} ${C} />`}}function ra(s){let r=s.match(/<Image\s+([^>]*?)\/?>/);if(!r)return null;let e=r[1],t={},n=/(\w+)(?:=(?:"([^"]*)"|'([^']*)'|(\{[^}]+\})))?/g,a;while((a=n.exec(e))!==null){let[,i,m,o,u]=a,l=m??o??u??!0;switch(i){case"src":t.src=String(l);break;case"alt":t.alt=String(l);break;case"width":t.width=Number(l)||l;break;case"height":t.height=Number(l)||l;break;case"sizes":t.sizes=String(l);break;case"loading":t.loading=l;break;case"priority":t.priority=l===!0||l==="true";break;case"quality":t.quality=Number(l);break;case"placeholder":t.placeholder=l;break;case"class":t.class=String(l);break;case"style":t.style=String(l);break;case"decoding":t.decoding=l;break;case"fetchpriority":t.fetchpriority=l;break;case"objectFit":t.objectFit=l;break;case"objectPosition":t.objectPosition=String(l);break}}if(!t.src||!t.alt)return null;return t}async function Pl(s,r){let e=/<Image\s+[^>]*?\/?>/g,t=[],n=[],a=s,i,m=[];while((i=e.exec(s))!==null)m.push({match:i[0],index:i.index});for(let o=m.length-1;o>=0;o--){let{match:u}=m[o],l=ra(u);if(l){let f=await r(l);if(a=a.replace(u,f.html),f.preloadLink)t.push(f.preloadLink);if(f.placeholderCss)n.push(f.placeholderCss)}}return{html:a,preloadLinks:t,styles:n}}function B(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var D=new Map;function Il(){D.clear()}async function X(s,r){let e=`${s}:${JSON.stringify(r)}`;if(D.has(e))return D.get(e);try{let t=await Te(s,r);return D.set(e,t),t}catch{return null}}function sa(){return xt({name:"image",hasEndTag:!1,description:"Render an optimized image with responsive variants",transform:async(s,r,e)=>{let{src:t,alt:n,options:a}=se(s,r,e);if(!t)return console.warn("@image directive: missing src argument"),"<!-- @image: missing src -->";let i={widths:a.widths||(a.width?[a.width]:Q),formats:a.formats||ee,quality:a.quality||te,placeholder:(a.placeholder==="color"?"dominant-color":a.placeholder)||"none"};if(!await me())return q(t,n||"",a);let o=await X(t,i);if(!o)return q(t,n||"",a);return ae(o,n||"",a)}})}function se(s,r,e){if(r.src)return{src:String(r.src),alt:String(r.alt||""),options:r.options||{}};let n=s.trim();if(n.startsWith("@image(")||n.startsWith("("))n=n.replace(/^@image\(/,"").replace(/^\(/,"").replace(/\)$/,"");let a=re(n),i=a[0]||"",m=a[1]||"",o={};if(i&&!i.startsWith("/")&&!i.startsWith(".")&&!i.startsWith("http")){let u=e[i];if(typeof u==="string")i=u}if(a[2])try{if(typeof a[2]==="string")o=JSON.parse(a[2]);else o=a[2]}catch{}return{src:i,alt:m,options:o}}function re(s){let r=[],e="",t=!1,n="",a=0,i=0;for(let m=0;m<s.length;m++){let o=s[m],u=m>0?s[m-1]:"";if((o==='"'||o==="'")&&u!=="\\"){if(!t)t=!0,n=o;else if(o===n)t=!1,n="";else e+=o;continue}if(!t){if(o==="{")a++;if(o==="}")a--;if(o==="[")i++;if(o==="]")i--;if(o===","&&a===0&&i===0){r.push(e.trim()),e="";continue}}e+=o}if(e.trim())r.push(e.trim());return r}function q(s,r,e){let t=[`src="${x(s)}"`];if(r)t.push(`alt="${x(r)}"`);if(e.width)t.push(`width="${e.width}"`);if(e.height)t.push(`height="${e.height}"`);if(e.class)t.push(`class="${x(e.class)}"`);if(e.style)t.push(`style="${x(e.style)}"`);if(e.lazy!==!1)t.push('loading="lazy"');return t.push('decoding="async"'),`<img ${t.join(" ")} />`}function ae(s,r,e){let{variants:t,placeholder:n,width:a,height:i,aspectRatio:m}=s,o=new Map;for(let g of t){let p=o.get(g.format)||[];p.push(g),o.set(g.format,p)}let u=["avif","webp","jpeg","png"],l=[];for(let g of u){let p=o.get(g);if(p&&p.length>0){let v=gt(p),w=ne(g),I=e.sizes||"100vw";l.push(` <source type="${w}" srcset="${x(v)}" sizes="${x(I)}" />`)}}let f=o.get("jpeg")||[],y=f.length>0?f[Math.floor(f.length/2)]:t[Math.floor(t.length/2)],c=[`src="${y?.url||s.src}"`,`alt="${x(r)}"`];if(e.width||a)c.push(`width="${e.width||a}"`);if(e.height||i)c.push(`height="${e.height||i}"`);if(e.class)c.push(`class="${x(e.class)}"`);let h=[];if(m)h.push(`aspect-ratio: ${m.toFixed(4)}`);if(e.style)h.push(e.style);if(h.length>0)c.push(`style="${h.join("; ")}"`);if(e.lazy!==!1&&!e.priority)c.push('loading="lazy"');if(c.push('decoding="async"'),e.priority)c.push('fetchpriority="high"');let d=`<picture>
34
34
  `;if(d+=l.join(`
35
35
  `)+`
36
36
  `,d+=` <img ${c.join(" ")} />
@@ -39,5 +39,5 @@ ${d}
39
39
  </div>`}else if(e.placeholder==="color"){let p=n.replace(/[^a-zA-Z0-9#(),.\s%-]/g,"");d=`<div id="${g}" class="stx-image-placeholder" style="background-color: ${p};">
40
40
  ${d}
41
41
  </div>`}}if(e.priority&&y){let g=ne(y.format);d=`<link rel="preload" as="image" href="${x(y.url)}" type="${g}" />
42
- `+d}return d}function x(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var Il=ra();import P from"fs";import j from"path";function Ol(s={}){let{inputDirs:r=["public","src/assets","assets"],outputDir:e="dist/images",baseUrl:t="/images",formats:n=ee,widths:a=Q,quality:i=te,placeholder:m="none",concurrency:o=4,cache:u=!0,cacheDir:l=".stx/image-cache",referencedOnly:f=!1,verbose:y=!1}=s,c={imageReferences:new Set,processedImages:new Map,stats:{totalImages:0,optimizedImages:0,savedBytes:0,variants:0}};return{name:"stx-image-optimization",async setup(h){if(!await me()){console.warn("[stx-images] no image backend available, optimization disabled");return}if(u)await P.promises.mkdir(l,{recursive:!0});if(y){let g=await Nn();console.log("[stx-images] Plugin initialized"),console.log(` Backend: ${g?"sharp (native fast path) + ts-images":"ts-images (pure TS)"}`),console.log(` Input dirs: ${r.join(", ")}`),console.log(` Output dir: ${e}`),console.log(` Formats: ${n.join(", ")}`),console.log(` Widths: ${a.join(", ")}`)}},async buildStart(){c.imageReferences.clear(),c.processedImages.clear(),c.stats={totalImages:0,optimizedImages:0,savedBytes:0,variants:0}},async transform(h,d){if(d.endsWith(".html")||d.endsWith(".stx")){let g=ie(h);for(let p of g)c.imageReferences.add(p)}if(h.includes("<Image")||h.includes("@image"))return await ce(h,{formats:n,widths:a,quality:i,placeholder:m,outputDir:e,baseUrl:t,processedImages:c.processedImages});return h},async buildEnd(h){if(!await me())return;await P.promises.mkdir(e,{recursive:!0});let g=[];for(let w of r){if(!P.existsSync(w))continue;let I=await N(w);g.push(...I)}let p=f?g.filter((w)=>oe(w,c.imageReferences)):g;if(c.stats.totalImages=p.length,y)console.log(`[stx-images] Processing ${p.length} images...`);let v=W(p,o);for(let w of v)await Promise.all(w.map(async(I)=>{try{let b=await Te(I,{formats:n,widths:a,quality:i,placeholder:m,outputDir:e,baseUrl:t});c.processedImages.set(I,b),c.stats.optimizedImages++,c.stats.variants+=b.variants.length;let A=P.statSync(I).size,S=jn(b.variants);if(c.stats.savedBytes+=Math.max(0,A-S/b.variants.length),y)console.log(` \u2713 ${j.basename(I)} \u2192 ${b.variants.length} variants`)}catch(b){console.error(`[stx-images] Error processing ${I}:`,b)}}));if(console.log("[stx-images] Optimization complete:"),console.log(` Images: ${c.stats.optimizedImages}/${c.stats.totalImages}`),console.log(` Variants: ${c.stats.variants}`),c.stats.savedBytes>0)console.log(` Saved: ~${Bn(c.stats.savedBytes)}`)}}}function ie(s){let r=[],e=/src=["']([^"']+\.(jpg|jpeg|png|webp|avif|gif))["']/gi,t;while((t=e.exec(s))!==null)r.push(t[1]);let n=/<Image[^>]+src=["']([^"']+)["']/gi;while((t=n.exec(s))!==null)r.push(t[1]);let a=/@image\s*\(\s*['"]([^'"]+)['"]/gi;while((t=a.exec(s))!==null)r.push(t[1]);let i=/background(?:-image)?:\s*url\(["']?([^"')]+\.(jpg|jpeg|png|webp|avif|gif))["']?\)/gi;while((t=i.exec(s))!==null)r.push(t[1]);return r}function oe(s,r){let e=j.basename(s);for(let t of r)if(t.endsWith(e)||t.includes(e))return!0;return!1}async function ce(s,r){return s}async function N(s){let r=[];async function e(t){let n=await P.promises.readdir(t,{withFileTypes:!0});for(let a of n){let i=j.join(t,a.name);if(a.isDirectory())await e(i);else if(a.isFile()&&Ln(i))r.push(i)}}return await e(s),r}function W(s,r){let e=[];for(let t=0;t<s.length;t+=r)e.push(s.slice(t,t+r));return e}async function Nl(s,r,e={}){if(!await me())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");return Te(s,{...e,outputDir:r})}async function Ml(s,r,e={}){let{formats:t=ee,widths:n=Q,quality:a=te,placeholder:i="none",concurrency:m=4,verbose:o=!1}=e;if(!await me())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");await P.promises.mkdir(r,{recursive:!0});let l=await N(s),f=[],y={totalImages:l.length,optimizedImages:0,savedBytes:0,variants:0},c=W(l,m);for(let h of c){let d=await Promise.all(h.map(async(g)=>{try{let p=await Te(g,{formats:t,widths:n,quality:a,placeholder:i,outputDir:r,baseUrl:"/"});if(y.optimizedImages++,y.variants+=p.variants.length,o)console.log(` \u2713 ${j.basename(g)}`);return p}catch(p){return console.error(`Error processing ${g}:`,p),null}}));f.push(...d.filter((g)=>g!==null))}return{processed:f,stats:y}}function sa(s){let r={};for(let e of s)r[e.src]={variants:e.variants,placeholder:e.placeholder};return r}async function Dl(s,r){let e=sa(s);await Bun.write(r,JSON.stringify(e,null,2))}var Yg={enabled:!0,widths:[320,640,768,1024,1280,1536,1920],formats:["webp","jpeg"],quality:80,devOptimize:!1,cacheDir:".stx/image-cache",placeholder:"none",inputDirs:["public","src/assets","assets"],outputDir:"dist/images",baseUrl:"/images"};
43
- export{Rl,na,Al,Pl,ra,Il,Ol,Nl,Ml,sa,Dl,Yg};
42
+ `+d}return d}function x(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var Ol=sa();import P from"fs";import j from"path";function Nl(s={}){let{inputDirs:r=["public","src/assets","assets"],outputDir:e="dist/images",baseUrl:t="/images",formats:n=ee,widths:a=Q,quality:i=te,placeholder:m="none",concurrency:o=4,cache:u=!0,cacheDir:l=".stx/image-cache",referencedOnly:f=!1,verbose:y=!1}=s,c={imageReferences:new Set,processedImages:new Map,stats:{totalImages:0,optimizedImages:0,savedBytes:0,variants:0}};return{name:"stx-image-optimization",async setup(h){if(!await me()){console.warn("[stx-images] no image backend available, optimization disabled");return}if(u)await P.promises.mkdir(l,{recursive:!0});if(y){let g=await Nn();console.log("[stx-images] Plugin initialized"),console.log(` Backend: ${g?"sharp (native fast path) + ts-images":"ts-images (pure TS)"}`),console.log(` Input dirs: ${r.join(", ")}`),console.log(` Output dir: ${e}`),console.log(` Formats: ${n.join(", ")}`),console.log(` Widths: ${a.join(", ")}`)}},async buildStart(){c.imageReferences.clear(),c.processedImages.clear(),c.stats={totalImages:0,optimizedImages:0,savedBytes:0,variants:0}},async transform(h,d){if(d.endsWith(".html")||d.endsWith(".stx")){let g=ie(h);for(let p of g)c.imageReferences.add(p)}if(h.includes("<Image")||h.includes("@image"))return await ce(h,{formats:n,widths:a,quality:i,placeholder:m,outputDir:e,baseUrl:t,processedImages:c.processedImages});return h},async buildEnd(h){if(!await me())return;await P.promises.mkdir(e,{recursive:!0});let g=[];for(let w of r){if(!P.existsSync(w))continue;let I=await N(w);g.push(...I)}let p=f?g.filter((w)=>oe(w,c.imageReferences)):g;if(c.stats.totalImages=p.length,y)console.log(`[stx-images] Processing ${p.length} images...`);let v=W(p,o);for(let w of v)await Promise.all(w.map(async(I)=>{try{let b=await Te(I,{formats:n,widths:a,quality:i,placeholder:m,outputDir:e,baseUrl:t});c.processedImages.set(I,b),c.stats.optimizedImages++,c.stats.variants+=b.variants.length;let A=P.statSync(I).size,S=jn(b.variants);if(c.stats.savedBytes+=Math.max(0,A-S/b.variants.length),y)console.log(` \u2713 ${j.basename(I)} \u2192 ${b.variants.length} variants`)}catch(b){console.error(`[stx-images] Error processing ${I}:`,b)}}));if(console.log("[stx-images] Optimization complete:"),console.log(` Images: ${c.stats.optimizedImages}/${c.stats.totalImages}`),console.log(` Variants: ${c.stats.variants}`),c.stats.savedBytes>0)console.log(` Saved: ~${Bn(c.stats.savedBytes)}`)}}}function ie(s){let r=[],e=/src=["']([^"']+\.(jpg|jpeg|png|webp|avif|gif))["']/gi,t;while((t=e.exec(s))!==null)r.push(t[1]);let n=/<Image[^>]+src=["']([^"']+)["']/gi;while((t=n.exec(s))!==null)r.push(t[1]);let a=/@image\s*\(\s*['"]([^'"]+)['"]/gi;while((t=a.exec(s))!==null)r.push(t[1]);let i=/background(?:-image)?:\s*url\(["']?([^"')]+\.(jpg|jpeg|png|webp|avif|gif))["']?\)/gi;while((t=i.exec(s))!==null)r.push(t[1]);return r}function oe(s,r){let e=j.basename(s);for(let t of r)if(t.endsWith(e)||t.includes(e))return!0;return!1}async function ce(s,r){return s}async function N(s){let r=[];async function e(t){let n=await P.promises.readdir(t,{withFileTypes:!0});for(let a of n){let i=j.join(t,a.name);if(a.isDirectory())await e(i);else if(a.isFile()&&Ln(i))r.push(i)}}return await e(s),r}function W(s,r){let e=[];for(let t=0;t<s.length;t+=r)e.push(s.slice(t,t+r));return e}async function Ml(s,r,e={}){if(!await me())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");return Te(s,{...e,outputDir:r})}async function Dl(s,r,e={}){let{formats:t=ee,widths:n=Q,quality:a=te,placeholder:i="none",concurrency:m=4,verbose:o=!1}=e;if(!await me())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");await P.promises.mkdir(r,{recursive:!0});let l=await N(s),f=[],y={totalImages:l.length,optimizedImages:0,savedBytes:0,variants:0},c=W(l,m);for(let h of c){let d=await Promise.all(h.map(async(g)=>{try{let p=await Te(g,{formats:t,widths:n,quality:a,placeholder:i,outputDir:r,baseUrl:"/"});if(y.optimizedImages++,y.variants+=p.variants.length,o)console.log(` \u2713 ${j.basename(g)}`);return p}catch(p){return console.error(`Error processing ${g}:`,p),null}}));f.push(...d.filter((g)=>g!==null))}return{processed:f,stats:y}}function oa(s){let r={};for(let e of s)r[e.src]={variants:e.variants,placeholder:e.placeholder};return r}async function Ll(s,r){let e=oa(s);await Bun.write(r,JSON.stringify(e,null,2))}var Zg={enabled:!0,widths:[320,640,768,1024,1280,1536,1920],formats:["webp","jpeg"],quality:80,devOptimize:!1,cacheDir:".stx/image-cache",placeholder:"none",inputDirs:["public","src/assets","assets"],outputDir:"dist/images",baseUrl:"/images"};
43
+ export{Al,ra,Pl,Il,sa,Ol,Nl,Ml,Dl,oa,Ll,Zg};