@stacksjs/stx 0.2.800 → 0.2.802

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 (148) hide show
  1. package/dist/{chunk-gzfvj15b.js → chunk-06hc6rs6.js} +1 -1
  2. package/dist/{chunk-rq5s1hc6.js → chunk-077dwzpp.js} +1 -1
  3. package/dist/{chunk-fes0t0js.js → chunk-0vztrb90.js} +32 -32
  4. package/dist/chunk-1338vj5g.js +2 -0
  5. package/dist/chunk-14qhn86r.js +2 -0
  6. package/dist/{chunk-kydgndkt.js → chunk-1pz11ez9.js} +1 -1
  7. package/dist/{chunk-szkmxk09.js → chunk-24x7s0x5.js} +3 -3
  8. package/dist/chunk-27p6cxa2.js +2 -0
  9. package/dist/chunk-2jwmtbsj.js +2 -0
  10. package/dist/{chunk-akcyaxwv.js → chunk-2vqpz4qv.js} +2 -2
  11. package/dist/{chunk-6c50nsgz.js → chunk-3dtp59r9.js} +1 -1
  12. package/dist/{chunk-95k6shcv.js → chunk-3j9zzpbd.js} +2 -2
  13. package/dist/{chunk-70j06zqt.js → chunk-3vfxn6g5.js} +1 -1
  14. package/dist/{chunk-rp9xzzmt.js → chunk-4gf3khd9.js} +2 -2
  15. package/dist/{chunk-s1eb3b3x.js → chunk-4q2fh4r4.js} +1 -1
  16. package/dist/{chunk-2ehn5r6d.js → chunk-50be1xy0.js} +1 -1
  17. package/dist/{chunk-48914p88.js → chunk-5hgghq24.js} +1 -1
  18. package/dist/chunk-6cgak0k1.js +2 -0
  19. package/dist/{chunk-et40w1wx.js → chunk-7j4tf0ba.js} +1 -1
  20. package/dist/{chunk-xa3xk823.js → chunk-7tkxshah.js} +8 -8
  21. package/dist/{chunk-jg4xvn1f.js → chunk-8fnhv8jq.js} +1 -1
  22. package/dist/{chunk-j0bbr6ee.js → chunk-8fvgsd9v.js} +3 -3
  23. package/dist/chunk-8hm4a8p2.js +2 -0
  24. package/dist/{chunk-2sgrapfw.js → chunk-9767yz39.js} +1 -1
  25. package/dist/{chunk-7z5ga45f.js → chunk-a0xxm3eh.js} +1 -1
  26. package/dist/{chunk-2yb1rwmy.js → chunk-a5byhf8f.js} +1 -1
  27. package/dist/{chunk-ssr3h26v.js → chunk-aj5na3d3.js} +1 -1
  28. package/dist/{chunk-9kadf7pv.js → chunk-antc6crh.js} +1 -1
  29. package/dist/chunk-b22yj5j5.js +2 -0
  30. package/dist/{chunk-dpctjkac.js → chunk-b29x9hsz.js} +1 -1
  31. package/dist/{chunk-sprgkk9j.js → chunk-bs02d6mm.js} +8 -8
  32. package/dist/{chunk-czsagff5.js → chunk-byatzyvf.js} +2 -2
  33. package/dist/chunk-bz3papjy.js +2 -0
  34. package/dist/{chunk-d47z4fky.js → chunk-c36bj74x.js} +1 -1
  35. package/dist/{chunk-04eq8yhz.js → chunk-casq5t61.js} +1 -1
  36. package/dist/{chunk-k3rcpnzm.js → chunk-cmnze7at.js} +2 -2
  37. package/dist/{chunk-8qhdbch9.js → chunk-cs38hg43.js} +8 -8
  38. package/dist/chunk-d3gncxq1.js +2 -0
  39. package/dist/{chunk-j2v9f2dk.js → chunk-dbbc84mj.js} +2 -2
  40. package/dist/{chunk-r32pqvpq.js → chunk-ddk34ppv.js} +5 -5
  41. package/dist/chunk-dwn8ye99.js +2 -0
  42. package/dist/{chunk-0gvrpg5x.js → chunk-dxemdr58.js} +41 -41
  43. package/dist/{chunk-xd8w1vf4.js → chunk-e1g3ns8y.js} +2 -2
  44. package/dist/{chunk-ysyh69a7.js → chunk-e5fszb5z.js} +1 -1
  45. package/dist/chunk-e88bsw36.js +2 -0
  46. package/dist/{chunk-ddhkhhc7.js → chunk-eayewa2s.js} +2 -2
  47. package/dist/{chunk-q3dsjk2b.js → chunk-esm9sdyf.js} +3 -3
  48. package/dist/chunk-ewhkvqce.js +72 -0
  49. package/dist/chunk-fq1dw4ph.js +3 -0
  50. package/dist/{chunk-2fkzsmcr.js → chunk-fsfj0s13.js} +6 -6
  51. package/dist/{chunk-qa358n74.js → chunk-fy6sdbak.js} +48 -48
  52. package/dist/{chunk-chgchzd9.js → chunk-g02jnsz5.js} +1 -1
  53. package/dist/chunk-g4sdthck.js +2 -0
  54. package/dist/chunk-gabw11g3.js +2 -0
  55. package/dist/{chunk-5h32se25.js → chunk-gk214p91.js} +2 -2
  56. package/dist/{chunk-dd1vqndp.js → chunk-gxrpf87x.js} +1 -1
  57. package/dist/{chunk-dwydz68f.js → chunk-h1dwth11.js} +1 -1
  58. package/dist/{chunk-4zv5vfv0.js → chunk-hzhsg5j7.js} +6 -6
  59. package/dist/chunk-j0jgc426.js +2 -0
  60. package/dist/{chunk-qkck7zx0.js → chunk-jdjv5x6q.js} +1 -1
  61. package/dist/chunk-jkn9garq.js +2 -0
  62. package/dist/chunk-jy9qmwpm.js +2 -0
  63. package/dist/chunk-krqj3cx9.js +2 -0
  64. package/dist/chunk-kzny87pz.js +2 -0
  65. package/dist/{chunk-p1d6hwty.js → chunk-kzt46v41.js} +1 -1
  66. package/dist/{chunk-8adf5x29.js → chunk-m0c64sna.js} +1 -1
  67. package/dist/{chunk-f4a6sbnt.js → chunk-m4w61tyq.js} +2 -2
  68. package/dist/{chunk-nm20k22y.js → chunk-md55r6zp.js} +1 -1
  69. package/dist/chunk-mv9k42dn.js +2 -0
  70. package/dist/{chunk-8ey61ppd.js → chunk-mz1kffvs.js} +2 -2
  71. package/dist/{chunk-33vr7x2t.js → chunk-n7arptzc.js} +3 -3
  72. package/dist/chunk-nhfksrce.js +3 -0
  73. package/dist/{chunk-cas0vn5m.js → chunk-ntwgk0tf.js} +1 -1
  74. package/dist/{chunk-7q0y6qg5.js → chunk-nya33asw.js} +3 -3
  75. package/dist/{chunk-83myk906.js → chunk-p4aaxpaw.js} +1 -1
  76. package/dist/{chunk-hcwjdpzv.js → chunk-p8wq37hd.js} +2 -2
  77. package/dist/{chunk-d5bhtsb5.js → chunk-pamtcna7.js} +1 -1
  78. package/dist/{chunk-gvnfb6s2.js → chunk-q7zwv88b.js} +2 -2
  79. package/dist/{chunk-aqf0kt1w.js → chunk-qx5jhe7h.js} +5 -5
  80. package/dist/{chunk-2yxva96k.js → chunk-r9e0r6jx.js} +2 -2
  81. package/dist/chunk-r9eyepbk.js +21 -0
  82. package/dist/{chunk-7tjw0mpm.js → chunk-rs0ejvjm.js} +1 -1
  83. package/dist/{chunk-t5vjt37c.js → chunk-rxhymzj8.js} +1 -1
  84. package/dist/{chunk-mb2d9spg.js → chunk-s81y1dw3.js} +4 -4
  85. package/dist/chunk-sfvdj9dj.js +2 -0
  86. package/dist/chunk-szma9dby.js +2 -0
  87. package/dist/{chunk-x8h81amr.js → chunk-t4j2rw91.js} +2 -2
  88. package/dist/chunk-txyyvtdp.js +2 -0
  89. package/dist/{chunk-8nsn1mkz.js → chunk-v18816jj.js} +8 -8
  90. package/dist/chunk-ved3r01r.js +420 -0
  91. package/dist/chunk-vxd3akt4.js +2 -0
  92. package/dist/{chunk-hp9e8nz6.js → chunk-we6jnjjp.js} +1 -1
  93. package/dist/{chunk-99jzhp6x.js → chunk-wes7vsze.js} +2 -2
  94. package/dist/chunk-wf6vjd41.js +2 -0
  95. package/dist/{chunk-ps9fcjyg.js → chunk-wghv9vr6.js} +1 -1
  96. package/dist/{chunk-w0zayhmg.js → chunk-wpendr22.js} +2 -2
  97. package/dist/{chunk-r1t4978q.js → chunk-wvnzq8w8.js} +3 -3
  98. package/dist/{chunk-qxt6hdat.js → chunk-wy0gghvh.js} +1 -1
  99. package/dist/{chunk-qph9n5vc.js → chunk-x0ttkvr7.js} +2 -2
  100. package/dist/chunk-xbvx8j82.js +2 -0
  101. package/dist/{chunk-e0vrayws.js → chunk-xndhzwdj.js} +5 -5
  102. package/dist/{chunk-dq87xd5c.js → chunk-xrvdef6x.js} +3 -3
  103. package/dist/{chunk-pfygdsms.js → chunk-yxsrerew.js} +1 -1
  104. package/dist/chunk-z0kx564w.js +2 -0
  105. package/dist/{chunk-y87whqd5.js → chunk-zwptpjjt.js} +16 -16
  106. package/dist/cli.js +13 -13
  107. package/dist/client-parameter-bindings.js +10 -6
  108. package/dist/craft-entry.js +1 -1
  109. package/dist/craft.js +1 -1
  110. package/dist/native/compiler/inline-style.js +51 -28
  111. package/dist/native/runtime/craft-bridge.js +37 -4
  112. package/dist/performance-utils.d.ts +255 -115
  113. package/dist/pwa.js +2 -2
  114. package/dist/safe-evaluator.js +28 -3
  115. package/dist/signal-processing.js +20 -41
  116. package/dist/ssg.js +3 -3
  117. package/package.json +5 -5
  118. package/dist/chunk-09vge2qv.js +0 -21
  119. package/dist/chunk-0h07bnrc.js +0 -2
  120. package/dist/chunk-0tbf7n5v.js +0 -2
  121. package/dist/chunk-2dmytnfq.js +0 -3
  122. package/dist/chunk-2f1kqrdc.js +0 -2
  123. package/dist/chunk-2g21c65w.js +0 -2
  124. package/dist/chunk-4q5y2b0z.js +0 -2
  125. package/dist/chunk-5fzvcr9v.js +0 -2
  126. package/dist/chunk-7m4eesp0.js +0 -2
  127. package/dist/chunk-b3b9tfpx.js +0 -2
  128. package/dist/chunk-baryfj93.js +0 -2
  129. package/dist/chunk-cn6cmy23.js +0 -2
  130. package/dist/chunk-eszpqrxy.js +0 -2
  131. package/dist/chunk-ex43dwnv.js +0 -431
  132. package/dist/chunk-f13yn6xw.js +0 -2
  133. package/dist/chunk-faqzszzs.js +0 -3
  134. package/dist/chunk-h2xrfjh8.js +0 -2
  135. package/dist/chunk-jfq3nwe0.js +0 -2
  136. package/dist/chunk-ktxatzbd.js +0 -2
  137. package/dist/chunk-m6a8mftb.js +0 -2
  138. package/dist/chunk-nq4d91zm.js +0 -2
  139. package/dist/chunk-q38vjqv2.js +0 -2
  140. package/dist/chunk-q78jxqnr.js +0 -2
  141. package/dist/chunk-qftr9bm2.js +0 -2
  142. package/dist/chunk-rp831mk8.js +0 -2
  143. package/dist/chunk-se44tmvx.js +0 -61
  144. package/dist/chunk-tmr6ey5s.js +0 -2
  145. package/dist/chunk-tq5mqv8d.js +0 -2
  146. package/dist/chunk-xqe2jt3f.js +0 -2
  147. package/dist/chunk-ys46rqxg.js +0 -2
  148. package/dist/chunk-zxm9hkqb.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{oe,de,gn,Ot,Nt,m,s,fe,p}from"./chunk-ex43dwnv.js";import{yt,Re,sc,is,No,Mo,i}from"./chunk-fes0t0js.js";import{ae,Tr,ke,B,Sn}from"./chunk-se44tmvx.js";import{St,pr,$s,Rs,As,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-j2v9f2dk.js";import{Ss,a,P}from"./chunk-qa358n74.js";import{ft,An,Ce,D,ca,mo,Xr,We,la,qe,Ee}from"./chunk-e0vrayws.js";import{lr,ur}from"./chunk-czsagff5.js";import{$n}from"./chunk-faqzszzs.js";import{e,cn,sr,y}from"./chunk-7q0y6qg5.js";import{Je}from"./chunk-8nsn1mkz.js";import{$e}from"./chunk-7sh9fa3q.js";import{K,be,we}from"./chunk-4zv5vfv0.js";import{c}from"./chunk-brhas9mp.js";import{X}from"./chunk-w0zayhmg.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
2
+ import{de,gn,It,Ot,m,s,fe,p}from"./chunk-ved3r01r.js";import{yt,Re,sc,is,No,Mo,i}from"./chunk-0vztrb90.js";import{ie,ae,Tr,ke,F,Sn}from"./chunk-ewhkvqce.js";import{St,pr,$s,Rs,As,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-dbbc84mj.js";import{Ss,a,I}from"./chunk-fy6sdbak.js";import{ft,An,Ce,L,ca,mo,Kr,We,la,qe,Ee}from"./chunk-xndhzwdj.js";import{lr,ur}from"./chunk-byatzyvf.js";import{$n}from"./chunk-nhfksrce.js";import{e,cn,sr,y}from"./chunk-nya33asw.js";import{Je}from"./chunk-v18816jj.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-hzhsg5j7.js";import{c}from"./chunk-brhas9mp.js";import{K}from"./chunk-wpendr22.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
3
3
  `),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
4
4
  `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,b=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:b}}function Wn(t,n){let r=[],d=Xt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Xt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
5
- `).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Gi(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=Te.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let b=l[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
5
+ `).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Gi(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=Te.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let b=l[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
6
6
 
7
7
  `)}function ir(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function ar(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function cr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function dr(t){let n=[],r=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(g)=>{if(d[g]!=="(")return null;let h=0,x="";for(let v=g;v<d.length;v++){let S=d[v];if(x!==""){if(S==="\\")v++;else if(S===x)x="";continue}if(S==="'"||S==='"'||S==="`"){x=S;continue}if(S==="(")h++;else if(S===")"){if(h--,h===0)return{expression:d.slice(g+1,v),end:v+1}}}return null},f=(g)=>{if(g==="")return;let h=0,x=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,v;while(v=x.exec(g)){if(v.index>h)n.push(`out += ${JSON.stringify(g.slice(h,v.index))};`);n.push(v[1]!==void 0?`out += __raw(${v[1]});`:`out += __escape(${v[2]});`),h=v.index+v[0].length}if(h<g.length)n.push(`out += ${JSON.stringify(g.slice(h))};`)};while(l=o.exec(d)){f(d.slice(r,l.index)),r=l.index+l[0].length;let h=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(r):null;if(h)r=h.end,o.lastIndex=h.end;let x=h?.expression;switch(l[1]){case"if":n.push(`if (${x}) {`);break;case"elseif":n.push(`} else if (${x}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let v=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((x||"").trim());if(!v){n.push(`out += ${JSON.stringify(l[0]+(h?`(${x})`:""))};`);break}let[,S,T,w]=v;n.push(T?`for (const [${T}, ${w}] of __entries(${S})) {`:`for (const ${w} of __values(${S})) {`);break}}}return f(d.slice(r)),n.join(`
8
- `)}function lt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function Mt(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,g="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(g+=x,x==="\\"){g+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,g+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(g),g="";continue}g+=x}return l.push(g),l.map((h)=>h.trim()).filter(Boolean)}function fr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Yt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function mr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},g=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(g<t.length&&/\s/.test(t[g]))g++},x;if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;x=t.slice(g,E),g=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(g));if(!E)return null;x=E[0],g+=E[0].length}if(h(),t[g]!=="=")return null;g++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(g)),S=Boolean(v);if(v)g+=v[0].length;let T=/^defineProps\b/.exec(t.slice(g));if(!T)return null;g+=T[0].length;let w="";if(h(),t[g]==="<"){let E=lt(t,g,"<",">");if(E===-1)return null;w=t.slice(g+1,E-1).trim(),g=E}if(h(),t[g]!=="(")return null;let b=lt(t,g,"(",")");if(b===-1)return null;let k=t.slice(g+1,b-1).trim();if(g=b,S){if(h(),t[g]===",")g++,h();if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;for(let[R,A]of Lt(t.slice(g,E)))l[R]=A;g=E}if(h(),t[g]===",")g++,h();if(t[g]===")")g++}if(t[g]===";")g++;let _=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of Mt(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of Lt(k)){if(u.push(E),!R.startsWith("{")){let A=Yt(R);if(A)o[E]=A;continue}for(let[A,C]of Lt(R))if(A==="default")l[E]=C;else if(A==="type"){let M=Yt(C);if(M)o[E]=M}}else if(k.startsWith("["))for(let E of Mt(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of Mt(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=fr(E),A=R===-1?E:E.slice(0,R),C=A.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=A.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,g),propNames:u,propBindings:f,defaults:l,declared:o,typeName:_}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",g=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(g,d).trim();if(h)r.push([l[1],h]);d++}return r}function gr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],g={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,b,k,_)=>{let E=Te.resolve(Te.dirname(n),k),R=Te.relative(r,E);return`${b}${R.startsWith(".")?R:`./${R}`}${_}`})),""});let v=mr(l);if(v)f.push(...v.propNames),Object.assign(g,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let b of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[b[1]]=b[2].trim(),w.push(b[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:g,defaults:h,declared:x}}function hr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let g=o.toLowerCase();n.add(g);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${g}="${f}"${h?` data-stx-mod-${g}="${h}"`:""}`}),eventTypes:[...n].sort()}}function yr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function br(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function xr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Qt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function vr(t,n,r){let d=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),o=await Gn(d,"utf8"),l=nr(o,d),u=Te.basename(d,".stx"),f=n.name||l.name||Qn(u),g=`${It(r.prefix||"stx")}-${It(u)}`,h=n.tag||l.tag||g;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Zn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,A])=>[R,Qt(R,A)])),S=hr(or(o)),T=yr(S.template),w=gr(o,d,Te.resolve(r.outputDir)),b=dr(T.template);for(let R of w.propNames){if(v[R])continue;let A=w.defaults[R];v[R]=Qt(R,{type:ir(w.declared[R])??ar(A),...A===void 0?{}:{default:cr(A)}})}let k=l.methods||{},_=n.methods||{},E=rr(o,d);return{file:Te.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Jt(o),shadowMode:er(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,..._,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:br(T.template),cssProperties:xr(Jt(o)),scope:w,render:b}}function wr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
8
+ `)}function lt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function Mt(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,g="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(g+=x,x==="\\"){g+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,g+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(g),g="";continue}g+=x}return l.push(g),l.map((h)=>h.trim()).filter(Boolean)}function fr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Yt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function mr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},g=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(g<t.length&&/\s/.test(t[g]))g++},x;if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;x=t.slice(g,E),g=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(g));if(!E)return null;x=E[0],g+=E[0].length}if(h(),t[g]!=="=")return null;g++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(g)),S=Boolean(v);if(v)g+=v[0].length;let T=/^defineProps\b/.exec(t.slice(g));if(!T)return null;g+=T[0].length;let w="";if(h(),t[g]==="<"){let E=lt(t,g,"<",">");if(E===-1)return null;w=t.slice(g+1,E-1).trim(),g=E}if(h(),t[g]!=="(")return null;let b=lt(t,g,"(",")");if(b===-1)return null;let k=t.slice(g+1,b-1).trim();if(g=b,S){if(h(),t[g]===",")g++,h();if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;for(let[R,O]of Lt(t.slice(g,E)))l[R]=O;g=E}if(h(),t[g]===",")g++,h();if(t[g]===")")g++}if(t[g]===";")g++;let D=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of Mt(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of Lt(k)){if(u.push(E),!R.startsWith("{")){let O=Yt(R);if(O)o[E]=O;continue}for(let[O,C]of Lt(R))if(O==="default")l[E]=C;else if(O==="type"){let A=Yt(C);if(A)o[E]=A}}else if(k.startsWith("["))for(let E of Mt(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of Mt(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=fr(E),O=R===-1?E:E.slice(0,R),C=O.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=O.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,g),propNames:u,propBindings:f,defaults:l,declared:o,typeName:D}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",g=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(g,d).trim();if(h)r.push([l[1],h]);d++}return r}function gr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],g={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,b,k,D)=>{let E=Te.resolve(Te.dirname(n),k),R=Te.relative(r,E);return`${b}${R.startsWith(".")?R:`./${R}`}${D}`})),""});let v=mr(l);if(v)f.push(...v.propNames),Object.assign(g,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let b of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[b[1]]=b[2].trim(),w.push(b[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:g,defaults:h,declared:x}}function hr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let g=o.toLowerCase();n.add(g);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${g}="${f}"${h?` data-stx-mod-${g}="${h}"`:""}`}),eventTypes:[...n].sort()}}function yr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function br(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function xr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Qt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function vr(t,n,r){let d=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),o=await Gn(d,"utf8"),l=nr(o,d),u=Te.basename(d,".stx"),f=n.name||l.name||Qn(u),g=`${jt(r.prefix||"stx")}-${jt(u)}`,h=n.tag||l.tag||g;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Zn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,O])=>[R,Qt(R,O)])),S=hr(or(o)),T=yr(S.template),w=gr(o,d,Te.resolve(r.outputDir)),b=dr(T.template);for(let R of w.propNames){if(v[R])continue;let O=w.defaults[R];v[R]=Qt(R,{type:ir(w.declared[R])??ar(O),...O===void 0?{}:{default:cr(O)}})}let k=l.methods||{},D=n.methods||{},E=rr(o,d);return{file:Te.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Jt(o),shadowMode:er(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...D,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:br(T.template),cssProperties:xr(Jt(o)),scope:w,render:b}}function wr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -339,7 +339,7 @@ ${r}${u}
339
339
 
