@stacksjs/stx 0.2.907 → 0.2.909

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 (83) hide show
  1. package/dist/chunk-0b0y695e.js +2 -0
  2. package/dist/{chunk-x39v2ch2.js → chunk-0mxkw6m6.js} +10 -5
  3. package/dist/{chunk-5m4zgt4m.js → chunk-162e363h.js} +1 -1
  4. package/dist/{chunk-bcspywrd.js → chunk-2epswh9w.js} +1 -1
  5. package/dist/{chunk-ta5fpj2a.js → chunk-2pagy1jn.js} +1 -1
  6. package/dist/{chunk-nmywrw6v.js → chunk-376714qg.js} +1 -1
  7. package/dist/{chunk-z0d1asbw.js → chunk-3b8epemd.js} +1 -1
  8. package/dist/{chunk-se0pjx71.js → chunk-3dx77nfw.js} +1 -1
  9. package/dist/{chunk-42z7zv92.js → chunk-3khg2ats.js} +1 -1
  10. package/dist/{chunk-w1pga3s6.js → chunk-440epzas.js} +1 -1
  11. package/dist/{chunk-rt6fn071.js → chunk-4ge69wvr.js} +1 -1
  12. package/dist/{chunk-e4tbq8a0.js → chunk-4nkzj2pj.js} +2 -2
  13. package/dist/{chunk-4a6mptfc.js → chunk-581qafp7.js} +1 -1
  14. package/dist/{chunk-vbh5tknp.js → chunk-59wq842b.js} +1 -1
  15. package/dist/{chunk-gjzs6p2v.js → chunk-5crybqrs.js} +1 -1
  16. package/dist/{chunk-wxk0t61p.js → chunk-5g2svr3g.js} +1 -1
  17. package/dist/{chunk-nzqr3w35.js → chunk-66tpsdpm.js} +4 -4
  18. package/dist/{chunk-96wdxfn4.js → chunk-69yqdxck.js} +1 -1
  19. package/dist/{chunk-ab1z38gj.js → chunk-73py4qeh.js} +1 -1
  20. package/dist/{chunk-m9cye9t8.js → chunk-8njqq95v.js} +5 -5
  21. package/dist/{chunk-yt8k715e.js → chunk-8zx8zgwe.js} +1 -1
  22. package/dist/{chunk-sjrx0dj8.js → chunk-9mmdtd5q.js} +1 -1
  23. package/dist/{chunk-9xzej52j.js → chunk-9yb1hke7.js} +1 -1
  24. package/dist/{chunk-kcphqn2k.js → chunk-c43kvce7.js} +1 -1
  25. package/dist/{chunk-mkm9drk3.js → chunk-drmp871t.js} +1 -1
  26. package/dist/{chunk-q2jag6wt.js → chunk-dyg45v6h.js} +1 -1
  27. package/dist/{chunk-zrsrhdxw.js → chunk-e5n8wfj2.js} +1 -1
  28. package/dist/{chunk-vmphrcaa.js → chunk-e6za83ty.js} +1 -1
  29. package/dist/chunk-e99ccfbw.js +2 -0
  30. package/dist/{chunk-c5cxpkfy.js → chunk-eavaz8vm.js} +2 -2
  31. package/dist/{chunk-xpcqyzdc.js → chunk-fkm2bf2x.js} +1 -1
  32. package/dist/chunk-g9dxcxk0.js +2 -0
  33. package/dist/{chunk-6qgrr453.js → chunk-gjk0nzyy.js} +1 -1
  34. package/dist/{chunk-wna2herj.js → chunk-gmjsnh5h.js} +1 -1
  35. package/dist/chunk-jvpnd7zd.js +2 -0
  36. package/dist/{chunk-3611xczp.js → chunk-k3eab0c5.js} +1 -1
  37. package/dist/{chunk-yqs88qj4.js → chunk-kp957mbs.js} +1 -1
  38. package/dist/{chunk-fwffn130.js → chunk-m2t2gpjb.js} +2 -2
  39. package/dist/{chunk-qvj0bzw5.js → chunk-mv1hr9d4.js} +4 -4
  40. package/dist/chunk-n73v0pcq.js +2 -0
  41. package/dist/chunk-p7rwa0xw.js +2 -0
  42. package/dist/{chunk-xfjp5q2m.js → chunk-p8p0xs8g.js} +2 -2
  43. package/dist/{chunk-83g4169y.js → chunk-pbs4db9n.js} +4 -4
  44. package/dist/chunk-pdfnq2gs.js +3 -0
  45. package/dist/{chunk-20zx1msx.js → chunk-q7k0eha6.js} +1 -1
  46. package/dist/{chunk-4dh1b9yr.js → chunk-q91hentn.js} +1 -1
  47. package/dist/{chunk-j90sfypd.js → chunk-r3hb020a.js} +1 -1
  48. package/dist/chunk-r643mp2v.js +2 -0
  49. package/dist/{chunk-jj78m9k1.js → chunk-r8gv2pcy.js} +4 -4
  50. package/dist/{chunk-xahn0h9f.js → chunk-rgrh0fpj.js} +1 -1
  51. package/dist/{chunk-3yr0wyc9.js → chunk-rmz99qwk.js} +1 -1
  52. package/dist/{chunk-fds6vvq0.js → chunk-snhsh171.js} +107 -107
  53. package/dist/{chunk-bpx9cys7.js → chunk-t9ad2qwm.js} +2 -2
  54. package/dist/{chunk-wk6g0b9h.js → chunk-tcytjgh5.js} +1 -1
  55. package/dist/{chunk-9bc23bv2.js → chunk-tktgaz78.js} +1 -1
  56. package/dist/{chunk-zcwx8z8z.js → chunk-tszsy2pv.js} +2 -2
  57. package/dist/chunk-tw1rbnc3.js +2 -0
  58. package/dist/{chunk-p3et6xjr.js → chunk-txsre59k.js} +1 -1
  59. package/dist/{chunk-exc8y30f.js → chunk-va00ve6h.js} +1 -1
  60. package/dist/{chunk-4345d8s9.js → chunk-w83rcgej.js} +1 -1
  61. package/dist/{chunk-r5xt6vdq.js → chunk-x6n0r41y.js} +1 -1
  62. package/dist/{chunk-afmmrqee.js → chunk-xf3j14d6.js} +1 -1
  63. package/dist/{chunk-gjnxnfrg.js → chunk-xprmhc0y.js} +1 -1
  64. package/dist/{chunk-tszhkmny.js → chunk-y7caf6hd.js} +3 -3
  65. package/dist/{chunk-6bgerbgh.js → chunk-yqxhy0nq.js} +1 -1
  66. package/dist/{chunk-4nc8vdef.js → chunk-yy71cxxj.js} +1 -1
  67. package/dist/cli.js +8 -8
  68. package/dist/client/signals-loop-conditional-runtime.js +5 -0
  69. package/dist/craft-entry.js +1 -1
  70. package/dist/craft.js +1 -1
  71. package/dist/pwa.js +1 -1
  72. package/dist/ssg.js +2 -2
  73. package/dist/stx-virtual-ts.js +5 -9
  74. package/package.json +5 -5
  75. package/dist/chunk-218pnbaf.js +0 -2
  76. package/dist/chunk-257msenj.js +0 -3
  77. package/dist/chunk-291860br.js +0 -2
  78. package/dist/chunk-3dy3hr8r.js +0 -2
  79. package/dist/chunk-47ver0g7.js +0 -2
  80. package/dist/chunk-4b9jx2c1.js +0 -2
  81. package/dist/chunk-j661q889.js +0 -2
  82. package/dist/chunk-qq31bcsq.js +0 -2
  83. package/dist/chunk-wchz1sye.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{B,An,Kt,Xt,y,s,Ce,g}from"./chunk-fds6vvq0.js";import{Pt,Ue,Oc,Es,si,oi,i}from"./chunk-jj78m9k1.js";import{we}from"./chunk-0jdz31q1.js";import{ce,Vr,De,K,jn}from"./chunk-c08jvjqt.js";import{Dt,Rr,Ks,Xs,Gs,Lt,jt,Bt,Ft,zt,Ht,We}from"./chunk-b234w3mf.js";import{zs,a,j}from"./chunk-xfjp5q2m.js";import{Et,cn,Be,V,Da,Bo,ps,ot,La,Tt,Fe}from"./chunk-tszhkmny.js";import{Er,Tr}from"./chunk-xpcqyzdc.js";import{e,Sn,xr,S}from"./chunk-e4tbq8a0.js";import{lt}from"./chunk-qvj0bzw5.js";import{He}from"./chunk-cwcmmgvz.js";import{Wn}from"./chunk-3611xczp.js";import{re,Ae,Pe}from"./chunk-nzqr3w35.js";import{l}from"./chunk-w4177qn3.js";import{ne}from"./chunk-e5rag6rh.js";import{c,f}from"./chunk-8tfpv6zf.js";async function Rn(n){try{let t=await Bun.file(n).text(),o=Pn(t),d=En(t,n),r=On(t,o),p=Dn(t,o);return{file:n,metrics:o,issues:d,suggestions:r,performance:p}}catch(t){throw Error(`Failed to analyze template ${n}: ${t instanceof Error?t.message:String(t)}`)}}function Pn(n){let t=n.split(`
2
+ import{B,An,Kt,Xt,y,s,Ce,g}from"./chunk-snhsh171.js";import{Pt,Ue,Oc,Es,si,oi,i}from"./chunk-r8gv2pcy.js";import{we}from"./chunk-0jdz31q1.js";import{ce,Vr,De,K,jn}from"./chunk-c08jvjqt.js";import{Dt,Rr,Ks,Xs,Gs,Lt,jt,Bt,Ft,zt,Ht,We}from"./chunk-b234w3mf.js";import{zs,a,j}from"./chunk-p8p0xs8g.js";import{Et,cn,Be,V,Da,Bo,ps,ot,La,Tt,Fe}from"./chunk-y7caf6hd.js";import{Er,Tr}from"./chunk-fkm2bf2x.js";import{e,Sn,xr,S}from"./chunk-4nkzj2pj.js";import{lt}from"./chunk-mv1hr9d4.js";import{He}from"./chunk-cwcmmgvz.js";import{Wn}from"./chunk-k3eab0c5.js";import{re,Ae,Pe}from"./chunk-66tpsdpm.js";import{l}from"./chunk-w4177qn3.js";import{ne}from"./chunk-e5rag6rh.js";import{c,f}from"./chunk-8tfpv6zf.js";async function Rn(n){try{let t=await Bun.file(n).text(),o=Pn(t),d=En(t,n),r=On(t,o),p=Dn(t,o);return{file:n,metrics:o,issues:d,suggestions:r,performance:p}}catch(t){throw Error(`Failed to analyze template ${n}: ${t instanceof Error?t.message:String(t)}`)}}function Pn(n){let t=n.split(`
3
3
  `),o=n.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),r=(o?o[1]:"").split(`
4
4
  `).length,p={conditionals:(n.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(n.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(n.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};p.total=p.conditionals+p.loops+p.includes+p.custom;let u=(n.match(/\{\{[\s\S]*?\}\}/g)||[]).length,m=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length,x=(n.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+m+x,b=(n.match(/<[A-Z][^>]*>/g)||[]).length,C=(n.match(/@(?:layout|extends)\(/g)||[]).length,R=0,O=0;for(let A of t)if(/@(?:if|unless|foreach|for|while|section)\b/.test(A)&&!/@end/.test(A)&&!/@else/.test(A))O++,R=Math.max(R,O);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(A))O--;let v=R>=4?3:0,w=Math.min(10,Math.ceil(p.total*0.5+h*0.1+b*0.3+(r>10?r*0.05:0)+v));return{lines:t.length,characters:n.length,directives:p,expressions:h,components:b,layouts:C,scriptLines:r,complexity:w}}function En(n,t){let o=[],d=Ut(n,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let r=Ut(n,"foreach","endforeach");if(r>0)o.push({type:"error",category:"syntax",message:`Found ${r} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let p=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let m=n.match(/<img[^>]*>/g);if(m){let b=m.filter((C)=>!C.includes("alt="));if(b.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let x=n.split(`
5
5
  `).filter((b)=>b.length>120);if(x.length>0)o.push({type:"info",category:"maintainability",message:`Found ${x.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(n.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function On(n,t){let o=[];if(t.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(t.complexity>5&&t.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(t.lines>100&&t.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(t.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(t.directives.total===0&&t.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(t.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Dn(n,t){let o=1;if(o+=t.directives.conditionals*0.1,o+=t.directives.loops*0.5,o+=t.directives.includes*2,o+=t.expressions*0.05,o+=t.components*1,t.scriptLines>10)o+=t.scriptLines*0.1;let d;if(t.expressions===0&&t.directives.total===0)d="high";else if(t.expressions<5&&t.directives.total<3)d="medium";else d="low";let r=[];if(o>10)r.push("Consider optimizing template complexity");if(d==="low"&&t.directives.total>5)r.push("Reduce dynamic content for better caching");if(t.components===0&&t.lines>40)r.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:t.complexity,cacheability:d,recommendations:r}}function Ut(n,t,o){let d=n.replace(/<!--[\s\S]*?-->/g,""),r=(d.match(new RegExp(`@${t}\\b`,"g"))||[]).length,p=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(r-p)}async function Ca(n=["**/*.stx"],t){let o=[],d=[];for(let p of n){let u=await Array.fromAsync(new Bun.Glob(p).scan({cwd:t||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((m)=>m.endsWith(".stx")))}for(let p of d)try{let u=await Rn(p);o.push(u)}catch(u){console.warn(`Failed to analyze ${p}:`,u)}let r=Mn(o);return{results:o,summary:r}}function Mn(n){let t=n.length,o=n.reduce((h,b)=>h+b.metrics.lines,0),d=t>0?n.reduce((h,b)=>h+b.metrics.complexity,0)/t:0,r=n.reduce((h,b)=>h+b.issues.length,0),p={};n.forEach((h)=>{h.issues.forEach((b)=>{p[b.category]=(p[b.category]||0)+1})});let u=t>0?n.reduce((h,b)=>h+b.performance.estimatedRenderTime,0)/t:0,m=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),x=[];if(d>6)x.push("Project has high average complexity. Consider refactoring complex templates.");if(r>t*2)x.push("High number of issues detected. Run detailed analysis on individual files.");if(p.security>0)x.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:t,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:r,issuesByCategory:p,performanceScore:m,recommendations:x}}var{serve:Un}=globalThis.Bun;import $t from"fs";import Ze from"path";function dt(){return`
@@ -454,7 +454,7 @@ else {
454
454
  };
455
455
  })();
456
456
  </script>
457
- `}function Ne(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function gt(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function ht(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function yt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var et=null;function xt(n){if(!et)et=new Wt(n);return et}function st(){if(et)et.stop(),et=null}import bt from"path";var tt={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${bt.relative(bt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await zs(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let w=await Er(u,o);if(w){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:w,loader:"html"}}}let x=await De(()=>Bun.file(u).text(),"",(w)=>{throw new Vr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${w.message}`)});if(!x)throw new Vr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:b,allScripts:C}=we.time("script-extraction",()=>{let w=x,A=B(x);if(A)w=A.content.trim();let U=x.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],se="",I=[];for(let k of U){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),q=D?D[1]:"";if(/\bserver\b/i.test(q))se=P;else I.push(k)}let L=w.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:se,templateContent:L,allScripts:I}}),R={__filename:u,__dirname:bt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await De(()=>y(h,R,u),void 0,(w)=>{let A=new ce(`Script execution failed in ${u}: ${w.message}`,u,void 0,void 0,h.substring(0,100));if(K.log(A,{filePath:u,scriptContent:h}),o.debug)throw A});let v=await we.timeAsync("directive-processing",async()=>await i(b,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:w}=await import("./chunk-96wdxfn4.js"),A=w(C.join(`
457
+ `}function Ne(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function gt(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function ht(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function yt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var et=null;function xt(n){if(!et)et=new Wt(n);return et}function st(){if(et)et.stop(),et=null}import bt from"path";var tt={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${bt.relative(bt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await zs(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let w=await Er(u,o);if(w){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:w,loader:"html"}}}let x=await De(()=>Bun.file(u).text(),"",(w)=>{throw new Vr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${w.message}`)});if(!x)throw new Vr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:b,allScripts:C}=we.time("script-extraction",()=>{let w=x,A=B(x);if(A)w=A.content.trim();let U=x.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],se="",I=[];for(let k of U){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),q=D?D[1]:"";if(/\bserver\b/i.test(q))se=P;else I.push(k)}let L=w.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:se,templateContent:L,allScripts:I}}),R={__filename:u,__dirname:bt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await De(()=>y(h,R,u),void 0,(w)=>{let A=new ce(`Script execution failed in ${u}: ${w.message}`,u,void 0,void 0,h.substring(0,100));if(K.log(A,{filePath:u,scriptContent:h}),o.debug)throw A});let v=await we.timeAsync("directive-processing",async()=>await i(b,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:w}=await import("./chunk-69yqdxck.js"),A=w(C.join(`
458
458
  `),R),U=v.search(/<\/body>/i);if(U!==-1)v=v.slice(0,U)+A+`
459
459
  `+v.slice(U);else v+=`
460
460
  ${A}`}if(v=await Pe(v),m.forEach((w)=>d.add(w)),o.cache&&o.cachePath){if(await Tr(u,v,m,o),o.debug)console.log(`Cached template ${u} with ${m.size} dependencies`)}return{contents:v,loader:"html"}}catch(m){let x=m instanceof Error?m:new ce(`Plugin processing failed: ${String(m)}`,u);if(K.log(x,{filePath:u,buildConfig:n.config}),jn.logDetailedError(x,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",x);let h=x,b=h.line||null,C=h.context||null;return{contents:o.debug||ne()?`<!DOCTYPE html>
@@ -517,7 +517,7 @@ ${A}`}if(v=await Pe(v),m.forEach((w)=>d.add(w)),o.cache&&o.cachePath){if(await T
517
517
  <h1>Something went wrong</h1>
518
518
  <p>An internal error occurred. Please try again later.</p>
519
519
  </body>
520
- </html>`,loader:"html"}}})}};async function os(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Rt(m,t);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let x=l(process.cwd(),"output");Ie.mkdirSync(x,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let h=null,b=async()=>{try{let P={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:x,plugins:[P,tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let q=D.outputs.find((xe)=>xe.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(q.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await b())return!1;let R=ge.dirname(m);await Sn(R);let O=o;try{if(O=await qe(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=xt({wsPort:P,verbose:!1}),u=p.start(P)}let v={},w=null,A;try{let{loadStxConfig:P}=await import("./chunk-3dy3hr8r.js"),D=await P();if(A=t.stxOptions?.serverApi??D.serverApi,D?.apiRouter)w=D?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(D?.apiRoutes){v=D.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(D?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Q}=await import("./chunk-cjq455ve.js"),xe=D.broadcasting;await q(xe);let pe=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${pe}/ws${e.reset}`);let ke=ge.join(process.cwd(),"channels.ts");if(Ie.existsSync(ke))try{let ie=await Q(ke);console.log(`${e.blue}Loaded ${e.bright}${ie} broadcast channel${ie!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ie){console.warn(`${e.yellow}Failed to load channels.ts: ${ie.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:U,isServerApiSource:se}=await import("./chunk-yt8k715e.js"),I=await U(process.cwd(),A);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${O}/${e.reset}...`),r)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let L=Kn({port:O,async fetch(P){return Wn(P,await(async()=>{let D=new URL(P.url);if([x,ge.dirname(m),ge.join(process.cwd(),"public")].some((ie)=>se(ge.join(ie,D.pathname),process.cwd(),A)))return new Response("Not Found",{status:404});if(w)try{let ie=await w.handleRequest(P);if(ie.status!==404)return ie}catch{}if(v[D.pathname])try{return await v[D.pathname](P)}catch(ie){return new Response(JSON.stringify({error:ie.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await I(P);if(q)return q;if(D.pathname==="/")return(async()=>{let F=await S(h||"");if(r)F=Ne(F,u);if(t.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(t.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Q=ge.join(x,D.pathname);if(Ie.existsSync(Q)&&Ie.statSync(Q).isFile()){let ie=Bun.file(Q),F=ge.extname(Q).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}let xe=ge.dirname(m),pe=ge.join(xe,D.pathname);if(Ie.existsSync(pe)&&Ie.statSync(pe).isFile()){let ie=Bun.file(pe),F=ge.extname(pe).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}let ke=ge.join(process.cwd(),"public",D.pathname);if(Ie.existsSync(ke)&&Ie.statSync(ke).isFile()){let ie=Bun.file(ke),F=ge.extname(ke).toLowerCase(),E="application/octet-stream";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}return new Response("Not Found",{status:404})})())},error(P){return new Response(`<pre>${P}
520
+ </html>`,loader:"html"}}})}};async function os(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Rt(m,t);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let x=l(process.cwd(),"output");Ie.mkdirSync(x,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let h=null,b=async()=>{try{let P={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:x,plugins:[P,tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let q=D.outputs.find((xe)=>xe.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(q.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await b())return!1;let R=ge.dirname(m);await Sn(R);let O=o;try{if(O=await qe(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=xt({wsPort:P,verbose:!1}),u=p.start(P)}let v={},w=null,A;try{let{loadStxConfig:P}=await import("./chunk-n73v0pcq.js"),D=await P();if(A=t.stxOptions?.serverApi??D.serverApi,D?.apiRouter)w=D?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(D?.apiRoutes){v=D.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(D?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Q}=await import("./chunk-cjq455ve.js"),xe=D.broadcasting;await q(xe);let pe=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${pe}/ws${e.reset}`);let ke=ge.join(process.cwd(),"channels.ts");if(Ie.existsSync(ke))try{let ie=await Q(ke);console.log(`${e.blue}Loaded ${e.bright}${ie} broadcast channel${ie!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ie){console.warn(`${e.yellow}Failed to load channels.ts: ${ie.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:U,isServerApiSource:se}=await import("./chunk-8zx8zgwe.js"),I=await U(process.cwd(),A);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${O}/${e.reset}...`),r)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let L=Kn({port:O,async fetch(P){return Wn(P,await(async()=>{let D=new URL(P.url);if([x,ge.dirname(m),ge.join(process.cwd(),"public")].some((ie)=>se(ge.join(ie,D.pathname),process.cwd(),A)))return new Response("Not Found",{status:404});if(w)try{let ie=await w.handleRequest(P);if(ie.status!==404)return ie}catch{}if(v[D.pathname])try{return await v[D.pathname](P)}catch(ie){return new Response(JSON.stringify({error:ie.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await I(P);if(q)return q;if(D.pathname==="/")return(async()=>{let F=await S(h||"");if(r)F=Ne(F,u);if(t.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(t.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Q=ge.join(x,D.pathname);if(Ie.existsSync(Q)&&Ie.statSync(Q).isFile()){let ie=Bun.file(Q),F=ge.extname(Q).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}let xe=ge.dirname(m),pe=ge.join(xe,D.pathname);if(Ie.existsSync(pe)&&Ie.statSync(pe).isFile()){let ie=Bun.file(pe),F=ge.extname(pe).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}let ke=ge.join(process.cwd(),"public",D.pathname);if(Ie.existsSync(ke)&&Ie.statSync(ke).isFile()){let ie=Bun.file(ke),F=ge.extname(ke).toLowerCase(),E="application/octet-stream";if(F===".ts"||F===".tsx"){let je=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ie.text(),Je=je.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(ie,{headers:{"Content-Type":E}})}return new Response("Not Found",{status:404})})())},error(P){return new Response(`<pre>${P}
521
521
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
522
522
  ${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(`
523
523
  ${e.bright}\u2192 ${e.cyan}http://localhost:${O}/${e.reset}`),console.log(`
@@ -1002,12 +1002,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
1002
1002
  ${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(`
1003
1003
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1004
1004
  ${e.yellow}Routes:${e.reset}`);let R=new Set(m.map((v)=>v.routeTemplate)),O=Object.entries(u).filter(([v])=>!R.has(v)).sort(([v],[w])=>v.localeCompare(w)).map(([v,w])=>({route:v==="/"?"/":v,filePath:Se.relative(process.cwd(),w.filePath),fileType:w.fileType}));for(let v of m){let w=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");O.push({route:w,filePath:Se.relative(process.cwd(),v.filePath),fileType:"stx"})}if(O.sort((v,w)=>v.route.localeCompare(w.route)),O.forEach((v,w)=>{let U=w===O.length-1?"\u2514\u2500 ":"\u251C\u2500 ",se=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${U}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${se}`)}),console.log(`
1005
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(C.url.toString(),()=>{if(d)Xe.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(p,{recursive:!0},async(w,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),lt.clear(),Ce(),await x()});process.on("SIGINT",()=>{v.close(),C.stop(),process.exit(0)})}return!0}function qt(n){return String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gn}=globalThis.Bun;import me from"fs";import oe from"path";async function Jt(n){try{return An(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=oe.extname(n).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"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function as(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=oe.resolve(n),{loadStxConfig:x}=await import("./chunk-3dy3hr8r.js"),h=await x(m),{createServerApi:b,isServerApiSource:C}=await import("./chunk-yt8k715e.js"),R=t.stxOptions?.serverApi??h.serverApi,O=await b(m,R),v=h.root&&h.root!=="."?oe.join(m,h.root):m,w=t.pagesDir||h.pagesDir||"pages",A=oe.join(v,w);if(!me.existsSync(A)&&!h._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${w}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${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 ${w}/index.stx for the homepage.${e.reset}`),!1;let U=re(v,{pagesDir:w,pagesDirs:h._layerPageDirs?[A,...h._layerPageDirs.slice(1)]:void 0});if(U.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${U.length}${e.blue} routes${e.reset}`);let se=h?._pluginPageDirs||[],I=[];for(let{dir:T,prefix:_}of se)if(me.existsSync(T)){let z=re(oe.dirname(T),{pagesDir:oe.basename(T)});for(let Z of z){let X=_==="/"?Z.pattern:`${_}${Z.pattern==="/"?"":Z.pattern}`;I.push({route:{...Z,pattern:X},prefix:_})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${_}${e.reset}`)}let L=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Da(m,t.stxOptions?.shell),P){if(k=await Bo(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Lt(),await Bt(m);let D=jt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let q={},Q=null;try{let{loadStxConfig:T}=await import("./chunk-3dy3hr8r.js"),_=await T(m);if(_?.apiRouter)Q=_?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(_?.apiRoutes){q=_.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Z}=await import("./chunk-cjq455ve.js"),X=_.broadcasting;await z(X);let Te=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Te}/ws${e.reset}`);let be=oe.join(process.cwd(),"channels.ts");if(me.existsSync(be))try{let N=await Z(be);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let xe=l(m,"output");me.mkdirSync(xe,{recursive:!0});let pe=new Map,ke=new Set,ie=async(T)=>{let _=Xs(A,T);if(!_)return null;try{let z=await Bun.build({entrypoints:[_],outdir:xe,plugins:[tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Z=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Z)return null;return await Bun.file(Z.path).text()}catch{return null}},F=new Map,E=async(T,_)=>{try{let{processDirectives:z,extractVariables:Z,defaultConfig:X,loadStxConfig:Te,injectRouterScript:be}=await import("./chunk-3dy3hr8r.js"),{checkCache:N,cacheTemplate:Y,readFileCached:W,templateCache:ue}=await import("./chunk-j90sfypd.js"),G=await Te(m),Ve=(le)=>{if(!le)return le;if(oe.isAbsolute(le))return le;return oe.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=Ve(de.partialsDir),de.componentsDir=Ve(de.componentsDir),de.layoutsDir=Ve(de.layoutsDir),de.storesDir=Ve(de.storesDir||"stores"),de.cachePath=Ve(de.cachePath)??l(m,"cache");let M=!_&&!t.profile,J=de.cache!==!1;if(J&&M){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let Le=!0;for(let ve of le.dependencies){if(!me.existsSync(ve)){Le=!1;break}if((await me.promises.stat(ve)).mtime.getTime()>le.mtime){Le=!1;break}}if(Le){let ve=le.output;if(k)ve=ot(ve,{preserveHead:!0});let rt=F.get(T.filePath);return{route:T,content:ve,status:rt?.status??await Jt(T.filePath),headers:rt?.headers}}}}catch{}let Me=await N(T.filePath,de);if(Me){let _e=Me;if(k)_e=ot(_e,{preserveHead:!0});let Le=F.get(T.filePath);return{route:T,content:_e,status:Le?.status??await Jt(T.filePath),headers:Le?.headers}}}let ee=J?await W(T.filePath):await Bun.file(T.filePath).text(),ae=An(ee),{classifyAllScripts:fe}=await import("./chunk-3dy3hr8r.js"),H=fe(ee),Oe=H.server.map((le)=>le.content),Re=ee;for(let le of H.server)Re=Re.replace(le.fullTag,"");let te={__filename:T.filePath,__dirname:oe.dirname(T.filePath),__stx_options:de,params:_??{},__stx_runtime_head:{}};for(let le of Oe)try{await Z(le,te,T.filePath)}catch(Me){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,Me?.message||Me)}let $e=new Set,he;if(t.profile){let le=performance.now();he=await z(Re,te,T.filePath,de,$e);let Me=performance.now()-le,_e=oe.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${_e} \u2192 ${Me.toFixed(2)}ms`)}else he=await z(Re,te,T.filePath,de,$e);if(!k)he=await be(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-96wdxfn4.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Me,_e,Le)=>{if(!/function\s+__stx_setup_/.test(Le))return Me;return`<script${_e}>${le(Le,te)}</script>`})}if(k)he=ot(he,{preserveHead:!0});if(J&&M)await Y(T.filePath,he,$e,de);let{extractStreamBoundaries:ct}=await import("./chunk-4b9jx2c1.js"),Ye=ct(te),nt=te.__streamTemplates;if(nt&&typeof nt==="object"&&Object.keys(nt).length>0){let le=te.streamBoundaries||{},Me={...de,autoShell:!1},_e=Object.keys(nt).map((ve)=>({id:ve,render:async()=>{let rt=typeof le[ve]==="function"?await le[ve]():void 0;return z(nt[ve],{...te,$boundary:rt},T.filePath,Me,new Set)}})),Le=new Set(_e.map((ve)=>ve.id));Ye=[...(Ye||[]).filter((ve)=>!Le.has(ve.id)),..._e]}if(Ye&&Ye.length>0)ke.add(T.pattern);else Ye=void 0;let _t=Kt(te),It=Xt(te);if(M)F.set(T.filePath,{status:_t,headers:It});return{route:T,content:he,status:_t??ae,headers:It,boundaries:Ye}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},je=8,ze=async()=>{let T=new Set(pe.keys()),_=new Set(L.keys());pe.clear(),L.clear();let z=t.prebuild===!1?U.filter((X)=>T.has(X.pattern)):U,Z=t.prebuild===!1?I.filter(({route:X})=>_.has(X.pattern)):I;for(let X=0;X<z.length;X+=je){let Te=z.slice(X,X+je),be=await Promise.all(Te.map((N)=>E(N)));for(let N of be)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Z.length;X+=je){let Te=Z.slice(X,X+je),be=await Promise.all(Te.map(({route:N})=>E(N)));for(let N of be)if(N)L.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?U.length+I.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Sn(m);let Ge=o;try{if(Ge=await qe(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Ge+1;p=xt({wsPort:T,verbose:!1}),u=p.start(T)}let wt=(T,_)=>{let Z=`<script data-stx-route-params>(function(){var p=${JSON.stringify(_).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(T.includes("</head>"))return f(T,Z,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Z}`);return Z+T};console.log(`${e.blue}Starting server...${e.reset}`);let St=Gn({port:Ge,hostname:t.hostname,async fetch(T){let _=new URL(T.url),z=t.stxOptions?.offline??h.offline;if(_.pathname===si&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});let M=[...U,...I.map(({route:J})=>J)].filter((J)=>!J.isDynamic).map((J)=>J.pattern);return new Response(T.method==="HEAD"?null:oi(z,Es(),M),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Z=h?.publicDir||"public",X=oe.join(m,Z,_.pathname),Te=oe.join(m,_.pathname),be=oe.join(xe,_.pathname);if([X,Te,be].some((M)=>C(M,m,R)))return new Response("Not Found",{status:404});let[N,Y,W]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Te).catch(()=>null),me.promises.stat(be).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(Y?.isFile()&&!C(Te,m,R))return Ot(Te);if(W?.isFile()&&!C(be,m,R))return Ot(be);if(_.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(_.pathname.slice(16));if(M)try{let J=`<${M} />`,ee={...buildConfig,autoShell:!1},ae=await processDirectives(J,{},oe.join(m,"components",`${M}.stx`),ee,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(J){return new Response(`<div class="stx-async-error">${J.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(_.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-h7xqba9k.js"),J=await M(T,{publicDir:oe.join(m,Z),cacheDir:l(m,"cache","img")});if(J)return J}if(Q)try{let M=await Q.handleRequest(T);if(M.status!==404)return M}catch{}if(q[_.pathname])try{return await q[_.pathname](T)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Rr(_.pathname,U);if(G){let M=pe.get(G.route.pattern),J=ke.has(G.route.pattern);if(!M||G.route.isDynamic&&Object.keys(G.params).length>0||J){let ee=await E(G.route,G.params);if(ee){if(M=ee,!G.route.isDynamic&&!J)pe.set(G.route.pattern,ee)}}if(M){let ee=M.status??200,ae=M.headers??{},fe=(G.route.filePath?Pt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Re=await ie(404);if(Re){let te=Re;if(te=await S(te,m),r)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Oe=Ft(_.pathname,G.params,fe,_.search),Re=zt(Oe,null,T,{isServer:!0}),te=await Ht(fe.middleware,Re);if(te.redirect){let $e=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",$e),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:$e,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${$e}</title></head><body><h1>Error ${$e}</h1><p>${he}</p></body></html>`,{status:$e,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let $e=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=f(M.content,$e,"")}}let H=M.content;if(k&&La(T)&&Tt(H,h?.router?.container||"main")){let Oe=We(H),Re=Ae(H),te=H.match(/<title[^>]*>([\s\S]*?)<\/title>/i),$e=te?cn(te[1].trim()):"";if(Object.keys(G.params).length>0)H=wt(H,G.params);H=await S(H,m);let he=h?.router?.container||"main";return H=Fe(H,he,!0),new Response(H,{status:ee,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Oe.layout,"X-STX-Layout-Group":Oe.group,"X-STX-Runtime":Re?"true":"false",...$e&&{"X-STX-Title":encodeURIComponent($e)},[Oc]:Es(),...V(),"Cache-Control":Et}})}if(k)H=ps(k,H);if(Object.keys(G.params).length>0)H=wt(H,G.params);if(H=await S(H,m),r)H=Ne(H,u);if(t.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;if(t.titlebarHidden)if(H.includes("<head>"))H=H.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 H=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${H}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Oe,streamToResponse:Re}=await import("./chunk-4b9jx2c1.js");return Re(Oe(H,M.boundaries,{timeoutMs:30000}),{status:ee,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(H,{status:ee,headers:{"Content-Type":"text/html",...V(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(I.length>0){let M=I.map((ee)=>ee.route),J=Rr(_.pathname,M);if(J){let ee=L.get(J.route.pattern);if(!ee||J.route.isDynamic){let ae=await E(J.route,J.params);if(ae){if(ee=ae,!J.route.isDynamic)L.set(J.route.pattern,ae)}}if(ee){let ae=ee.content;if(k)ae=ps(k,ae);if(Object.keys(J.params).length>0)ae=wt(ae,J.params);if(ae=await S(ae,m),r)ae=Ne(ae,u);return new Response(ae,{status:ee.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ee}of se)if(ee!=="/"&&_.pathname.startsWith(ee)){let ae=L.get(ee)||L.get(ee+"/");if(!ae){let fe=I.find(({route:H})=>H.pattern===ee||H.pattern===`${ee}/`);if(fe){let H=await E(fe.route);if(H)ae=H,L.set(fe.route.pattern,H)}}if(ae){let fe=ae.content;if(k)fe=ps(k,fe);if(fe=await S(fe,m),r)fe=Ne(fe,u);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Dt(_.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ve=pe.get("/");if(Ve){let M=Ve.content;if(M=await S(M,m),r)M=Ne(M,u);if(t.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await ie(404);if(de){let M=de;if(M=await S(M,m),r)M=Ne(M,u);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let _=await ie(500);if(_)return new Response(_,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
1005
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(C.url.toString(),()=>{if(d)Xe.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(p,{recursive:!0},async(w,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),lt.clear(),Ce(),await x()});process.on("SIGINT",()=>{v.close(),C.stop(),process.exit(0)})}return!0}function qt(n){return String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gn}=globalThis.Bun;import me from"fs";import oe from"path";async function Jt(n){try{return An(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=oe.extname(n).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"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function as(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=oe.resolve(n),{loadStxConfig:x}=await import("./chunk-n73v0pcq.js"),h=await x(m),{createServerApi:b,isServerApiSource:C}=await import("./chunk-8zx8zgwe.js"),R=t.stxOptions?.serverApi??h.serverApi,O=await b(m,R),v=h.root&&h.root!=="."?oe.join(m,h.root):m,w=t.pagesDir||h.pagesDir||"pages",A=oe.join(v,w);if(!me.existsSync(A)&&!h._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${w}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${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 ${w}/index.stx for the homepage.${e.reset}`),!1;let U=re(v,{pagesDir:w,pagesDirs:h._layerPageDirs?[A,...h._layerPageDirs.slice(1)]:void 0});if(U.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${U.length}${e.blue} routes${e.reset}`);let se=h?._pluginPageDirs||[],I=[];for(let{dir:T,prefix:_}of se)if(me.existsSync(T)){let z=re(oe.dirname(T),{pagesDir:oe.basename(T)});for(let Z of z){let X=_==="/"?Z.pattern:`${_}${Z.pattern==="/"?"":Z.pattern}`;I.push({route:{...Z,pattern:X},prefix:_})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${_}${e.reset}`)}let L=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Da(m,t.stxOptions?.shell),P){if(k=await Bo(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Lt(),await Bt(m);let D=jt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let q={},Q=null;try{let{loadStxConfig:T}=await import("./chunk-n73v0pcq.js"),_=await T(m);if(_?.apiRouter)Q=_?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(_?.apiRoutes){q=_.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Z}=await import("./chunk-cjq455ve.js"),X=_.broadcasting;await z(X);let Te=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Te}/ws${e.reset}`);let be=oe.join(process.cwd(),"channels.ts");if(me.existsSync(be))try{let N=await Z(be);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let xe=l(m,"output");me.mkdirSync(xe,{recursive:!0});let pe=new Map,ke=new Set,ie=async(T)=>{let _=Xs(A,T);if(!_)return null;try{let z=await Bun.build({entrypoints:[_],outdir:xe,plugins:[tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Z=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Z)return null;return await Bun.file(Z.path).text()}catch{return null}},F=new Map,E=async(T,_)=>{try{let{processDirectives:z,extractVariables:Z,defaultConfig:X,loadStxConfig:Te,injectRouterScript:be}=await import("./chunk-n73v0pcq.js"),{checkCache:N,cacheTemplate:Y,readFileCached:W,templateCache:ue}=await import("./chunk-r3hb020a.js"),G=await Te(m),Ve=(le)=>{if(!le)return le;if(oe.isAbsolute(le))return le;return oe.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=Ve(de.partialsDir),de.componentsDir=Ve(de.componentsDir),de.layoutsDir=Ve(de.layoutsDir),de.storesDir=Ve(de.storesDir||"stores"),de.cachePath=Ve(de.cachePath)??l(m,"cache");let M=!_&&!t.profile,J=de.cache!==!1;if(J&&M){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let Le=!0;for(let ve of le.dependencies){if(!me.existsSync(ve)){Le=!1;break}if((await me.promises.stat(ve)).mtime.getTime()>le.mtime){Le=!1;break}}if(Le){let ve=le.output;if(k)ve=ot(ve,{preserveHead:!0});let rt=F.get(T.filePath);return{route:T,content:ve,status:rt?.status??await Jt(T.filePath),headers:rt?.headers}}}}catch{}let Me=await N(T.filePath,de);if(Me){let _e=Me;if(k)_e=ot(_e,{preserveHead:!0});let Le=F.get(T.filePath);return{route:T,content:_e,status:Le?.status??await Jt(T.filePath),headers:Le?.headers}}}let ee=J?await W(T.filePath):await Bun.file(T.filePath).text(),ae=An(ee),{classifyAllScripts:fe}=await import("./chunk-n73v0pcq.js"),H=fe(ee),Oe=H.server.map((le)=>le.content),Re=ee;for(let le of H.server)Re=Re.replace(le.fullTag,"");let te={__filename:T.filePath,__dirname:oe.dirname(T.filePath),__stx_options:de,params:_??{},__stx_runtime_head:{}};for(let le of Oe)try{await Z(le,te,T.filePath)}catch(Me){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,Me?.message||Me)}let $e=new Set,he;if(t.profile){let le=performance.now();he=await z(Re,te,T.filePath,de,$e);let Me=performance.now()-le,_e=oe.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${_e} \u2192 ${Me.toFixed(2)}ms`)}else he=await z(Re,te,T.filePath,de,$e);if(!k)he=await be(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-69yqdxck.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Me,_e,Le)=>{if(!/function\s+__stx_setup_/.test(Le))return Me;return`<script${_e}>${le(Le,te)}</script>`})}if(k)he=ot(he,{preserveHead:!0});if(J&&M)await Y(T.filePath,he,$e,de);let{extractStreamBoundaries:ct}=await import("./chunk-jvpnd7zd.js"),Ye=ct(te),nt=te.__streamTemplates;if(nt&&typeof nt==="object"&&Object.keys(nt).length>0){let le=te.streamBoundaries||{},Me={...de,autoShell:!1},_e=Object.keys(nt).map((ve)=>({id:ve,render:async()=>{let rt=typeof le[ve]==="function"?await le[ve]():void 0;return z(nt[ve],{...te,$boundary:rt},T.filePath,Me,new Set)}})),Le=new Set(_e.map((ve)=>ve.id));Ye=[...(Ye||[]).filter((ve)=>!Le.has(ve.id)),..._e]}if(Ye&&Ye.length>0)ke.add(T.pattern);else Ye=void 0;let _t=Kt(te),It=Xt(te);if(M)F.set(T.filePath,{status:_t,headers:It});return{route:T,content:he,status:_t??ae,headers:It,boundaries:Ye}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},je=8,ze=async()=>{let T=new Set(pe.keys()),_=new Set(L.keys());pe.clear(),L.clear();let z=t.prebuild===!1?U.filter((X)=>T.has(X.pattern)):U,Z=t.prebuild===!1?I.filter(({route:X})=>_.has(X.pattern)):I;for(let X=0;X<z.length;X+=je){let Te=z.slice(X,X+je),be=await Promise.all(Te.map((N)=>E(N)));for(let N of be)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Z.length;X+=je){let Te=Z.slice(X,X+je),be=await Promise.all(Te.map(({route:N})=>E(N)));for(let N of be)if(N)L.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?U.length+I.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Sn(m);let Ge=o;try{if(Ge=await qe(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Ge+1;p=xt({wsPort:T,verbose:!1}),u=p.start(T)}let wt=(T,_)=>{let Z=`<script data-stx-route-params>(function(){var p=${JSON.stringify(_).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(T.includes("</head>"))return f(T,Z,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Z}`);return Z+T};console.log(`${e.blue}Starting server...${e.reset}`);let St=Gn({port:Ge,hostname:t.hostname,async fetch(T){let _=new URL(T.url),z=t.stxOptions?.offline??h.offline;if(_.pathname===si&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});let M=[...U,...I.map(({route:J})=>J)].filter((J)=>!J.isDynamic).map((J)=>J.pattern);return new Response(T.method==="HEAD"?null:oi(z,Es(),M),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Z=h?.publicDir||"public",X=oe.join(m,Z,_.pathname),Te=oe.join(m,_.pathname),be=oe.join(xe,_.pathname);if([X,Te,be].some((M)=>C(M,m,R)))return new Response("Not Found",{status:404});let[N,Y,W]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Te).catch(()=>null),me.promises.stat(be).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(Y?.isFile()&&!C(Te,m,R))return Ot(Te);if(W?.isFile()&&!C(be,m,R))return Ot(be);if(_.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(_.pathname.slice(16));if(M)try{let J=`<${M} />`,ee={...buildConfig,autoShell:!1},ae=await processDirectives(J,{},oe.join(m,"components",`${M}.stx`),ee,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(J){return new Response(`<div class="stx-async-error">${J.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(_.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-h7xqba9k.js"),J=await M(T,{publicDir:oe.join(m,Z),cacheDir:l(m,"cache","img")});if(J)return J}if(Q)try{let M=await Q.handleRequest(T);if(M.status!==404)return M}catch{}if(q[_.pathname])try{return await q[_.pathname](T)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Rr(_.pathname,U);if(G){let M=pe.get(G.route.pattern),J=ke.has(G.route.pattern);if(!M||G.route.isDynamic&&Object.keys(G.params).length>0||J){let ee=await E(G.route,G.params);if(ee){if(M=ee,!G.route.isDynamic&&!J)pe.set(G.route.pattern,ee)}}if(M){let ee=M.status??200,ae=M.headers??{},fe=(G.route.filePath?Pt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Re=await ie(404);if(Re){let te=Re;if(te=await S(te,m),r)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Oe=Ft(_.pathname,G.params,fe,_.search),Re=zt(Oe,null,T,{isServer:!0}),te=await Ht(fe.middleware,Re);if(te.redirect){let $e=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",$e),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:$e,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${$e}</title></head><body><h1>Error ${$e}</h1><p>${he}</p></body></html>`,{status:$e,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let $e=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=f(M.content,$e,"")}}let H=M.content;if(k&&La(T)&&Tt(H,h?.router?.container||"main")){let Oe=We(H),Re=Ae(H),te=H.match(/<title[^>]*>([\s\S]*?)<\/title>/i),$e=te?cn(te[1].trim()):"";if(Object.keys(G.params).length>0)H=wt(H,G.params);H=await S(H,m);let he=h?.router?.container||"main";return H=Fe(H,he,!0),new Response(H,{status:ee,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Oe.layout,"X-STX-Layout-Group":Oe.group,"X-STX-Runtime":Re?"true":"false",...$e&&{"X-STX-Title":encodeURIComponent($e)},[Oc]:Es(),...V(),"Cache-Control":Et}})}if(k)H=ps(k,H);if(Object.keys(G.params).length>0)H=wt(H,G.params);if(H=await S(H,m),r)H=Ne(H,u);if(t.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;if(t.titlebarHidden)if(H.includes("<head>"))H=H.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 H=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${H}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Oe,streamToResponse:Re}=await import("./chunk-jvpnd7zd.js");return Re(Oe(H,M.boundaries,{timeoutMs:30000}),{status:ee,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(H,{status:ee,headers:{"Content-Type":"text/html",...V(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(I.length>0){let M=I.map((ee)=>ee.route),J=Rr(_.pathname,M);if(J){let ee=L.get(J.route.pattern);if(!ee||J.route.isDynamic){let ae=await E(J.route,J.params);if(ae){if(ee=ae,!J.route.isDynamic)L.set(J.route.pattern,ae)}}if(ee){let ae=ee.content;if(k)ae=ps(k,ae);if(Object.keys(J.params).length>0)ae=wt(ae,J.params);if(ae=await S(ae,m),r)ae=Ne(ae,u);return new Response(ae,{status:ee.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ee}of se)if(ee!=="/"&&_.pathname.startsWith(ee)){let ae=L.get(ee)||L.get(ee+"/");if(!ae){let fe=I.find(({route:H})=>H.pattern===ee||H.pattern===`${ee}/`);if(fe){let H=await E(fe.route);if(H)ae=H,L.set(fe.route.pattern,H)}}if(ae){let fe=ae.content;if(k)fe=ps(k,fe);if(fe=await S(fe,m),r)fe=Ne(fe,u);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Dt(_.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ve=pe.get("/");if(Ve){let M=Ve.content;if(M=await S(M,m),r)M=Ne(M,u);if(t.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await ie(404);if(de){let M=de;if(M=await S(M,m),r)M=Ne(M,u);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let _=await ie(500);if(_)return new Response(_,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
1006
1006
  ${T.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1007
1007
  ${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(`
1008
1008
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),r)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1009
1009
  ${e.yellow}Routes:${e.reset}`);let kt=[...Gs(U,m)];for(let{route:T}of I)kt.push(`${T.pattern}`);if(kt.forEach((T,_)=>{let Z=_===kt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Z}${e.reset}${T}`)}),console.log(`
1010
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(St.url.toString(),()=>{if(p)st();St.stop()}),t.native){let T,_=oe.join(A,"index.stx");if(me.existsSync(_)){let Z=await Bun.file(_).text();T=mt(Z)}let z=h?.app?.window??{};await Qe(Ge,{title:h?.app?.head?.title||oe.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),_=(N)=>{let Y=N.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},z=new Map,Z=()=>{let N=new Set([m,...h._layerGraph?.layers.map((Y)=>Y.root)??[],...h._layerGraph?.configDependencies.map((Y)=>oe.dirname(Y))??[]].filter((Y)=>me.existsSync(Y)).map((Y)=>me.realpathSync(Y)));for(let Y of h._layerGraph?.layers??[])for(let W of Object.values(Y.resources)){if(!me.existsSync(W))continue;let ue=me.realpathSync(W);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${oe.sep}`)))N.add(ue)}for(let[Y,W]of z)if(!N.has(Y))W.close(),z.delete(Y);for(let Y of N)if(!z.has(Y)&&me.existsSync(Y))z.set(Y,me.watch(Y,{recursive:!0},(W,ue)=>{Te(Y,W,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Te=(N,Y,W)=>(X=X.catch(()=>{}).then(()=>be(N,Y,W)),X),be=async(N,Y,W)=>{if(!W||yt(W))return;if(ht(W)){if(h._layerGraph){let ue=await x(m);Object.assign(h,ue),U.splice(0,U.length,...re(v,{pagesDir:w,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Z()}if(T(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),r&&p)p.reload(W)}else if(_(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),lt.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-j90sfypd.js");ue(oe.resolve(N,W)),G.delete(oe.resolve(N,W))}catch{}if(P&&W){if(oe.resolve(N,W)===P||oe.basename(P)===W){let G=await Bo(P,t.stxOptions||{});if(G)k=G}}if(await ze(),await xr(m),r&&p)p.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),lt.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-j90sfypd.js");ue(oe.resolve(N,W)),G.delete(oe.resolve(N,W))}catch{}if(await ze(),r&&p)p.reload(W)}}else if(gt(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),r&&p)p.updateCss(W)}};Z(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(p)st();St.stop(),process.exit(0)})}return!0}import At from"fs";import it from"path";async function Jn(n){try{let o=(await Bun.file(n).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],r=[],p=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=p.exec(d))!==null){let m=u[1],x=u[2]||u[3]||u[4];if(!x)continue;let h={name:x},b=m.match(/@type\s+\{([^}]+)\}/i);if(b)h.type=b[1].trim();if(m.match(/@required/i))h.required=!0;let R=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(R)h.default=R[1].trim();let O=m.split(`
1010
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(St.url.toString(),()=>{if(p)st();St.stop()}),t.native){let T,_=oe.join(A,"index.stx");if(me.existsSync(_)){let Z=await Bun.file(_).text();T=mt(Z)}let z=h?.app?.window??{};await Qe(Ge,{title:h?.app?.head?.title||oe.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),_=(N)=>{let Y=N.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},z=new Map,Z=()=>{let N=new Set([m,...h._layerGraph?.layers.map((Y)=>Y.root)??[],...h._layerGraph?.configDependencies.map((Y)=>oe.dirname(Y))??[]].filter((Y)=>me.existsSync(Y)).map((Y)=>me.realpathSync(Y)));for(let Y of h._layerGraph?.layers??[])for(let W of Object.values(Y.resources)){if(!me.existsSync(W))continue;let ue=me.realpathSync(W);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${oe.sep}`)))N.add(ue)}for(let[Y,W]of z)if(!N.has(Y))W.close(),z.delete(Y);for(let Y of N)if(!z.has(Y)&&me.existsSync(Y))z.set(Y,me.watch(Y,{recursive:!0},(W,ue)=>{Te(Y,W,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Te=(N,Y,W)=>(X=X.catch(()=>{}).then(()=>be(N,Y,W)),X),be=async(N,Y,W)=>{if(!W||yt(W))return;if(ht(W)){if(h._layerGraph){let ue=await x(m);Object.assign(h,ue),U.splice(0,U.length,...re(v,{pagesDir:w,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Z()}if(T(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),r&&p)p.reload(W)}else if(_(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),lt.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-r3hb020a.js");ue(oe.resolve(N,W)),G.delete(oe.resolve(N,W))}catch{}if(P&&W){if(oe.resolve(N,W)===P||oe.basename(P)===W){let G=await Bo(P,t.stxOptions||{});if(G)k=G}}if(await ze(),await xr(m),r&&p)p.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),lt.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-r3hb020a.js");ue(oe.resolve(N,W)),G.delete(oe.resolve(N,W))}catch{}if(await ze(),r&&p)p.reload(W)}}else if(gt(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),r&&p)p.updateCss(W)}};Z(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(p)st();St.stop(),process.exit(0)})}return!0}import At from"fs";import it from"path";async function Jn(n){try{let o=(await Bun.file(n).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],r=[],p=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=p.exec(d))!==null){let m=u[1],x=u[2]||u[3]||u[4];if(!x)continue;let h={name:x},b=m.match(/@type\s+\{([^}]+)\}/i);if(b)h.type=b[1].trim();if(m.match(/@required/i))h.required=!0;let R=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(R)h.default=R[1].trim();let O=m.split(`
1011
1011
  `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);h.description=O.join(" ").trim(),r.push(h)}if(r.length===0){let m=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(m){let h=m[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of h){let[C]=b.split(":").map((R)=>R.trim());if(C)r.push({name:C})}}}return r}catch(t){return console.error(`Error extracting props from ${n}:`,t),[]}}async function Yn(n){try{let t=await Bun.file(n).text(),o=t.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||t.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
1012
1012
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Qn(n,t=!1,o){let d=it.basename(n,".stx"),r=await Jn(n),p=await Yn(n),u="";if(t&&o)u=`<${o}></${o}>`;else{let m=r.map((x)=>{if(x.type==="boolean")return`:${x.name}="true"`;return`${x.name}="value"`}).join(`
1013
1013
  `);u=`<${d}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{vn,ei,ti,ni,iy,ri}from"./chunk-p3et6xjr.js";import"./chunk-mpfm5ctr.js";import"./chunk-b234w3mf.js";import"./chunk-w98yt4d4.js";export{ti as buildServerApi,iy as createServerApi,vn as discoverServerApi,ei as generateApiTypes,ri as isServerApiSource,ni as productionApiDispatcher};
2
+ import{vn,ei,ti,ni,iy,ri}from"./chunk-txsre59k.js";import"./chunk-mpfm5ctr.js";import"./chunk-b234w3mf.js";import"./chunk-w98yt4d4.js";export{ti as buildServerApi,iy as createServerApi,vn as discoverServerApi,ei as generateApiTypes,ri as isServerApiSource,ni as productionApiDispatcher};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{uy,fg,lt,Dc,dy,Ts,$s,Rs}from"./chunk-qvj0bzw5.js";import"./chunk-exc8y30f.js";import"./chunk-257msenj.js";import"./chunk-9bexzgws.js";import"./chunk-v0yay1kw.js";import"./chunk-fds6vvq0.js";import"./chunk-ab1z38gj.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{dy as clearOnceStore,Dc as onceStore,lt as partialsCache,Ts as processIncludes,$s as processStackPushDirectives,Rs as processStackReplacements,uy as resetUnscopedSignalWarnings,fg as topLevelElements};
2
+ import{uy,fg,lt,Dc,dy,Ts,$s,Rs}from"./chunk-mv1hr9d4.js";import"./chunk-va00ve6h.js";import"./chunk-pdfnq2gs.js";import"./chunk-9bexzgws.js";import"./chunk-v0yay1kw.js";import"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{dy as clearOnceStore,Dc as onceStore,lt as partialsCache,Ts as processIncludes,$s as processStackPushDirectives,Rs as processStackReplacements,uy as resetUnscopedSignalWarnings,fg as topLevelElements};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Dn,Ji}from"./chunk-ab1z38gj.js";import"./chunk-w98yt4d4.js";export{Ji as generateRuntimeConfigTypes,Dn as prepareRuntimeConfig};
2
+ import{Dn,Ji}from"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";export{Ji as generateRuntimeConfigTypes,Dn as prepareRuntimeConfig};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import"./chunk-0jdz31q1.js";import"./chunk-c08jvjqt.js";import"./chunk-4b110x6r.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-fds6vvq0.js";import"./chunk-w98yt4d4.js";import"./chunk-ab1z38gj.js";import"./chunk-razwegar.js";import"./chunk-6qgrr453.js";import{l}from"./chunk-w4177qn3.js";import u from"fs";import m from"path";async function d(e,t={}){let s=Date.now(),n={total:0,passed:0,failed:0,new:0,failures:[],duration:0},i=t.snapshotDir||l(e.root,"story","snapshots");await u.promises.mkdir(i,{recursive:!0});let r=e.storyFiles;if(t.filter&&t.filter.length>0)r=r.filter((a)=>t.filter.some((o)=>a.fileName.toLowerCase().includes(o.toLowerCase())));for(let a of r)await h(a,i,t,n);return n.duration=Date.now()-s,n}async function h(e,t,s,n){let i=e.story;if(!i)return;for(let r of i.variants){n.total++;let a=m.join(t,`${e.id}-${r.id}.snap`),o=g(r.source||""),f=await w(a);if(s.update||!f){let p={storyId:e.id,variantId:r.id,component:e.fileName,timestamp:Date.now(),hash:o};if(await u.promises.writeFile(a,JSON.stringify(p,null,2)),!f)n.new++;n.passed++}else try{let p=await u.promises.readFile(a,"utf-8"),c=JSON.parse(p);if(c.hash===o)n.passed++;else n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:"Snapshot mismatch",difference:y(c.hash,o)})}catch(p){n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:`Error reading snapshot: ${p}`})}}}async function x(e,t={}){return(await d(e,{...t,update:!0})).total}function g(e){let t=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);t=(t<<5)-t+n,t=t&t}return t.toString(16)}function y(e,t){if(e===t)return 0;let s=Math.abs(Number.parseInt(e,16)-Number.parseInt(t,16));return Math.min(s/1e6,1)}async function w(e){try{return await u.promises.access(e),!0}catch{return!1}}function F(e){let t=[];if(t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(" STX Story Visual Regression Tests"),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),e.failures.length>0){t.push(" \u274C Failures:"),t.push("");for(let s of e.failures){if(t.push(` \u2022 ${s.component} / ${s.variantId}`),t.push(` ${s.message}`),s.difference!==void 0)t.push(` Difference: ${(s.difference*100).toFixed(2)}%`);t.push("")}}if(t.push(" Summary:"),t.push(` Total: ${e.total}`),t.push(` Passed: ${e.passed} \u2713`),t.push(` Failed: ${e.failed} \u2717`),e.new>0)t.push(` New: ${e.new} \u26A1`);return t.push(` Time: ${e.duration}ms`),t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),t.join(`
2
+ import"./chunk-0jdz31q1.js";import"./chunk-c08jvjqt.js";import"./chunk-4b110x6r.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-snhsh171.js";import"./chunk-w98yt4d4.js";import"./chunk-73py4qeh.js";import"./chunk-razwegar.js";import"./chunk-gjk0nzyy.js";import{l}from"./chunk-w4177qn3.js";import u from"fs";import m from"path";async function d(e,t={}){let s=Date.now(),n={total:0,passed:0,failed:0,new:0,failures:[],duration:0},i=t.snapshotDir||l(e.root,"story","snapshots");await u.promises.mkdir(i,{recursive:!0});let r=e.storyFiles;if(t.filter&&t.filter.length>0)r=r.filter((a)=>t.filter.some((o)=>a.fileName.toLowerCase().includes(o.toLowerCase())));for(let a of r)await h(a,i,t,n);return n.duration=Date.now()-s,n}async function h(e,t,s,n){let i=e.story;if(!i)return;for(let r of i.variants){n.total++;let a=m.join(t,`${e.id}-${r.id}.snap`),o=g(r.source||""),f=await w(a);if(s.update||!f){let p={storyId:e.id,variantId:r.id,component:e.fileName,timestamp:Date.now(),hash:o};if(await u.promises.writeFile(a,JSON.stringify(p,null,2)),!f)n.new++;n.passed++}else try{let p=await u.promises.readFile(a,"utf-8"),c=JSON.parse(p);if(c.hash===o)n.passed++;else n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:"Snapshot mismatch",difference:y(c.hash,o)})}catch(p){n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:`Error reading snapshot: ${p}`})}}}async function x(e,t={}){return(await d(e,{...t,update:!0})).total}function g(e){let t=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);t=(t<<5)-t+n,t=t&t}return t.toString(16)}function y(e,t){if(e===t)return 0;let s=Math.abs(Number.parseInt(e,16)-Number.parseInt(t,16));return Math.min(s/1e6,1)}async function w(e){try{return await u.promises.access(e),!0}catch{return!1}}function F(e){let t=[];if(t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(" STX Story Visual Regression Tests"),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),e.failures.length>0){t.push(" \u274C Failures:"),t.push("");for(let s of e.failures){if(t.push(` \u2022 ${s.component} / ${s.variantId}`),t.push(` ${s.message}`),s.difference!==void 0)t.push(` Difference: ${(s.difference*100).toFixed(2)}%`);t.push("")}}if(t.push(" Summary:"),t.push(` Total: ${e.total}`),t.push(` Passed: ${e.passed} \u2713`),t.push(` Failed: ${e.failed} \u2717`),e.new>0)t.push(` New: ${e.new} \u26A1`);return t.push(` Time: ${e.duration}ms`),t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),t.join(`
3
3
  `)}export{F as formatTestResults,d as runVisualTests,x as updateSnapshots};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$m}from"./chunk-vmphrcaa.js";import"./chunk-xfjp5q2m.js";import"./chunk-6qgrr453.js";import"./chunk-razwegar.js";import"./chunk-mpfm5ctr.js";import"./chunk-eca022er.js";import"./chunk-b234w3mf.js";import"./chunk-fds6vvq0.js";import"./chunk-ab1z38gj.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{$m as buildApp};
2
+ import{$m}from"./chunk-e6za83ty.js";import"./chunk-p8p0xs8g.js";import"./chunk-gjk0nzyy.js";import"./chunk-razwegar.js";import"./chunk-mpfm5ctr.js";import"./chunk-eca022er.js";import"./chunk-b234w3mf.js";import"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{$m as buildApp};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{y,Ui,Sl,kl,Hg,Ug,Vg,Wg,qg,po,Kg,Ye,ie,Ze,Xg,Hr,Gg,El,Tl,qi,Qe,s,On,$l,b,Ce,Iy}from"./chunk-fds6vvq0.js";import"./chunk-ab1z38gj.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{Tl as SIGNAL_COMPOSABLE_CALL,Ce as clearComponentCache,qi as componentClientSignalNames,Ui as convertToCommonJS,b as createDetailedErrorMessage,qg as extractDirectiveNames,Sl as extractScriptFromTemplate,y as extractVariables,s as fileExists,Iy as getComponentCacheStats,Ug as getPositionInfo,ie as getSharedTranspiler,$l as getSourceLineInfo,Wg as hasDirectives,kl as hasVariables,Gg as isHydrateTrigger,Kg as isJavaScriptScript,Qe as renderComponentWithSlot,On as resolveTemplatePath,Xg as scopeOnRootElement,po as scopeSequenceKey,Ye as shouldTranspileTypeScript,El as slotContentHasExpressions,Ze as transpileTypeScript,Hr as userComponentFileExists,Vg as validateDirective,Hg as validateTemplate};
2
+ import{y,Ui,Sl,kl,Hg,Ug,Vg,Wg,qg,po,Kg,Ye,ie,Ze,Xg,Hr,Gg,El,Tl,qi,Qe,s,On,$l,b,Ce,Iy}from"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{Tl as SIGNAL_COMPOSABLE_CALL,Ce as clearComponentCache,qi as componentClientSignalNames,Ui as convertToCommonJS,b as createDetailedErrorMessage,qg as extractDirectiveNames,Sl as extractScriptFromTemplate,y as extractVariables,s as fileExists,Iy as getComponentCacheStats,Ug as getPositionInfo,ie as getSharedTranspiler,$l as getSourceLineInfo,Wg as hasDirectives,kl as hasVariables,Gg as isHydrateTrigger,Kg as isJavaScriptScript,Qe as renderComponentWithSlot,On as resolveTemplatePath,Xg as scopeOnRootElement,po as scopeSequenceKey,Ye as shouldTranspileTypeScript,El as slotContentHasExpressions,Ze as transpileTypeScript,Hr as userComponentFileExists,Vg as validateDirective,Hg as validateTemplate};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{P}from"./chunk-fds6vvq0.js";import{i}from"./chunk-jj78m9k1.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,o)=>{if(t[0]&&u[t[0]]){let n=u[t[0]];console.log(`
2
+ import{P}from"./chunk-snhsh171.js";import{i}from"./chunk-r8gv2pcy.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,o)=>{if(t[0]&&u[t[0]]){let n=u[t[0]];console.log(`
3
3
  ${e.bold}${t[0]}${e.reset} - ${n.description}`),console.log(` Usage: ${e.cyan}${n.usage}${e.reset}
4
4
  `)}else{console.log(`
5
5
  ${e.bold}Available Commands:${e.reset}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{a}from"./chunk-xfjp5q2m.js";import{zo}from"./chunk-fznjm7qt.js";import p from"path";async function $m(t={}){let l=performance.now(),s=t.root||process.cwd(),e=await a(s),o=t.ssr?.routeRules??e.routeRules??{};if(zo(o),!e.ssr&&Object.keys(o).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let u,n;if(r==="ssg"){let{generateStaticSite:i}=await import("./ssg.js");u=await i({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:i}=await import("./chunk-wchz1sye.js");n=await i({root:s,outputDir:".output",debug:t.debug,...t.ssr})}let d=Math.round(performance.now()-l);return{mode:r,ssg:u,ssr:n,duration:d}}
2
+ import{a}from"./chunk-p8p0xs8g.js";import{zo}from"./chunk-fznjm7qt.js";import p from"path";async function $m(t={}){let l=performance.now(),s=t.root||process.cwd(),e=await a(s),o=t.ssr?.routeRules??e.routeRules??{};if(zo(o),!e.ssr&&Object.keys(o).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let u,n;if(r==="ssg"){let{generateStaticSite:i}=await import("./ssg.js");u=await i({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:i}=await import("./chunk-0b0y695e.js");n=await i({root:s,outputDir:".output",debug:t.debug,...t.ssr})}let d=Math.round(performance.now()-l);return{mode:r,ssg:u,ssr:n,duration:d}}
3
3
  export{$m};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Rm}from"./chunk-k3eab0c5.js";import"./chunk-y7caf6hd.js";import"./chunk-376714qg.js";import"./chunk-txsre59k.js";import"./chunk-pdfnq2gs.js";import"./chunk-66tpsdpm.js";import"./chunk-p8p0xs8g.js";import"./chunk-gjk0nzyy.js";import"./chunk-razwegar.js";import"./chunk-mpfm5ctr.js";import"./chunk-eca022er.js";import"./chunk-b234w3mf.js";import"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{Rm as startProductionServer};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{St,kt,_t}from"./chunk-5jc9hmwg.js";import"./chunk-4b110x6r.js";import"./chunk-phzhmnnm.js";import"./chunk-0jdz31q1.js";import"./chunk-ck4ypzet.js";import{y}from"./chunk-fds6vvq0.js";import"./chunk-c08jvjqt.js";import"./chunk-w98yt4d4.js";import"./chunk-ab1z38gj.js";import{nn,Eo,rn,va,xt,xa,To,sn,ka,on}from"./chunk-gfp39bzr.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{xa("Config file changed, restarting...");try{await e.onChange()}catch(p){xt(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),u=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,f=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:f,variantViews:n,avgTimeSpent:u}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:dt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function dt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
2
+ import{St,kt,_t}from"./chunk-5jc9hmwg.js";import"./chunk-4b110x6r.js";import"./chunk-phzhmnnm.js";import"./chunk-0jdz31q1.js";import"./chunk-ck4ypzet.js";import{y}from"./chunk-snhsh171.js";import"./chunk-c08jvjqt.js";import"./chunk-w98yt4d4.js";import"./chunk-73py4qeh.js";import{nn,Eo,rn,va,xt,xa,To,sn,ka,on}from"./chunk-gfp39bzr.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{xa("Config file changed, restarting...");try{await e.onChange()}catch(p){xt(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),u=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,f=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:f,variantViews:n,avgTimeSpent:u}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:dt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function dt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
3
3
  <script>
4
4
  (function() {
5
5
  const ws = new WebSocket('${t}');
@@ -556,7 +556,7 @@ window.__stxPerformance = {
556
556
 
557
557
  window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
558
558
  </script>
559
- `}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-218pnbaf.js"),p={},u=h(n);if(u)try{await y(u,p,e)}catch(g){o.push(`Warning: Could not extract script variables: ${g instanceof Error?g.message:String(g)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function gt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await y(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await gt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return ft(t,a.source,c);return b(t,e.path,{props:c})}async function ft(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-218pnbaf.js"),c={...r},n=h(e);if(n)try{await y(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
559
+ `}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-tw1rbnc3.js"),p={},u=h(n);if(u)try{await y(u,p,e)}catch(g){o.push(`Warning: Could not extract script variables: ${g instanceof Error?g.message:String(g)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function gt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await y(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await gt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return ft(t,a.source,c);return b(t,e.path,{props:c})}async function ft(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-tw1rbnc3.js"),c={...r},n=h(e);if(n)try{await y(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
560
560
  `)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
561
561
  `)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function rt(t,e){let r=await sn(t);kt(t,r);let s=on(t.config,r);_t(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let g=new URL(i.url).pathname;if(g==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(g.startsWith("/api/"))return yt(t,g,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return ht(t,g,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),u=`http://${o}:${e.port}`,f=ka(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await sn(t);kt(t,m);let g=on(t.config,m);if(_t(t,g),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=u;try{let{exec:l}=await import("child_process"),m=process.platform;l(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:u,close:async()=>{f(),p.stop()}}}async function yt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],u=d[1]||"default",f,i=n.searchParams.get("props");if(i)try{f=JSON.parse(i)}catch{}let l=t.storyFiles.find((m)=>m.id===p);if(!l)return new Response("Story not found",{status:404});try{let m=await Y(t,l,u,f);return Response.json({html:m.html,css:m.css,js:m.js,errors:m.errors,duration:m.duration})}catch(m){return Response.json({html:"",css:"",js:"",errors:[m instanceof Error?m.message:String(m)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((u)=>u.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function ht(t,e,r){let s=vt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function vt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
562
562
  <html lang="en" class="${r.darkClass||"dark"}">
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{il,s,Ce}from"./chunk-fds6vvq0.js";import{gt}from"./chunk-zkwkhesc.js";import{l}from"./chunk-w4177qn3.js";import o from"fs";import u from"path";var wg=new Map,m=new Map;async function yy(e){let n;for(let i=0;i<3;i++)try{let g=(await o.promises.stat(e)).mtime.getTime(),a=m.get(e);if(a&&a.mtime===g)return a.content;let h=await Bun.file(e).text(),w=(await o.promises.stat(e)).mtime.getTime();if(w!==g)continue;return m.set(e,{content:h,mtime:w}),h}catch(r){n=r;break}throw m.delete(e),Error(`File not found: ${e}${n?` (${n.message})`:""}`)}function by(e){m.delete(e)}function wy(e){for(let t of m.keys())if(t.startsWith(e))m.delete(t)}var f=null,B=null,x=null;function vy(e){x=e}async function vg(e=!1){let t=x??await import("./chunk-rt6fn071.js");if(e)return t.generateSignalsRuntimeDev();if(f===null)f=t.generateSignalsRuntime();return f}var S=null;async function xg(){if(S===null){let{getRouterScript:e}=await import("./chunk-pp89n1et.js");S=e()}return S}var y={};async function xy(e,t=!1){let n=e==="runtime"?await vg(t):await xg(),i=e==="runtime"&&t?"runtime-debug":e,r=y[i];if(!r||r.content!==n)r={content:n,hash:Bun.hash(n).toString(16).padStart(16,"0").slice(0,16)},y[i]=r;return{content:n,hash:r.hash,url:`/_stx/${e}.${r.hash}.js`}}var E=500,T=33554432,c=new Map,p=0;function C(e){return l(process.cwd(),"module-bundles",`${e}.js`)}function Sy(e){let t=Bun.hash(e).toString(16).padStart(16,"0").slice(0,16),n=c.get(t),i=n!==void 0;if(i)c.delete(t),p-=n.length*2;c.set(t,e),p+=e.length*2;while(c.size>1&&(c.size>E||p>T)){let r=c.keys().next().value;p-=c.get(r).length*2,c.delete(r)}if(!i)try{let r=C(t);if(!o.existsSync(r))o.mkdirSync(u.dirname(r),{recursive:!0}),o.writeFileSync(r,e)}catch{}return`/_stx/modules.${t}.js`}function wi(e){if(!/^[0-9a-f]{16}$/.test(e))return;let t=c.get(e);if(t!==void 0)return t;try{return o.readFileSync(C(e),"utf8")}catch{return}}function ky(){m.clear(),Ce(),il(),f=null,B=null,S=null}function v(e){let t={debug:e.debug===!0,middleware:(e.middleware??[]).map((n)=>({name:n.name,timing:n.timing,handler:String(n.handler)})),customDirectives:(e.customDirectives??[]).map((n)=>({name:n.name,hasEndTag:n.hasEndTag===!0,rawParams:n.rawParams===!0,handler:String(n.handler)}))};return new Bun.CryptoHasher("sha1").update(JSON.stringify(t)).digest("hex")}async function Er(e,t){try{if(!t.cachePath)return null;let n=u.resolve(t.cachePath),i=u.join(n,`${Bs(e)}.html`),r=u.join(n,`${Bs(e)}.meta.json`);if(!await s(i)||!await s(r))return null;let g=await Bun.file(r).text(),a=JSON.parse(g);if(a.cacheVersion!==t.cacheVersion)return null;if(a.engine!==gt())return null;if(a.optionsSignature!==v(t))return null;if((await o.promises.stat(e)).mtime.getTime()>a.mtime)return null;for(let d of a.dependencies)if(await s(d)){if((await o.promises.stat(d)).mtime.getTime()>a.mtime)return null}else return null;return await Bun.file(i).text()}catch(n){return console.warn(`Cache error for ${e}:`,n),null}}async function Tr(e,t,n,i){try{if(!i.cachePath)return;let r=u.resolve(i.cachePath);await o.promises.mkdir(r,{recursive:!0});let g=u.join(r,`${Bs(e)}.html`),a=u.join(r,`${Bs(e)}.meta.json`),h=await o.promises.stat(e);await Bun.write(g,t);let d={sourcePath:e,mtime:h.mtime.getTime(),dependencies:Array.from(n),cacheVersion:i.cacheVersion,engine:gt(),optionsSignature:v(i),generatedAt:Date.now()};await Bun.write(a,JSON.stringify(d,null,2)),wg.set(e,{output:t,mtime:h.mtime.getTime(),dependencies:n})}catch(r){console.warn(`Failed to cache template ${e}:`,r)}}var _=16;function Bs(e){return new Bun.CryptoHasher("sha1").update(e).digest("hex").substring(0,_)}
2
+ import{il,s,Ce}from"./chunk-snhsh171.js";import{gt}from"./chunk-zkwkhesc.js";import{l}from"./chunk-w4177qn3.js";import o from"fs";import u from"path";var wg=new Map,m=new Map;async function yy(e){let n;for(let i=0;i<3;i++)try{let g=(await o.promises.stat(e)).mtime.getTime(),a=m.get(e);if(a&&a.mtime===g)return a.content;let h=await Bun.file(e).text(),w=(await o.promises.stat(e)).mtime.getTime();if(w!==g)continue;return m.set(e,{content:h,mtime:w}),h}catch(r){n=r;break}throw m.delete(e),Error(`File not found: ${e}${n?` (${n.message})`:""}`)}function by(e){m.delete(e)}function wy(e){for(let t of m.keys())if(t.startsWith(e))m.delete(t)}var f=null,B=null,x=null;function vy(e){x=e}async function vg(e=!1){let t=x??await import("./chunk-4ge69wvr.js");if(e)return t.generateSignalsRuntimeDev();if(f===null)f=t.generateSignalsRuntime();return f}var S=null;async function xg(){if(S===null){let{getRouterScript:e}=await import("./chunk-pp89n1et.js");S=e()}return S}var y={};async function xy(e,t=!1){let n=e==="runtime"?await vg(t):await xg(),i=e==="runtime"&&t?"runtime-debug":e,r=y[i];if(!r||r.content!==n)r={content:n,hash:Bun.hash(n).toString(16).padStart(16,"0").slice(0,16)},y[i]=r;return{content:n,hash:r.hash,url:`/_stx/${e}.${r.hash}.js`}}var E=500,T=33554432,c=new Map,p=0;function C(e){return l(process.cwd(),"module-bundles",`${e}.js`)}function Sy(e){let t=Bun.hash(e).toString(16).padStart(16,"0").slice(0,16),n=c.get(t),i=n!==void 0;if(i)c.delete(t),p-=n.length*2;c.set(t,e),p+=e.length*2;while(c.size>1&&(c.size>E||p>T)){let r=c.keys().next().value;p-=c.get(r).length*2,c.delete(r)}if(!i)try{let r=C(t);if(!o.existsSync(r))o.mkdirSync(u.dirname(r),{recursive:!0}),o.writeFileSync(r,e)}catch{}return`/_stx/modules.${t}.js`}function wi(e){if(!/^[0-9a-f]{16}$/.test(e))return;let t=c.get(e);if(t!==void 0)return t;try{return o.readFileSync(C(e),"utf8")}catch{return}}function ky(){m.clear(),Ce(),il(),f=null,B=null,S=null}function v(e){let t={debug:e.debug===!0,middleware:(e.middleware??[]).map((n)=>({name:n.name,timing:n.timing,handler:String(n.handler)})),customDirectives:(e.customDirectives??[]).map((n)=>({name:n.name,hasEndTag:n.hasEndTag===!0,rawParams:n.rawParams===!0,handler:String(n.handler)}))};return new Bun.CryptoHasher("sha1").update(JSON.stringify(t)).digest("hex")}async function Er(e,t){try{if(!t.cachePath)return null;let n=u.resolve(t.cachePath),i=u.join(n,`${Bs(e)}.html`),r=u.join(n,`${Bs(e)}.meta.json`);if(!await s(i)||!await s(r))return null;let g=await Bun.file(r).text(),a=JSON.parse(g);if(a.cacheVersion!==t.cacheVersion)return null;if(a.engine!==gt())return null;if(a.optionsSignature!==v(t))return null;if((await o.promises.stat(e)).mtime.getTime()>a.mtime)return null;for(let d of a.dependencies)if(await s(d)){if((await o.promises.stat(d)).mtime.getTime()>a.mtime)return null}else return null;return await Bun.file(i).text()}catch(n){return console.warn(`Cache error for ${e}:`,n),null}}async function Tr(e,t,n,i){try{if(!i.cachePath)return;let r=u.resolve(i.cachePath);await o.promises.mkdir(r,{recursive:!0});let g=u.join(r,`${Bs(e)}.html`),a=u.join(r,`${Bs(e)}.meta.json`),h=await o.promises.stat(e);await Bun.write(g,t);let d={sourcePath:e,mtime:h.mtime.getTime(),dependencies:Array.from(n),cacheVersion:i.cacheVersion,engine:gt(),optionsSignature:v(i),generatedAt:Date.now()};await Bun.write(a,JSON.stringify(d,null,2)),wg.set(e,{output:t,mtime:h.mtime.getTime(),dependencies:n})}catch(r){console.warn(`Failed to cache template ${e}:`,r)}}var _=16;function Bs(e){return new Bun.CryptoHasher("sha1").update(e).digest("hex").substring(0,_)}
3
3
  export{wg,yy,by,wy,vy,vg,xg,xy,Sy,wi,ky,Er,Tr,Bs};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Tm}from"./chunk-e5n8wfj2.js";import"./chunk-r8gv2pcy.js";import"./chunk-4nkzj2pj.js";import"./chunk-mv1hr9d4.js";import"./chunk-fs43342z.js";import"./chunk-va00ve6h.js";import"./chunk-pdfnq2gs.js";import"./chunk-440epzas.js";import"./chunk-9bexzgws.js";import"./chunk-m2t2gpjb.js";import"./chunk-66tpsdpm.js";import"./chunk-v0yay1kw.js";import"./chunk-fkm2bf2x.js";import"./chunk-13awnyq0.js";import"./chunk-p8p0xs8g.js";import"./chunk-gjk0nzyy.js";import"./chunk-razwegar.js";import"./chunk-mpfm5ctr.js";import"./chunk-eca022er.js";import"./chunk-b234w3mf.js";import"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{Tm as startInteractive};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{M,n,u}from"./chunk-c08jvjqt.js";import{ae}from"./chunk-fds6vvq0.js";import{xi}from"./chunk-razwegar.js";import E from"path";var S;async function W(){if(S!==void 0)return S;try{let e=await import("@stacksjs/ts-i18n");S=e.loadLocale??null}catch{S=null}return S}var T={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},v={},L={},k={};function J(e,s=0){if(s<=0)return!1;return Date.now()-e.loadedAt>s}async function G(e,s){if({...T,...s.i18n}.cache&&v[e]){let t=v[e],o=s.i18n?.cacheMaxAge??0;if(!J(t,o))return t.translations}if(L[e]?.state==="loading")return L[e].promise;k[e]="loading";let r=C(e,s).then((t)=>(k[e]="loaded",delete L[e],t)).catch((t)=>{throw k[e]="error",L[e]={promise:r,state:"error",error:t instanceof Error?t:Error(String(t))},t});return L[e]={promise:r,state:"loading"},r}async function C(e,s){let i={...T,...s.i18n},r=E.isAbsolute(i.translationsDir)?i.translationsDir:E.resolve(s.root||process.cwd(),i.translationsDir);try{let t=await W(),o=t?await t(e,{translationsDir:r,defaultLocale:i.defaultLocale,sources:ee(i.format)}):await Y(e,i,r);if(o===void 0){let c=e!==i.defaultLocale?await C(i.defaultLocale,s):{};if(i.cache)v[e]={translations:c,loadedAt:Date.now(),locale:e};return c}let l=o;if(i.cache)v[e]={translations:l,loadedAt:Date.now(),locale:e};return l}catch(t){if(s.debug)console.error(`Error loading translation file for locale "${e}":`,t);if(e!==i.defaultLocale)return C(i.defaultLocale,s);return{}}}async function Y(e,s,i){let r=E.join(i,`${e}${Z(s.format)}`);try{let t=await import(r);return t.default||t}catch(t){try{let o=await Bun.file(r).text();if(s.format==="yaml"||s.format==="yml")return Q(o);if(s.format==="json")return JSON.parse(o);throw t}catch{return}}}function Z(e){switch(e){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"ts":return".ts";case"json":default:return".json"}}function Q(e){let s={},i=e.split(`
2
+ import{M,n,u}from"./chunk-c08jvjqt.js";import{ae}from"./chunk-snhsh171.js";import{xi}from"./chunk-razwegar.js";import E from"path";var S;async function W(){if(S!==void 0)return S;try{let e=await import("@stacksjs/ts-i18n");S=e.loadLocale??null}catch{S=null}return S}var T={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},v={},L={},k={};function J(e,s=0){if(s<=0)return!1;return Date.now()-e.loadedAt>s}async function G(e,s){if({...T,...s.i18n}.cache&&v[e]){let t=v[e],o=s.i18n?.cacheMaxAge??0;if(!J(t,o))return t.translations}if(L[e]?.state==="loading")return L[e].promise;k[e]="loading";let r=C(e,s).then((t)=>(k[e]="loaded",delete L[e],t)).catch((t)=>{throw k[e]="error",L[e]={promise:r,state:"error",error:t instanceof Error?t:Error(String(t))},t});return L[e]={promise:r,state:"loading"},r}async function C(e,s){let i={...T,...s.i18n},r=E.isAbsolute(i.translationsDir)?i.translationsDir:E.resolve(s.root||process.cwd(),i.translationsDir);try{let t=await W(),o=t?await t(e,{translationsDir:r,defaultLocale:i.defaultLocale,sources:ee(i.format)}):await Y(e,i,r);if(o===void 0){let c=e!==i.defaultLocale?await C(i.defaultLocale,s):{};if(i.cache)v[e]={translations:c,loadedAt:Date.now(),locale:e};return c}let l=o;if(i.cache)v[e]={translations:l,loadedAt:Date.now(),locale:e};return l}catch(t){if(s.debug)console.error(`Error loading translation file for locale "${e}":`,t);if(e!==i.defaultLocale)return C(i.defaultLocale,s);return{}}}async function Y(e,s,i){let r=E.join(i,`${e}${Z(s.format)}`);try{let t=await import(r);return t.default||t}catch(t){try{let o=await Bun.file(r).text();if(s.format==="yaml"||s.format==="yml")return Q(o);if(s.format==="json")return JSON.parse(o);throw t}catch{return}}}function Z(e){switch(e){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"ts":return".ts";case"json":default:return".json"}}function Q(e){let s={},i=e.split(`
3
3
  `),r=[{obj:s,indent:-1}];for(let t of i){let o=t.replace(/#.*$/,"").trimEnd();if(!o.trim())continue;let l=o.search(/\S/);if(l===-1)continue;while(r.length>1&&r[r.length-1].indent>=l)r.pop();let c=r[r.length-1].obj,a=o.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(a){let[,,g,p]=a,f=g.trim(),m=p.trim();if(m==="")c[f]={},r.push({obj:c[f],indent:l});else c[f]=X(m)}}return s}function X(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let s=e.toLowerCase();if(s==="true"||s==="yes")return!0;if(s==="false"||s==="no")return!1;if(s==="null"||s==="~")return null;let i=Number(e);if(!Number.isNaN(i)&&e!=="")return i;return e}function ee(e){switch(e){case"yaml":case"yml":return["yaml"];case"js":case"ts":return["ts"];case"json":default:return["json"]}}async function te(e,s){return G(e,s)}function re(e,s){for(let i of e){let r=i.trim(),t=r.match(/^\{(\d+)\}\s*(.*)$/);if(t){let l=Number.parseInt(t[1],10);if(s===l)return t[2];continue}let o=r.match(/^\[(\d+),(\d+|\*)\]\s*(.*)$/);if(o){let l=Number.parseInt(o[1],10),c=o[2]==="*"?Number.POSITIVE_INFINITY:Number.parseInt(o[2],10);if(s>=l&&s<=c)return o[3];continue}}if(e.length===2)return s===1?e[0].trim():e[1].trim();if(s<e.length)return e[s].trim();return e[e.length-1].trim()}function ne(e,s={}){return j(e,s)}function j(e,s){let i="",r=0;while(r<e.length)if(e[r]==="{"){let t=ie(e,r);if(t===-1){i+=e[r],r++;continue}let o=e.slice(r+1,t);i+=se(o,s),r=t+1}else if(e[r]==="'"&&r+1<e.length)if(e[r+1]==="'")i+="'",r+=2;else if(e[r+1]==="{"||e[r+1]==="}")i+=e[r+1],r+=2;else i+=e[r],r++;else i+=e[r],r++;return i}function ie(e,s){let i=0;for(let r=s;r<e.length;r++)if(e[r]==="{")i++;else if(e[r]==="}"){if(i--,i===0)return r}return-1}function se(e,s){let i=oe(e);if(i.length===0)return`{${e}}`;let r=i[0].trim(),t=s[r];if(i.length===1)return t!==void 0?String(t):`{${r}}`;switch(i[1].trim().toLowerCase()){case"plural":return le(t,i.slice(2).join(","),s);case"select":return ue(t,i.slice(2).join(","));case"selectordinal":return de(t,i.slice(2).join(","));case"number":return pe(t,i[2]?.trim());case"date":return fe(t,i[2]?.trim());case"time":return me(t,i[2]?.trim());default:return t!==void 0?String(t):`{${e}}`}}function oe(e){let s=[],i="",r=0;for(let t=0;t<e.length;t++){let o=e[t];if(o==="{")r++,i+=o;else if(o==="}")r--,i+=o;else if(o===","&&r===0)s.push(i),i="";else i+=o}if(i)s.push(i);return s}function le(e,s,i){let r=Number(e)||0,t=P(s),o=`=${r}`;if(t[o])return R(t[o],r,i);let l=ce(r);if(t[l])return R(t[l],r,i);if(t.other)return R(t.other,r,i);return String(r)}function R(e,s,i){let r=e.replace(/#/g,String(s));return j(r,i)}function ce(e){let s=Math.abs(e),i=Math.floor(s),r=String(e).includes(".")?String(e).split(".")[1].length:0;if(i===1&&r===0)return"one";return"other"}function ue(e,s){let i=String(e||""),r=P(s);if(r[i])return r[i];return r.other||String(e)}function de(e,s){let i=Number(e)||0,r=P(s),t=ge(i);if(r[t])return r[t].replace(/#/g,String(i));if(r.other)return r.other.replace(/#/g,String(i));return String(i)}function ge(e){let s=Math.abs(e),i=s%10,r=s%100;if(i===1&&r!==11)return"one";if(i===2&&r!==12)return"two";if(i===3&&r!==13)return"few";return"other"}function P(e){let s={},i=/(\w+|=\d+)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,r=i.exec(e);while(r!==null)s[r[1]]=r[2],r=i.exec(e);return s}function pe(e,s){let i=Number(e);if(Number.isNaN(i))return String(e);switch(s){case"integer":return Math.floor(i).toLocaleString();case"percent":return`${(i*100).toFixed(0)}%`;case"currency":return i.toLocaleString(void 0,{style:"currency",currency:"USD"});default:return i.toLocaleString()}}function fe(e,s){let i=e instanceof Date?e:new Date(String(e));if(Number.isNaN(i.getTime()))return String(e);let r={};switch(s){case"short":r.dateStyle="short";break;case"medium":r.dateStyle="medium";break;case"long":r.dateStyle="long";break;case"full":r.dateStyle="full";break;default:r.dateStyle="medium"}return i.toLocaleDateString(void 0,r)}function me(e,s){let i=e instanceof Date?e:new Date(String(e));if(Number.isNaN(i.getTime()))return String(e);let r={};switch(s){case"short":r.timeStyle="short";break;case"medium":r.timeStyle="medium";break;case"long":r.timeStyle="long";break;case"full":r.timeStyle="full";break;default:r.timeStyle="short"}return i.toLocaleTimeString(void 0,r)}function be(e){return/\{[^}]+,\s*(?:plural|select|selectordinal|number|date|time)\s*,/.test(e)}function O(e,s,i=!0,r={}){let t=e.split("."),o=s;for(let c of t){if(o===void 0||o===null)break;o=o[c]}if(o===void 0||o===null)return i?e:"";let l=String(o);if(be(l))return ne(l,r);if(l.includes("|")&&"count"in r){let c=Number(r.count),a=l.split("|");l=re(a,c)}for(let[c,a]of Object.entries(r)){let g=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");l=l.replace(new RegExp(`:${g}`,"g"),()=>String(a))}return l}var D=new Set(["ar","arc","ckb","dv","fa","he","khw","ks","nqo","prs","ps","sd","syr","ug","ur","uz-af","yi"]),he=new Set(["adlm","arab","aran","hebr","nkoo","rohg","syrc","thaa","yezi"]);function q(e){if(!e)return"ltr";let s=e.trim().toLowerCase().replace(/_/g,"-").split("-"),i=s[0];if(!i)return"ltr";let r=s[1]?.length===4?s[1]:void 0;if(r)return he.has(r)?"rtl":"ltr";if(s.length>1&&D.has(`${i}-${s[1]}`))return"rtl";return D.has(i)?"rtl":"ltr"}async function qc(e,s,i,r){let t=e,o=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,l={...T,...r.i18n},c=await te(l.locale,r);s.__translations=c,s.__locale=l.locale,s.__i18nConfig=l,t=await F(t,o,async(p,f,m,w,h)=>{try{let b={};if(m)try{let d=[()=>JSON.parse(m),()=>{let x=`{"data":${m}}`,A=JSON.parse(x);return typeof A.data==="object"?A.data:{}},()=>M(m,s)];for(let x of d)try{if(b=x(),Object.keys(b).length>0)break}catch{}}catch(d){if(r.debug)console.error("Error parsing parameters for @translate directive:",d)}let y=O(f,c,l.fallbackToKey,b);return y?ae(t,h,y,!1,p.length):w.trim()}catch(b){if(r.debug)console.error("Error processing @translate directive:",b);return u("Translate",`Error in @translate('${f}'): ${b instanceof Error?b.message:String(b)}`,n.EVALUATION_ERROR)}});let a=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(r.debug){console.warn(`Processing translations in template. Sections: ${t.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let p=[...t.matchAll(a)];console.warn(`Found ${p.length} @translate matches`),p.forEach((f,m)=>console.warn(`Match ${m}: ${f[0]}, Key: ${f[1]}, Params: ${f[2]||"none"}`))}return t=await F(t,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(p,f,m,w)=>{try{let h={};if(m)try{let b=[()=>JSON.parse(m),()=>{let y=`{"data":${m}}`,d=JSON.parse(y);return typeof d.data==="object"?d.data:{}},()=>M(m,s)];for(let y of b)try{if(h=y(),Object.keys(h).length>0)break}catch{}}catch(b){if(r.debug)console.error("Error parsing parameters for @translate directive:",b)}return ae(t,w,O(f,c,l.fallbackToKey,h),!1,p.length)}catch(h){if(r.debug)console.error("Error processing @translate directive:",h);return u("Translate",`Error in @translate('${f}'): ${h instanceof Error?h.message:String(h)}`,n.EVALUATION_ERROR)}}),t}async function F(e,s,i){let r=[];return e.replace(s,(o,...l)=>{let c=i(o,...l).then((a)=>({match:o,replacement:a}));return r.push(c),o}),(await Promise.all(r)).reduce((o,{match:l,replacement:c})=>o.replace(l,()=>c),e)}function _(e,s){if(!e||q(e)!=="rtl")return!1;return!s||s.trim().toLowerCase()!=="rtl"}function V(e){if(!e)return!1;return e.trim().split(/\s+/)[0]?.toLowerCase()==="presentation"||e.trim().split(/\s+/)[0]?.toLowerCase()==="none"}function I(e,s){let i=new RegExp(`\\b${s}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`,"i").exec(e);if(!i)return null;return i[2]??i[3]??i[4]??null}function Kc(e,s,i,r){let t=e;t=t.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(l,c,a)=>{let p={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[c]||"Make this element accessible";return`<!-- a11y-hint: ${a||p} -->`});let o=/@screenReader\(([^@]*)\)@endScreenReader/g;return t=t.replace(o,(l,c)=>`<span class="sr-only">${c.trim()}</span>`),t=t.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(l,c,a)=>`<span id="${`desc-${c}`}" class="sr-only">${a}</span>`),t}function ye(){return typeof globalThis.document<"u"&&typeof globalThis.document.createElement==="function"}function xe(e){let s=new Map,i=e.replace(/<(\/?)([A-Z][\w:.-]*)(?=[\s/>])/g,(t,o,l)=>{let c=s.get(l);if(!c)c=`stx-a11y-component-${s.size}`,s.set(l,c);return`<${o}${c}`}),r=new Map([...s.entries()].map(([t,o])=>[o,t]));return{protectedSource:i,restore:(t)=>t.replace(/<(\/?)(stx-a11y-component-\d+)(?=[\s/>])/g,(o,l,c)=>{let a=r.get(c);return a?`<${l}${a}`:o})}}function we(e,s){let i=[],r=/<img\s+([^>]*)>/gi,t;t=r.exec(e);while(t!==null){let d=t[1];if(!/\balt\s*=/i.test(d))i.push({type:"missing-alt",element:t[0].substring(0,100),message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"});t=r.exec(e)}let o=/<button([^>]*)>\s*<\/button>/gi;t=o.exec(e);while(t!==null){let d=t[1];if(!/\baria-label\s*=/i.test(d)&&!/\btitle\s*=/i.test(d))i.push({type:"missing-accessible-name",element:t[0].substring(0,100),message:"Empty button missing accessible name",impact:"critical",help:"Add text content, aria-label, or title",helpUrl:"https://web.dev/learn/accessibility/aria-html/"});t=o.exec(e)}let l=/<a\s+([^>]*)>\s*<\/a>/gi;t=l.exec(e);while(t!==null){let d=t[1];if(!/\baria-label\s*=/i.test(d)&&!/\btitle\s*=/i.test(d))i.push({type:"link-missing-text",element:t[0].substring(0,100),message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"});t=l.exec(e)}let c=/<(input|select|textarea)\s+([^>]*)>/gi;t=c.exec(e);while(t!==null){let d=t[2];if(/\btype\s*=\s*["']hidden["']/i.test(d)){t=c.exec(e);continue}let x=/\baria-label\s*=/i.test(d)||/\baria-labelledby\s*=/i.test(d),A=d.match(/\bid\s*=\s*["']([^"']+)["']/i);if(!x){let B=A&&new RegExp(`<label[^>]*\\bfor\\s*=\\s*["']${A[1]}["']`,"i").test(e),U=t.index,N=e.substring(0,U),Se=e.substring(U),H=(N.match(/<label\b/gi)||[]).length,z=(N.match(/<\/label>/gi)||[]).length,K=H>z;if(!B&&!K)i.push({type:"input-missing-label",element:t[0].substring(0,100),message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})}t=c.exec(e)}let a=/<h([1-6])[^>]*>/gi,g=[];t=a.exec(e);while(t!==null)g.push(Number.parseInt(t[1],10)),t=a.exec(e);let p=0;for(let d of g){if(p>0&&d>p+1)i.push({type:"heading-skip",element:`<h${d}>`,message:`Heading level skipped from h${p} to h${d}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});p=d}if(/<html\b/i.test(e)&&!/<html[^>]*\slang\s*=/i.test(e))i.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"});let f=e.match(/<html\b([^>]*)>/i);if(f&&_(I(f[1],"lang"),I(f[1],"dir")))i.push({type:"missing-dir",element:f[0].substring(0,100),message:'Document language is right-to-left but dir="rtl" is not set',impact:"serious",help:'Add dir="rtl" to the html element so the layout mirrors the text',helpUrl:"https://www.w3.org/International/questions/qa-html-dir"});let m=/<table([^>]*)>([\s\S]*?)<\/table>/gi;t=m.exec(e);while(t!==null){let d=t[2];if(!V(I(t[1],"role"))&&!/<th\b/i.test(d))i.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});t=m.exec(e)}let w=/<(video|audio)[^>]*\sautoplay\s[^>]*>/gi;t=w.exec(e);while(t!==null){if(!/\bmuted\b/i.test(t[0]))i.push({type:"autoplay-audio",element:`<${t[1]}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"});t=w.exec(e)}let h=/\btabindex\s*=\s*["']([1-9]\d*)["']/gi;t=h.exec(e);while(t!==null)i.push({type:"positive-tabindex",element:`tabindex="${t[1]}"`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"}),t=h.exec(e);let b=/<iframe\s+([^>]*)>/gi;t=b.exec(e);while(t!==null){let d=t[1];if(!/\btitle\s*=/i.test(d)&&!/\baria-label\s*=/i.test(d))i.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"});t=b.exec(e)}let y=/<([a-z]+)\s+([^>]*role\s*=\s*["']button["'][^>]*)>/gi;t=y.exec(e);while(t!==null){let d=t[1].toLowerCase(),x=t[2];if(d!=="button"&&!/\btabindex\s*=/i.test(x))i.push({type:"button-not-focusable",element:t[0].substring(0,100),message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"});t=y.exec(e)}return i}async function Ae(e,s){let{protectedSource:i}=xe(e);if(!ye())return we(i,s);let r=[];try{let t=globalThis.document.createElement("div");t.innerHTML=i,t.querySelectorAll("img").forEach((a)=>{if(!a.hasAttribute("alt"))r.push({type:"missing-alt",element:`<${a.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),t.querySelectorAll('button, a, [role="button"]').forEach((a)=>{if(!(a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby")||a.textContent&&a.textContent.trim().length>0))r.push({type:"missing-accessible-name",element:`<${a.outerHTML}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"})}),t.querySelectorAll("input, select, textarea").forEach((a)=>{let g=a.getAttribute("id"),p=g&&t.querySelector(`label[for="${g}"]`),f=a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby"),m=a.closest("label")!==null;if(!p&&!f&&!m)r.push({type:"input-missing-label",element:`<${a.outerHTML}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})});let o=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6")),l=0;for(let a of o){let g=Number.parseInt(a.tagName.charAt(1));if(l>0&&g>l+1)r.push({type:"heading-skip",element:`<${a.outerHTML}>`,message:`Heading level skipped from h${l} to h${g}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});l=g}let c=t.querySelector("html");if(i.includes("<html")&&c&&!c.hasAttribute("lang"))r.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"});if(c&&_(c.getAttribute("lang"),c.getAttribute("dir")))r.push({type:"missing-dir",element:"<html>",message:'Document language is right-to-left but dir="rtl" is not set',impact:"serious",help:'Add dir="rtl" to the html element so the layout mirrors the text',helpUrl:"https://www.w3.org/International/questions/qa-html-dir"});if(t.querySelectorAll("a").forEach((a)=>{let g=a.textContent&&a.textContent.trim().length>0,p=a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby"),f=a.hasAttribute("title"),m=a.querySelector("img[alt]");if(!g&&!p&&!f&&!m)r.push({type:"link-missing-text",element:`<${a.outerHTML}>`,message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"})}),i.includes("<nav")||i.includes("<header")){if(!t.querySelector('a[href="#main"], a[href="#content"], .skip-link, [class*="skip"]')&&t.querySelectorAll("a").length>5)r.push({type:"missing-skip-link",element:"<nav>",message:"Consider adding a skip navigation link",impact:"minor",help:"Add a skip link to allow keyboard users to bypass navigation",helpUrl:"https://web.dev/learn/accessibility/focus/#skip-links"})}if(t.querySelectorAll("table").forEach((a)=>{if(V(a.getAttribute("role")))return;let g=a.querySelector("caption");if(!a.querySelector("th"))r.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});if(!g&&!a.hasAttribute("aria-label")&&!a.hasAttribute("aria-labelledby"))r.push({type:"table-missing-caption",element:"<table>",message:"Table missing caption or accessible name",impact:"minor",help:"Add a caption element or aria-label to describe the table",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"})}),t.querySelectorAll('[style*="color"]').forEach((a)=>{let g=a.getAttribute("style")||"";if(g.includes("color:")&&!g.includes("background"))r.push({type:"potential-contrast-issue",element:`<${a.tagName.toLowerCase()}>`,message:"Element has inline color style - verify contrast ratio",impact:"minor",help:"Ensure text has sufficient contrast ratio (4.5:1 for normal text)",helpUrl:"https://web.dev/learn/accessibility/color-contrast/"})}),t.querySelectorAll("video[autoplay], audio[autoplay]").forEach((a)=>{if(!a.hasAttribute("muted"))r.push({type:"autoplay-audio",element:`<${a.tagName.toLowerCase()}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"})}),t.querySelectorAll("[tabindex]").forEach((a)=>{if(Number.parseInt(a.getAttribute("tabindex")||"0")>0)r.push({type:"positive-tabindex",element:`<${a.tagName.toLowerCase()}>`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"})}),t.querySelectorAll('[role="button"]').forEach((a)=>{if(!a.hasAttribute("tabindex"))r.push({type:"button-not-focusable",element:`<${a.outerHTML}>`,message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"})}),i.includes("<body")&&!t.querySelector('main, [role="main"]'))r.push({type:"missing-main-landmark",element:"<body>",message:"Document missing main landmark region",impact:"moderate",help:"Add a main element to identify the primary content",helpUrl:"https://web.dev/learn/accessibility/structure/#landmarks"});t.querySelectorAll("iframe").forEach((a)=>{if(!a.hasAttribute("title")&&!a.hasAttribute("aria-label"))r.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"})})}catch(t){console.error(`Error checking accessibility in ${s}:`,t)}return r}async function Xc(e,s={}){let i={},{recursive:r=!0,ignorePaths:t=[]}=s,o=Array.isArray(e)?e:[e],l=await xi(o,{recursive:r,ignorePaths:t}),c=[];for(let a of l)try{let g=await Bun.file(a).text();if(a.endsWith("good-a11y.stx"))continue;let p=await Ae(g,a);if(c.push(a),p.length>0)i[a]=p}catch(g){console.error(`Error scanning ${a}:`,g)}return{results:i,scannedFiles:c}}var Gc={name:"a11y",handler:(e,s,i,r)=>{if(!s.length)return e;let t=s[0].replace(/['"]/g,""),o=s.length>1?s[1].replace(/['"]/g,""):"",c={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[t]||"Make this element accessible";return`<!-- a11y-hint: ${o||c} -->${e}`},hasEndTag:!1},Jc={name:"screenReader",handler:(e)=>`<span class="sr-only">${e}</span>`,hasEndTag:!0};
4
4
  export{qc,Kc,Xc,Gc,Jc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{k,E,A,ee,O,so,ie}from"./chunk-fds6vvq0.js";import{je}from"./chunk-ck4ypzet.js";import{Z}from"./chunk-13awnyq0.js";import{C}from"./chunk-4b110x6r.js";import{D,zn}from"./chunk-phzhmnnm.js";import{a}from"./chunk-xfjp5q2m.js";import{$e,yn,bn,wn}from"./chunk-wk6g0b9h.js";import{Ot}from"./chunk-fwffn130.js";import{Rt,sr,un,ve}from"./chunk-jz37h2z0.js";import{I,rt}from"./chunk-e5rag6rh.js";import w from"path";var x=new Map,P=new Map,R=k(64),T=new Map,ne=["composables","functions"];function W(e){let s=w.basename(e,".ts");return s==="index"||s==="types"||e.endsWith(".d.ts")}async function se(e){if(e)return w.resolve(e);let s=`<default>:${process.cwd()}`,i=T.get(s);if(i!==void 0)return i;let t=await oe();if(t!==null)T.set(s,t);return t}async function oe(){let e=await a(),s=e.root||process.cwd(),i=e.composablesDir;if(i)return w.resolve(s,i);for(let t of ne){let n=w.resolve(s,t);try{let c=new Bun.Glob("**/*.ts");for await(let r of c.scan({cwd:n,absolute:!0}))if(!W(r))return n}catch{}}return null}async function X(e){let s=Array.isArray(e)?e:e?[w.resolve(e)]:(await a())._layerComposableDirs??[await se()].filter((t)=>!!t),i=new Map;for(let t of s){let n=new Bun.Glob("**/*.ts");try{for await(let c of n.scan({cwd:t,absolute:!0})){let r=w.relative(t,c);if(!W(c)&&!i.has(r))i.set(r,c)}}catch{}}return{key:s.join("\x00"),files:[...i.values()].sort()}}async function Uo(e){let{files:s}=await X(e),i=ie({loader:"ts",target:"browser",define:A()}),t=[];for(let n of s)try{let c=await Bun.file(n).text(),r=i.scan(c).exports.filter((d)=>d!=="default");if(r.length>0)t.push({file:n,names:r})}catch{}return t}function re(e,s){return new RegExp(`\\b${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e)}function Q(e,s){let i=new Set(e.match(/\w+/g)),t=new Set;for(let n of s)if(/^\w+$/.test(n)?i.has(n):re(e,n))t.add(n);return t}var H=k(64);function U(e,s){let i=E(e,s.size),t=H.get(i);if(t)return t;let n;try{n=je(e,s)}catch{n=Q(e,s)}let c=[...e.matchAll(/(?:const|let|var)\s*\{([^}]*)\}\s*=\s*window\.__composables\u0008/g),...e.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@composables['"]/g)];for(let r of c)for(let d of r[1].split(",")){let f=d.trim().split(/\s*(?::|\u0008as\u0008)\s*/)[0];if(f&&s.has(f))n.add(f)}return H.set(i,n),n}function ae(e){return!e||/^(?:module|(?:text|application)\/(?:java|ecma)script|application\/stx-[\w-]+)$/i.test(e)}var q=k(256);function ce(e,s){let i=new Set(s),t="",n=0,c=new Set;for(let r of ee(e)){t+=e.slice(n,r.start),n=r.end;let d=O(r.attrs),f=e.slice(r.bodyStart,r.bodyEnd),u=d.get("type"),m=typeof u==="string"?u.trim():void 0;if(!ae(m)){if(!/json/i.test(m??""))t+=` ${f} `;continue}let h=Q(f,i);if(h.size===0)continue;let _=E(f,[...h].sort().join(",")),b=q.get(_);if(!b)b=U(f,h),q.set(_,b);for(let v of b)c.add(v)}t+=e.slice(n);for(let r of so(t))for(let d of U(r.code,i))c.add(d);return c}function le(e,s,i){let t=new Map;for(let{file:f,names:u}of e)for(let m of u)if(!t.has(m))t.set(m,f);let n=new Set(t.keys()),c=(f)=>{let u=[];for(let m of U(f,n))u.push(t.get(m));return u},r=new Set,d=i.flatMap((f,u)=>u===0?[...ce(f,t.keys())].map((m)=>t.get(m)):c(f));while(d.length>0){let f=[];for(let u of d){if(r.has(u))continue;r.add(u);for(let m of c(s.get(u)??""))if(!r.has(m))f.push(m)}d=f}return r}async function Vh(e,s,i,t){let{key:n,files:c}=await X(e);if(!n)return null;let r=()=>[...new Set([...c,...c.flatMap((o)=>$e(o))])],d=Rt(r());if(c.length===0)return ve(x,n,d,""),null;c.sort();let f=ie({loader:"ts",target:"browser",define:A()}),u=un(P,n,d);if(!u){let o=new Map,l=[];for(let p of c)try{let S=await Bun.file(p).text();o.set(p,S);let g=f.scan(S).exports.filter((te)=>te!=="default");if(g.length>0)l.push({file:p,names:g})}catch{o.set(p,"")}u=ve(P,n,d,{codeByFile:o,modules:l})}let{codeByFile:m,modules:h}=u,_;if(s===void 0)_=new Set(c);else{let o=i?[s,...i]:[s],l=E(o.join("\x00"),n,o.length,d),p=R.get(l);if(_=p??le(h,m,o),!p)R.set(l,_)}if(_.size===0)return null;let b=c.filter((o)=>_.has(o)),v=()=>{if(!t)return;for(let o of b)t.push(o,...$e(o))},N=`${n}\x00${b.join("\x00")}\x00${bn()}`,z=un(x,N,d);if(z!==void 0)return v(),z||null;let F=[],B=new Set,K=new Set;for(let o of b)try{let l=m.get(o)??await Bun.file(o).text(),p=w.basename(o,".ts");for(let g of l.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(g[1])K.add(g[1]);let S=[];try{for(let g of f.scan(l).exports)if(g!=="default")B.add(g),S.push(g)}catch{}if(l=D(l),yn(l))l=await wn(l,o,{projectRoot:process.cwd(),externalizeUserModules:!1,expose:S}),l=Ot(l);l=zn(l),l=l.replace(/^export\s+(default\s+)?/gm,""),l=f.transformSync(l),F.push(`// Composable: ${p}
2
+ import{k,E,A,ee,O,so,ie}from"./chunk-snhsh171.js";import{je}from"./chunk-ck4ypzet.js";import{Z}from"./chunk-13awnyq0.js";import{C}from"./chunk-4b110x6r.js";import{D,zn}from"./chunk-phzhmnnm.js";import{a}from"./chunk-p8p0xs8g.js";import{$e,yn,bn,wn}from"./chunk-tcytjgh5.js";import{Ot}from"./chunk-m2t2gpjb.js";import{Rt,sr,un,ve}from"./chunk-jz37h2z0.js";import{I,rt}from"./chunk-e5rag6rh.js";import w from"path";var x=new Map,P=new Map,R=k(64),T=new Map,ne=["composables","functions"];function W(e){let s=w.basename(e,".ts");return s==="index"||s==="types"||e.endsWith(".d.ts")}async function se(e){if(e)return w.resolve(e);let s=`<default>:${process.cwd()}`,i=T.get(s);if(i!==void 0)return i;let t=await oe();if(t!==null)T.set(s,t);return t}async function oe(){let e=await a(),s=e.root||process.cwd(),i=e.composablesDir;if(i)return w.resolve(s,i);for(let t of ne){let n=w.resolve(s,t);try{let c=new Bun.Glob("**/*.ts");for await(let r of c.scan({cwd:n,absolute:!0}))if(!W(r))return n}catch{}}return null}async function X(e){let s=Array.isArray(e)?e:e?[w.resolve(e)]:(await a())._layerComposableDirs??[await se()].filter((t)=>!!t),i=new Map;for(let t of s){let n=new Bun.Glob("**/*.ts");try{for await(let c of n.scan({cwd:t,absolute:!0})){let r=w.relative(t,c);if(!W(c)&&!i.has(r))i.set(r,c)}}catch{}}return{key:s.join("\x00"),files:[...i.values()].sort()}}async function Uo(e){let{files:s}=await X(e),i=ie({loader:"ts",target:"browser",define:A()}),t=[];for(let n of s)try{let c=await Bun.file(n).text(),r=i.scan(c).exports.filter((d)=>d!=="default");if(r.length>0)t.push({file:n,names:r})}catch{}return t}function re(e,s){return new RegExp(`\\b${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e)}function Q(e,s){let i=new Set(e.match(/\w+/g)),t=new Set;for(let n of s)if(/^\w+$/.test(n)?i.has(n):re(e,n))t.add(n);return t}var H=k(64);function U(e,s){let i=E(e,s.size),t=H.get(i);if(t)return t;let n;try{n=je(e,s)}catch{n=Q(e,s)}let c=[...e.matchAll(/(?:const|let|var)\s*\{([^}]*)\}\s*=\s*window\.__composables\u0008/g),...e.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@composables['"]/g)];for(let r of c)for(let d of r[1].split(",")){let f=d.trim().split(/\s*(?::|\u0008as\u0008)\s*/)[0];if(f&&s.has(f))n.add(f)}return H.set(i,n),n}function ae(e){return!e||/^(?:module|(?:text|application)\/(?:java|ecma)script|application\/stx-[\w-]+)$/i.test(e)}var q=k(256);function ce(e,s){let i=new Set(s),t="",n=0,c=new Set;for(let r of ee(e)){t+=e.slice(n,r.start),n=r.end;let d=O(r.attrs),f=e.slice(r.bodyStart,r.bodyEnd),u=d.get("type"),m=typeof u==="string"?u.trim():void 0;if(!ae(m)){if(!/json/i.test(m??""))t+=` ${f} `;continue}let h=Q(f,i);if(h.size===0)continue;let _=E(f,[...h].sort().join(",")),b=q.get(_);if(!b)b=U(f,h),q.set(_,b);for(let v of b)c.add(v)}t+=e.slice(n);for(let r of so(t))for(let d of U(r.code,i))c.add(d);return c}function le(e,s,i){let t=new Map;for(let{file:f,names:u}of e)for(let m of u)if(!t.has(m))t.set(m,f);let n=new Set(t.keys()),c=(f)=>{let u=[];for(let m of U(f,n))u.push(t.get(m));return u},r=new Set,d=i.flatMap((f,u)=>u===0?[...ce(f,t.keys())].map((m)=>t.get(m)):c(f));while(d.length>0){let f=[];for(let u of d){if(r.has(u))continue;r.add(u);for(let m of c(s.get(u)??""))if(!r.has(m))f.push(m)}d=f}return r}async function Vh(e,s,i,t){let{key:n,files:c}=await X(e);if(!n)return null;let r=()=>[...new Set([...c,...c.flatMap((o)=>$e(o))])],d=Rt(r());if(c.length===0)return ve(x,n,d,""),null;c.sort();let f=ie({loader:"ts",target:"browser",define:A()}),u=un(P,n,d);if(!u){let o=new Map,l=[];for(let p of c)try{let S=await Bun.file(p).text();o.set(p,S);let g=f.scan(S).exports.filter((te)=>te!=="default");if(g.length>0)l.push({file:p,names:g})}catch{o.set(p,"")}u=ve(P,n,d,{codeByFile:o,modules:l})}let{codeByFile:m,modules:h}=u,_;if(s===void 0)_=new Set(c);else{let o=i?[s,...i]:[s],l=E(o.join("\x00"),n,o.length,d),p=R.get(l);if(_=p??le(h,m,o),!p)R.set(l,_)}if(_.size===0)return null;let b=c.filter((o)=>_.has(o)),v=()=>{if(!t)return;for(let o of b)t.push(o,...$e(o))},N=`${n}\x00${b.join("\x00")}\x00${bn()}`,z=un(x,N,d);if(z!==void 0)return v(),z||null;let F=[],B=new Set,K=new Set;for(let o of b)try{let l=m.get(o)??await Bun.file(o).text(),p=w.basename(o,".ts");for(let g of l.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(g[1])K.add(g[1]);let S=[];try{for(let g of f.scan(l).exports)if(g!=="default")B.add(g),S.push(g)}catch{}if(l=D(l),yn(l))l=await wn(l,o,{projectRoot:process.cwd(),externalizeUserModules:!1,expose:S}),l=Ot(l);l=zn(l),l=l.replace(/^export\s+(default\s+)?/gm,""),l=f.transformSync(l),F.push(`// Composable: ${p}
3
3
  ${l.trim()}`)}catch(l){console.warn(`[stx] Failed to load composable ${o}:`,l)}if(F.length===0||B.size===0)return ve(x,N,d,""),null;let V=[...B].map((o)=>` try { if (!(${JSON.stringify(o)} in __c)) __c[${JSON.stringify(o)}] = ${o}; } catch (e) {}`).join(`
4
4
  `),G=JSON.stringify([...B]),M=F.join(`
5
5
 
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{mh,Ka,Uu,hh,yh,bh,wh,vh,Vu,Wu,xh,Sh,kh,_h}from"./chunk-kp957mbs.js";import"./chunk-r8gv2pcy.js";import"./chunk-4nkzj2pj.js";import"./chunk-mv1hr9d4.js";import"./chunk-fs43342z.js";import"./chunk-va00ve6h.js";import"./chunk-pdfnq2gs.js";import"./chunk-440epzas.js";import"./chunk-9bexzgws.js";import"./chunk-m2t2gpjb.js";import"./chunk-66tpsdpm.js";import"./chunk-v0yay1kw.js";import"./chunk-fkm2bf2x.js";import"./chunk-13awnyq0.js";import"./chunk-p8p0xs8g.js";import"./chunk-gjk0nzyy.js";import"./chunk-razwegar.js";import"./chunk-mpfm5ctr.js";import"./chunk-eca022er.js";import"./chunk-b234w3mf.js";import"./chunk-snhsh171.js";import"./chunk-73py4qeh.js";import"./chunk-w98yt4d4.js";import"./chunk-c08jvjqt.js";import"./chunk-phzhmnnm.js";import"./chunk-ck4ypzet.js";import"./chunk-0jdz31q1.js";import"./chunk-4b110x6r.js";export{Uu as SUSPENSE_RESOLVER_RUNTIME,Ka as buildSuspenseResolveScript,vh as createStreamRenderer,bh as extractStreamBoundaries,_h as generateHydrationRuntime,Wu as islandDirective,Sh as processSectionDirectives,yh as processStreamDirectives,xh as registerStreamingDirectives,hh as renderStreamingPage,mh as streamTemplate,wh as streamTemplateSimple,kh as streamToResponse,Vu as streamingSuspenseDirective};