@stacksjs/stx 0.2.588 → 0.2.589

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 (163) hide show
  1. package/dist/{chunk-s043hpvd.js → chunk-04gt67sv.js} +1 -1
  2. package/dist/chunk-122y2fkw.js +3 -0
  3. package/dist/chunk-138zjhwa.js +2 -0
  4. package/dist/{chunk-751b5zv9.js → chunk-14t0wps0.js} +1 -1
  5. package/dist/{chunk-03qf2z4d.js → chunk-18ws9heh.js} +1 -1
  6. package/dist/{chunk-33q5zka4.js → chunk-1944jgb2.js} +1 -1
  7. package/dist/{chunk-tc15vkfh.js → chunk-25zpd110.js} +2 -2
  8. package/dist/{chunk-emxa2djv.js → chunk-2qt63502.js} +1 -1
  9. package/dist/{chunk-qhr1tkhj.js → chunk-38mt83wa.js} +6 -6
  10. package/dist/chunk-3bx12g3y.js +2 -0
  11. package/dist/{chunk-j8v5164e.js → chunk-3q312svf.js} +1 -1
  12. package/dist/chunk-3vcvsc17.js +2 -0
  13. package/dist/{chunk-k1szsenr.js → chunk-48s1nprc.js} +2 -2
  14. package/dist/{chunk-qf3axv86.js → chunk-4st1qw62.js} +2 -2
  15. package/dist/chunk-55bmmwtx.js +2 -0
  16. package/dist/{chunk-cqr5cv7h.js → chunk-5rs5jnqk.js} +5 -5
  17. package/dist/chunk-64xcx3y4.js +2 -0
  18. package/dist/{chunk-y5x8xnnf.js → chunk-6eg9a3mt.js} +2 -2
  19. package/dist/{chunk-3qmx12d3.js → chunk-6qnemg0e.js} +298 -298
  20. package/dist/{chunk-ww28zfwt.js → chunk-7b0svfg0.js} +1 -1
  21. package/dist/chunk-7frsbxzd.js +2 -0
  22. package/dist/chunk-7nr3f2bw.js +2 -0
  23. package/dist/chunk-83rmpb0b.js +2 -0
  24. package/dist/chunk-88mj71mb.js +2 -0
  25. package/dist/{chunk-9qsnq026.js → chunk-9cgga2aw.js} +2 -2
  26. package/dist/{chunk-45x4myqe.js → chunk-9e49fnj9.js} +2 -2
  27. package/dist/{chunk-f29fk7dw.js → chunk-9h1ytsgm.js} +2 -2
  28. package/dist/{chunk-jtx74677.js → chunk-9q079ttt.js} +1 -1
  29. package/dist/chunk-9t6gzmze.js +2 -0
  30. package/dist/{chunk-vf15db1j.js → chunk-9wtb959p.js} +5 -5
  31. package/dist/{chunk-794v5crp.js → chunk-9x4r15mv.js} +2 -2
  32. package/dist/{chunk-pxw4edw8.js → chunk-a7crvy3b.js} +2 -2
  33. package/dist/chunk-acm2tym9.js +2 -0
  34. package/dist/{chunk-c6egfhy6.js → chunk-b3c1gggs.js} +2 -2
  35. package/dist/chunk-bd5gxtt2.js +2 -0
  36. package/dist/chunk-bepj7q9j.js +2 -0
  37. package/dist/{chunk-t212h9zm.js → chunk-cxhqps9m.js} +1 -1
  38. package/dist/chunk-d81h4mxd.js +2 -0
  39. package/dist/{chunk-b217d16p.js → chunk-dbp1sj5f.js} +36 -36
  40. package/dist/chunk-dgtxj56t.js +3 -0
  41. package/dist/chunk-ds66kaac.js +127 -0
  42. package/dist/chunk-emx9v5z8.js +2 -0
  43. package/dist/chunk-eqa0wdv9.js +4 -0
  44. package/dist/{chunk-haag5n42.js → chunk-f17rcvdb.js} +1 -1
  45. package/dist/chunk-ffykng6w.js +2 -0
  46. package/dist/{chunk-076h7nb9.js → chunk-fjw3sn55.js} +5 -5
  47. package/dist/chunk-fn9gdw2x.js +2 -0
  48. package/dist/{chunk-bhg4pvtn.js → chunk-frm8k9gj.js} +1 -1
  49. package/dist/chunk-fwt5fh5w.js +2 -0
  50. package/dist/{chunk-m7ddgrsm.js → chunk-g6ew2drc.js} +4 -4
  51. package/dist/{chunk-6cg03r93.js → chunk-g7fjra7a.js} +4 -4
  52. package/dist/{chunk-03xsf9jm.js → chunk-gh181dnr.js} +8 -8
  53. package/dist/{chunk-6hgngmn0.js → chunk-gzpxvca7.js} +1 -1
  54. package/dist/{chunk-d0tmc6v5.js → chunk-h9gbsgrt.js} +1 -1
  55. package/dist/{chunk-qx0tcsdm.js → chunk-hhcmn37g.js} +3 -3
  56. package/dist/chunk-hhwnd24n.js +2 -0
  57. package/dist/chunk-hq4mtcp0.js +2 -0
  58. package/dist/{chunk-7fghm9zy.js → chunk-j1dmkt29.js} +1 -1
  59. package/dist/chunk-jhswy523.js +2 -0
  60. package/dist/{chunk-mmbspaqh.js → chunk-jtq8e3b0.js} +2 -2
  61. package/dist/chunk-jyqanvwp.js +2 -0
  62. package/dist/chunk-k6bmhf83.js +2 -0
  63. package/dist/{chunk-3ybbat49.js → chunk-khdvzjzd.js} +1 -1
  64. package/dist/{chunk-q03kn4d1.js → chunk-krvaknk7.js} +1 -1
  65. package/dist/{chunk-30acme5g.js → chunk-kx52xt96.js} +2 -2
  66. package/dist/chunk-m0ngddr1.js +2 -0
  67. package/dist/{chunk-yhhfxx17.js → chunk-mkmgy50k.js} +4 -4
  68. package/dist/chunk-n06xznty.js +2 -0
  69. package/dist/{chunk-048eyjyj.js → chunk-nb0ytx70.js} +2 -2
  70. package/dist/chunk-nft0k8sy.js +2 -0
  71. package/dist/{chunk-wkrf41se.js → chunk-nmfnstjg.js} +1 -1
  72. package/dist/chunk-p69ay3bg.js +2 -0
  73. package/dist/{chunk-hj8tr9g0.js → chunk-p9yqetnj.js} +1 -1
  74. package/dist/{chunk-07869zev.js → chunk-pb7vste8.js} +3 -3
  75. package/dist/chunk-pbvtyw5h.js +2 -0
  76. package/dist/{chunk-a30mtx17.js → chunk-ph2hzxz7.js} +2 -2
  77. package/dist/chunk-pq9yr5f5.js +2 -0
  78. package/dist/chunk-q5rqp7rm.js +2 -0
  79. package/dist/{chunk-cy07dhqh.js → chunk-q66ry997.js} +2 -2
  80. package/dist/{chunk-pg164sdw.js → chunk-q6h6yjg4.js} +2 -2
  81. package/dist/{chunk-91pdg853.js → chunk-qf39z0hg.js} +3 -3
  82. package/dist/chunk-qhy84exn.js +2 -0
  83. package/dist/chunk-san161h4.js +2 -0
  84. package/dist/{chunk-7ydavm3h.js → chunk-shnsvsg4.js} +2 -2
  85. package/dist/{chunk-kfhghjh6.js → chunk-shnvs7x9.js} +2 -2
  86. package/dist/{chunk-s2h601k7.js → chunk-sjehpstn.js} +7 -7
  87. package/dist/{chunk-w24qmxc3.js → chunk-t19th11m.js} +1 -1
  88. package/dist/{chunk-awgvt956.js → chunk-tc3ne706.js} +9 -9
  89. package/dist/chunk-td7a6wwq.js +2 -0
  90. package/dist/{chunk-3y5tzxm6.js → chunk-tds3d65g.js} +2 -2
  91. package/dist/{chunk-mnnxa3r7.js → chunk-vhgdz0qf.js} +2 -2
  92. package/dist/{chunk-j7kcjgxy.js → chunk-vn6h03nq.js} +68 -40
  93. package/dist/chunk-w3k1r8r5.js +2 -0
  94. package/dist/{chunk-e556dvy4.js → chunk-wkxzzdzs.js} +2 -2
  95. package/dist/{chunk-ns1jqzqk.js → chunk-wr6gw263.js} +1 -1
  96. package/dist/chunk-wrp7m33d.js +2 -0
  97. package/dist/{chunk-7xw1e8t6.js → chunk-y0qjpcc8.js} +3 -3
  98. package/dist/chunk-y3g9jaa4.js +2 -0
  99. package/dist/{chunk-fkq55rh7.js → chunk-y3wdf7v7.js} +1 -1
  100. package/dist/chunk-y6909jm7.js +2 -0
  101. package/dist/{chunk-ede39b7h.js → chunk-zvs13kgh.js} +2 -2
  102. package/dist/cli.js +14 -14
  103. package/dist/client/signals-component-hydration-runtime.js +57 -29
  104. package/dist/craft-entry.js +1 -1
  105. package/dist/craft.js +1 -1
  106. package/dist/dev-server/ts-css.js +7 -2
  107. package/dist/native/compiler/app-theme.d.ts +9 -0
  108. package/dist/native/compiler/app-theme.js +51 -0
  109. package/dist/native/compiler/bundle.js +7 -3
  110. package/dist/native/compiler/headwind-to-style.d.ts +6 -0
  111. package/dist/native/compiler/headwind-to-style.js +7 -0
  112. package/dist/native/compiler/html-to-ir.js +7 -1
  113. package/dist/native/compiler/render-screen.js +2 -1
  114. package/dist/native/ui.d.ts +90 -0
  115. package/dist/native/ui.js +37 -0
  116. package/dist/pwa.js +3 -3
  117. package/dist/ssg.js +10 -10
  118. package/dist/theme-tokens.d.ts +38 -3
  119. package/dist/theme-tokens.js +18 -6
  120. package/dist/ts-css-config.d.ts +1 -0
  121. package/dist/ts-css-config.js +4 -3
  122. package/package.json +5 -5
  123. package/dist/chunk-11jmasqb.js +0 -2
  124. package/dist/chunk-2wx2aczp.js +0 -2
  125. package/dist/chunk-4dpab4j6.js +0 -2
  126. package/dist/chunk-4vnwge6p.js +0 -2
  127. package/dist/chunk-4w37cqg9.js +0 -2
  128. package/dist/chunk-51pz8cwa.js +0 -2
  129. package/dist/chunk-65agttgm.js +0 -2
  130. package/dist/chunk-7ae40484.js +0 -2
  131. package/dist/chunk-7dtyf7hq.js +0 -2
  132. package/dist/chunk-7ebt9n43.js +0 -4
  133. package/dist/chunk-80g8kaes.js +0 -2
  134. package/dist/chunk-9pk5jhqa.js +0 -3
  135. package/dist/chunk-a3d5g1ss.js +0 -122
  136. package/dist/chunk-a3k4nfq2.js +0 -2
  137. package/dist/chunk-c8fdccgp.js +0 -2
  138. package/dist/chunk-cw76edds.js +0 -2
  139. package/dist/chunk-czrs87r9.js +0 -2
  140. package/dist/chunk-d9vjsqs4.js +0 -2
  141. package/dist/chunk-ddgyj88h.js +0 -2
  142. package/dist/chunk-dj90w48e.js +0 -2
  143. package/dist/chunk-dngzks8e.js +0 -2
  144. package/dist/chunk-eztvhppz.js +0 -2
  145. package/dist/chunk-h2534p6q.js +0 -2
  146. package/dist/chunk-h9gtc6bk.js +0 -2
  147. package/dist/chunk-hwnvfke9.js +0 -2
  148. package/dist/chunk-hygxh993.js +0 -2
  149. package/dist/chunk-jqy5q8m0.js +0 -2
  150. package/dist/chunk-jy7yzat1.js +0 -2
  151. package/dist/chunk-n7yk4nc1.js +0 -2
  152. package/dist/chunk-qd4snptd.js +0 -2
  153. package/dist/chunk-r90v2jz6.js +0 -2
  154. package/dist/chunk-rtgf9fgc.js +0 -2
  155. package/dist/chunk-sjkdpsca.js +0 -3
  156. package/dist/chunk-sqpme1hg.js +0 -2
  157. package/dist/chunk-thydj877.js +0 -2
  158. package/dist/chunk-vv1kr9dn.js +0 -2
  159. package/dist/chunk-wm9nzg76.js +0 -2
  160. package/dist/chunk-x5qymgxa.js +0 -2
  161. package/dist/chunk-xnbkyj4g.js +0 -2
  162. package/dist/chunk-xyepqdjy.js +0 -2
  163. package/dist/chunk-y93y2qat.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{G,b,fn,gn,e,Pt,bn,f,Ve,It,Ue,We,te,L,de,J,u,xe,Ri,Os,n,r,ne,dr,o,P,pe}from"./chunk-3qmx12d3.js";import{Y,An,re,I,Lt}from"./chunk-qhr1tkhj.js";import{rt,Nn,_r,Er,Tr,st,ot,it,at,ct,lt,Ee}from"./chunk-pxw4edw8.js";import{Oe,Co,se,T,_o,Fr,Un,ye,Eo,oe}from"./chunk-076h7nb9.js";import{Ft}from"./chunk-kfhghjh6.js";import{le}from"./chunk-3y5tzxm6.js";import{a}from"./chunk-sjkdpsca.js";import{N}from"./chunk-ede39b7h.js";async function Gn(t){try{let s=await Bun.file(t).text(),i=Jn(s),d=Yn(s,t),c=Qn(s,i),l=Zn(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Jn(t){let s=t.split(`
2
+ import{G,b,hn,yn,e,Dt,wn,f,Ge,Nt,Ke,Xe,ne,L,fe,J,u,_e,Ri,Os,n,r,re,dr,o,P,ge}from"./chunk-6qnemg0e.js";import{Y,In,se,I,Ft}from"./chunk-38mt83wa.js";import{at,Ln,_r,Er,Tr,ct,lt,ut,dt,pt,ft,Ae}from"./chunk-a7crvy3b.js";import{Le,Co,oe,T,_o,Fr,qn,ve,Eo,ie}from"./chunk-fjw3sn55.js";import{Vt}from"./chunk-shnvs7x9.js";import{ue}from"./chunk-tds3d65g.js";import{a}from"./chunk-dgtxj56t.js";import{N}from"./chunk-zvs13kgh.js";async function Gn(t){try{let s=await Bun.file(t).text(),i=Jn(s),d=Yn(s,t),c=Qn(s,i),l=Zn(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Jn(t){let s=t.split(`
3
3
  `),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[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 m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+p+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,R=0;for(let C of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,S=Math.max(S,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function Yn(t,s){let i=[],d=Jt(t,"if","endif");if(d>0)i.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Jt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} 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)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let y=p.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
5
- `).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Qn(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.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)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Zn(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:d,recommendations:c}}function Jt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function uo(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await Gn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Pe from"path";function rn(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 on=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Bt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(d){let c=await rr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Pe.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function pr(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=m.exec(l)){let h=p[1];if(on.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}return i}function ur(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
5
+ `).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Qn(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.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)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Zn(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:d,recommendations:c}}function Jt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function uo(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await Gn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Re from"path";function rn(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 on=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.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 ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(d){let c=await rr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Re.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function pr(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=m.exec(l)){let h=p[1];if(on.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}return i}function ur(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
6
6
 
7
7
  `)}function fr(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function mr(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 gr(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 hr(t){let s=[],i=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(d[h]!=="(")return null;let g=0,y="";for(let w=h;w<d.length;w++){let S=d[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:d.slice(h+1,w),end:w+1}}}return null},p=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(d)){p(d.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,R,v]=w;s.push(R?`for (const [${R}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return p(d.slice(i)),s.join(`
8
- `)}function bt(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function jt(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function yr(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Zt(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 br(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let R="";if(h(),t[p]==="<"){let k=bt(t,p,"<",">");if(k===-1)return null;R=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=bt(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;for(let[H,D]of Ht(t.slice(p,k)))l[H]=D;p=k}if(h(),t[p]===",")p++,h();if(t[p]===")")p++}if(t[p]===";")p++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of jt(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Ht(x)){if(m.push(k),!H.startsWith("{")){let D=Zt(H);if(D)c[k]=D;continue}for(let[D,_]of Ht(H))if(D==="default")l[k]=_;else if(D==="type"){let E=Zt(_);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of jt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of jt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=yr(k),_=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!_)continue;if(m.push(_),H!==-1)l[_]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(d,p),propNames:m,defaults:l,declared:c,typeName:C}}function Ht(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],d=0;while(d<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=d;let l=c.exec(s);if(!l)break;d=c.lastIndex;let m=0,p="",h=d;while(d<s.length){let y=s[d];if(p){if(y==="\\")d++;else if(y===p)p=""}else if(y==="'"||y==='"'||y==="`")p=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;d++}let g=s.slice(h,d).trim();if(g)i.push([l[1],g]);d++}return i}function xr(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],p=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Pe.resolve(Pe.dirname(s),x),H=Pe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${C}`})),""});let y=br(l);if(y)p.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let R=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!p.includes(S))p.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:p,defaults:h,declared:g}}function vr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,c,l,m,p)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${p}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function wr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,c,l,m)=>{let p=s.length;return s.push({id:p,name:c,expression:m}),` data-stx-bind-${p}=""`}),bindings:s}}function Sr(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function kr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function $r(t,s,i){let d=Pe.isAbsolute(s.file)?s.file:Pe.resolve(t,s.file),c=await nr(d,"utf8"),l=lr(c,d),m=Pe.basename(d,".stx"),p=s.name||l.name||sr(m),h=`${Bt(i.prefix||"stx")}-${Bt(m)}`,g=s.tag||l.tag||h;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!ir(g))throw Error(`${d}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([D,_])=>[D,en(D,_)])),S=vr(ur(c)),R=wr(S.template),v=xr(c,d,Pe.resolve(i.outputDir)),x=hr(R.template);for(let D of v.propNames){if(w[D])continue;let _=v.defaults[D];w[D]=en(D,{type:fr(v.declared[D])??mr(_),..._===void 0?{}:{default:gr(_)}})}let C=l.methods||{},k=s.methods||{},H=pr(c,d);return{file:Pe.relative(t,d),sourcePath:d,name:p,tag:g,description:s.description||l.description||"",template:R.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...H},eventTypes:S.eventTypes,bindings:R.bindings,slots:Sr(R.template),cssProperties:kr(Qt(c)),scope:v,render:x}}function Cr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
8
+ `)}function bt(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Lt(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function yr(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Zt(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 br(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let R="";if(h(),t[p]==="<"){let k=bt(t,p,"<",">");if(k===-1)return null;R=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=bt(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;for(let[H,D]of It(t.slice(p,k)))l[H]=D;p=k}if(h(),t[p]===",")p++,h();if(t[p]===")")p++}if(t[p]===";")p++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of Lt(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of It(x)){if(m.push(k),!H.startsWith("{")){let D=Zt(H);if(D)c[k]=D;continue}for(let[D,_]of It(H))if(D==="default")l[k]=_;else if(D==="type"){let E=Zt(_);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of Lt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of Lt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=yr(k),_=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!_)continue;if(m.push(_),H!==-1)l[_]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(d,p),propNames:m,defaults:l,declared:c,typeName:C}}function It(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],d=0;while(d<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=d;let l=c.exec(s);if(!l)break;d=c.lastIndex;let m=0,p="",h=d;while(d<s.length){let y=s[d];if(p){if(y==="\\")d++;else if(y===p)p=""}else if(y==="'"||y==='"'||y==="`")p=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;d++}let g=s.slice(h,d).trim();if(g)i.push([l[1],g]);d++}return i}function xr(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],p=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Re.resolve(Re.dirname(s),x),H=Re.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${C}`})),""});let y=br(l);if(y)p.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let R=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!p.includes(S))p.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:p,defaults:h,declared:g}}function vr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,c,l,m,p)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${p}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function wr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,c,l,m)=>{let p=s.length;return s.push({id:p,name:c,expression:m}),` data-stx-bind-${p}=""`}),bindings:s}}function Sr(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function kr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function $r(t,s,i){let d=Re.isAbsolute(s.file)?s.file:Re.resolve(t,s.file),c=await nr(d,"utf8"),l=lr(c,d),m=Re.basename(d,".stx"),p=s.name||l.name||sr(m),h=`${jt(i.prefix||"stx")}-${jt(m)}`,g=s.tag||l.tag||h;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!ir(g))throw Error(`${d}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([D,_])=>[D,en(D,_)])),S=vr(ur(c)),R=wr(S.template),v=xr(c,d,Re.resolve(i.outputDir)),x=hr(R.template);for(let D of v.propNames){if(w[D])continue;let _=v.defaults[D];w[D]=en(D,{type:fr(v.declared[D])??mr(_),..._===void 0?{}:{default:gr(_)}})}let C=l.methods||{},k=s.methods||{},H=pr(c,d);return{file:Re.relative(t,d),sourcePath:d,name:p,tag:g,description:s.description||l.description||"",template:R.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...H},eventTypes:S.eventTypes,bindings:R.bindings,slots:Sr(R.template),cssProperties:kr(Qt(c)),scope:v,render:x}}function Cr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -374,7 +374,7 @@ ${c}
374
374
  }
375
375
 
376
376
  export {}
377
- `}function Mr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,d])=>({kind:"field",name:i,description:d.description,type:{text:xt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||Bt(i),reflects:d.reflect})),events:Object.entries(s.events).map(([i,d])=>({name:i,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
377
+ `}function Mr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,d])=>({kind:"field",name:i,description:d.description,type:{text:xt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||jt(i),reflects:d.reflect})),events:Object.entries(s.events).map(([i,d])=>({name:i,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
378
378
  ${s}
379
379
  }`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Lr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
380
380
  `);return`const definitions = ${JSON.stringify(c,null,2)};
@@ -410,7 +410,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
410
410
  }
411
411
 
412
412
  ${l}
413
- `}async function po(t){let s=Pe.resolve(t.inputDir),i=Pe.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>$r(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let p=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Pe.join(i,x);return await or(k,C.endsWith(`
413
+ `}async function po(t){let s=Re.resolve(t.inputDir),i=Re.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>$r(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let p=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Re.join(i,x);return await or(k,C.endsWith(`
414
414
  `)?C:`${C}
415
415
  `,"utf8"),h.push(k),k};await g("runtime.js",Cr());for(let x of l){if(await g(`${x.tag}.js`,Rr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Pr(x));if(t.css!==!1&&x.styles){let C=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(C):C)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
416
  `);if(await g("index.js",y),await g("ssr.js",Lr(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
@@ -420,11 +420,11 @@ export declare function renderComponent(tag: string, props?: Record<string, unkn
420
420
  ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
421
421
  `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Mr(l),null,2));let S;if(t.css!==!1){let x=l.filter((C)=>!C.shadowMode&&C.styles).map(tn).join(`
422
422
 
423
- `);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Pe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Pe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],H=k.map((D)=>String(D).trim()).filter(Boolean).join(`
423
+ `);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Re.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Re.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],H=k.map((D)=>String(D).trim()).filter(Boolean).join(`
424
424
  `);throw AggregateError(k,`Failed to bundle component library${H?`
425
425
  ${H}`:""}`)}if(!x.success){let C=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
426
  `);throw AggregateError(x.logs,`Failed to bundle component library${C?`
427
- ${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Pe.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}var{serve:qr}=globalThis.Bun;import Nt from"fs";import pt from"path";function vt(){return`
427
+ ${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Re.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}var{serve:qr}=globalThis.Bun;import Bt from"fs";import ot from"path";function vt(){return`
428
428
  /* Theme selector for code blocks */
429
429
  .theme-selector {
430
430
  margin: 1rem 0;
@@ -504,19 +504,19 @@ else {
504
504
  <span class="frontmatter-label">${s}:</span>
505
505
  <span>${Array.isArray(i)?i.join(", "):String(i)}</span>
506
506
  </div>`).join("")}
507
- </div>`}import sn from"net";async function jr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await Br(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var zr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Nr(){try{let t=await import("./chunk-y8h823cb.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let i={...zr,...s},d=await Nr();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 c=await d.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
507
+ </div>`}import sn from"net";async function jr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await Br(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var zr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Nr(){try{let t=await import("./chunk-y8h823cb.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function rt(t,s={}){let i={...zr,...s},d=await Nr();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 c=await d.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
508
508
  ${l}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
- `,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let c=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function zt(){console.log(`
511
- Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Ur(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),zt()}function Wr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let d="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(d+=c,d.endsWith("\r")||d.endsWith(`
512
- `)){let l=d.trim().toLowerCase();d="",Vr(l,t,s,i)}})}function Vr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Wr(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Ur(s);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=pt.resolve(t);if(!Nt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await pe(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],H=[...new Set([...x,...C])].map((D)=>`<option value="${D}"${D===v?" selected":""}>${D}</option>`).join(`
510
+ `,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let c=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
511
+ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Ur(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function Wr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let d="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(d+=c,d.endsWith("\r")||d.endsWith(`
512
+ `)){let l=d.trim().toLowerCase();d="",Vr(l,t,s,i)}})}function Vr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Wr(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Ur(s);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Ht();break;default:break}}async function zt(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=ot.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await ge(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],H=[...new Set([...x,...C])].map((D)=>`<option value="${D}"${D===v?" selected":""}>${D}</option>`).join(`
513
513
  `);return l=`
514
514
  <!DOCTYPE html>
515
515
  <html lang="en">
516
516
  <head>
517
517
  <meta charset="UTF-8">
518
518
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
519
- <title>${Kr(S.title||pt.basename(c))}</title>
519
+ <title>${Kr(S.title||ot.basename(c))}</title>
520
520
  <!-- Syntax highlighting styles -->
521
521
  <style id="syntax-theme">
522
522
  :root {
@@ -676,8 +676,8 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
676
676
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
677
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
678
678
  ${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
679
- ${e.yellow}Routes:${e.reset}`);let y=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
680
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(d)Nt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(d){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Nt.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function Kr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gr}=globalThis.Bun;import Be from"fs";import Se from"path";class an{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let d=0;d<i;d++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let p=JSON.parse(m);if(p.type==="console"&&Array.isArray(p.args)){let h=p.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${y}[browser]${p.level!=="log"?` ${p.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let d of this.clients)try{if(d.readyState===1)d.send(s),i++}catch{this.clients.delete(d)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Xr(t,s={}){let{showOverlay:i=!0,reconnectInterval:d=1000,maxReconnectAttempts:c=10}=s;return`
679
+ ${e.yellow}Routes:${e.reset}`);let y=ot.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
680
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(d)Bt.watch(ot.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await rt(h,{title:ot.basename(c,".md")});if(d){let w=ot.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function Kr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gr}=globalThis.Bun;import Be from"fs";import we from"path";class an{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let d=0;d<i;d++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let p=JSON.parse(m);if(p.type==="console"&&Array.isArray(p.args)){let h=p.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${y}[browser]${p.level!=="log"?` ${p.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let d of this.clients)try{if(d.readyState===1)d.send(s),i++}catch{this.clients.delete(d)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Xr(t,s={}){let{showOverlay:i=!0,reconnectInterval:d=1000,maxReconnectAttempts:c=10}=s;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function Xe(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Et(t){if(!ut)ut=new an(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Ot from"path";var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Ot.relative(Ot.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await dr(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await fn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await re(()=>Bun.file(m).text(),"",(x)=>{throw new An(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new An(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=G.time("script-extraction",()=>{let x=h,C=te(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",D=[];for(let E of k){let M=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=E.match(/<script\b([^>]*)>/i),q=B?B[1]:"";if(/\bserver\b/i.test(q))H=M;else D.push(E)}let _=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:_,allScripts:D}}),S={__filename:m,__dirname:Ot.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await re(()=>u(g,S,m),void 0,(x)=>{let C=new Y(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(I.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await G.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-sqpme1hg.js"),C=x(w.join(`
879
+ `}function Ve(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function ht(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await dr(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await hn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await se(()=>Bun.file(m).text(),"",(x)=>{throw new In(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new In(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=G.time("script-extraction",()=>{let x=h,C=ne(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",D=[];for(let E of k){let M=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=E.match(/<script\b([^>]*)>/i),q=B?B[1]:"";if(/\bserver\b/i.test(q))H=M;else D.push(E)}let _=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:_,allScripts:D}}),S={__filename:m,__dirname:Pt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await se(()=>u(g,S,m),void 0,(x)=>{let C=new Y(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(I.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await G.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-55bmmwtx.js"),C=x(w.join(`
880
880
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
881
881
  `+v.slice(k);else v+=`
882
- ${C}`}if(v=await J(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await gn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new Y(`Plugin processing failed: ${String(p)}`,m);if(I.log(h,{filePath:m,buildConfig:t.config}),Lt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||N()?`<!DOCTYPE html>
882
+ ${C}`}if(v=await J(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await yn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new Y(`Plugin processing failed: ${String(p)}`,m);if(I.log(h,{filePath:m,buildConfig:t.config}),Ft.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||N()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -920,7 +920,7 @@ ${C}`}if(v=await J(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await gn
920
920
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
921
921
  <li>Verify that all variables used in the template are properly defined</li>
922
922
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
923
- <li>Run <code>stx debug ${b(Ot.basename(m))}</code> for detailed analysis</li>
923
+ <li>Run <code>stx debug ${b(Pt.basename(m))}</code> for detailed analysis</li>
924
924
  <li>Enable debug mode in your stx config for more detailed error messages</li>
925
925
  </ul>
926
926
  </div>
@@ -939,12 +939,12 @@ ${C}`}if(v=await J(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await gn
939
939
  <h1>Something went wrong</h1>
940
940
  <p>An internal error occurred. Please try again later.</p>
941
941
  </body>
942
- </html>`,loader:"html"}}})}};async function jn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=Se.resolve(t);if(!Be.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return Ut(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Be.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let M={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[M,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let q=B.outputs.find(($e)=>$e.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(q.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await y())return!1;let S=Se.dirname(p);await Pt(S);let R=i;try{if(R=await Ye(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let M=s.hmrPort||R+1;l=Et({wsPort:M,verbose:!1}),m=l.start(M)}let v={},x=null,C;try{let{loadStxConfig:M}=await import("./chunk-cw76edds.js"),B=await M();if(C=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Z}=await import("./chunk-wn2gzwmv.js"),$e=B.broadcasting;await q($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(Be.existsSync(De))try{let ae=await Z(De);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-r90v2jz6.js"),D=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let _=Gr({port:R,async fetch(M){return Ft(M,await(async()=>{let B=new URL(M.url);if([h,Se.dirname(p),Se.join(process.cwd(),"public")].some((ae)=>H(Se.join(ae,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(M);if(ae.status!==404)return ae}catch{}if(v[B.pathname])try{return await v[B.pathname](M)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await D(M);if(q)return q;if(B.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Z=Se.join(h,B.pathname);if(Be.existsSync(Z)&&Be.statSync(Z).isFile()){let ae=Bun.file(Z),U=Se.extname(Z).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=Fe.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let $e=Se.dirname(p),he=Se.join($e,B.pathname);if(Be.existsSync(he)&&Be.statSync(he).isFile()){let ae=Bun.file(he),U=Se.extname(he).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=Fe.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let De=Se.join(process.cwd(),"public",B.pathname);if(Be.existsSync(De)&&Be.statSync(De).isFile()){let ae=Bun.file(De),U=Se.extname(De).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=Fe.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
942
+ </html>`,loader:"html"}}})}};async function Fn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=we.resolve(t);if(!Be.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Be.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let M={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[M,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let q=B.outputs.find((Te)=>Te.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(q.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await y())return!1;let S=we.dirname(p);await Dt(S);let R=i;try{if(R=await Ye(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let M=s.hmrPort||R+1;l=Et({wsPort:M,verbose:!1}),m=l.start(M)}let v={},x=null,C;try{let{loadStxConfig:M}=await import("./chunk-san161h4.js"),B=await M();if(C=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Z}=await import("./chunk-wn2gzwmv.js"),Te=B.broadcasting;await q(Te);let he=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Pe=we.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ae=await Z(Pe);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-td7a6wwq.js"),D=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let _=Gr({port:R,async fetch(M){return Vt(M,await(async()=>{let B=new URL(M.url);if([h,we.dirname(p),we.join(process.cwd(),"public")].some((ae)=>H(we.join(ae,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(M);if(ae.status!==404)return ae}catch{}if(v[B.pathname])try{return await v[B.pathname](M)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await D(M);if(q)return q;if(B.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Ve(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Z=we.join(h,B.pathname);if(Be.existsSync(Z)&&Be.statSync(Z).isFile()){let ae=Bun.file(Z),U=we.extname(Z).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ae.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let Te=we.dirname(p),he=we.join(Te,B.pathname);if(Be.existsSync(he)&&Be.statSync(he).isFile()){let ae=Bun.file(he),U=we.extname(he).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ae.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let Pe=we.join(process.cwd(),"public",B.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ae=Bun.file(Pe),U=we.extname(Pe).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ae.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
943
943
  ${M.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
944
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
945
945
  ${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
946
- ${e.yellow}Routes:${e.reset}`);let E=Se.relative(process.cwd(),p);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
947
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(_.url.toString(),()=>{if(d)Be.watch(Se.dirname(p),{recursive:!0}).close();_.stop()}),s.native){let M=await Bun.file(p).text(),B=Tt(M);await dt(R,{title:Se.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(d){let M=Se.dirname(p);console.log(`${e.blue}Watching ${e.bright}${M}${e.reset} for changes...`);let B=Be.watch(M,{recursive:!0},async(q,Z)=>{if(!Z||Rt(Z))return;if(Ct(Z)){console.log(`${e.yellow}File ${e.bright}${Z}${e.yellow} changed, rebuilding...${e.reset}`),xe.clear(),ne();let $e=await y();if(await bn(S),c&&l)if($e)l.reload(Z);else l.error("Build failed - check console for details")}else if($t(Z)){if(console.log(`${e.cyan}CSS ${e.bright}${Z}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Z)}});process.on("SIGINT",()=>{if(B.close(),l)ht();_.stop(),process.exit(0)})}return!0}var{serve:Jr}=globalThis.Bun;import Ze from"fs";import Ae from"path";var cn=`
946
+ ${e.yellow}Routes:${e.reset}`);let E=we.relative(process.cwd(),p);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
947
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(_.url.toString(),()=>{if(d)Be.watch(we.dirname(p),{recursive:!0}).close();_.stop()}),s.native){let M=await Bun.file(p).text(),B=Tt(M);await rt(R,{title:we.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(d){let M=we.dirname(p);console.log(`${e.blue}Watching ${e.bright}${M}${e.reset} for changes...`);let B=Be.watch(M,{recursive:!0},async(q,Z)=>{if(!Z||Rt(Z))return;if(Ct(Z)){console.log(`${e.yellow}File ${e.bright}${Z}${e.yellow} changed, rebuilding...${e.reset}`),_e.clear(),re();let Te=await y();if(await wn(S),c&&l)if(Te)l.reload(Z);else l.error("Build failed - check console for details")}else if($t(Z)){if(console.log(`${e.cyan}CSS ${e.bright}${Z}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Z)}});process.on("SIGINT",()=>{if(B.close(),l)ht();_.stop(),process.exit(0)})}return!0}var{serve:Jr}=globalThis.Bun;import Ze from"fs";import Ee from"path";var cn=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,14 +1255,14 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function dn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Ae.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Ae.sep)}async function Bn(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=dn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await pe(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),D=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,_=D?.defaultTheme||"github-dark",E=["github-dark"],M=D?.additionalThemes||[],q=[...new Set([...E,...M])].map((De)=>`<option value="${De}"${De===_?" selected":""}>${De}</option>`).join(`
1258
+ `;function dn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Ee.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Ee.sep)}async function zn(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Ee.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=dn(t.map((v)=>Ee.dirname(Ee.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Ee.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await ge(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),D=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,_=D?.defaultTheme||"github-dark",E=["github-dark"],M=D?.additionalThemes||[],q=[...new Set([...E,...M])].map((Pe)=>`<option value="${Pe}"${Pe===_?" selected":""}>${Pe}</option>`).join(`
1259
1259
  `),Z=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
1262
1262
  <head>
1263
1263
  <meta charset="UTF-8">
1264
1264
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
- <title>${ln(H.title||Ae.basename(x))}</title>
1265
+ <title>${ln(H.title||Ee.basename(x))}</title>
1266
1266
  <!-- Syntax highlighting styles -->
1267
1267
  <style id="syntax-theme">
1268
1268
  :root {
@@ -1418,25 +1418,25 @@ else {
1418
1418
  </script>
1419
1419
  </body>
1420
1420
  </html>
1421
- `,he=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(M)=>({path:M.path,external:!0}))}},H;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,le(E.logs,x));continue}let M=E.outputs.find((B)=>B.path.endsWith(".html"));if(!M){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(M.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
- ${le(E,x)}`);continue}let _=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(_.endsWith("/index"))_=_.slice(0,-6)||"/";if(_.includes("[")){let{regex:E,params:M}=_r(_,{page:!0});p.push({pattern:E,paramNames:M,filePath:x,routeTemplate:_,fileType:"stx"}),m[_]={filePath:x,content:H,fileType:"stx"}}else m[_||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,le(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=Jr({port:y,async fetch(v){let x=new URL(v.url),C=Ae.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(C)&&Ze.statSync(C).isFile()){let D=Bun.file(C),_=Ae.extname(C).toLowerCase(),E="application/octet-stream";if(_===".ts"||_===".tsx"){let M=new Bun.Transpiler({loader:_===".tsx"?"tsx":"ts"}),B=await D.text(),q=M.transformSync(B);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(_){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let D of p){let _=x.pathname.match(D.pattern);if(_){let E=m[D.routeTemplate];if(E){let M={};for(let Z=0;Z<D.paramNames.length;Z++)M[D.paramNames[Z]]=decodeURIComponent(_[Z+1]);let B=E.content,q=`<script>window.__routeParams = ${JSON.stringify(M)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${q}
1421
+ `,he=`/${Ee.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(M)=>({path:M.path,external:!0}))}},H;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,it],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,ue(E.logs,x));continue}let M=E.outputs.find((B)=>B.path.endsWith(".html"));if(!M){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(M.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${ue(E,x)}`);continue}let _=`/${Ee.relative(l,x).replace(/\.stx$/,"")}`;if(_.endsWith("/index"))_=_.slice(0,-6)||"/";if(_.includes("[")){let{regex:E,params:M}=_r(_,{page:!0});p.push({pattern:E,paramNames:M,filePath:x,routeTemplate:_,fileType:"stx"}),m[_]={filePath:x,content:H,fileType:"stx"}}else m[_||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ue(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=Jr({port:y,async fetch(v){let x=new URL(v.url),C=Ee.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(C)&&Ze.statSync(C).isFile()){let D=Bun.file(C),_=Ee.extname(C).toLowerCase(),E="application/octet-stream";if(_===".ts"||_===".tsx"){let M=new Bun.Transpiler({loader:_===".tsx"?"tsx":"ts"}),B=await D.text(),q=M.transformSync(B);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(_){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let D of p){let _=x.pathname.match(D.pattern);if(_){let E=m[D.routeTemplate];if(E){let M={};for(let Z=0;Z<D.paramNames.length;Z++)M[D.paramNames[Z]]=decodeURIComponent(_[Z+1]);let B=E.content,q=`<script>window.__routeParams = ${JSON.stringify(M)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${q}
1423
1423
  </head>`);else B=q+B;k={...E,content:B}}break}}if(k)return f(k.content).then((D)=>{if(D.includes("</head>"))D=D.replace("</head>",`${cn}
1424
- </head>`);return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Ae.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let D=Bun.file(H),_=Ae.extname(H).toLowerCase(),E="text/plain";if(_===".ts"||_===".tsx"){let M=new Bun.Transpiler({loader:_===".tsx"?"tsx":"ts"}),B=await D.text(),q=M.transformSync(B);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(_){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let D=se(v);return f(m["/"].content).then((_)=>{if(D){let E=_.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let M=_.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=M?M[1]:"",q=`<!DOCTYPE html><html><head><title>${ln(B)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(q,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":Oe,Pragma:"no-cache",Expires:"0"}})}}return new Response(_,{headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1424
+ </head>`);return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Ee.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let D=Bun.file(H),_=Ee.extname(H).toLowerCase(),E="text/plain";if(_===".ts"||_===".tsx"){let M=new Bun.Transpiler({loader:_===".tsx"?"tsx":"ts"}),B=await D.text(),q=M.transformSync(B);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(_){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let D=oe(v);return f(m["/"].content).then((_)=>{if(D){let E=_.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let M=_.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=M?M[1]:"",q=`<!DOCTYPE html><html><head><title>${ln(B)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(q,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":Le,Pragma:"no-cache",Expires:"0"}})}}return new Response(_,{headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1425
1425
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1426
1426
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1427
1427
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
1428
- ${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),xe.clear(),ne(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Yr}=globalThis.Bun;import ve from"fs";import ie from"path";async function pn(t){try{return It(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),i=ie.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(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function Fn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-cw76edds.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-r90v2jz6.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?ie.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=ie.join(v,x);if(!ve.existsSync(C)&&!g._layerPageDirs?.some((O)=>ve.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],D=[];for(let{dir:O,prefix:F}of H)if(ve.existsSync(O)){let z=L(ie.dirname(O),{pagesDir:ie.basename(O)});for(let W of z){let we=F==="/"?W.pattern:`${F}${W.pattern==="/"?"":W.pattern}`;D.push({route:{...W,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let _=new Map,E=null,M=null;if(s.stxOptions?.shell!==!1){if(M=await _o(p,s.stxOptions?.shell),M){if(E=await Fr(M,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(p,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}st(),await it(p);let B=ot();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let q={},Z=null;try{let{loadStxConfig:O}=await import("./chunk-cw76edds.js"),F=await O(p);if(F?.apiRouter)Z=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){q=F.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:W}=await import("./chunk-wn2gzwmv.js"),we=F.broadcasting;await z(we);let ze=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let ee=await W(Ge);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(p,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,De=new Set,ae=async(O)=>{let F=Er(C,O);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let W=z.outputs.find((we)=>we.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,j=async(O,F)=>{try{let{processDirectives:z,extractVariables:W,defaultConfig:we,loadStxConfig:ze,injectRouterScript:Ge}=await import("./chunk-cw76edds.js"),{checkCache:ee,cacheTemplate:Q,readFileCached:V,templateCache:K}=await import("./chunk-4vnwge6p.js"),ke=await ze(p),Je=(ce)=>{if(!ce)return ce;if(ie.isAbsolute(ce))return ce;return ie.resolve(p,ce)},A={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)A.debug=!0;A.partialsDir=Je(A.partialsDir),A.componentsDir=Je(A.componentsDir),A.layoutsDir=Je(A.layoutsDir),A.storesDir=Je(A.storesDir||"stores"),A.cachePath=Je(A.cachePath)??a(p,"cache");let be=!F&&!s.profile,ue=A.cache!==!1;if(ue&&be){let ce=K.get(O.filePath);if(ce)try{if((await ve.promises.stat(O.filePath)).mtime.getTime()<=ce.mtime){let He=!0;for(let Re of ce.dependencies){if(!ve.existsSync(Re)){He=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>ce.mtime){He=!1;break}}if(He){let Re=ce.output;if(E)Re=ye(Re,{preserveHead:!0});let gt=U.get(O.filePath);return{route:O,content:Re,status:gt?.status??await pn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await ee(O.filePath,A);if(Ie){let je=Ie;if(E)je=ye(je,{preserveHead:!0});let He=U.get(O.filePath);return{route:O,content:je,status:He?.status??await pn(O.filePath),headers:He?.headers}}}let ge=ue?await V(O.filePath):await Bun.file(O.filePath).text(),Ce=It(ge),{classifyAllScripts:X}=await import("./chunk-cw76edds.js"),Le=X(ge),Ne=Le.server.map((ce)=>ce.content),fe=ge;for(let ce of Le.server)fe=fe.replace(ce.fullTag,"");let me={__filename:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:A,params:F??{},__stx_runtime_head:{}};for(let ce of Ne)try{await W(ce,me,O.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let ce=performance.now();Me=await z(fe,me,O.filePath,A,Ke);let Ie=performance.now()-ce,je=ie.relative(p,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,O.filePath,A,Ke);if(!E)Me=await Ge(Me,{router:A.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-sqpme1hg.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ce(He,me)}</script>`})}if(E)Me=ye(Me,{preserveHead:!0});if(ue&&be)await Q(O.filePath,Me,Ke,A);let{extractStreamBoundaries:Kn}=await import("./chunk-bhg4pvtn.js"),nt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=me.streamBoundaries||{},Ie={...A,autoShell:!1},je=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof ce[Re]==="function"?await ce[Re]():void 0;return z(mt[Re],{...me,$boundary:gt},O.filePath,Ie,new Set)}})),He=new Set(je.map((Re)=>Re.id));nt=[...(nt||[]).filter((Re)=>!He.has(Re.id)),...je]}if(nt&&nt.length>0)De.add(O.pattern);else nt=void 0;let Kt=Ue(me),Xt=We(me);if(be)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Me,status:Kt??Ce,headers:Xt,boundaries:nt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,z),null}},Fe=8,qe=async()=>{he.clear(),_.clear();for(let O=0;O<k.length;O+=Fe){let F=k.slice(O,O+Fe),z=await Promise.all(F.map((W)=>j(W)));for(let W of z)if(W)he.set(W.route.pattern,W)}for(let O=0;O<D.length;O+=Fe){let F=D.slice(O,O+Fe),z=await Promise.all(F.map(({route:W})=>j(W)));for(let W of z)if(W)_.set(W.route.pattern,W)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Pt(p);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let O=s.hmrPort||et+1;l=Et({wsPort:O,verbose:!1}),m=l.start(O)}let Dt=(O,F)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(O.includes("</head>"))return O.replace("</head>",`${W}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+O};console.log(`${e.blue}Starting server...${e.reset}`);let Mt=Yr({port:et,async fetch(O){let F=new URL(O.url),z=g?.publicDir||"public",W=ie.join(p,z,F.pathname),we=ie.join(p,F.pathname),ze=ie.join($e,F.pathname);if([W,we,ze].some((A)=>w(A,p,S)))return new Response("Not Found",{status:404});let[Ge,ee,Q]=await Promise.all([ve.promises.stat(W).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(ze).catch(()=>null)]);if(Ge?.isFile()&&!w(W,p,S))return Wt(W);if(ee?.isFile()&&!w(we,p,S))return Wt(we);if(Q?.isFile()&&!w(ze,p,S))return Wt(ze);if(F.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(F.pathname.slice(16));if(A)try{let be=`<${A} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(p,"components",`${A}.stx`),ue,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-7ae40484.js"),be=await A(O,{publicDir:ie.join(p,z),cacheDir:a(p,"cache","img")});if(be)return be}if(Z)try{let A=await Z.handleRequest(O);if(A.status!==404)return A}catch{}if(q[F.pathname])try{return await q[F.pathname](O)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(O);if(V)return V;let K=Nn(F.pathname,k);if(K){let A=he.get(K.route.pattern),be=De.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||be){let ue=await j(K.route,K.params);if(ue)A=ue}if(A){let ue=A.status??200,ge=A.headers??{},Ce=(K.route.filePath?Ve(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:K.params})){let Ne=await ae(404);if(Ne){let fe=Ne;if(fe=await f(fe,p),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Le=at(F.pathname,K.params,Ce,F.search),Ne=ct(Le,null,O,{isServer:!0}),fe=await lt(Ce.middleware,Ne);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${me}</head>`)}}let X=A.content;if(E&&Eo(O)){let Le=Ee(X),Ne=de(X),fe=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?Co(fe[1].trim()):"";if(Object.keys(K.params).length>0)X=Dt(X,K.params);X=await f(X,p);let Ke=g?.router?.container||"main";return X=oe(X,Ke),new Response(X,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ne?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[Ri]:Os(),...T(),"Cache-Control":Oe}})}if(E)X=Un(E,X);if(Object.keys(K.params).length>0)X=Dt(X,K.params);if(X=await f(X,p),c)X=Xe(X,m);if(s.native)if(X.includes("<head>"))X=X.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 X="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+X;if(s.titlebarHidden)if(X.includes("<head>"))X=X.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 X=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${X}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ne}=await import("./chunk-bhg4pvtn.js");return Ne(Le(X,A.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:ue,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(D.length>0){let A=D.map((ue)=>ue.route),be=Nn(F.pathname,A);if(be){let ue=_.get(be.route.pattern);if(ue){let ge=ue.content;if(E)ge=Un(E,ge);if(Object.keys(be.params).length>0)ge=Dt(ge,be.params);if(ge=await f(ge,p),c)ge=Xe(ge,m);return new Response(ge,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let ge=_.get(ue)||_.get(ue+"/");if(ge){let Ce=ge.content;if(E)Ce=Un(E,Ce);if(Ce=await f(Ce,p),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(rt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let A=ke.content;if(A=await f(A,p),c)A=Xe(A,m);if(s.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let A=Je;if(A=await f(A,p),c)A=Xe(A,m);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
1428
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),_e.clear(),re(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Yr}=globalThis.Bun;import be from"fs";import te from"path";async function pn(t){try{return Nt(await Bun.file(t).text())}catch{return}}function Ut(t){let s=Bun.file(t),i=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(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function Hn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-san161h4.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-td7a6wwq.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!be.existsSync(C)&&!g._layerPageDirs?.some((O)=>be.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],D=[];for(let{dir:O,prefix:F}of H)if(be.existsSync(O)){let z=L(te.dirname(O),{pagesDir:te.basename(O)});for(let W of z){let xe=F==="/"?W.pattern:`${F}${W.pattern==="/"?"":W.pattern}`;D.push({route:{...W,pattern:xe},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let _=new Map,E=null,M=null;if(s.stxOptions?.shell!==!1){if(M=await _o(p,s.stxOptions?.shell),M){if(E=await Fr(M,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}ct(),await ut(p);let B=lt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let q={},Z=null;try{let{loadStxConfig:O}=await import("./chunk-san161h4.js"),F=await O(p);if(F?.apiRouter)Z=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){q=F.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:W}=await import("./chunk-wn2gzwmv.js"),xe=F.broadcasting;await z(xe);let ze=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(be.existsSync(qe))try{let ee=await W(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let Te=a(p,"output");be.mkdirSync(Te,{recursive:!0});let he=new Map,Pe=new Set,ae=async(O)=>{let F=Er(C,O);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:Te,plugins:[it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let W=z.outputs.find((xe)=>xe.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,j=async(O,F)=>{try{let{processDirectives:z,extractVariables:W,defaultConfig:xe,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-san161h4.js"),{checkCache:ee,cacheTemplate:Q,readFileCached:V,templateCache:K}=await import("./chunk-pq9yr5f5.js"),Se=await ze(p),Je=(ce)=>{if(!ce)return ce;if(te.isAbsolute(ce))return ce;return te.resolve(p,ce)},A={...xe,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)A.debug=!0;A.partialsDir=Je(A.partialsDir),A.componentsDir=Je(A.componentsDir),A.layoutsDir=Je(A.layoutsDir),A.storesDir=Je(A.storesDir||"stores"),A.cachePath=Je(A.cachePath)??a(p,"cache");let ye=!F&&!s.profile,le=A.cache!==!1;if(le&&ye){let ce=K.get(O.filePath);if(ce)try{if((await be.promises.stat(O.filePath)).mtime.getTime()<=ce.mtime){let He=!0;for(let Ce of ce.dependencies){if(!be.existsSync(Ce)){He=!1;break}if((await be.promises.stat(Ce)).mtime.getTime()>ce.mtime){He=!1;break}}if(He){let Ce=ce.output;if(E)Ce=ve(Ce,{preserveHead:!0});let gt=U.get(O.filePath);return{route:O,content:Ce,status:gt?.status??await pn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await ee(O.filePath,A);if(Ie){let je=Ie;if(E)je=ve(je,{preserveHead:!0});let He=U.get(O.filePath);return{route:O,content:je,status:He?.status??await pn(O.filePath),headers:He?.headers}}}let me=le?await V(O.filePath):await Bun.file(O.filePath).text(),$e=Nt(me),{classifyAllScripts:X}=await import("./chunk-san161h4.js"),Me=X(me),Ne=Me.server.map((ce)=>ce.content),de=me;for(let ce of Me.server)de=de.replace(ce.fullTag,"");let pe={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:A,params:F??{},__stx_runtime_head:{}};for(let ce of Ne)try{await W(ce,pe,O.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let We=new Set,Oe;if(s.profile){let ce=performance.now();Oe=await z(de,pe,O.filePath,A,We);let Ie=performance.now()-ce,je=te.relative(p,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Oe=await z(de,pe,O.filePath,A,We);if(!E)Oe=await qe(Oe,{router:A.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-55bmmwtx.js");Oe=Oe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ce(He,pe)}</script>`})}if(E)Oe=ve(Oe,{preserveHead:!0});if(le&&ye)await Q(O.filePath,Oe,We,A);let{extractStreamBoundaries:Kn}=await import("./chunk-frm8k9gj.js"),nt=Kn(pe),mt=pe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=pe.streamBoundaries||{},Ie={...A,autoShell:!1},je=Object.keys(mt).map((Ce)=>({id:Ce,render:async()=>{let gt=typeof ce[Ce]==="function"?await ce[Ce]():void 0;return z(mt[Ce],{...pe,$boundary:gt},O.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));nt=[...(nt||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(nt&&nt.length>0)Pe.add(O.pattern);else nt=void 0;let Kt=Ke(pe),Xt=Xe(pe);if(ye)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Oe,status:Kt??$e,headers:Xt,boundaries:nt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,z),null}},Fe=8,Ue=async()=>{he.clear(),_.clear();for(let O=0;O<k.length;O+=Fe){let F=k.slice(O,O+Fe),z=await Promise.all(F.map((W)=>j(W)));for(let W of z)if(W)he.set(W.route.pattern,W)}for(let O=0;O<D.length;O+=Fe){let F=D.slice(O,O+Fe),z=await Promise.all(F.map(({route:W})=>j(W)));for(let W of z)if(W)_.set(W.route.pattern,W)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Dt(p);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let O=s.hmrPort||et+1;l=Et({wsPort:O,verbose:!1}),m=l.start(O)}let At=(O,F)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(O.includes("</head>"))return O.replace("</head>",`${W}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+O};console.log(`${e.blue}Starting server...${e.reset}`);let Mt=Yr({port:et,async fetch(O){let F=new URL(O.url),z=g?.publicDir||"public",W=te.join(p,z,F.pathname),xe=te.join(p,F.pathname),ze=te.join(Te,F.pathname);if([W,xe,ze].some((A)=>w(A,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Q]=await Promise.all([be.promises.stat(W).catch(()=>null),be.promises.stat(xe).catch(()=>null),be.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(W,p,S))return Ut(W);if(ee?.isFile()&&!w(xe,p,S))return Ut(xe);if(Q?.isFile()&&!w(ze,p,S))return Ut(ze);if(F.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(F.pathname.slice(16));if(A)try{let ye=`<${A} />`,le={...buildConfig,autoShell:!1},me=await processDirectives(ye,{},te.join(p,"components",`${A}.stx`),le,new Set);return new Response(me,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-jyqanvwp.js"),ye=await A(O,{publicDir:te.join(p,z),cacheDir:a(p,"cache","img")});if(ye)return ye}if(Z)try{let A=await Z.handleRequest(O);if(A.status!==404)return A}catch{}if(q[F.pathname])try{return await q[F.pathname](O)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(O);if(V)return V;let K=Ln(F.pathname,k);if(K){let A=he.get(K.route.pattern),ye=Pe.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||ye){let le=await j(K.route,K.params);if(le)A=le}if(A){let le=A.status??200,me=A.headers??{},$e=(K.route.filePath?Ge(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if($e.validate){if(!await $e.validate({params:K.params})){let Ne=await ae(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if($e.middleware){let Me=dt(F.pathname,K.params,$e,F.search),Ne=pt(Me,null,O,{isServer:!0}),de=await ft($e.middleware,Ne);if(de.redirect){let pe=de.redirect.path,We=de.redirect.options.redirectCode||302,Oe=new Headers(de.responseHeaders);return Oe.set("Location",pe),new Response(null,{status:We,headers:Oe})}if(de.abort){let{statusCode:pe,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${pe}</title></head><body><h1>Error ${pe}</h1><p>${We}</p></body></html>`,{status:pe,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let pe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${pe}</head>`)}}let X=A.content;if(E&&Eo(O)){let Me=Ae(X),Ne=fe(X),de=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),pe=de?Co(de[1].trim()):"";if(Object.keys(K.params).length>0)X=At(X,K.params);X=await f(X,p);let We=g?.router?.container||"main";return X=ie(X,We),new Response(X,{status:le,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ne?"true":"false",...pe&&{"X-STX-Title":encodeURIComponent(pe)},[Ri]:Os(),...T(),"Cache-Control":Le}})}if(E)X=qn(E,X);if(Object.keys(K.params).length>0)X=At(X,K.params);if(X=await f(X,p),c)X=Ve(X,m);if(s.native)if(X.includes("<head>"))X=X.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 X="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+X;if(s.titlebarHidden)if(X.includes("<head>"))X=X.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 X=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${X}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:Ne}=await import("./chunk-frm8k9gj.js");return Ne(Me(X,A.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...me}})}}if(D.length>0){let A=D.map((le)=>le.route),ye=Ln(F.pathname,A);if(ye){let le=_.get(ye.route.pattern);if(le){let me=le.content;if(E)me=qn(E,me);if(Object.keys(ye.params).length>0)me=At(me,ye.params);if(me=await f(me,p),c)me=Ve(me,m);return new Response(me,{status:le.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:le}of H)if(le!=="/"&&F.pathname.startsWith(le)){let me=_.get(le)||_.get(le+"/");if(me){let $e=me.content;if(E)$e=qn(E,$e);if($e=await f($e,p),c)$e=Ve($e,m);return new Response($e,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(at(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=he.get("/");if(Se){let A=Se.content;if(A=await f(A,p),c)A=Ve(A,m);if(s.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let A=Je;if(A=await f(A,p),c)A=Ve(A,m);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
1430
1430
  ${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1431
1431
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1432
1432
  ${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
1433
  ${e.yellow}Routes:${e.reset}`);let _t=[...Tr(k,p)];for(let{route:O}of D)_t.push(`${O.pattern}`);if(_t.forEach((O,F)=>{let W=F===_t.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${W}${e.reset}${O}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Mt.url.toString(),()=>{if(l)ht();Mt.stop()}),s.native){let O,F=ie.join(C,"index.stx");if(ve.existsSync(F)){let W=await Bun.file(F).text();O=Tt(W)}let z=g?.app?.window??{};await dt(et,{title:g?.app?.head?.title||ie.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),F=(ee)=>{let Q=ee.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,W=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let V of Object.values(Q.resources)){if(!ve.existsSync(V))continue;let K=ve.realpathSync(V);if(![...ee].some((ke)=>K===ke||K.startsWith(`${ke}${ie.sep}`)))ee.add(K)}for(let[Q,V]of z)if(!ee.has(Q))V.close(),z.delete(Q);for(let Q of ee)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(V,K)=>{ze(Q,V,K).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),ze=(ee,Q,V)=>(we=we.catch(()=>{}).then(()=>Ge(ee,Q,V)),we),Ge=async(ee,Q,V)=>{if(!V||Rt(V))return;if(Ct(V)){if(g._layerGraph){let K=await h(p);Object.assign(g,K),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[C,...K._layerPageDirs.slice(1)]:void 0})),W()}if(O(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),c&&l)l.reload(V)}else if(F(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),xe.clear(),ne();try{let{invalidateFileCache:K,templateCache:ke}=await import("./chunk-4vnwge6p.js");K(ie.resolve(ee,V)),ke.delete(ie.resolve(ee,V))}catch{}if(M&&V){if(ie.resolve(ee,V)===M||ie.basename(M)===V){let ke=await Fr(M,s.stxOptions||{});if(ke)E=ke}}if(await qe(),await bn(p),c&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),xe.clear(),ne();try{let{invalidateFileCache:K,templateCache:ke}=await import("./chunk-4vnwge6p.js");K(ie.resolve(ee,V)),ke.delete(ie.resolve(ee,V))}catch{}if(await qe(),c&&l)l.reload(V)}}else if($t(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),c&&l)l.updateCss(V)}};W(),process.on("SIGINT",()=>{for(let ee of z.values())ee.close();if(l)ht();Mt.stop(),process.exit(0)})}return!0}import Vt from"fs";import yt from"path";async function Qr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=p.split(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Mt.url.toString(),()=>{if(l)ht();Mt.stop()}),s.native){let O,F=te.join(C,"index.stx");if(be.existsSync(F)){let W=await Bun.file(F).text();O=Tt(W)}let z=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),F=(ee)=>{let Q=ee.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,W=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>te.dirname(Q))??[]].filter((Q)=>be.existsSync(Q)).map((Q)=>be.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let V of Object.values(Q.resources)){if(!be.existsSync(V))continue;let K=be.realpathSync(V);if(![...ee].some((Se)=>K===Se||K.startsWith(`${Se}${te.sep}`)))ee.add(K)}for(let[Q,V]of z)if(!ee.has(Q))V.close(),z.delete(Q);for(let Q of ee)if(!z.has(Q)&&be.existsSync(Q))z.set(Q,be.watch(Q,{recursive:!0},(V,K)=>{ze(Q,V,K).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},xe=Promise.resolve(),ze=(ee,Q,V)=>(xe=xe.catch(()=>{}).then(()=>qe(ee,Q,V)),xe),qe=async(ee,Q,V)=>{if(!V||Rt(V))return;if(Ct(V)){if(g._layerGraph){let K=await h(p);Object.assign(g,K),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[C,...K._layerPageDirs.slice(1)]:void 0})),W()}if(O(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),c&&l)l.reload(V)}else if(F(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),_e.clear(),re();try{let{invalidateFileCache:K,templateCache:Se}=await import("./chunk-pq9yr5f5.js");K(te.resolve(ee,V)),Se.delete(te.resolve(ee,V))}catch{}if(M&&V){if(te.resolve(ee,V)===M||te.basename(M)===V){let Se=await Fr(M,s.stxOptions||{});if(Se)E=Se}}if(await Ue(),await wn(p),c&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),_e.clear(),re();try{let{invalidateFileCache:K,templateCache:Se}=await import("./chunk-pq9yr5f5.js");K(te.resolve(ee,V)),Se.delete(te.resolve(ee,V))}catch{}if(await Ue(),c&&l)l.reload(V)}}else if($t(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),c&&l)l.updateCss(V)}};W(),process.on("SIGINT",()=>{for(let ee of z.values())ee.close();if(l)ht();Mt.stop(),process.exit(0)})}return!0}import Wt from"fs";import yt from"path";async function Qr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=p.split(`
1435
1435
  `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=R.join(" ").trim(),c.push(g)}if(c.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Zr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
1436
1436
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function eo(t,s=!1,i){let d=yt.basename(t,".stx"),c=await Qr(t),l=await Zr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let p=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
1437
1437
  `);m=`<${d}
1438
1438
  ${p}
1439
- />`}return{name:d,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function un(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){let c=yt.join(t,d.name);if(d.isDirectory()){let l=await un(c);i.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function to(t,s){try{if(!await r(t))return[];let i=await un(t),d=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),p=!!m,h=m?.tag,g=await eo(l,p,h);d.push(g)}return d}catch(i){return console.error("Error generating component docs:",i),[]}}async function no(t){try{if(!await r(t))return[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let c=yt.join(t,d.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=p?p[1].split(`
1439
+ />`}return{name:d,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function un(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){let c=yt.join(t,d.name);if(d.isDirectory()){let l=await un(c);i.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function to(t,s){try{if(!await r(t))return[];let i=await un(t),d=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),p=!!m,h=m?.tag,g=await eo(l,p,h);d.push(g)}return d}catch(i){return console.error("Error generating component docs:",i),[]}}async function no(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let c=yt.join(t,d.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=p?p[1].split(`
1440
1440
  `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=R.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function ro(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1441
1441
  <p>Welcome, {{ user.name }}!</p>
1442
1442
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
@@ -1570,12 +1570,12 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Mt.
1570
1570
  <td>@${l.name}</td>
1571
1571
  <td>${l.description||"-"}</td>
1572
1572
  <td>${l.hasEndTag?"Yes":"No"}</td>
1573
- </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function io(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ao(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Vt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await to(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await no(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ro(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=oo(p,h,g,w),R="md";break;case"html":S=so(p,h,g,w),R="html";break;case"json":S=io(p,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function fo(t){let s={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},i=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return ao({componentsDir:i,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var hn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Ir(t,s={}){let i={...hn,...s};if(t.trim()==="")return`
1573
+ </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function io(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ao(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await to(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await no(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ro(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=oo(p,h,g,w),R="md";break;case"html":S=so(p,h,g,w),R="html";break;case"json":S=io(p,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function fo(t){let s={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},i=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return ao({componentsDir:i,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Ir(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1574
1574
  `;let d=t;if(i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=bo(d,i),d=So(d,i),d=xo(d,i),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1575
1575
  `).replace(/\r/g,`
1576
1576
  `),!d.endsWith(`
1577
1577
  `))d+=`
1578
- `;return d}function go(t,s={}){let i={...hn,...s};if(t.trim()==="")return`
1578
+ `;return d}function go(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1579
1579
  `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,p,h)=>{let g=p.split(`
1580
1580
  `),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let C=x.match(/^( *)/);return C?C[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
1581
  `),v=Ir(S,i).trimEnd().split(`
@@ -1601,9 +1601,9 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,p)=>{let h=p.substring(Math.max
1601
1601
  `),s=s.split(`
1602
1602
  `).map((c)=>c.trim()).join(`
1603
1603
  `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function bo(t,s){let d=yo(t).split(`
1604
- `),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let R=y===">";if(mn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&wo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),D=y.startsWith("</"),_=y.startsWith("<")&&!D&&!H&&!k,E=y.includes("/>")||vo(y),M=mn(y);if(D||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(p.repeat(B)+y);if(_&&!E&&!M&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
- `)}function xo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,d,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,d,c)=>{if(c.trim()==="")return`@${d}`;return`@${d}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,d)=>`{!! ${d.trim()} !!}`);return t}function vo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let d=i[1];return s.includes(d.toLowerCase())}return!1}function mn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function wo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function So(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,d,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1606
- `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],p;while((p=l.exec(c))!==null)m.push({name:p[1],value:p[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${h?` ${h}`:""}>`})}import yn from"fs";import qt from"path";async function mo(t="index.stx",s={}){try{let i=s.force||!1,d=qt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(d);if(!yn.existsSync(c))yn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=qt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=xn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=xn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function xn(t){switch(t){case"basic":return vn();case"component":return ko();case"layout":return To();case"blog":return $o();case"api":return Ro();case"app":return Po();default:return vn()}}function vn(){return`<script>
1604
+ `),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let R=y===">";if(fn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&wo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),D=y.startsWith("</"),_=y.startsWith("<")&&!D&&!H&&!k,E=y.includes("/>")||vo(y),M=fn(y);if(D||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(p.repeat(B)+y);if(_&&!E&&!M&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
+ `)}function xo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,d,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,d,c)=>{if(c.trim()==="")return`@${d}`;return`@${d}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,d)=>`{!! ${d.trim()} !!}`);return t}function vo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let d=i[1];return s.includes(d.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function wo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function So(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,d,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1606
+ `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],p;while((p=l.exec(c))!==null)m.push({name:p[1],value:p[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${h?` ${h}`:""}>`})}import gn from"fs";import qt from"path";async function mo(t="index.stx",s={}){try{let i=s.force||!1,d=qt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(d);if(!gn.existsSync(c))gn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=qt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=bn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=bn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function bn(t){switch(t){case"basic":return xn();case"component":return ko();case"layout":return To();case"blog":return $o();case"api":return Ro();case"app":return Po();default:return xn()}}function xn(){return`<script>
1607
1607
  const title = "My stx Page"
1608
1608
  const description = "A page built with stx"
1609
1609
  const features = [
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
2032
- </html>`}var ho="f9c3713";function ca(t){return t}function la(t){return t}function lo(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}import _e from"fs";import Te from"path";function En(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function At(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Di(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Pn(t,s="stx"){let i=Te.resolve(t);for(let d=0;d<10;d++){let c=Te.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var On=["@stacksjs/stx","bun-plugin-stx"];function Mi(t){try{let s=_e.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function _i(t,s=6){let i=Te.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=_e.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of On){let S=Te.join(p,w),R=Mi(S);if(R!==null)d.push({name:w,version:R,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=_e.readdirSync(p,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=Te.join(S,x.name,"node_modules");if(_e.existsSync(C))l(C,h+1)}continue}let R=Te.join(S,"node_modules");if(_e.existsSync(R))l(R,h+1)}}let m=Te.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return d}function Li(t){let s=[];for(let i of On){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function Or(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Di,d=Date.now(),c=[],l=i("@stacksjs/stx",s);c.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 m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Li(_i(s)))c.push(h);let p=Pn(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(p,"src/signals.ts"),g=[Te.join(p,"dist/index.js"),Te.join(p,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,y=En(h),w=g?En(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} but no src/signals.ts to compare`});else if(w==null)c.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 ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${At(w,d)}) is OLDER than src/signals.ts (${At(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${At(y,d)}, dist ${At(w,d)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=_e.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(p)}catch{return p}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.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(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function Dr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
2033
- `)}export{lo,uo,po,fo,Ir,go,mo,ho,ca,la,Or,Dr,jn,Bn,Fn};
2032
+ </html>`}var ho="f9c3713";function ca(t){return t}function la(t){return t}function lo(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}import De from"fs";import ke from"path";function En(t){try{return De.statSync(t).mtimeMs}catch{return null}}function Ot(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Di(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Pn(t,s="stx"){let i=ke.resolve(t);for(let d=0;d<10;d++){let c=ke.join(i,"pantry","@stacksjs",s);if(De.existsSync(c))return c;let l=ke.dirname(i);if(l===i)break;i=l}return null}var On=["@stacksjs/stx","bun-plugin-stx"];function Mi(t){try{let s=De.readFileSync(ke.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function _i(t,s=6){let i=ke.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=De.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of On){let S=ke.join(p,w),R=Mi(S);if(R!==null)d.push({name:w,version:R,dir:ke.relative(i,S)||S,nested:h>0})}let y;try{y=De.readdirSync(p,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ke.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=De.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=ke.join(S,x.name,"node_modules");if(De.existsSync(C))l(C,h+1)}continue}let R=ke.join(S,"node_modules");if(De.existsSync(R))l(R,h+1)}}let m=ke.join(i,"node_modules");if(De.existsSync(m))l(m,0);return d}function Li(t){let s=[];for(let i of On){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function Or(t={}){let s=t.cwd?ke.resolve(t.cwd):process.cwd(),i=t.resolve??Di,d=Date.now(),c=[],l=i("@stacksjs/stx",s);c.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 m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Li(_i(s)))c.push(h);let p=Pn(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=ke.join(p,"src/signals.ts"),g=[ke.join(p,"dist/index.js"),ke.join(p,"dist/signals.js")].find((v)=>De.existsSync(v))||null,y=En(h),w=g?En(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} but no src/signals.ts to compare`});else if(w==null)c.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 ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Ot(w,d)}) is OLDER than src/signals.ts (${Ot(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Ot(y,d)}, dist ${Ot(w,d)})`});let S=ke.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=De.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=De.realpathSync(S)}catch{}let x=(()=>{try{return De.realpathSync(p)}catch{return p}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.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(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function Dr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
2033
+ `)}export{lo,uo,po,fo,Ir,go,mo,ho,ca,la,Or,Dr,Fn,zn,Hn};