340
340
  defineComponent(${t.name}, ${n});
341
341
  export default ${t.name};
342
- `}function jt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function kr(t){let n=Object.entries(t.properties).map(([o,l])=>` ${o}${l.required?"":"?"}: ${jt(l)}`).join(`
342
+ `}function Ht(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function kr(t){let n=Object.entries(t.properties).map(([o,l])=>` ${o}${l.required?"":"?"}: ${Ht(l)}`).join(`
343
343
  `),r=Object.entries(t.events).map(([o,l])=>` ${JSON.stringify(o)}: CustomEvent<${l.detailType||"unknown"}>`).join(`
344
344
  `),d=Object.keys(t.methods).map((o)=>` ${o}($event?: Event): unknown`).join(`
345
345
  `);return`export interface ${t.name}Props {
@@ -369,7 +369,7 @@ export default ${t.name}
369
369
  `}function $r(t){return`declare global {
370
370
  namespace JSX {
371
371
  interface IntrinsicElements {
372
- ${t.map((r)=>{let d=Object.entries(r.properties).map(([l,u])=>` ${JSON.stringify(l)}?: ${jt(u)}`).join(`
372
+ ${t.map((r)=>{let d=Object.entries(r.properties).map(([l,u])=>` ${JSON.stringify(l)}?: ${Ht(u)}`).join(`
373
373
  `),o=Object.keys(r.events).map((l)=>` ${`on${l.split(/[-:]/).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join("")}`}?: (event: CustomEvent<${r.events[l].detailType||"unknown"}>) => void`).join(`
374
374
  `);return` ${JSON.stringify(r.tag)}: {
375
375
  ${d}
@@ -385,7 +385,7 @@ ${o}
385
385
  }
386
386
 
387
387
  export {}
388
- `}function Cr(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([r,d])=>({kind:"field",name:r,description:d.description,type:{text:jt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||It(r),reflects:d.reflect})),events:Object.entries(n.events).map(([r,d])=>({name:r,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function Zt(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
388
+ `}function Cr(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([r,d])=>({kind:"field",name:r,description:d.description,type:{text:Ht(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||jt(r),reflects:d.reflect})),events:Object.entries(n.events).map(([r,d])=>({name:r,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function Zt(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
389
389
  ${n}
390
390
  }`}function en(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Rr(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),l=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
391
391
  `);return`const definitions = ${JSON.stringify(o,null,2)};
@@ -421,9 +421,9 @@ export function renderComponent(tag, props = {}, slots = {}) {
421
421
  }
422
422
 
423
423
  ${l}
424
- `}async function Ji(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Gt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await tr(n)).map((b)=>({file:b}));if(!o.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(o.map((b)=>vr(n,b,t)));l.sort((b,k)=>b.tag.localeCompare(k.tag));let u=l.filter((b,k)=>l.findIndex((_)=>_.tag===b.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((b,k)=>l.findIndex((_)=>_.name===b.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Xn(r,{recursive:!0});let g=[],h=async(b,k)=>{let _=Te.join(r,b);return await Yn(_,k.endsWith(`
424
+ `}async function Ji(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Gt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await tr(n)).map((b)=>({file:b}));if(!o.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(o.map((b)=>vr(n,b,t)));l.sort((b,k)=>b.tag.localeCompare(k.tag));let u=l.filter((b,k)=>l.findIndex((D)=>D.tag===b.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((b,k)=>l.findIndex((D)=>D.name===b.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Xn(r,{recursive:!0});let g=[],h=async(b,k)=>{let D=Te.join(r,b);return await Yn(D,k.endsWith(`
425
425
  `)?k:`${k}
426
- `,"utf8"),g.push(_),_};await h("runtime.js",wr());for(let b of l){if(await h(`${b.tag}.js`,Sr(b)),t.declarations!==!1)await h(`${b.tag}.d.ts`,kr(b));if(t.css!==!1&&b.styles){let k=b.shadowMode?b.styles:Zt(b);await h(`${b.tag}.css`,t.minify?en(k):k)}}let x=l.map((b)=>`export { ${b.name}, default as ${b.name}Element } from './${b.tag}.js';`).join(`
426
+ `,"utf8"),g.push(D),D};await h("runtime.js",wr());for(let b of l){if(await h(`${b.tag}.js`,Sr(b)),t.declarations!==!1)await h(`${b.tag}.d.ts`,kr(b));if(t.css!==!1&&b.styles){let k=b.shadowMode?b.styles:Zt(b);await h(`${b.tag}.css`,t.minify?en(k):k)}}let x=l.map((b)=>`export { ${b.name}, default as ${b.name}Element } from './${b.tag}.js';`).join(`
427
427
  `);if(await h("index.js",x),await h("ssr.js",Rr(l)),t.declarations!==!1)await h("index.d.ts",l.map((b)=>`export * from './${b.tag}.js'`).join(`
428
428
  `)),await h("custom-elements.d.ts",$r(l)),await h("ssr.d.ts",`${l.map((b)=>`export declare const render${b.name}: (props?: ${b.name}Props, slots?: Record<string, string>) => string`).join(`
429
429
  `)}
@@ -431,11 +431,11 @@ export declare function renderComponent(tag: string, props?: Record<string, unkn
431
431
  ${l.map((b)=>`import type { ${b.name}Props } from './${b.tag}.js'`).join(`
432
432
  `)}`);let v;if(t.manifest!==!1)v=await h("custom-elements.json",JSON.stringify(Cr(l),null,2));let S;if(t.css!==!1){let b=l.filter((k)=>!k.shadowMode&&k.styles).map(Zt).join(`
433
433
 
434
- `);if(b)S=await h("bundle.css",t.minify?en(b):b)}let T;if(t.bundle!==!1){T=Te.join(r,"bundle.js");let b;try{b=await Bun.build({entrypoints:[Te.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(k){let _=k instanceof AggregateError?k.errors:[k],E=_.map((R)=>String(R).trim()).filter(Boolean).join(`
435
- `);throw AggregateError(_,`Failed to bundle component library${E?`
436
- ${E}`:""}`)}if(!b.success){let k=b.logs.map((_)=>String(_).trim()).filter(Boolean).join(`
434
+ `);if(b)S=await h("bundle.css",t.minify?en(b):b)}let T;if(t.bundle!==!1){T=Te.join(r,"bundle.js");let b;try{b=await Bun.build({entrypoints:[Te.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(k){let D=k instanceof AggregateError?k.errors:[k],E=D.map((R)=>String(R).trim()).filter(Boolean).join(`
435
+ `);throw AggregateError(D,`Failed to bundle component library${E?`
436
+ ${E}`:""}`)}if(!b.success){let k=b.logs.map((D)=>String(D).trim()).filter(Boolean).join(`
437
437
  `);throw AggregateError(b.logs,`Failed to bundle component library${k?`
438
- ${k}`:""}`)}if(g.push(T),t.sourcemap==="external")g.push(`${T}.map`)}let w=await Promise.all(g.map(async(b)=>(await Gt(b)).size));return{components:l.map((b)=>({name:b.name,tag:b.tag,source:b.sourcePath,module:Te.join(r,`${b.tag}.js`)})),files:g,manifest:v,bundle:T,cssBundle:S,totalBytes:w.reduce((b,k)=>b+k,0)}}var{serve:Ir}=globalThis.Bun;import Bt from"fs";import tt from"path";function dt(){return`
438
+ ${k}`:""}`)}if(g.push(T),t.sourcemap==="external")g.push(`${T}.map`)}let w=await Promise.all(g.map(async(b)=>(await Gt(b)).size));return{components:l.map((b)=>({name:b.name,tag:b.tag,source:b.sourcePath,module:Te.join(r,`${b.tag}.js`)})),files:g,manifest:v,bundle:T,cssBundle:S,totalBytes:w.reduce((b,k)=>b+k,0)}}var{serve:Ir}=globalThis.Bun;import Ft from"fs";import tt from"path";function dt(){return`
439
439
  /* Theme selector for code blocks */
440
440
  .theme-selector {
441
441
  margin: 1rem 0;
@@ -515,12 +515,12 @@ else {
515
515
  <span class="frontmatter-label">${n}:</span>
516
516
  <span>${Array.isArray(r)?r.join(", "):String(r)}</span>
517
517
  </div>`).join("")}
518
- </div>`}import rn from"net";async function Er(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"0.0.0.0")})}async function Pr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"::")})}async function Or(t){if(!await Er(t))return!1;return await Pr(t)}async function Ve(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Or(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Ar={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Dr(){try{let t=await import("./chunk-dd1vqndp.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let r={...Ar,...n},d=await Dr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
518
+ </div>`}import rn from"net";async function Er(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"0.0.0.0")})}async function Pr(t){return new Promise((n)=>{let r=rn.createServer();r.once("error",()=>n(!1)),r.once("listening",()=>{r.close(()=>n(!0))}),r.listen(t,"::")})}async function Or(t){if(!await Er(t))return!1;return await Pr(t)}async function Ve(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Or(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Ar={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Dr(){try{let t=await import("./chunk-gxrpf87x.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let r={...Ar,...n},d=await Dr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
519
519
  ${l}
520
520
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
521
- `,g=Function(u)();if(g)return g}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function Ht(){console.log(`
522
- 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 Mr(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 _r(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ke(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let d="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(d+=o,d.endsWith("\r")||d.endsWith(`
523
- `)){let l=d.trim().toLowerCase();d="",Lr(l,t,n,r)}})}function Lr(t,n,r,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else _r(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Mr(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Ht();break;default:break}}async function Ft(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=tt.resolve(t);if(!Bt.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,u=async()=>{try{let{content:v,data:S}=await Re(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),T=n.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,w=T?.defaultTheme||"github-dark",b=["github-dark"],k=T?.additionalThemes||[],E=[...new Set([...b,...k])].map((R)=>`<option value="${R}"${R===w?" selected":""}>${R}</option>`).join(`
521
+ `,g=Function(u)();if(g)return g}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function Bt(){console.log(`
522
+ 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 Mr(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`),Bt()}function _r(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ke(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Bt();let d="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(d+=o,d.endsWith("\r")||d.endsWith(`
523
+ `)){let l=d.trim().toLowerCase();d="",Lr(l,t,n,r)}})}function Lr(t,n,r,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else _r(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Mr(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Bt();break;default:break}}async function zt(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=tt.resolve(t);if(!Ft.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,u=async()=>{try{let{content:v,data:S}=await Re(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:I.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),T=n.markdown?.syntaxHighlighting||I.markdown?.syntaxHighlighting,w=T?.defaultTheme||"github-dark",b=["github-dark"],k=T?.additionalThemes||[],E=[...new Set([...b,...k])].map((R)=>`<option value="${R}"${R===w?" selected":""}>${R}</option>`).join(`
524
524
  `);return l=`
525
525
  <!DOCTYPE html>
526
526
  <html lang="en">
@@ -688,7 +688,7 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
688
688
  ${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(`
689
689
  ${e.bright}\u2192 ${e.cyan}http://localhost:${g}/${e.reset}`),console.log(`
690
690
  ${e.yellow}Routes:${e.reset}`);let x=tt.relative(process.cwd(),o);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${x}${e.reset}`),console.log(`
691
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(h.url.toString(),()=>{if(d)Bt.watch(tt.dirname(o),{recursive:!0}).close();h.stop()}),n.native)await Ze(g,{title:tt.basename(o,".md")});if(d){let v=tt.dirname(o);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Bt.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function jr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fr}=globalThis.Bun;import Be from"fs";import ge from"path";class on{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let d=0;d<r;d++)try{if(this.server=Bun.serve({port:n,fetch(o,l){if(l.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let g=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${g}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),r++}catch{this.clients.delete(d)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Br(t,n={}){let{showOverlay:r=!0,reconnectInterval:d=1000,maxReconnectAttempts:o=10}=n;return`
691
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(h.url.toString(),()=>{if(d)Ft.watch(tt.dirname(o),{recursive:!0}).close();h.stop()}),n.native)await Ze(g,{title:tt.basename(o,".md")});if(d){let v=tt.dirname(o);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Ft.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function jr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fr}=globalThis.Bun;import Be from"fs";import ge from"path";class on{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let d=0;d<r;d++)try{if(this.server=Bun.serve({port:n,fetch(o,l){if(l.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let g=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${g}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),r++}catch{this.clients.delete(d)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Br(t,n={}){let{showOverlay:r=!0,reconnectInterval:d=1000,maxReconnectAttempts:o=10}=n;return`
692
692
  <script>
693
693
  (function() {
694
694
  // stx Hot Reload Client
@@ -887,10 +887,10 @@ else {
887
887
  };
888
888
  })();
889
889
  </script>
890
- `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Ss(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let b=await lr(u,r);if(b){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Tr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Tr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let M=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=M;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-et40w1wx.js"),k=b(v.join(`
891
- `),S),_=w.search(/<\/body>/i);if(_!==-1)w=w.slice(0,_)+k+`
892
- `+w.slice(_);else w+=`
893
- ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),r.cache&&r.cachePath){if(await ur(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(B.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:r.debug||X()?`<!DOCTYPE html>
890
+ `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Ss(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let b=await lr(u,r);if(b){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Tr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Tr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ie.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let D=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of D){let A=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",_=C.match(/<script\b([^>]*)>/i),V=_?_[1]:"";if(/\bserver\b/i.test(V))E=A;else R.push(C)}let O=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:O,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(F.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ie.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-7j4tf0ba.js"),k=b(v.join(`
891
+ `),S),D=w.search(/<\/body>/i);if(D!==-1)w=w.slice(0,D)+k+`
892
+ `+w.slice(D);else w+=`
893
+ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),r.cache&&r.cachePath){if(await ur(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(F.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:r.debug||K()?`<!DOCTYPE html>
894
894
  <html lang="en">
895
895
  <head>
896
896
  <meta charset="UTF-8">
@@ -950,12 +950,12 @@ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),r.cache&&r.cachePath){if(await u
950
950
  <h1>Something went wrong</h1>
951
951
  <p>An internal error occurred. Please try again later.</p>
952
952
  </body>
953
- </html>`,loader:"html"}}})}};async function zr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let M={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[M,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=r;try{if(T=await Ve(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let M=n.hmrPort||T+1;l=vt({wsPort:M,verbose:!1}),u=l.start(M)}let w={},b=null,k;try{let{loadStxConfig:M}=await import("./chunk-rp831mk8.js"),I=await M();if(k=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)b=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){w=I.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-mt95md1e.js"),xe=I.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:_,isServerApiSource:E}=await import("./chunk-xqe2jt3f.js"),R=await _(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Fr({port:T,async fetch(M){return $n(M,await(async()=>{let I=new URL(M.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,I.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(M);if(ne.status!==404)return ne}catch{}if(w[I.pathname])try{return await w[I.pathname](M)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(M);if(V)return V;if(I.pathname==="/")return(async()=>{let z=await y(h||"");if(o)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let xe=ge.dirname(f),le=ge.join(xe,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Oe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),L="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
954
- ${M.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
953
+ </html>`,loader:"html"}}})}};async function zr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return zt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let A={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},_=await Bun.build({entrypoints:[f],outdir:g,plugins:[A,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!_.success)return console.error(`${e.red}Build failed:${e.reset}`,_.logs),!1;let V=_.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(A){return console.error(`${e.red}Error building stx file:${e.reset}`,A),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=r;try{if(T=await Ve(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let A=n.hmrPort||T+1;l=vt({wsPort:A,verbose:!1}),u=l.start(A)}let w={},b=null,k;try{let{loadStxConfig:A}=await import("./chunk-vxd3akt4.js"),_=await A();if(k=n.stxOptions?.serverApi??_.serverApi,_?.apiRouter)b=_?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(_?.apiRoutes){w=_.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-mt95md1e.js"),xe=_.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:D,isServerApiSource:E}=await import("./chunk-j0jgc426.js"),R=await D(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let O=Fr({port:T,async fetch(A){return $n(A,await(async()=>{let _=new URL(A.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,_.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(A);if(ne.status!==404)return ne}catch{}if(w[_.pathname])try{return await w[_.pathname](A)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(A);if(V)return V;if(_.pathname==="/")return(async()=>{let z=await y(h||"");if(o)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,_.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let xe=ge.dirname(f),le=ge.join(xe,_.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),M="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}let Oe=ge.join(process.cwd(),"public",_.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),M="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":M="text/html";break;case".css":M="text/css";break;case".js":M="text/javascript";break;case".json":M="application/json";break;case".png":M="image/png";break;case".jpg":case".jpeg":M="image/jpeg";break;case".gif":M="image/gif";break;case".svg":M="image/svg+xml";break;case".ico":M="image/x-icon";break;case".woff":M="font/woff";break;case".woff2":M="font/woff2";break;case".ttf":M="font/ttf";break;case".otf":M="font/otf";break;case".eot":M="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":M}})}return new Response("Not Found",{status:404})})())},error(A){return new Response(`<pre>${A}
954
+ ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
955
955
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
956
956
  ${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
957
957
  ${e.yellow}Routes:${e.reset}`);let C=ge.relative(process.cwd(),f);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${C}${e.reset}`),console.log(`
958
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(A.url.toString(),()=>{if(d)Be.watch(ge.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let M=await Bun.file(f).text(),I=gt(M);await Ze(T,{title:ge.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!I,sidebarConfig:I})}if(d){let M=ge.dirname(f);console.log(`${e.blue}Watching ${e.bright}${M}${e.reset} for changes...`);let I=Be.watch(M,{recursive:!0},async(V,Y)=>{if(!Y||xt(Y))return;if(bt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe();let xe=await x();if(await sr(S),o&&l)if(xe)l.reload(Y);else l.error("Build failed - check console for details")}else if(ht(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),o&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(I.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Pe from"path";var sn=`
958
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(O.url.toString(),()=>{if(d)Be.watch(ge.dirname(f),{recursive:!0}).close();O.stop()}),n.native){let A=await Bun.file(f).text(),_=gt(A);await Ze(T,{title:ge.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!_,sidebarConfig:_})}if(d){let A=ge.dirname(f);console.log(`${e.blue}Watching ${e.bright}${A}${e.reset} for changes...`);let _=Be.watch(A,{recursive:!0},async(V,Y)=>{if(!Y||xt(Y))return;if(bt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe();let xe=await x();if(await sr(S),o&&l)if(xe)l.reload(Y);else l.error("Build failed - check console for details")}else if(ht(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),o&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(_.close(),l)it();O.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Pe from"path";var sn=`
959
959
  <script data-stx-helpers>
960
960
  (function() {
961
961
  'use strict'
@@ -1266,7 +1266,7 @@ else {
1266
1266
 
1267
1267
  })()
1268
1268
  </script>
1269
- `;function ln(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split(Pe.sep)),r=[];for(let d=0;d<n[0].length;d++){let o=n[0][d];if(n.every((l)=>l[d]===o))r.push(o);else break}return r.join(Pe.sep)}async function Hr(t,n={}){let r=n.port||3000,d=n.watch!==!1;for(let w of t){let b=Pe.resolve(w);if(!Xe.existsSync(b))return console.error(`${e.red}Error: File not found: ${e.bright}${b}${e.reset}`),!1;if(!b.endsWith(".stx")&&!b.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${b}${e.reset}. Only .stx and .md files are supported.`),!1}let o=c(process.cwd(),"output");Xe.mkdirSync(o,{recursive:!0});let l=ln(t.map((w)=>Pe.dirname(Pe.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],g=async()=>{try{for(let w of t){let b=Pe.resolve(w);if(b.endsWith(".md"))try{let{content:_,data:E}=await Re(b,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,A=R?.defaultTheme||"github-dark",C=["github-dark"],M=R?.additionalThemes||[],V=[...new Set([...C,...M])].map((Oe)=>`<option value="${Oe}"${Oe===A?" selected":""}>${Oe}</option>`).join(`
1269
+ `;function ln(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split(Pe.sep)),r=[];for(let d=0;d<n[0].length;d++){let o=n[0][d];if(n.every((l)=>l[d]===o))r.push(o);else break}return r.join(Pe.sep)}async function Hr(t,n={}){let r=n.port||3000,d=n.watch!==!1;for(let w of t){let b=Pe.resolve(w);if(!Xe.existsSync(b))return console.error(`${e.red}Error: File not found: ${e.bright}${b}${e.reset}`),!1;if(!b.endsWith(".stx")&&!b.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${b}${e.reset}. Only .stx and .md files are supported.`),!1}let o=c(process.cwd(),"output");Xe.mkdirSync(o,{recursive:!0});let l=ln(t.map((w)=>Pe.dirname(Pe.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],g=async()=>{try{for(let w of t){let b=Pe.resolve(w);if(b.endsWith(".md"))try{let{content:D,data:E}=await Re(b,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:I.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||I.markdown?.syntaxHighlighting,O=R?.defaultTheme||"github-dark",C=["github-dark"],A=R?.additionalThemes||[],V=[...new Set([...C,...A])].map((Oe)=>`<option value="${Oe}"${Oe===O?" selected":""}>${Oe}</option>`).join(`
1270
1270
  `),Y=`
1271
1271
  <!DOCTYPE html>
1272
1272
  <html lang="en">
@@ -1422,32 +1422,32 @@ else {
1422
1422
  ${mt(E)}
1423
1423
  ${pt(V)}
1424
1424
 
1425
- ${_}
1425
+ ${D}
1426
1426
 
1427
1427
  <script>
1428
1428
  ${ut()}
1429
1429
  </script>
1430
1430
  </body>
1431
1431
  </html>
1432
- `,le=`/${Pe.relative(l,b).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";u[le||"/"]={filePath:b,content:Y,fileType:"md"}}catch(_){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,_);continue}else{let _={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(M)=>({path:M.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[b],outdir:o,plugins:[_,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,$e(C.logs,b));continue}let M=C.outputs.find((I)=>I.path.endsWith(".html"));if(!M){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(M.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
1433
- ${$e(C,b)}`);continue}let A=`/${Pe.relative(l,b).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:M}=$s(A,{page:!0});f.push({pattern:C,paramNames:M,filePath:b,routeTemplate:A,fileType:"stx"}),u[A]={filePath:b,content:E,fileType:"stx"}}else u[A||"/"]={filePath:b,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,$e(w)),!1}};if(!await g())return!1;let x=r;try{if(x=await Ve(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} 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:${x}/${e.reset}...`);let v=Nr({port:x,async fetch(w){let b=new URL(w.url),k=Pe.join(process.cwd(),"public",b.pathname);if(Xe.existsSync(k)&&Xe.statSync(k).isFile()){let R=Bun.file(k),A=Pe.extname(k).toLowerCase(),C="application/octet-stream";if(A===".ts"||A===".tsx"){let M=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),I=await R.text(),V=M.transformSync(I);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let _=u[b.pathname];if(!_&&!b.pathname.endsWith("/"))_=u[`${b.pathname}/`];if(!_)for(let R of f){let A=b.pathname.match(R.pattern);if(A){let C=u[R.routeTemplate];if(C){let M={};for(let Y=0;Y<R.paramNames.length;Y++)M[R.paramNames[Y]]=decodeURIComponent(A[Y+1]);let I=C.content,V=`<script>window.__routeParams = ${JSON.stringify(M)};</script>`;if(I.includes("</head>"))I=I.replace("</head>",`${V}
1434
- </head>`);else I=V+I;_={...C,content:I}}break}}if(_)return y(_.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${sn}
1435
- </head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Pe.join(o,b.pathname);if(Xe.existsSync(E)&&Xe.statSync(E).isFile()){let R=Bun.file(E),A=Pe.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let M=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),I=await R.text(),V=M.transformSync(I);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(b.pathname!=="/"&&u["/"]){let R=Ce(w);return y(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let M=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),I=M?M[1]:"",V=`<!DOCTYPE html><html><head><title>${an(I)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...D(),"Cache-Control":ft,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
1432
+ `,le=`/${Pe.relative(l,b).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";u[le||"/"]={filePath:b,content:Y,fileType:"md"}}catch(D){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,D);continue}else{let D={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(A)=>({path:A.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[b],outdir:o,plugins:[D,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,$e(C.logs,b));continue}let A=C.outputs.find((_)=>_.path.endsWith(".html"));if(!A){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(A.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
1433
+ ${$e(C,b)}`);continue}let O=`/${Pe.relative(l,b).replace(/\.stx$/,"")}`;if(O.endsWith("/index"))O=O.slice(0,-6)||"/";if(O.includes("[")){let{regex:C,params:A}=$s(O,{page:!0});f.push({pattern:C,paramNames:A,filePath:b,routeTemplate:O,fileType:"stx"}),u[O]={filePath:b,content:E,fileType:"stx"}}else u[O||"/"]={filePath:b,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,$e(w)),!1}};if(!await g())return!1;let x=r;try{if(x=await Ve(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} 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:${x}/${e.reset}...`);let v=Nr({port:x,async fetch(w){let b=new URL(w.url),k=Pe.join(process.cwd(),"public",b.pathname);if(Xe.existsSync(k)&&Xe.statSync(k).isFile()){let R=Bun.file(k),O=Pe.extname(k).toLowerCase(),C="application/octet-stream";if(O===".ts"||O===".tsx"){let A=new Bun.Transpiler({loader:O===".tsx"?"tsx":"ts"}),_=await R.text(),V=A.transformSync(_);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(O){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let D=u[b.pathname];if(!D&&!b.pathname.endsWith("/"))D=u[`${b.pathname}/`];if(!D)for(let R of f){let O=b.pathname.match(R.pattern);if(O){let C=u[R.routeTemplate];if(C){let A={};for(let Y=0;Y<R.paramNames.length;Y++)A[R.paramNames[Y]]=decodeURIComponent(O[Y+1]);let _=C.content,V=`<script>window.__routeParams = ${JSON.stringify(A)};</script>`;if(_.includes("</head>"))_=_.replace("</head>",`${V}
1434
+ </head>`);else _=V+_;D={...C,content:_}}break}}if(D)return y(D.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${sn}
1435
+ </head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Pe.join(o,b.pathname);if(Xe.existsSync(E)&&Xe.statSync(E).isFile()){let R=Bun.file(E),O=Pe.extname(E).toLowerCase(),C="text/plain";if(O===".ts"||O===".tsx"){let A=new Bun.Transpiler({loader:O===".tsx"?"tsx":"ts"}),_=await R.text(),V=A.transformSync(_);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(O){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(b.pathname!=="/"&&u["/"]){let R=Ce(w);return y(u["/"].content).then((O)=>{if(R){let C=O.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let A=O.match(/<title[^>]*>([\s\S]*?)<\/title>/i),_=A?A[1]:"",V=`<!DOCTYPE html><html><head><title>${an(_)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...L(),"Cache-Control":ft,Pragma:"no-cache",Expires:"0"}})}}return new Response(O,{headers:{"Content-Type":"text/html",...L(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
1436
1436
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1437
1437
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1438
1438
  ${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
1439
- ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let _=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${_}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Vr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-rp831mk8.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-xqe2jt3f.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=K(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=K(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,M=null;if(n.stxOptions?.shell!==!1){if(M=await ca(f,n.stxOptions?.shell),M){if(C=await mo(M,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-rp831mk8.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-mt95md1e.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=c(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Rs(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-rp831mk8.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-pfygdsms.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-rp831mk8.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-et40w1wx.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-m6a8mftb.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=r;try{if(Ge=await Ve(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let O=n.hmrPort||Ge+1;l=vt({wsPort:O,verbose:!1}),u=l.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Ur({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Mo(N,is()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-7m4eesp0.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&la(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[sc]:is(),...D(),"Cache-Control":ft}})}if(C)F=Xr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),o)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-m6a8mftb.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Xr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),o)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=Xr(C,ue);if(ue=await y(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
1441
- ${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1439
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let D=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${D}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Vr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-vxd3akt4.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-j0jgc426.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let D=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(D.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${D.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:j}of E)if(me.existsSync(P)){let N=X(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let O=new Map,C=null,A=null;if(n.stxOptions?.shell!==!1){if(A=await ca(f,n.stxOptions?.shell),A){if(C=await mo(A,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,A)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let _=_t();if(_.length>0)console.log(`${e.blue}Loaded ${e.bright}${_.length}${e.blue} middleware: ${e.dim}${_.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-vxd3akt4.js"),j=await P(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-mt95md1e.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=c(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(P)=>{let j=Rs(k,P);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,M=async(P,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-vxd3akt4.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-yxsrerew.js"),G=await Ae(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let se=pe.get(P.filePath);if(se)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=gn(Z),{classifyAllScripts:ue}=await import("./chunk-vxd3akt4.js"),B=ue(Z),Le=B.server.map((se)=>se.content),Me=Z;for(let se of B.server)Me=Me.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let se=performance.now();he=await N(Me,ee,P.filePath,ce,De);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,P.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:se}=await import("./chunk-7j4tf0ba.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-z0kx564w.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(P.pattern);else Qe=void 0;let Vt=It(ee),qt=Ot(ee);if(H)z.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),j=new Set(O.keys());le.clear(),O.clear();let N=n.prebuild===!1?D.filter((q)=>P.has(q.pattern)):D,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>M(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>M(U)));for(let U of ve)if(U)O.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?D.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=r;try{if(Ge=await Ve(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Ur({port:Ge,hostname:n.hostname,async fetch(P){let j=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Mo(N,is()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Ae,f,S))return Nt(Ae);if(W?.isFile()&&!v(ve,f,S))return Nt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-jy9qmwpm.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(P);if(pe)return pe;let G=pr(j.pathname,D);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await M(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,P,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let B=H.content;if(C&&la(P)&&qe(B,h?.router?.container||"main")){let Le=et(B),Me=be(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)B=Pt(B,G.params);B=await y(B,f);let he=h?.router?.container||"main";return B=Ee(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[sc]:is(),...L(),"Cache-Control":ft}})}if(C)B=Kr(C,B);if(Object.keys(G.params).length>0)B=Pt(B,G.params);if(B=await y(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-z0kx564w.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...L(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=O.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await M(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)O.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=Kr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await y(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let oe=O.get(Z)||O.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await M(ue.route);if(B)oe=B,O.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=Kr(C,ue);if(ue=await y(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1441
+ ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1442
1442
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1443
1443
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
- ${e.yellow}Routes:${e.reset}`);let Dt=[...As(_,f)];for(let{route:O}of R)Dt.push(`${O.pattern}`);if(Dt.forEach((O,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${O}`)}),console.log(`
1445
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...K(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-pfygdsms.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(M&&W){if(te.resolve(U,W)===M||te.basename(M)===W){let G=await mo(M,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-pfygdsms.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1444
+ ${e.yellow}Routes:${e.reset}`);let Dt=[...As(D,f)];for(let{route:P}of R)Dt.push(`${P.pattern}`);if(Dt.forEach((P,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1445
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();P=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),D.splice(0,D.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-yxsrerew.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(A&&W){if(te.resolve(U,W)===A||te.basename(A)===W){let G=await mo(A,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-yxsrerew.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1446
1446
  `).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function qr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1447
- `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Wr(t),l=await qr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
1447
+ `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Wr(t),l=await qr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
1448
1448
  `);u=`<${d}
1449
1449
  ${f}
1450
- />`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function pn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){let o=at.join(t,d.name);if(d.isDirectory()){let l=await pn(o);r.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Gr(t,n){try{if(!await s(t))return[];let r=await pn(t),d=[],o=new Map;if(n?.components?.length)for(let l of n.components)o.set(l.file,l);for(let l of r){let u=o.get(l),f=!!u,g=u?.tag,h=await Kr(l,f,g);d.push(h)}return d}catch(r){return console.error("Error generating component docs:",r),[]}}async function Jr(t){try{if(!await s(t))return[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let o=at.join(t,d.name),l=await Bun.file(o).text(),u=at.basename(o,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),g=f?f[1].split(`
1450
+ />`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function pn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){let o=at.join(t,d.name);if(d.isDirectory()){let l=await pn(o);r.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Gr(t,n){try{if(!await s(t))return[];let r=await pn(t),d=[],o=new Map;if(n?.components?.length)for(let l of n.components)o.set(l.file,l);for(let l of r){let u=o.get(l),f=!!u,g=u?.tag,h=await Xr(l,f,g);d.push(h)}return d}catch(r){return console.error("Error generating component docs:",r),[]}}async function Jr(t){try{if(!await s(t))return[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let o=at.join(t,d.name),l=await Bun.file(o).text(),u=at.basename(o,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),g=f?f[1].split(`
1451
1451
  `).map((b)=>b.trim().replace(/^\*\s*/,"")).join(" ").trim():"",h=/@component\(\s*['"]([^'"]+)['"]/g,x=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,v=new Set,S;while((S=h.exec(l))!==null)v.add(S[1]);while((S=x.exec(l))!==null)if(S[1]&&S[1]!=="slot")v.add(S[1]);let T=/@([a-z]+)(?:\s*\(|\s+|$)/g,w=new Set;while((S=T.exec(l))!==null)w.add(S[1]);r.push({name:u,path:o,description:g,components:[...v],directives:[...w]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function Yr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1452
1452
  <p>Welcome, {{ user.name }}!</p>
1453
1453
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
@@ -1581,7 +1581,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.
1581
1581
  <td>@${l.name}</td>
1582
1582
  <td>${l.description||"-"}</td>
1583
1583
  <td>${l.hasEndTag?"Yes":"No"}</td>
1584
- </tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function eo(t=[],n=[],r=[],d){return JSON.stringify({components:t,templates:n,directives:r,extraContent:d||""},null,2)}async function to(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:d,customDirectives:o,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Gr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&r)console.log("Generating template documentation..."),g=await Jr(r),console.log(`Found ${g.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Yr(o),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Qr(f,g,h,v),T="md";break;case"html":S=Zr(f,g,h,v),T="html";break;case"json":S=eo(f,g,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function Yi(t){let n={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},r=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return to({componentsDir:r,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:n})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function io(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1584
+ </tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function eo(t=[],n=[],r=[],d){return JSON.stringify({components:t,templates:n,directives:r,extraContent:d||""},null,2)}async function to(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:d,customDirectives:o,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Gr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&r)console.log("Generating template documentation..."),g=await Jr(r),console.log(`Found ${g.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Yr(o),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Qr(f,g,h,v),T="md";break;case"html":S=Zr(f,g,h,v),T="html";break;case"json":S=eo(f,g,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function Yi(t){let n={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},r=t.componentsDir||I.componentsDir,d=t.templatesDir||".";return to({componentsDir:r,templatesDir:d,webComponentsConfig:I.webComponents,customDirectives:I.customDirectives,config:n})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function io(t,n={}){let r={...fn,...n};if(t.trim()==="")return`
1585
1585
  `;let d=t;if(r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=oo(d,r),d=uo(d,r),d=so(d,r),r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!d.endsWith(`
@@ -1612,7 +1612,7 @@ ${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,l,u,f)=>{let g=f.substring(Math.max
1612
1612
  `),n=n.split(`
1613
1613
  `).map((o)=>o.trim()).join(`
1614
1614
  `),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function oo(t,n){let d=ro(t).split(`
1615
- `),o=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let g=0;g<d.length;g++){let h=d[g],x=h.trim();if(x===""){o.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){o.push(h);continue}let T=x===">";if(un(x)&&!x.startsWith("<")&&!x.startsWith("@")){o.push(f.repeat(l)+x);continue}let w=x.startsWith("@end"),b=x.startsWith("@else")||x.startsWith("@elseif"),k=x.startsWith("@")&&po(x),_=x.startsWith("<!DOCTYPE")||x.startsWith("<!doctype"),E=x.startsWith("<!--"),R=x.startsWith("</"),A=x.startsWith("<")&&!R&&!E&&!_,C=x.includes("/>")||lo(x),M=un(x);if(R||w)l=Math.max(0,l-1);let I=b?Math.max(0,l-1):l;if(T)o.push(h);else o.push(f.repeat(I)+x);if(A&&!C&&!M&&!T||k)l++;if(v)u=!0;if(S)u=!1}return o.join(`
1615
+ `),o=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let g=0;g<d.length;g++){let h=d[g],x=h.trim();if(x===""){o.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){o.push(h);continue}let T=x===">";if(un(x)&&!x.startsWith("<")&&!x.startsWith("@")){o.push(f.repeat(l)+x);continue}let w=x.startsWith("@end"),b=x.startsWith("@else")||x.startsWith("@elseif"),k=x.startsWith("@")&&po(x),D=x.startsWith("<!DOCTYPE")||x.startsWith("<!doctype"),E=x.startsWith("<!--"),R=x.startsWith("</"),O=x.startsWith("<")&&!R&&!E&&!D,C=x.includes("/>")||lo(x),A=un(x);if(R||w)l=Math.max(0,l-1);let _=b?Math.max(0,l-1):l;if(T)o.push(h);else o.push(f.repeat(_)+x);if(O&&!C&&!A&&!T||k)l++;if(v)u=!0;if(S)u=!1}return o.join(`
1616
1616
  `)}function so(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,d,o)=>{let l=o.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,d,o)=>{if(o.trim()==="")return`@${d}`;return`@${d}(${o.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,d)=>`{!! ${d.trim()} !!}`);return t}function lo(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let r=t.match(/<(\w+)/);if(r){let d=r[1];return n.includes(d.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function po(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of n)if(t.startsWith(`@${r}`))return!t.includes(`@end${r}`);return!1}function uo(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(r,d,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
1617
1617
  `)||o.includes("@"))return r;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(o))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let g=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${g?` ${g}`:""}>`})}import mn from"fs";import Wt from"path";async function Qi(t="index.stx",n={}){try{let r=n.force||!1,d=Wt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Wt.dirname(d);if(!mn.existsSync(o))mn.mkdirSync(o,{recursive:!0});let l;if(n.template){let u=Wt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)l=hn(n.preset),console.warn(`Using '${n.preset}' preset template`);else l=hn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function hn(t){switch(t){case"basic":return yn();case"component":return fo();case"layout":return go();case"blog":return ho();case"api":return yo();case"app":return bo();default:return yn()}}function yn(){return`<script>
1618
1618
  const title = "My stx Page"
@@ -2040,5 +2040,5 @@ const features = [
2040
2040
  })();
2041
2041
  </script>
2042
2042
  </body>
2043
- </html>`}var ea="f9c3713";function El(t){return t}function Tl(t){return t}function Ki(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function Rn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Rt(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $i(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function En(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Ci(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ri(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,g){if(g>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Pn){let S=ye.join(f,v),T=Ci(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:g>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let b of w){let k=ye.join(S,b.name,"node_modules");if(_e.existsSync(k))l(k,g+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,g+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ei(t){let n=[];for(let r of Pn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function ao(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??$i,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let g of Ei(Ri(n)))o.push(g);let f=En(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let g=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=Rn(g),v=h?Rn(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(v,d)}) is OLDER than src/signals.ts (${Rt(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(x,d)}, dist ${Rt(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let b=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===b?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(g){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${g.message}`})}return{checks:o,ok:!o.some((g)=>g.status==="error")}}function co(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2044
- `)}export{Ki,Gi,Ji,Yi,io,Zi,Qi,ea,El,Tl,ao,co,zr,Hr,Vr};
2043
+ </html>`}var ea="f9c3713";function El(t){return t}function Tl(t){return t}function Xi(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function Rn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Rt(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $i(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function En(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Ci(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ri(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,g){if(g>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Pn){let S=ye.join(f,v),T=Ci(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:g>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let b of w){let k=ye.join(S,b.name,"node_modules");if(_e.existsSync(k))l(k,g+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,g+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ei(t){let n=[];for(let r of Pn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function ao(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??$i,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let g of Ei(Ri(n)))o.push(g);let f=En(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let g=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=Rn(g),v=h?Rn(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(v,d)}) is OLDER than src/signals.ts (${Rt(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(x,d)}, dist ${Rt(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let b=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===b?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(g){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${g.message}`})}return{checks:o,ok:!o.some((g)=>g.status==="error")}}function co(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2044
+ `)}export{Xi,Gi,Ji,Yi,io,Zi,Qi,ea,El,Tl,ao,co,zr,Hr,Vr};