@stacksjs/stx 0.2.835 → 0.2.836

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 (81) hide show
  1. package/dist/{chunk-w5g788r7.js → chunk-0ee6a69c.js} +1 -1
  2. package/dist/{chunk-5n988caw.js → chunk-14dmmthm.js} +1 -1
  3. package/dist/{chunk-12bwztw2.js → chunk-1av9cx4h.js} +1 -1
  4. package/dist/{chunk-88b319bz.js → chunk-1rgex0bn.js} +5 -5
  5. package/dist/{chunk-6eqjf0r6.js → chunk-2b25kjyx.js} +1 -1
  6. package/dist/{chunk-pq6x35gz.js → chunk-3sty93sy.js} +1 -1
  7. package/dist/{chunk-rsg4zdt3.js → chunk-6c3wj83w.js} +1 -1
  8. package/dist/{chunk-anckn6bc.js → chunk-71vj7v61.js} +1 -1
  9. package/dist/{chunk-a1fp1nyf.js → chunk-7kzxmm80.js} +6 -6
  10. package/dist/{chunk-3s70qc9v.js → chunk-876qk7ct.js} +1 -1
  11. package/dist/{chunk-3fk1cm0n.js → chunk-8dr42g11.js} +1 -1
  12. package/dist/{chunk-7ygadxrq.js → chunk-8p9bphp5.js} +1 -1
  13. package/dist/{chunk-waz6g84g.js → chunk-8tktmm5d.js} +1 -1
  14. package/dist/{chunk-9q378vgc.js → chunk-8xmm692p.js} +1 -1
  15. package/dist/{chunk-8f49t8wb.js → chunk-91qky0er.js} +2 -2
  16. package/dist/{chunk-x6ck5s29.js → chunk-92j6qkbh.js} +1 -1
  17. package/dist/{chunk-wpy1ytv9.js → chunk-944tcqgg.js} +4 -4
  18. package/dist/{chunk-7phzt95j.js → chunk-9gg6hm3q.js} +1 -1
  19. package/dist/{chunk-q4h6mhn1.js → chunk-9wsrkcyw.js} +2 -2
  20. package/dist/{chunk-nbz025jk.js → chunk-a20xgjzx.js} +1 -1
  21. package/dist/{chunk-mvk7rm5q.js → chunk-c3n6rbr8.js} +1 -1
  22. package/dist/{chunk-wz24zyt1.js → chunk-cjna1thj.js} +1 -1
  23. package/dist/{chunk-53gp3w46.js → chunk-cyd6s7tj.js} +1 -1
  24. package/dist/{chunk-2xcnynmg.js → chunk-d6twwydm.js} +2 -2
  25. package/dist/{chunk-02s0hzwa.js → chunk-d85fvcf5.js} +2 -2
  26. package/dist/{chunk-7v372ds3.js → chunk-d9m9azzk.js} +4 -4
  27. package/dist/chunk-dcsg4h3n.js +2 -0
  28. package/dist/{chunk-9cy3fy0k.js → chunk-dq9mrthz.js} +1 -1
  29. package/dist/{chunk-hzs22cc9.js → chunk-ek3gqadc.js} +1 -1
  30. package/dist/{chunk-k23nn7k9.js → chunk-eydfzmdj.js} +1 -1
  31. package/dist/{chunk-j6146c13.js → chunk-fn0419dn.js} +1 -1
  32. package/dist/chunk-fxc0q5g6.js +2 -0
  33. package/dist/{chunk-35vsv68x.js → chunk-h12ekfb7.js} +1 -1
  34. package/dist/chunk-hf8750kf.js +2 -0
  35. package/dist/{chunk-e3pkgwd8.js → chunk-hrzef4vb.js} +1 -1
  36. package/dist/{chunk-k5jmnt0z.js → chunk-hzp3yf39.js} +1 -1
  37. package/dist/{chunk-rkk2mb0h.js → chunk-kkvyy9an.js} +1 -1
  38. package/dist/{chunk-7chq9qj0.js → chunk-mpd57aqc.js} +1 -1
  39. package/dist/{chunk-x7bbbmgd.js → chunk-nzybzbh4.js} +1 -1
  40. package/dist/chunk-pb1f52s7.js +2 -0
  41. package/dist/{chunk-zr4e0jrh.js → chunk-pj904eyr.js} +4 -4
  42. package/dist/{chunk-9q3pqtx8.js → chunk-pkxy74j9.js} +1 -1
  43. package/dist/{chunk-h8pp1dsq.js → chunk-qq19g7e2.js} +1 -1
  44. package/dist/{chunk-hhh6v5cw.js → chunk-s5g6gtz3.js} +1 -1
  45. package/dist/chunk-s5gt7k23.js +2 -0
  46. package/dist/chunk-t02y9hrh.js +2 -0
  47. package/dist/{chunk-n82sms5e.js → chunk-tc7s3tny.js} +4 -4
  48. package/dist/{chunk-sstbhctt.js → chunk-tj24x37q.js} +1 -1
  49. package/dist/{chunk-6vx101bj.js → chunk-v8mh2xvp.js} +1 -1
  50. package/dist/chunk-vdyvtnbs.js +2 -0
  51. package/dist/{chunk-0nc94zjd.js → chunk-vjh6va50.js} +1 -1
  52. package/dist/{chunk-mejtwsgy.js → chunk-vrptmxvt.js} +1 -1
  53. package/dist/{chunk-1q3gjt3t.js → chunk-vxmfeys6.js} +1 -1
  54. package/dist/{chunk-vmj0hqzc.js → chunk-we6yqv3w.js} +1 -1
  55. package/dist/{chunk-pzavparv.js → chunk-we7cc5x7.js} +1 -1
  56. package/dist/{chunk-h6w7jr4b.js → chunk-wsaann3r.js} +2 -2
  57. package/dist/{chunk-gy3pegf9.js → chunk-xa8jn2ym.js} +1 -1
  58. package/dist/chunk-xg852k9h.js +3 -0
  59. package/dist/chunk-xvwpc56h.js +2 -0
  60. package/dist/chunk-y8ban8z2.js +2 -0
  61. package/dist/{chunk-tj90sfcs.js → chunk-yjp3bggk.js} +1 -1
  62. package/dist/{chunk-mmm5t7jf.js → chunk-z9rm4rcv.js} +1 -1
  63. package/dist/{chunk-ws9ypnvs.js → chunk-zbnxrj3b.js} +2 -2
  64. package/dist/{chunk-1pg50kva.js → chunk-zwgxnjmx.js} +3 -3
  65. package/dist/cli.js +7 -7
  66. package/dist/component-image-usage.js +7 -3
  67. package/dist/craft-entry.js +1 -1
  68. package/dist/craft.js +1 -1
  69. package/dist/pwa.js +1 -1
  70. package/dist/ssg.js +2 -2
  71. package/package.json +5 -5
  72. package/dist/chunk-0ygvav3v.js +0 -3
  73. package/dist/chunk-213skjvq.js +0 -2
  74. package/dist/chunk-8tm6701m.js +0 -2
  75. package/dist/chunk-9fk98kja.js +0 -2
  76. package/dist/chunk-bsm5ds0r.js +0 -2
  77. package/dist/chunk-fcy7n409.js +0 -2
  78. package/dist/chunk-g40zerct.js +0 -2
  79. package/dist/chunk-mr97dmgb.js +0 -2
  80. package/dist/chunk-vbwtx73e.js +0 -2
  81. package/dist/chunk-x4x1xj40.js +0 -2
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{nt}from"./chunk-29f6vmyz.js";import{yt,Un}from"./chunk-w0a6yz73.js";import{Rr,Ar,Pr,Or,Ce}from"./chunk-txd2js5v.js";import{De,hn,el,tl}from"./chunk-a1fp1nyf.js";import{M}from"./chunk-vfj9wp11.js";import{Si}from"./chunk-6eqjf0r6.js";import{b}from"./chunk-q4h6mhn1.js";import{i}from"./chunk-zr4e0jrh.js";import{F,a}from"./chunk-02s0hzwa.js";import{_c}from"./chunk-amg6kr1p.js";import{On,qe,Te,da,pa,Nn}from"./chunk-1pg50kva.js";import{an,Io}from"./chunk-53gp3w46.js";import{Mn}from"./chunk-fvgk1w9s.js";import{Qt,Qn,er}from"./chunk-s3j5vxy9.js";import{G}from"./chunk-wpy1ytv9.js";import m from"fs";import c from"path";import{createHash as Q}from"crypto";function J(n){return Q("sha256").update(n).digest("hex").slice(0,8)}function U(n=!1){let l=n?Un():yt(),o=J(l);return{content:l,filename:`runtime.${o}.js`,hash:o}}function V(){let n=nt(),l=J(n);return{content:n,filename:`router.${l}.js`,hash:l}}import q from"path";import{createHash as ee}from"crypto";function te(n={}){let l=new Set;return{context:new Proxy(n,{get(r,e){if(e in r)return r[e];if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return},has(r,e){if(e in r)return!0;if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return!1}}),accessedKeys:l}}async function X(n,l,o={}){let r=q.resolve(n),e=await Bun.file(r).text(),S=ee("sha256").update(e).digest("hex").slice(0,16);el();let _={};try{_=await a(o.configDir)}catch{}let h=[],d=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,g;while((g=d.exec(e))!==null){let R=g[1];if(/\bserver\b/.test(R))h.push(g[2])}let u=new Set(h.flatMap((R)=>De(R))),{context:D}=te({__filename:r,__dirname:q.dirname(r),__stx_serverDeclared:u}),A=new Set,T={...F,..._,...o,buildMode:"compile",strict:!1},y=await i(e,D,r,T,A),w=On(y)+qe(y),j=tl();return{route:l,sourceFile:n,html:y,fragment:w,placeholders:j,hasServerScripts:h.length>0,serverScriptContent:h,dependencies:Array.from(A),contentHash:S,status:hn(e),streamTemplates:D.__streamTemplates}}var re=new Set([".DS_Store","Thumbs.db","desktop.ini",".gitkeep",".gitignore"]);function Z(n,l){let o=0,r=0;if(!m.existsSync(n))return{copied:o,bytes:r};m.mkdirSync(l,{recursive:!0});function e(S,_){let h=m.readdirSync(S,{withFileTypes:!0});for(let d of h){if(re.has(d.name))continue;let g=c.join(S,d.name),u=c.join(_,d.name);if(d.isDirectory())m.mkdirSync(u,{recursive:!0}),e(g,u);else if(d.isFile()){if(m.existsSync(u))continue;m.copyFileSync(g,u),o++,r+=m.statSync(u).size}}}return e(n,l),{copied:o,bytes:r}}async function om(n={}){let l=Date.now(),o=c.resolve(n.root||process.cwd()),r=c.resolve(o,n.outputDir||".output");console.log("[stx build] Starting production build...");let e=await a(o),S=c.resolve(o,n.componentsDir??e.componentsDir??"components"),_=c.resolve(o,n.partialsDir??e.partialsDir??"partials"),h=c.resolve(o,n.layoutsDir??e.layoutsDir??"layouts"),d=n.publicDir??e.publicDir??"public",g=Ce(e.app?.head,{known:Or,source:"app.head"}),u=e.app?.colorMode,D=e.router?.container||"main",A=n.routeRules??e.routeRules??{},T=Mn(A),y=n.serverApi??e.serverApi,w=typeof y==="object"?y:{};if(y)an(o,w);if(e.runtimeConfig)M(e.runtimeConfig,{});if(m.existsSync(r))m.rmSync(r,{recursive:!0});let j=[c.join(r,"public","__stx"),c.join(r,"public","assets"),c.join(r,"server","pages"),c.join(r,"server","fragments")];for(let s of j)m.mkdirSync(s,{recursive:!0});console.log("[stx build] Discovering routes...");let R=G(o,{pagesDirs:e._layerPageDirs}),Y=["components","layouts","partials"],P=R.filter((s)=>!Y.some((f)=>s.pattern.startsWith(`/${f}/`)||s.pattern===`/${f}`));console.log(`[stx build] Found ${P.length} page routes (${R.length-P.length} non-page files excluded)`),console.log("[stx build] Generating shared assets...");let v=U(n.debug),x=V();await Bun.write(c.join(r,"public","__stx",v.filename),v.content),await Bun.write(c.join(r,"public","__stx",x.filename),x.content),console.log(`[stx build] Runtime: ${v.filename} (${(v.content.length/1024).toFixed(1)}KB)`),console.log(`[stx build] Router: ${x.filename} (${(x.content.length/1024).toFixed(1)}KB)`),console.log("[stx build] Compiling templates...");let B=[],H=[];for(let s of P){let f=T(s.pattern),O=f.rendering==="prerender";if(O&&(s.pattern.includes(":")||s.pattern.includes("[")))throw Error(`Cannot prerender parameter route ${s.pattern}; use dynamic rendering (explicit path enumeration is not supported here)`);try{let t=await X(s.filePath,s.pattern,{configDir:o,componentsDir:S,partialsDir:_,layoutsDir:h,debug:n.debug});if(B.push(t),t.html=t.html.replace(/runtime\.__STX_HASH__\.js/g,v.filename).replace(/router\.__STX_HASH__\.js/g,x.filename),t.html=Pr(t.html,g,{bodyScripts:[`<script src="/__stx/${x.filename}"></script>`],...u&&{colorMode:u}}),u)t.html=Rr(t.html,u);if(g.htmlAttrs)t.html=Ar(t.html,g.htmlAttrs);if(!/<body[^>]*\bdata-stx=/.test(t.html)){let p=t.html.match(/<(?!body\b)[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?\s(data-stx="[^"]+")[^>]*>/);if(p&&p[1]){let W=p[1];t.html=t.html.replace(" "+W,""),t.html=t.html.replace(/<body([^>]*)>/,`<body$1 ${W}>`)}}if(t.html=t.html.replace(/<style data-css="generated">[\s\S]*?<\/style>\s*/g,""),t.html=await b(t.html),O){let p=await Nn(t,{params:{},request:new Request(`http://stx.build${s.pattern}`),method:"GET",__stx_strict_hydration:!0});if(p.redirect||p.cookies?.length||p.boundaries?.length||p.headers&&Object.keys(p.headers).length)throw Error(`Prerendered route ${s.pattern} cannot set response headers/cookies, redirect or stream`);t.html=p.html,t.status=p.status??t.status,t.hasServerScripts=!1,t.serverScriptContent=[],t.placeholders={}}t.fragment=Te(t.html,D,!0);let L=s.pattern==="/"?"index":s.pattern.slice(1).replace(/\//g,"-").replace(/[[\]]/g,"_"),z=c.join("server","pages",`${L}.compiled.json`),I=c.join("server","fragments",`${L}.html`);await Bun.write(c.join(r,z),JSON.stringify(t,null,2)),await Bun.write(c.join(r,I),t.fragment),H.push({pattern:s.pattern,compiledPath:z,fragmentPath:I,isDynamic:t.hasServerScripts,hasParams:s.pattern.includes(":")||s.pattern.includes("["),prerendered:O}),console.log(`[stx build] \u2713 ${s.pattern}`)}catch(t){if(Object.keys(f).length)throw t;console.error(`[stx build] \u2717 ${s.pattern}:`,t instanceof Error?t.message:t)}}let k=c.resolve(o,d);if(m.existsSync(k)){let{copied:s,bytes:f}=Z(k,c.join(r,"public"));if(s>0)console.log(`[stx build] Copied ${s} public asset${s===1?"":"s"} (${(f/1024).toFixed(1)}KB) from ${d}/`)}let E=er(o);if(E){let{copied:s,bytes:f}=Z(E,c.join(r,"public",Qn));if(s>0)console.log(`[stx build] Copied ${s} asset${s===1?"":"s"} (${(f/1024).toFixed(1)}KB) from ${Qt}/`)}let N={runtime:v.filename,router:x.filename},C=da(H,N,r);if(C.routeRules=A,C.routerContainer=D,y)C.apiRoutes=await Io(o,r,w);if(e.runtimeConfig)await Bun.write(c.join(r,"server/runtime-config.json"),JSON.stringify(e.runtimeConfig)),await Si(o,e.runtimeConfig);if(e._layerGraph)await Bun.write(c.join(r,"server/layers.json"),JSON.stringify(_c(e._layerGraph),null,2));pa(C,r);let K=Date.now()-l;return console.log(`
2
+ import{nt}from"./chunk-29f6vmyz.js";import{yt,Un}from"./chunk-w0a6yz73.js";import{Rr,Ar,Pr,Or,Ce}from"./chunk-txd2js5v.js";import{De,hn,el,tl}from"./chunk-7kzxmm80.js";import{M}from"./chunk-vfj9wp11.js";import{Si}from"./chunk-2b25kjyx.js";import{b}from"./chunk-9wsrkcyw.js";import{i}from"./chunk-pj904eyr.js";import{F,a}from"./chunk-d85fvcf5.js";import{_c}from"./chunk-amg6kr1p.js";import{On,qe,Te,da,pa,Nn}from"./chunk-zwgxnjmx.js";import{an,Io}from"./chunk-cyd6s7tj.js";import{Mn}from"./chunk-fvgk1w9s.js";import{Qt,Qn,er}from"./chunk-s3j5vxy9.js";import{G}from"./chunk-944tcqgg.js";import m from"fs";import c from"path";import{createHash as Q}from"crypto";function J(n){return Q("sha256").update(n).digest("hex").slice(0,8)}function U(n=!1){let l=n?Un():yt(),o=J(l);return{content:l,filename:`runtime.${o}.js`,hash:o}}function V(){let n=nt(),l=J(n);return{content:n,filename:`router.${l}.js`,hash:l}}import q from"path";import{createHash as ee}from"crypto";function te(n={}){let l=new Set;return{context:new Proxy(n,{get(r,e){if(e in r)return r[e];if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return},has(r,e){if(e in r)return!0;if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return!1}}),accessedKeys:l}}async function X(n,l,o={}){let r=q.resolve(n),e=await Bun.file(r).text(),S=ee("sha256").update(e).digest("hex").slice(0,16);el();let _={};try{_=await a(o.configDir)}catch{}let h=[],d=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,g;while((g=d.exec(e))!==null){let R=g[1];if(/\bserver\b/.test(R))h.push(g[2])}let u=new Set(h.flatMap((R)=>De(R))),{context:D}=te({__filename:r,__dirname:q.dirname(r),__stx_serverDeclared:u}),A=new Set,T={...F,..._,...o,buildMode:"compile",strict:!1},y=await i(e,D,r,T,A),w=On(y)+qe(y),j=tl();return{route:l,sourceFile:n,html:y,fragment:w,placeholders:j,hasServerScripts:h.length>0,serverScriptContent:h,dependencies:Array.from(A),contentHash:S,status:hn(e),streamTemplates:D.__streamTemplates}}var re=new Set([".DS_Store","Thumbs.db","desktop.ini",".gitkeep",".gitignore"]);function Z(n,l){let o=0,r=0;if(!m.existsSync(n))return{copied:o,bytes:r};m.mkdirSync(l,{recursive:!0});function e(S,_){let h=m.readdirSync(S,{withFileTypes:!0});for(let d of h){if(re.has(d.name))continue;let g=c.join(S,d.name),u=c.join(_,d.name);if(d.isDirectory())m.mkdirSync(u,{recursive:!0}),e(g,u);else if(d.isFile()){if(m.existsSync(u))continue;m.copyFileSync(g,u),o++,r+=m.statSync(u).size}}}return e(n,l),{copied:o,bytes:r}}async function om(n={}){let l=Date.now(),o=c.resolve(n.root||process.cwd()),r=c.resolve(o,n.outputDir||".output");console.log("[stx build] Starting production build...");let e=await a(o),S=c.resolve(o,n.componentsDir??e.componentsDir??"components"),_=c.resolve(o,n.partialsDir??e.partialsDir??"partials"),h=c.resolve(o,n.layoutsDir??e.layoutsDir??"layouts"),d=n.publicDir??e.publicDir??"public",g=Ce(e.app?.head,{known:Or,source:"app.head"}),u=e.app?.colorMode,D=e.router?.container||"main",A=n.routeRules??e.routeRules??{},T=Mn(A),y=n.serverApi??e.serverApi,w=typeof y==="object"?y:{};if(y)an(o,w);if(e.runtimeConfig)M(e.runtimeConfig,{});if(m.existsSync(r))m.rmSync(r,{recursive:!0});let j=[c.join(r,"public","__stx"),c.join(r,"public","assets"),c.join(r,"server","pages"),c.join(r,"server","fragments")];for(let s of j)m.mkdirSync(s,{recursive:!0});console.log("[stx build] Discovering routes...");let R=G(o,{pagesDirs:e._layerPageDirs}),Y=["components","layouts","partials"],P=R.filter((s)=>!Y.some((f)=>s.pattern.startsWith(`/${f}/`)||s.pattern===`/${f}`));console.log(`[stx build] Found ${P.length} page routes (${R.length-P.length} non-page files excluded)`),console.log("[stx build] Generating shared assets...");let v=U(n.debug),x=V();await Bun.write(c.join(r,"public","__stx",v.filename),v.content),await Bun.write(c.join(r,"public","__stx",x.filename),x.content),console.log(`[stx build] Runtime: ${v.filename} (${(v.content.length/1024).toFixed(1)}KB)`),console.log(`[stx build] Router: ${x.filename} (${(x.content.length/1024).toFixed(1)}KB)`),console.log("[stx build] Compiling templates...");let B=[],H=[];for(let s of P){let f=T(s.pattern),O=f.rendering==="prerender";if(O&&(s.pattern.includes(":")||s.pattern.includes("[")))throw Error(`Cannot prerender parameter route ${s.pattern}; use dynamic rendering (explicit path enumeration is not supported here)`);try{let t=await X(s.filePath,s.pattern,{configDir:o,componentsDir:S,partialsDir:_,layoutsDir:h,debug:n.debug});if(B.push(t),t.html=t.html.replace(/runtime\.__STX_HASH__\.js/g,v.filename).replace(/router\.__STX_HASH__\.js/g,x.filename),t.html=Pr(t.html,g,{bodyScripts:[`<script src="/__stx/${x.filename}"></script>`],...u&&{colorMode:u}}),u)t.html=Rr(t.html,u);if(g.htmlAttrs)t.html=Ar(t.html,g.htmlAttrs);if(!/<body[^>]*\bdata-stx=/.test(t.html)){let p=t.html.match(/<(?!body\b)[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?\s(data-stx="[^"]+")[^>]*>/);if(p&&p[1]){let W=p[1];t.html=t.html.replace(" "+W,""),t.html=t.html.replace(/<body([^>]*)>/,`<body$1 ${W}>`)}}if(t.html=t.html.replace(/<style data-css="generated">[\s\S]*?<\/style>\s*/g,""),t.html=await b(t.html),O){let p=await Nn(t,{params:{},request:new Request(`http://stx.build${s.pattern}`),method:"GET",__stx_strict_hydration:!0});if(p.redirect||p.cookies?.length||p.boundaries?.length||p.headers&&Object.keys(p.headers).length)throw Error(`Prerendered route ${s.pattern} cannot set response headers/cookies, redirect or stream`);t.html=p.html,t.status=p.status??t.status,t.hasServerScripts=!1,t.serverScriptContent=[],t.placeholders={}}t.fragment=Te(t.html,D,!0);let L=s.pattern==="/"?"index":s.pattern.slice(1).replace(/\//g,"-").replace(/[[\]]/g,"_"),z=c.join("server","pages",`${L}.compiled.json`),I=c.join("server","fragments",`${L}.html`);await Bun.write(c.join(r,z),JSON.stringify(t,null,2)),await Bun.write(c.join(r,I),t.fragment),H.push({pattern:s.pattern,compiledPath:z,fragmentPath:I,isDynamic:t.hasServerScripts,hasParams:s.pattern.includes(":")||s.pattern.includes("["),prerendered:O}),console.log(`[stx build] \u2713 ${s.pattern}`)}catch(t){if(Object.keys(f).length)throw t;console.error(`[stx build] \u2717 ${s.pattern}:`,t instanceof Error?t.message:t)}}let k=c.resolve(o,d);if(m.existsSync(k)){let{copied:s,bytes:f}=Z(k,c.join(r,"public"));if(s>0)console.log(`[stx build] Copied ${s} public asset${s===1?"":"s"} (${(f/1024).toFixed(1)}KB) from ${d}/`)}let E=er(o);if(E){let{copied:s,bytes:f}=Z(E,c.join(r,"public",Qn));if(s>0)console.log(`[stx build] Copied ${s} asset${s===1?"":"s"} (${(f/1024).toFixed(1)}KB) from ${Qt}/`)}let N={runtime:v.filename,router:x.filename},C=da(H,N,r);if(C.routeRules=A,C.routerContainer=D,y)C.apiRoutes=await Io(o,r,w);if(e.runtimeConfig)await Bun.write(c.join(r,"server/runtime-config.json"),JSON.stringify(e.runtimeConfig)),await Si(o,e.runtimeConfig);if(e._layerGraph)await Bun.write(c.join(r,"server/layers.json"),JSON.stringify(_c(e._layerGraph),null,2));pa(C,r);let K=Date.now()-l;return console.log(`
3
3
  [stx build] Done in ${K}ms \u2014 ${B.length} pages compiled`),{pageCount:B.length,assets:N,outputDir:r,duration:K}}
4
4
  export{om};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{A,_i,Xs,u,f,P,ot,d,Gs,t,l,x}from"./chunk-txd2js5v.js";import{xe,Pt,Y,N,Dt,Q,_}from"./chunk-a1fp1nyf.js";import{ar}from"./chunk-8f49t8wb.js";import{oe}from"./chunk-3bjnrmha.js";import{ws}from"./chunk-ya6bp08c.js";var he=1000,me=!1;function be(n,r){let i=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,s;while((s=i.exec(n))!==null){let a=s.index+s[0].length,y=s.index+s[0].indexOf("("),b=x(n,"(",")",y);if(b===-1)continue;let p=n.slice(a,b).trim();if(!p)continue;if(!Object.keys(r).some((g)=>new RegExp(`(?:^|[^\\w$.])${g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(p)))continue;let m;try{let g=P(p,r);if(!g||typeof g!=="object")continue;m=JSON.stringify(g)}catch{continue}e+=n.slice(o,a)+m,o=b,i.lastIndex=b}return o===0?n:e+n.slice(o)}function ye(n,r){let i=/@component\s*\(/g,e=n,o,s=[];while((o=i.exec(e))!==null){let a=o.index,y=a+o[0].length-1,b=1,p=y+1;while(p<e.length&&b>0){if(e[p]==="(")b++;else if(e[p]===")"){if(b--,b===0)break}p++}if(b!==0)continue;let c=e.substring(y+1,p),m=p+1,g=c.match(/^\s*['"]([^'"]+)['"]/);if(!g)continue;let E=g[1],h=c.slice(g[0].length),O=h.match(/^\s*,\s*/);if(!O)continue;let I=h.slice(O[0].length).trim();if(!I)continue;try{let v=P(I,r),B=JSON.stringify(v),S=`@component('${E}', ${B})`;s.push({start:a,end:m,replacement:S})}catch{continue}}for(let a=s.length-1;a>=0;a--){let{start:y,end:b,replacement:p}=s[a];e=e.substring(0,y)+p+e.substring(b)}return e}function ce(n,r,i){let e=n,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),s;while((s=o.exec(e))!==null){let a=s.index,y=a+s[0].length-1,b=1,p=y+1,c=null,m=!1;while(p<e.length&&b>0){let h=e[p];if(m){m=!1,p++;continue}if(h==="\\"&&c){m=!0,p++;continue}if(c){if(h===c)c=null;p++;continue}if(h==='"'||h==="'"||h==="`"){c=h,p++;continue}if(h==="(")b++;else if(h===")"){if(b--,b===0)break}p++}if(b!==0)break;let g=e.substring(y+1,p),E=i(g);e=e.substring(0,a)+E+e.substring(p+1)}return e}function Ee(n,r){let i=n;return i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,s)=>{try{if(N(s,r.__stx_client_signal_names||[]))return e;let a=Object.keys(r),y=Object.values(r);_i(s);let b=!1,c=d(s,a,()=>{b=!0})(...y);if(b)return e;let m=JSON.stringify(c);if(m===void 0){if(!ot(s).some((h)=>!(h in r)))return"";return e}let g=Buffer.from(m,"utf8").toString("base64");return`__stx_${o}="${g}"`}catch(a){return e}}),i}var ne="<!--__STX_BREAK__-->",te="<!--__STX_CONTINUE__-->";function ue(n,r){let i=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let s=i.exec(n);s;s=i.exec(n)){if(!s[1]){let p=s[0].length===3&&s[0]==="{{{"?3:2,c=s[0]==="{!!"?n.indexOf("!!}",i.lastIndex):xe(n,s.index,p);if(c<0)break;i.lastIndex=c+(s[0]==="{!!"?3:p);continue}let a=i.lastIndex,y=!0,b=/^\s*\(/.exec(n.slice(a));if(b){let p=a+b[0].length-1,c=x(n,"(",")",p);if(c<0)break;a=c+1;try{let m=`!!(${n.slice(p+1,c).trim()})`;y=f(m)?Boolean(d(m,Object.keys(r))(...Object.values(r))):Boolean(u(m,r))}catch{y=!1}}if(e+=n.slice(o,s.index),y)return e+(s[1]==="break"?ne:te);o=a,i.lastIndex=a}return e+n.slice(o)}function fe(n){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),i="",e=0;return Dt(n,(o,s,a)=>(i+=le(r(n.slice(e,a))),i+=`\${__stxRenderLoopValue(${a}, (${s}), ${o.length})}`,e=a+o.length,o)),i+le(r(n.slice(e)))}function ge(n,r,i,e){return Q(n,r,i==null?"":String(i),!1,e)}function le(n){let r=n;return r=ce(r,"@break",(i)=>{let e=i.trim();if(!Gs(e))return"";return`\`; if (${e}) { break; } result += \``}),r=ce(r,"@continue",(i)=>{let e=i.trim();if(!Gs(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function _e(n){let r=/@forelse\s*\(/g,i,e=[],o=/@foreach\s*\(/g,s=/@endforeach/g,a;while((a=o.exec(n))!==null)e.push({pos:a.index,delta:1});while((a=s.exec(n))!==null)e.push({pos:a.index,delta:-1});e.sort((c,m)=>c.pos-m.pos);let y=[],b=0;for(let c of e)b+=c.delta,y.push({pos:c.pos,depth:b});function p(c){let m=0,g=y.length-1,E=0;while(m<=g){let h=m+g>>1;if(y[h].pos<=c)E=y[h].depth,m=h+1;else g=h-1}return E}while((i=r.exec(n))!==null){if(p(i.index)>0)continue;let c=i.index,m=i.index+i[0].length-1,g=1,E=m+1,h=-1;while(E<n.length&&g>0){if(n[E]==="(")g++;else if(n[E]===")"){if(g--,g===0){h=E;break}}E++}if(h===-1)continue;let O=n.substring(m+1,h),I=Pt(O);if(!I)continue;let{arrayExpr:v,itemVar:B}=I,S=h+1,w=1,T=S,K=/@forelse\s*\(/g,L=/@endforelse/g,V=-1;while(w>0&&T<n.length){K.lastIndex=T,L.lastIndex=T;let C=K.exec(n),R=L.exec(n);if(!R)break;if(C&&C.index<R.index)w++,T=C.index+C[0].length;else{if(w--,w===0){V=R.index;break}T=R.index+11}}if(V===-1)continue;let k=n.substring(S,V),Z=V+11,z=-1,D=0,M=0;while(M<k.length){let C=k.indexOf("@",M);if(C===-1)break;let R=k.substring(C);if(/^@forelse\s*\(/.test(R))D++,M=C+1;else if(R.startsWith("@endforelse"))D--,M=C+11;else if(D===0&&R.startsWith("@empty")){if(k.length<=C+6||!/[a-z]/i.test(k[C+6])){z=C;break}M=C+1}else M=C+1}if(z===-1)continue;return{start:c,end:Z,arrayExpr:v,itemVar:B,foreachContent:k.substring(0,z),emptyContent:k.substring(z+6)}}return null}function ae(n,r){let i=n;while(!0){let e=_e(i);if(!e)break;let{start:o,end:s,arrayExpr:a,itemVar:y,foreachContent:b,emptyContent:p}=e;try{let c;if(f(a))c=d(a,Object.keys(r))(...Object.values(r));else c=u(a,r);let m;if(!Array.isArray(c)||c.length===0)m=p;else m=`@foreach (${a} as ${y})${b}@endforeach`;i=i.substring(0,o)+m+i.substring(s)}catch(c){let m=c instanceof Error?c.message:String(c),g=l("Forelse",`Error in @forelse(${a} as ${y}): ${m}`,t.EVALUATION_ERROR);i=i.substring(0,o)+g+i.substring(s)}}return i}var de="<!--stx:foreach-not-iterable:",$e=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function Re(n,r){return`${de}${encodeURIComponent(n)}|${encodeURIComponent(r)}-->`}function Ae(n,r){console.warn(`[stx] @foreach(${n}) in ${r}: ${n} is not iterable server-side, so the loop rendered nothing. `+"Values a server loop reads must come from <script server> or the page context \u2014 "+"a plain <script> runs in the browser.")}function ps(n){if(!n.includes(de))return n;return n.replace($e,(r,i,e)=>(Ae(decodeURIComponent(i),decodeURIComponent(e)),""))}function Df(n,r,i,e,o=!1){let s=re(n,r,i,e,o),a=s.next();while(!a.done)a=s.next();return a.value}async function zo(n,r,i,e,o=!1){let s=re(n,r,i,e,o),a=s.next();while(!a.done)await A(),a=s.next();return a.value}function*re(n,r,i,e,o=!1){let s=n,a=new Set(r.__stx_client_signal_names||[]);for(let c of ar(n))a.add(c);if(a.size)r={...r,__stx_client_signal_names:[...a]};s=ae(s,r);function y(c){let m=/@foreach\s*\(/g,g;while((g=m.exec(c))!==null){let E=g.index,h=g.index+g[0].length-1,O=1,I=h+1,v=-1;while(I<c.length&&O>0){if(c[I]==="(")O++;else if(c[I]===")"){if(O--,O===0){v=I;break}}I++}if(v===-1)continue;let B=c.substring(h+1,v),S=Pt(B);if(!S)continue;let w=E,{arrayExpr:T,itemVar:K}=S,L=v+1,V=1,k=L,Z=/@foreach\s*\(/g,z=/@endforeach/g;while(V>0&&k<c.length){Z.lastIndex=k,z.lastIndex=k;let D=Z.exec(c),M=z.exec(c);if(!M)break;if(D&&D.index<M.index)V++,k=D.index+D[0].length;else{if(V--,V===0){let C=c.substring(L,M.index),R=M.index+11;return{start:w,end:R,arrayExpr:T,itemVar:K,content:C}}k=M.index+11}}}return null}function*b(c,m){let g=c;while(!0){let E=y(g);if(!E)break;let{start:h,end:O,arrayExpr:I,itemVar:v,content:B}=E;try{let S=I.trim(),w;if(f(S))w=d(S,Object.keys(m))(...Object.values(m));else w=u(S,m);let T=!1;if(!Array.isArray(w))if(w instanceof Map)w=Array.from(w),T=!0;else if(w instanceof Set)w=Array.from(w);else if(typeof w==="string")w=Array.from(w);else if(w&&typeof w==="object"&&!(w instanceof Date)&&!(w instanceof RegExp))w=Object.entries(w),T=!0;else{let R=Re(S,i)+l("Foreach",`Error in @foreach: ${S} is not iterable`,t.TYPE_ERROR);g=g.substring(0,h)+R+g.substring(O);continue}let K=e?.loops?.useAltLoopVariable??me,L=v.trim(),V=null,k,Z=!1;if(L.includes("=>")){let R=L.split("=>").map((W)=>W.trim());if(R.length===2&&R[0]&&R[1])V=R[0],k=R[1];else k=L}else if(!L.startsWith("[")&&!L.startsWith("{")&&L.includes(",")){let R=L.split(",").map((W)=>W.trim());if(R.length===2&&R[0]&&R[1])k=R[0],V=R[1],Z=!0;else k=L}else k=L;let z="",D=new Set(Y(`${I} as ${v}`)),M=w,C=m[Xs]??new WeakMap;for(let R=0;R<M.length;R++){if(R%16===0)yield;let W=M[R],se={index:R,iteration:R+1,first:R===0,last:R===M.length-1,count:M.length},j={...m,loop:se,$loop:se,[Xs]:C};if(Array.isArray(m.__stx_client_signal_names))j.__stx_client_signal_names=m.__stx_client_signal_names.filter((H)=>!D.has(H));if(k.startsWith("[")&&k.endsWith("]")){let H=k.slice(1,-1).split(",").map((U)=>U.trim());if(Array.isArray(W))H.forEach((U,X)=>{if(U)j[U]=W[X]});else j[k]=W}else if(k.startsWith("{")&&k.endsWith("}")){let H=k.slice(1,-1).split(",").map((U)=>U.trim()).filter(Boolean);if(W!==null&&typeof W==="object")H.forEach((U)=>{let X=U.indexOf(":"),ee=(X===-1?U:U.slice(0,X)).trim(),ie=X===-1?ee:U.slice(X+1).trim();if(ee&&ie)j[ie]=W[ee]});else j[k]=W}else j[k]=W;if(V)if(!Z&&T&&Array.isArray(W)&&W.length===2)j[V]=W[0],j[k]=W[1];else j[V]=R;let F=ae(B,j);F=yield*re(F,j,i,e,!0),F=oe(F,j,i),F=ue(F,j);let J=F.indexOf(ne),G=F.indexOf(te),q=J<0?G:G<0?J:Math.min(J,G);if(q>=0)F=F.slice(0,q);if(F=_(F,j,i),F=Ee(F,j),F=ye(F,j),F=be(F,j),z+=F,q>=0&&q===J)break}g=g.substring(0,h)+z+g.substring(O)}catch(S){let w=l("Foreach",`Error in @foreach(${I.trim()} as ${v.trim()}): ${S instanceof Error?S.message:String(S)}`,t.EVALUATION_ERROR);g=g.substring(0,h)+w+g.substring(O)}}return g}s=yield*b(s,r),s=we(s,r,i,e);let p=e?.loops?.maxWhileIterations??he;return s=Ie(s,r,p),o?s:ps(s)}function Lf(n){let r=/^(\s*)([A-Za-z_$][\w$]*|\[[^\]]*\]|\{[^}]*\})(\s+(?:of|in)\s)/.exec(n);if(!r||/^(?:const|let|var)$/.test(r[2]))return n;return`${r[1]}let ${n.slice(r[1].length)}`}function pe(n){return Gs(n)}function we(n,r,i,e){let o=n,s=!0;while(s){s=!1;let a=o.match(/@for\s*\(/);if(!a||a.index===void 0)break;let y=a.index,b=y+a[0].length-1,p=x(o,"(",")",b);if(p===-1)break;let c=Lf(o.slice(b+1,p)),m=p+1,g=ws(o.slice(y),"for","endfor");if(g.length===0)break;let E=g[0].content,h=y+g[0].end;if(!pe(c)){let O=l("For",`Unsafe expression in @for: ${c}`,t.UNSAFE_EXPRESSION);o=o.substring(0,y)+O+o.substring(h),s=!0;continue}try{let O=Oe(c),I=/@(?:for|foreach|if|unless)\s*\(/.test(E);if(O.length>0&&I){let K=ke({forExpr:c,content:E,iterVarNames:O,context:r,filePath:i,options:e});o=o.substring(0,y)+K+o.substring(h),s=!0;continue}let v=Object.keys(r),B=Object.values(r),S=fe(E),T=Function(...v,"__stxRenderLoopValue",`
2
+ import{A,_i,Xs,u,f,P,ot,d,Gs,t,l,x}from"./chunk-txd2js5v.js";import{xe,Pt,Y,N,Dt,Q,_}from"./chunk-7kzxmm80.js";import{ar}from"./chunk-91qky0er.js";import{oe}from"./chunk-3bjnrmha.js";import{ws}from"./chunk-ya6bp08c.js";var he=1000,me=!1;function be(n,r){let i=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,s;while((s=i.exec(n))!==null){let a=s.index+s[0].length,y=s.index+s[0].indexOf("("),b=x(n,"(",")",y);if(b===-1)continue;let p=n.slice(a,b).trim();if(!p)continue;if(!Object.keys(r).some((g)=>new RegExp(`(?:^|[^\\w$.])${g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(p)))continue;let m;try{let g=P(p,r);if(!g||typeof g!=="object")continue;m=JSON.stringify(g)}catch{continue}e+=n.slice(o,a)+m,o=b,i.lastIndex=b}return o===0?n:e+n.slice(o)}function ye(n,r){let i=/@component\s*\(/g,e=n,o,s=[];while((o=i.exec(e))!==null){let a=o.index,y=a+o[0].length-1,b=1,p=y+1;while(p<e.length&&b>0){if(e[p]==="(")b++;else if(e[p]===")"){if(b--,b===0)break}p++}if(b!==0)continue;let c=e.substring(y+1,p),m=p+1,g=c.match(/^\s*['"]([^'"]+)['"]/);if(!g)continue;let E=g[1],h=c.slice(g[0].length),O=h.match(/^\s*,\s*/);if(!O)continue;let I=h.slice(O[0].length).trim();if(!I)continue;try{let v=P(I,r),B=JSON.stringify(v),S=`@component('${E}', ${B})`;s.push({start:a,end:m,replacement:S})}catch{continue}}for(let a=s.length-1;a>=0;a--){let{start:y,end:b,replacement:p}=s[a];e=e.substring(0,y)+p+e.substring(b)}return e}function ce(n,r,i){let e=n,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),s;while((s=o.exec(e))!==null){let a=s.index,y=a+s[0].length-1,b=1,p=y+1,c=null,m=!1;while(p<e.length&&b>0){let h=e[p];if(m){m=!1,p++;continue}if(h==="\\"&&c){m=!0,p++;continue}if(c){if(h===c)c=null;p++;continue}if(h==='"'||h==="'"||h==="`"){c=h,p++;continue}if(h==="(")b++;else if(h===")"){if(b--,b===0)break}p++}if(b!==0)break;let g=e.substring(y+1,p),E=i(g);e=e.substring(0,a)+E+e.substring(p+1)}return e}function Ee(n,r){let i=n;return i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,s)=>{try{if(N(s,r.__stx_client_signal_names||[]))return e;let a=Object.keys(r),y=Object.values(r);_i(s);let b=!1,c=d(s,a,()=>{b=!0})(...y);if(b)return e;let m=JSON.stringify(c);if(m===void 0){if(!ot(s).some((h)=>!(h in r)))return"";return e}let g=Buffer.from(m,"utf8").toString("base64");return`__stx_${o}="${g}"`}catch(a){return e}}),i}var ne="<!--__STX_BREAK__-->",te="<!--__STX_CONTINUE__-->";function ue(n,r){let i=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let s=i.exec(n);s;s=i.exec(n)){if(!s[1]){let p=s[0].length===3&&s[0]==="{{{"?3:2,c=s[0]==="{!!"?n.indexOf("!!}",i.lastIndex):xe(n,s.index,p);if(c<0)break;i.lastIndex=c+(s[0]==="{!!"?3:p);continue}let a=i.lastIndex,y=!0,b=/^\s*\(/.exec(n.slice(a));if(b){let p=a+b[0].length-1,c=x(n,"(",")",p);if(c<0)break;a=c+1;try{let m=`!!(${n.slice(p+1,c).trim()})`;y=f(m)?Boolean(d(m,Object.keys(r))(...Object.values(r))):Boolean(u(m,r))}catch{y=!1}}if(e+=n.slice(o,s.index),y)return e+(s[1]==="break"?ne:te);o=a,i.lastIndex=a}return e+n.slice(o)}function fe(n){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),i="",e=0;return Dt(n,(o,s,a)=>(i+=le(r(n.slice(e,a))),i+=`\${__stxRenderLoopValue(${a}, (${s}), ${o.length})}`,e=a+o.length,o)),i+le(r(n.slice(e)))}function ge(n,r,i,e){return Q(n,r,i==null?"":String(i),!1,e)}function le(n){let r=n;return r=ce(r,"@break",(i)=>{let e=i.trim();if(!Gs(e))return"";return`\`; if (${e}) { break; } result += \``}),r=ce(r,"@continue",(i)=>{let e=i.trim();if(!Gs(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function _e(n){let r=/@forelse\s*\(/g,i,e=[],o=/@foreach\s*\(/g,s=/@endforeach/g,a;while((a=o.exec(n))!==null)e.push({pos:a.index,delta:1});while((a=s.exec(n))!==null)e.push({pos:a.index,delta:-1});e.sort((c,m)=>c.pos-m.pos);let y=[],b=0;for(let c of e)b+=c.delta,y.push({pos:c.pos,depth:b});function p(c){let m=0,g=y.length-1,E=0;while(m<=g){let h=m+g>>1;if(y[h].pos<=c)E=y[h].depth,m=h+1;else g=h-1}return E}while((i=r.exec(n))!==null){if(p(i.index)>0)continue;let c=i.index,m=i.index+i[0].length-1,g=1,E=m+1,h=-1;while(E<n.length&&g>0){if(n[E]==="(")g++;else if(n[E]===")"){if(g--,g===0){h=E;break}}E++}if(h===-1)continue;let O=n.substring(m+1,h),I=Pt(O);if(!I)continue;let{arrayExpr:v,itemVar:B}=I,S=h+1,w=1,T=S,K=/@forelse\s*\(/g,L=/@endforelse/g,V=-1;while(w>0&&T<n.length){K.lastIndex=T,L.lastIndex=T;let C=K.exec(n),R=L.exec(n);if(!R)break;if(C&&C.index<R.index)w++,T=C.index+C[0].length;else{if(w--,w===0){V=R.index;break}T=R.index+11}}if(V===-1)continue;let k=n.substring(S,V),Z=V+11,z=-1,D=0,M=0;while(M<k.length){let C=k.indexOf("@",M);if(C===-1)break;let R=k.substring(C);if(/^@forelse\s*\(/.test(R))D++,M=C+1;else if(R.startsWith("@endforelse"))D--,M=C+11;else if(D===0&&R.startsWith("@empty")){if(k.length<=C+6||!/[a-z]/i.test(k[C+6])){z=C;break}M=C+1}else M=C+1}if(z===-1)continue;return{start:c,end:Z,arrayExpr:v,itemVar:B,foreachContent:k.substring(0,z),emptyContent:k.substring(z+6)}}return null}function ae(n,r){let i=n;while(!0){let e=_e(i);if(!e)break;let{start:o,end:s,arrayExpr:a,itemVar:y,foreachContent:b,emptyContent:p}=e;try{let c;if(f(a))c=d(a,Object.keys(r))(...Object.values(r));else c=u(a,r);let m;if(!Array.isArray(c)||c.length===0)m=p;else m=`@foreach (${a} as ${y})${b}@endforeach`;i=i.substring(0,o)+m+i.substring(s)}catch(c){let m=c instanceof Error?c.message:String(c),g=l("Forelse",`Error in @forelse(${a} as ${y}): ${m}`,t.EVALUATION_ERROR);i=i.substring(0,o)+g+i.substring(s)}}return i}var de="<!--stx:foreach-not-iterable:",$e=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function Re(n,r){return`${de}${encodeURIComponent(n)}|${encodeURIComponent(r)}-->`}function Ae(n,r){console.warn(`[stx] @foreach(${n}) in ${r}: ${n} is not iterable server-side, so the loop rendered nothing. `+"Values a server loop reads must come from <script server> or the page context \u2014 "+"a plain <script> runs in the browser.")}function ps(n){if(!n.includes(de))return n;return n.replace($e,(r,i,e)=>(Ae(decodeURIComponent(i),decodeURIComponent(e)),""))}function Df(n,r,i,e,o=!1){let s=re(n,r,i,e,o),a=s.next();while(!a.done)a=s.next();return a.value}async function zo(n,r,i,e,o=!1){let s=re(n,r,i,e,o),a=s.next();while(!a.done)await A(),a=s.next();return a.value}function*re(n,r,i,e,o=!1){let s=n,a=new Set(r.__stx_client_signal_names||[]);for(let c of ar(n))a.add(c);if(a.size)r={...r,__stx_client_signal_names:[...a]};s=ae(s,r);function y(c){let m=/@foreach\s*\(/g,g;while((g=m.exec(c))!==null){let E=g.index,h=g.index+g[0].length-1,O=1,I=h+1,v=-1;while(I<c.length&&O>0){if(c[I]==="(")O++;else if(c[I]===")"){if(O--,O===0){v=I;break}}I++}if(v===-1)continue;let B=c.substring(h+1,v),S=Pt(B);if(!S)continue;let w=E,{arrayExpr:T,itemVar:K}=S,L=v+1,V=1,k=L,Z=/@foreach\s*\(/g,z=/@endforeach/g;while(V>0&&k<c.length){Z.lastIndex=k,z.lastIndex=k;let D=Z.exec(c),M=z.exec(c);if(!M)break;if(D&&D.index<M.index)V++,k=D.index+D[0].length;else{if(V--,V===0){let C=c.substring(L,M.index),R=M.index+11;return{start:w,end:R,arrayExpr:T,itemVar:K,content:C}}k=M.index+11}}}return null}function*b(c,m){let g=c;while(!0){let E=y(g);if(!E)break;let{start:h,end:O,arrayExpr:I,itemVar:v,content:B}=E;try{let S=I.trim(),w;if(f(S))w=d(S,Object.keys(m))(...Object.values(m));else w=u(S,m);let T=!1;if(!Array.isArray(w))if(w instanceof Map)w=Array.from(w),T=!0;else if(w instanceof Set)w=Array.from(w);else if(typeof w==="string")w=Array.from(w);else if(w&&typeof w==="object"&&!(w instanceof Date)&&!(w instanceof RegExp))w=Object.entries(w),T=!0;else{let R=Re(S,i)+l("Foreach",`Error in @foreach: ${S} is not iterable`,t.TYPE_ERROR);g=g.substring(0,h)+R+g.substring(O);continue}let K=e?.loops?.useAltLoopVariable??me,L=v.trim(),V=null,k,Z=!1;if(L.includes("=>")){let R=L.split("=>").map((W)=>W.trim());if(R.length===2&&R[0]&&R[1])V=R[0],k=R[1];else k=L}else if(!L.startsWith("[")&&!L.startsWith("{")&&L.includes(",")){let R=L.split(",").map((W)=>W.trim());if(R.length===2&&R[0]&&R[1])k=R[0],V=R[1],Z=!0;else k=L}else k=L;let z="",D=new Set(Y(`${I} as ${v}`)),M=w,C=m[Xs]??new WeakMap;for(let R=0;R<M.length;R++){if(R%16===0)yield;let W=M[R],se={index:R,iteration:R+1,first:R===0,last:R===M.length-1,count:M.length},j={...m,loop:se,$loop:se,[Xs]:C};if(Array.isArray(m.__stx_client_signal_names))j.__stx_client_signal_names=m.__stx_client_signal_names.filter((H)=>!D.has(H));if(k.startsWith("[")&&k.endsWith("]")){let H=k.slice(1,-1).split(",").map((U)=>U.trim());if(Array.isArray(W))H.forEach((U,X)=>{if(U)j[U]=W[X]});else j[k]=W}else if(k.startsWith("{")&&k.endsWith("}")){let H=k.slice(1,-1).split(",").map((U)=>U.trim()).filter(Boolean);if(W!==null&&typeof W==="object")H.forEach((U)=>{let X=U.indexOf(":"),ee=(X===-1?U:U.slice(0,X)).trim(),ie=X===-1?ee:U.slice(X+1).trim();if(ee&&ie)j[ie]=W[ee]});else j[k]=W}else j[k]=W;if(V)if(!Z&&T&&Array.isArray(W)&&W.length===2)j[V]=W[0],j[k]=W[1];else j[V]=R;let F=ae(B,j);F=yield*re(F,j,i,e,!0),F=oe(F,j,i),F=ue(F,j);let J=F.indexOf(ne),G=F.indexOf(te),q=J<0?G:G<0?J:Math.min(J,G);if(q>=0)F=F.slice(0,q);if(F=_(F,j,i),F=Ee(F,j),F=ye(F,j),F=be(F,j),z+=F,q>=0&&q===J)break}g=g.substring(0,h)+z+g.substring(O)}catch(S){let w=l("Foreach",`Error in @foreach(${I.trim()} as ${v.trim()}): ${S instanceof Error?S.message:String(S)}`,t.EVALUATION_ERROR);g=g.substring(0,h)+w+g.substring(O)}}return g}s=yield*b(s,r),s=we(s,r,i,e);let p=e?.loops?.maxWhileIterations??he;return s=Ie(s,r,p),o?s:ps(s)}function Lf(n){let r=/^(\s*)([A-Za-z_$][\w$]*|\[[^\]]*\]|\{[^}]*\})(\s+(?:of|in)\s)/.exec(n);if(!r||/^(?:const|let|var)$/.test(r[2]))return n;return`${r[1]}let ${n.slice(r[1].length)}`}function pe(n){return Gs(n)}function we(n,r,i,e){let o=n,s=!0;while(s){s=!1;let a=o.match(/@for\s*\(/);if(!a||a.index===void 0)break;let y=a.index,b=y+a[0].length-1,p=x(o,"(",")",b);if(p===-1)break;let c=Lf(o.slice(b+1,p)),m=p+1,g=ws(o.slice(y),"for","endfor");if(g.length===0)break;let E=g[0].content,h=y+g[0].end;if(!pe(c)){let O=l("For",`Unsafe expression in @for: ${c}`,t.UNSAFE_EXPRESSION);o=o.substring(0,y)+O+o.substring(h),s=!0;continue}try{let O=Oe(c),I=/@(?:for|foreach|if|unless)\s*\(/.test(E);if(O.length>0&&I){let K=ke({forExpr:c,content:E,iterVarNames:O,context:r,filePath:i,options:e});o=o.substring(0,y)+K+o.substring(h),s=!0;continue}let v=Object.keys(r),B=Object.values(r),S=fe(E),T=Function(...v,"__stxRenderLoopValue",`
3
3
  let result = '';
4
4
  for (${c}) {
5
5
  result += \`${S}\`;
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Se,It,ui,js,Oc,Nc,Mc,Dc,Bs,pi,Lc,jc,fi,bn}from"./chunk-a1fp1nyf.js";import{k}from"./chunk-4ntm3dtk.js";import{a}from"./chunk-02s0hzwa.js";import{vo}from"./chunk-waz6g84g.js";import{c}from"./chunk-9w3r1ch2.js";import{existsSync as B,readFileSync as K}from"fs";import h from"path";var ge=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),ee=bn.filter((e)=>!ge.has(e)).sort(),te=[...k].sort(),he=[...new Set([...ee,...te])].sort(),be=new Set(ee),xe=new Set(te),ye=new Set(he),Y=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function ke(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ne(e,t){let s=[];for(let f of t){if(f.offset===void 0)continue;let i=f.kind==="server"?be:xe;Y.lastIndex=0;for(let p of f.code.matchAll(Y)){let g=p.index+p[0].indexOf("{")+1;for(let d of p[1].matchAll(/[^,]+/g)){let y=d[0];if(/^\s*type\s/.test(y))continue;let b=/^\s*([A-Za-z_$][\w$]*)/.exec(y);if(!b)continue;let r=b[1];if(!ye.has(r)||i.has(r))continue;let o=f.offset+g+d.index+b[0].length-r.length,u=e.slice(0,o),S=u.split(`
2
+ import{Se,It,ui,js,Oc,Nc,Mc,Dc,Bs,pi,Lc,jc,fi,bn}from"./chunk-7kzxmm80.js";import{k}from"./chunk-4ntm3dtk.js";import{a}from"./chunk-d85fvcf5.js";import{vo}from"./chunk-8tktmm5d.js";import{c}from"./chunk-9w3r1ch2.js";import{existsSync as B,readFileSync as K}from"fs";import h from"path";var ge=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),ee=bn.filter((e)=>!ge.has(e)).sort(),te=[...k].sort(),he=[...new Set([...ee,...te])].sort(),be=new Set(ee),xe=new Set(te),ye=new Set(he),Y=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function ke(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ne(e,t){let s=[];for(let f of t){if(f.offset===void 0)continue;let i=f.kind==="server"?be:xe;Y.lastIndex=0;for(let p of f.code.matchAll(Y)){let g=p.index+p[0].indexOf("{")+1;for(let d of p[1].matchAll(/[^,]+/g)){let y=d[0];if(/^\s*type\s/.test(y))continue;let b=/^\s*([A-Za-z_$][\w$]*)/.exec(y);if(!b)continue;let r=b[1];if(!ye.has(r)||i.has(r))continue;let o=f.offset+g+d.index+b[0].length-r.length,u=e.slice(0,o),S=u.split(`
3
3
  `).length;s.push({line:S,column:o-(u.lastIndexOf(`
4
4
  `)+1)+1,offset:o,length:r.length,name:r,kind:f.kind,message:ke(r,f.kind)})}}}return s}import E from"path";var we="@stacksjs/stx-typescript-plugin";function $e(e,t){let s=E.resolve(e);for(;;){let f=E.join(s,"tsconfig.json");if(t(f))return f;let i=E.dirname(s);if(i===s)return;s=i}}function ie(e,t,s){let f=$e(e,s);if(!f)return;let i=new Set,p=(g)=>{if(i.has(g))return;i.add(g);let d=t(g);if(!d)return;let y=d.compilerOptions?.plugins;if(Array.isArray(y)){let r=y.find((u)=>u?.name===we),o=Array.isArray(r?.libs)?r.libs.filter((u)=>typeof u==="string"):[];return r?{configPath:g,libs:o.map((u)=>E.resolve(E.dirname(g),u))}:null}let b=typeof d.extends==="string"?[d.extends]:Array.isArray(d.extends)?d.extends:[];for(let r of[...b].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let o=E.resolve(E.dirname(g),r.endsWith(".json")?r:`${r}.json`),u=p(o);if(u!==void 0)return u}return};return p(f)??void 0}function aa(e,t="",s=""){let f=e.startLine>1?`
5
5
  `.repeat(e.startLine-1):"",i=ui(pi(e)+e.code,t),p=js(i.code),g=e.kind==="client"||e.kind==="plain"?Mc(t,e.code):"",d=(f+p).split(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{pe,hn,Ot,Nt,m,s,ge,p}from"./chunk-a1fp1nyf.js";import{bt,Ae,oc,is,Mo,Do,i}from"./chunk-zr4e0jrh.js";import{ae,ce,Tr,_e,z,_n}from"./chunk-txd2js5v.js";import{kt,fr,$s,Rs,As,_t,Ct,Et,Tt,$t,Rt,tt}from"./chunk-29f6vmyz.js";import{Ss,a,O}from"./chunk-02s0hzwa.js";import{gt,In,Ee,j,la,ho,Kr,qe,ua,Ke,Te}from"./chunk-1pg50kva.js";import{ur,dr}from"./chunk-k23nn7k9.js";import{An}from"./chunk-9cy3fy0k.js";import{e,ln,ir,b}from"./chunk-q4h6mhn1.js";import{Ye}from"./chunk-7v372ds3.js";import{Re}from"./chunk-tx8wk6h7.js";import{G,we,ve}from"./chunk-wpy1ytv9.js";import{c}from"./chunk-9w3r1ch2.js";import{X}from"./chunk-jr0r5pzw.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
2
+ import{pe,hn,Ot,Nt,m,s,ge,p}from"./chunk-7kzxmm80.js";import{bt,Ae,oc,is,Mo,Do,i}from"./chunk-pj904eyr.js";import{ae,ce,Tr,_e,z,_n}from"./chunk-txd2js5v.js";import{kt,fr,$s,Rs,As,_t,Ct,Et,Tt,$t,Rt,tt}from"./chunk-29f6vmyz.js";import{Ss,a,O}from"./chunk-d85fvcf5.js";import{gt,In,Ee,j,la,ho,Kr,qe,ua,Ke,Te}from"./chunk-zwgxnjmx.js";import{ur,dr}from"./chunk-eydfzmdj.js";import{An}from"./chunk-dq9mrthz.js";import{e,ln,ir,b}from"./chunk-9wsrkcyw.js";import{Ye}from"./chunk-d9m9azzk.js";import{Re}from"./chunk-tx8wk6h7.js";import{G,we,ve}from"./chunk-944tcqgg.js";import{c}from"./chunk-9w3r1ch2.js";import{X}from"./chunk-jr0r5pzw.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
3
3
  `),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
4
4
  `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:y}}function Wn(t,n){let r=[],d=Xt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Xt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
5
5
  `).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Ji(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import ke from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
@@ -887,7 +887,7 @@ else {
887
887
  };
888
888
  })();
889
889
  </script>
890
- `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Ss(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await ur(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let g=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Tr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!g)throw new Tr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ae.time("script-extraction",()=>{let y=g,k=pe(g);if(k)y=k.content.trim();let M=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await _e(()=>m(h,S,u),void 0,(y)=>{let k=new ce(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ae.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-35vsv68x.js"),k=y(v.join(`
890
+ `}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Ss(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await ur(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let g=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Tr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!g)throw new Tr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ae.time("script-extraction",()=>{let y=g,k=pe(g);if(k)y=k.content.trim();let M=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await _e(()=>m(h,S,u),void 0,(y)=>{let k=new ce(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ae.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-h12ekfb7.js"),k=y(v.join(`
891
891
  `),S),M=w.search(/<\/body>/i);if(M!==-1)w=w.slice(0,M)+k+`
892
892
  `+w.slice(M);else w+=`
893
893
  ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await dr(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ce(`Plugin processing failed: ${String(f)}`,u);if(z.log(g,{filePath:u,buildConfig:t.config}),_n.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:r.debug||X()?`<!DOCTYPE html>
@@ -950,7 +950,7 @@ ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await d
950
950
  <h1>Something went wrong</h1>
951
951
  <p>An internal error occurred. Please try again later.</p>
952
952
  </body>
953
- </html>`,loader:"html"}}})}};async function zr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await ln(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=vt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-9fk98kja.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-db1c0c3c.js"),be=L.broadcasting;await V(be);let le=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Ce=me.join(process.cwd(),"channels.ts");if(Be.existsSync(Ce))try{let ne=await Y(Ce);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-7ygadxrq.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Fr({port:T,async fetch(D){return An(D,await(async()=>{let L=new URL(D.url);if([g,me.dirname(f),me.join(process.cwd(),"public")].some((ne)=>E(me.join(ne,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let ne=await y.handleRequest(D);if(ne.status!==404)return ne}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=me.join(g,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=me.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let be=me.dirname(f),le=me.join(be,L.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=me.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let Ce=me.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ce)&&Be.statSync(Ce).isFile()){let ne=Bun.file(Ce),F=me.extname(Ce).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
953
+ </html>`,loader:"html"}}})}};async function zr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await ln(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=vt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-t02y9hrh.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-db1c0c3c.js"),be=L.broadcasting;await V(be);let le=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Ce=me.join(process.cwd(),"channels.ts");if(Be.existsSync(Ce))try{let ne=await Y(Ce);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-8p9bphp5.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Fr({port:T,async fetch(D){return An(D,await(async()=>{let L=new URL(D.url);if([g,me.dirname(f),me.join(process.cwd(),"public")].some((ne)=>E(me.join(ne,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let ne=await y.handleRequest(D);if(ne.status!==404)return ne}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=me.join(g,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=me.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let be=me.dirname(f),le=me.join(be,L.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=me.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let Ce=me.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ce)&&Be.statSync(Ce).isFile()){let ne=Bun.file(Ce),F=me.extname(Ce).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
954
954
  ${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
955
955
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
956
956
  ${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
1437
1437
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1438
1438
  ${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
1439
1439
  ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:$e.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:$e.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import fe from"fs";import te from"path";async function dn(t){try{return hn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Vr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-9fk98kja.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-7ygadxrq.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await la(f,n.stxOptions?.shell),D){if(C=await ho(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-9fk98kja.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-db1c0c3c.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=Rs(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-9fk98kja.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-rsg4zdt3.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=hn(Z),{classifyAllScripts:ue}=await import("./chunk-9fk98kja.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-35vsv68x.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-hhh6v5cw.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=r;try{if(Ge=await We(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Ur({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===Mo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Do(N,is()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-tvw571ab.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=fr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&ua(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?In(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[oc]:is(),...j(),"Cache-Control":gt}})}if(C)B=Kr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-hhh6v5cw.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=fr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=Kr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=Kr(C,ue);if(ue=await b(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1440
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import fe from"fs";import te from"path";async function dn(t){try{return hn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Vr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-t02y9hrh.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-8p9bphp5.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await la(f,n.stxOptions?.shell),D){if(C=await ho(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-t02y9hrh.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-db1c0c3c.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=Rs(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-t02y9hrh.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-6c3wj83w.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=hn(Z),{classifyAllScripts:ue}=await import("./chunk-t02y9hrh.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-h12ekfb7.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-s5g6gtz3.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=r;try{if(Ge=await We(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Ur({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===Mo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Do(N,is()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-tvw571ab.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=fr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&ua(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?In(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[oc]:is(),...j(),"Cache-Control":gt}})}if(C)B=Kr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-s5g6gtz3.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=fr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=Kr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=Kr(C,ue);if(ue=await b(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1441
1441
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1442
1442
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1443
1443
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
1444
  ${e.yellow}Routes:${e.reset}`);let Dt=[...As(M,f)];for(let{route:P}of R)Dt.push(`${P.pattern}`);if(Dt.forEach((P,I)=>{let Q=I===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1445
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-rsg4zdt3.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(D&&W){if(te.resolve(U,W)===D||te.basename(D)===W){let K=await ho(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await ir(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-rsg4zdt3.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1445
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-6c3wj83w.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(D&&W){if(te.resolve(U,W)===D||te.basename(D)===W){let K=await ho(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await ir(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-6c3wj83w.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1446
1446
  `).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function qr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1447
1447
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Wr(t),l=await qr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
1448
1448
  `);u=`<${d}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{kn,M}from"./chunk-vfj9wp11.js";import m from"fs";import e from"path";async function Sn(r,o,i){if(r.__stx_runtime_config)return;let n=kn();if(n||i){r.__stx_runtime_config=n??M(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-tj90sfcs.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=M(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Si(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
2
+ import{kn,M}from"./chunk-vfj9wp11.js";import m from"fs";import e from"path";async function Sn(r,o,i){if(r.__stx_runtime_config)return;let n=kn();if(n||i){r.__stx_runtime_config=n??M(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-yjp3bggk.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=M(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Si(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
3
3
  declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${i(o.public??{})} }
4
4
  `),await Bun.write(e.join(r,".stx/runtime-config-server.d.ts"),`import '@stacksjs/stx/runtime-config-server'
5
5
  declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${i(o.private??{})} }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Oe,C,Z}from"./chunk-a1fp1nyf.js";import{k}from"./chunk-4ntm3dtk.js";import{I,$n}from"./chunk-s6r54dyf.js";import{a}from"./chunk-02s0hzwa.js";import{ye,rn,sn,on}from"./chunk-3fk1cm0n.js";import{vt}from"./chunk-8f49t8wb.js";import{ht,Vn,Jt,le}from"./chunk-33czswpt.js";import{E,Tn}from"./chunk-jr0r5pzw.js";import A from"fs";import b from"path";import x from"process";function B(s,o){for(let e of s.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(e[1])o.add(e[1]);for(let e of s.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let t of(e[1]??"").split(",")){let r=((t.includes(":")?t.split(":").pop():t)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(r))o.add(r)}for(let e of s.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let t of(e[1]??"").split(",")){let n=t.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(n))o.add(n)}}var h=new Map;async function O(s,o=E()){let e;if(s)e=b.resolve(s);else{let l=await a();e=b.resolve(l.root||x.cwd(),l.storesDir||"stores")}let t=`${e}\x00${sn()}\x00${o?"shared":"inline"}`,n=new Bun.Glob("*.ts"),r=[];try{for await(let l of n.scan({cwd:e,absolute:!0})){let c=b.basename(l,".ts");if(["index","types"].includes(c))continue;if(l.includes(".d.ts"))continue;r.push(l)}}catch{return le(h,t,"",{chunks:[]}),null}let i=()=>[...new Set([...r,...r.flatMap((l)=>ye(l))])],f=ht(i()),u=Jt(h,t,f);if(u!==void 0)return u.chunks.length>0?u:null;if(r.length===0)return le(h,t,f,{chunks:[]}),null;let m=[];for(let l of r){let c=await Bun.file(l).text();m.push({file:l,hasUseStore:/useStore\s*\(/.test(c)})}m.sort((l,c)=>{if(l.hasUseStore===c.hasUseStore)return 0;return l.hasUseStore?1:-1});let p=m.map((l)=>l.file),g=[],d=Z({loader:"ts",target:"browser",define:C()});for(let l of p)try{let c=await Bun.file(l).text(),_=b.basename(l,".ts"),y=new Set;B(c,y);let v=[...c.matchAll(/\bdefineStore\s*(?:<[^>()]*>)?\(\s*(['"`])([^'"`$\\]+)\1/g)].map((U)=>U[2]),N=c.match(/\bdefineStore\s*(?:<[^>()]*>)?\(/g)?.length??0;if(rn(c))c=await on(c,l,{projectRoot:x.cwd(),externalizeUserModules:o});c=vt(c),c=I(c),c=$n(c),c=c.replace(/^export\s+(default\s+)?/gm,""),c=d.transformSync(c),g.push({name:_,ids:v.length===N?v:[],declared:y,code:`// Store: ${_}
2
+ import{Oe,C,Z}from"./chunk-7kzxmm80.js";import{k}from"./chunk-4ntm3dtk.js";import{I,$n}from"./chunk-s6r54dyf.js";import{a}from"./chunk-d85fvcf5.js";import{ye,rn,sn,on}from"./chunk-8dr42g11.js";import{vt}from"./chunk-91qky0er.js";import{ht,Vn,Jt,le}from"./chunk-33czswpt.js";import{E,Tn}from"./chunk-jr0r5pzw.js";import A from"fs";import b from"path";import x from"process";function B(s,o){for(let e of s.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(e[1])o.add(e[1]);for(let e of s.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let t of(e[1]??"").split(",")){let r=((t.includes(":")?t.split(":").pop():t)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(r))o.add(r)}for(let e of s.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let t of(e[1]??"").split(",")){let n=t.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(n))o.add(n)}}var h=new Map;async function O(s,o=E()){let e;if(s)e=b.resolve(s);else{let l=await a();e=b.resolve(l.root||x.cwd(),l.storesDir||"stores")}let t=`${e}\x00${sn()}\x00${o?"shared":"inline"}`,n=new Bun.Glob("*.ts"),r=[];try{for await(let l of n.scan({cwd:e,absolute:!0})){let c=b.basename(l,".ts");if(["index","types"].includes(c))continue;if(l.includes(".d.ts"))continue;r.push(l)}}catch{return le(h,t,"",{chunks:[]}),null}let i=()=>[...new Set([...r,...r.flatMap((l)=>ye(l))])],f=ht(i()),u=Jt(h,t,f);if(u!==void 0)return u.chunks.length>0?u:null;if(r.length===0)return le(h,t,f,{chunks:[]}),null;let m=[];for(let l of r){let c=await Bun.file(l).text();m.push({file:l,hasUseStore:/useStore\s*\(/.test(c)})}m.sort((l,c)=>{if(l.hasUseStore===c.hasUseStore)return 0;return l.hasUseStore?1:-1});let p=m.map((l)=>l.file),g=[],d=Z({loader:"ts",target:"browser",define:C()});for(let l of p)try{let c=await Bun.file(l).text(),_=b.basename(l,".ts"),y=new Set;B(c,y);let v=[...c.matchAll(/\bdefineStore\s*(?:<[^>()]*>)?\(\s*(['"`])([^'"`$\\]+)\1/g)].map((U)=>U[2]),N=c.match(/\bdefineStore\s*(?:<[^>()]*>)?\(/g)?.length??0;if(rn(c))c=await on(c,l,{projectRoot:x.cwd(),externalizeUserModules:o});c=vt(c),c=I(c),c=$n(c),c=c.replace(/^export\s+(default\s+)?/gm,""),c=d.transformSync(c),g.push({name:_,ids:v.length===N?v:[],declared:y,code:`// Store: ${_}
3
3
  ${c.trim()}`})}catch(c){console.warn(`[stx] Failed to load store ${l}:`,c)}if(g.length===0)return le(h,t,f,{chunks:[]}),null;f=ht(i());let S={chunks:g};return le(h,t,f,S),S}function R(s){let o=new Set;for(let r of s)for(let i of r.declared)o.add(i);let e=s.map((r)=>r.code).join(`
4
4
 
5
5
  `),n=`;(function(){
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ff,Lh,jh,Bh,Fh,zf,Hf,zh,Hh,Jo,Vh,ur,dr,vs}from"./chunk-k23nn7k9.js";import{rt}from"./chunk-car6nhfe.js";import"./chunk-a1fp1nyf.js";import"./chunk-6eqjf0r6.js";import"./chunk-vfj9wp11.js";import"./chunk-txd2js5v.js";import"./chunk-s6r54dyf.js";import"./chunk-4ntm3dtk.js";export{Fh as __setSignalsGeneratorsForTest,rt as cacheEngineFingerprint,dr as cacheTemplate,ur as checkCache,Vh as clearDevCaches,Hf as getCachedRouterScript,zf as getCachedSignalsRuntime,zh as getServeClientAsset,Jo as getServeModuleBundle,vs as hashFilePath,jh as invalidateFileCache,Bh as invalidateFileCacheByDir,Lh as readFileCached,Hh as registerServeModuleBundle,Ff as templateCache};
2
+ import{Ff,Lh,jh,Bh,Fh,zf,Hf,zh,Hh,Jo,Vh,ur,dr,vs}from"./chunk-eydfzmdj.js";import{rt}from"./chunk-car6nhfe.js";import"./chunk-7kzxmm80.js";import"./chunk-2b25kjyx.js";import"./chunk-vfj9wp11.js";import"./chunk-txd2js5v.js";import"./chunk-s6r54dyf.js";import"./chunk-4ntm3dtk.js";export{Fh as __setSignalsGeneratorsForTest,rt as cacheEngineFingerprint,dr as cacheTemplate,ur as checkCache,Vh as clearDevCaches,Hf as getCachedRouterScript,zf as getCachedSignalsRuntime,zh as getServeClientAsset,Jo as getServeModuleBundle,vs as hashFilePath,jh as invalidateFileCache,Bh as invalidateFileCacheByDir,Lh as readFileCached,Hh as registerServeModuleBundle,Ff as templateCache};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ml,hl}from"./chunk-4ntm3dtk.js";import{f,P,ot,d}from"./chunk-txd2js5v.js";import{U,br,Ns,Ms,ai,ci,Ds,vr,fn,Me,fe,J,Sr,ie,Y,N,st,kr,di,Er,ze,s,p,W,xn}from"./chunk-a1fp1nyf.js";import{n}from"./chunk-0ygvav3v.js";import{oe}from"./chunk-3bjnrmha.js";import{r}from"./chunk-fwktw49p.js";import{g}from"./chunk-0dve54ne.js";import{createHash as Ct}from"crypto";import Q from"fs";import Z from"path";import{decode as on,generateThumbHash as an}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import je from"fs";function Ce(e,i,t){let o=Buffer.alloc(t),a=je.readSync(e,o,0,t,i);return o.subarray(0,a)}function Le(e){if(e.length<25)return!1;let i=(o,a)=>String.fromCharCode(...e.subarray(o,a));if(i(0,4)!=="RIFF"||i(8,12)!=="WEBP")return!1;let t=i(12,16);if(t==="VP8X")return(e[20]&16)!==0;if(t==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Ue(e){let i;try{i=je.openSync(e,"r");let t=Ce(i,0,33);if(t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255)return"none";if(t.length>=26&&t[0]===137&&t.toString("latin1",1,4)==="PNG"){let o=t[25];if(o===4||o===6)return"possible";let a=8;for(let c=0;c<64;c++){let l=Ce(i,a,8);if(l.length<8)return"unknown";let m=l.toString("latin1",4,8);if(m==="tRNS")return"possible";if(m==="IDAT"||m==="IEND")return"none";a+=12+l.readUInt32BE(0)}return"unknown"}if(t.length>=25&&t.toString("latin1",0,4)==="RIFF"&&t.toString("latin1",8,12)==="WEBP"){if(Le(t))return"possible";let o=t.toString("latin1",12,16);return o==="VP8 "||o==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(i!==void 0)je.closeSync(i)}}import Yt from"fs";import ke from"os";import{join as gt}from"path";import{fileURLToPath as pt}from"url";var Pe=Symbol("stx.image-worker.unavailable");function Qt(e=typeof ke.availableParallelism==="function"?ke.availableParallelism():ke.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function en(){if(Ae<Qt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function tn(){Ae--,ht.shift()?.()}var nn="@stacksjs/stx/builtins/image-warmup-worker";function rn(e=process.cwd()){let i=import.meta.url.endsWith(".ts")?"ts":"js";try{let t=new URL(`./image-warmup-worker.${i}`,import.meta.url);if(t.protocol==="file:"&&Yt.existsSync(pt(t)))return pt(t)}catch{}try{let t=typeof Bun<"u"?Bun.resolveSync(nn,e):void 0;return t&&sn(t)?t:void 0}catch{return}}function sn(e,i=process.env){let t=e.replace(/\\/g,"/");if(t.split("/").some((a)=>/@\d[^/]*@@@\d+$/.test(a)))return!1;return![i.BUN_INSTALL_CACHE_DIR,gt(i.BUN_INSTALL||gt(ke.homedir(),".bun"),"install","cache")].filter((a)=>!!a).map((a)=>`${a.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((a)=>t.startsWith(a))}var mt=!1;function ue(e){if(!mt)mt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return Pe}function Re(e){return e instanceof Error?e.message:String(e)}async function Fe(e,i){let t;try{t=(await import("worker_threads")).Worker}catch(a){return ue(`could not load node:worker_threads: ${Re(a)}`)}if(typeof t!=="function")return ue("node:worker_threads has no Worker in this runtime");let o=rn();if(!o)return ue("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await en();try{return await new Promise((a,c)=>{let l;try{l=new t(o)}catch(y){a(ue(`could not start ${o}: ${Re(y)}`));return}let m=!1,u=!1,x=(y)=>{if(u)return;u=!0,y(),l.terminate()};l.on("message",(y)=>{if(y.type==="ready"){m=!0,l.postMessage({task:e,args:i});return}if(y.type==="result"){x(()=>a(y.value));return}let h=Error(y.error?.message??"image worker failed");if(y.error?.name)h.name=y.error.name;if(y.error?.stack)h.stack=y.error.stack;x(()=>c(h))}),l.on("error",(y)=>{x(()=>m?c(y instanceof Error?y:Error(Re(y)||"image worker crashed")):a(ue(`the worker failed before it was ready: ${Re(y)}`)))}),l.on("exit",(y)=>{x(()=>m?c(Error("image worker exited before it finished")):a(ue(`the worker exited with code ${y} before it was ready`)))})})}finally{tn()}}var cn=new Set([".avif",".jpeg",".jpg",".png",".webp"]),ln=[320,640,960,1280,1920],ye="/_stx/images",un=`stx:${ye}:alpha-1`,dn=`stx:${ye}:opaque-1`,gn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Ie;function pn(e,i){let t=Z.dirname(Bun.resolveSync(e,i));while(t!==Z.dirname(t)){let o=Z.join(t,"package.json");if(Q.existsSync(o)){let a=JSON.parse(Q.readFileSync(o,"utf8"));if(a.name===e)return a.version}t=Z.dirname(t)}return}function bt(){if(Ie!==void 0)return Ie;let e;try{e=Z.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Ie=gn.map((i)=>{let t;try{t=e?pn(i,e):void 0}catch{}return`${i.replace("@stacksjs/","")}@${t??"unknown"}`}).join("+"),Ie}var vt=Symbol.for("stx.image-delivery");function be(){let e=globalThis;return e[vt]??={catalog:new Map,transparent:new Set},e[vt]}var xt=new Set;function mn(e){return`/${e.split(Z.sep).map(encodeURIComponent).join("/")}`}function hn(e){let i=Z.extname(e),t=e.slice(0,-i.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),o=Ct("sha256").update(e).digest("hex").slice(0,8);return`${t||"image"}-${o}`}function wt(e,i=`stx:${ye}`){let t=(o)=>`${ye}/${o.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:i,async stat(o){let a=Z.join(e,o);try{let c=await Q.promises.stat(a);return c.size>0?{bytes:c.size,path:a,url:t(o)}:null}catch{return null}},async write(o,a){let c=Z.join(e,o);await Q.promises.mkdir(Z.dirname(c),{recursive:!0});let l=`${c}.${process.pid}.tmp`;return await Q.promises.writeFile(l,a),await Q.promises.rename(l,c),{bytes:a.byteLength,path:c,url:t(o)}},url:t}}async function Rt(e,i=e){let t=await Q.promises.readdir(i,{withFileTypes:!0});t.sort((a,c)=>a.name.localeCompare(c.name));let o=[];for(let a of t){let c=Z.join(i,a.name);if(a.isDirectory()){o.push(...await Rt(e,c));continue}if(!a.isFile()||!cn.has(Z.extname(a.name).toLowerCase()))continue;o.push({absolutePath:c,relativePath:Z.relative(e,c)})}return o}function $t(e,i){return e.map((t)=>({key:mn(t.relativePath),input:t.absolutePath,name:hn(t.relativePath),...yn(t.absolutePath)?{options:{storage:i}}:{}}))}function yn(e){return Ue(e)==="possible"}function bn(e){for(let i=3;i<e.length;i+=4)if(e[i]!==255)return!0;return!1}async function vn(e){let i=Object.entries(e).filter(([,a])=>a.fallback.format==="png"),t=new Set,o=8;for(let a=0;a<i.length;a+=8)await Promise.all(i.slice(a,a+8).map(async([c,l])=>{let m=l.variants.filter((u)=>u.format==="png").sort((u,x)=>u.width-x.width)[0];try{let u=await on(new Uint8Array(await Q.promises.readFile(m?.path??l.fallback.path)));if(bn(u.data))t.add(c)}catch{t.add(c)}}));return t}function wn(e,i){let t=[];for(let o of i){let a=e[o],c=a?.variants.filter((m)=>m.format==="webp")??[];if(!a||c.length===0)continue;if(!c.some((m)=>{let u;try{return u=Q.openSync(m.path,"r"),!Le(Ce(u,0,32))}catch{return!0}finally{if(u!==void 0)Q.closeSync(u)}}))continue;if(a.variants=a.variants.filter((m)=>m.format!=="webp"),delete a.sources.webp,t.push(o),!xt.has(o))xt.add(o),console.warn(`[stx-images] ${o} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return t}async function $n(e){let i=[],t=8;for(let o=0;o<e.length;o+=8){let a=e.slice(o,o+8),c=await Promise.all(a.map(async(l)=>{try{return await an(l.absolutePath),l}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${l.relativePath}`),null}}));i.push(...c.filter((l)=>l!==null))}return i}function We(e){return Z.join(e,"undecodable.json")}function Sn(e){try{let i=Q.readFileSync(We(e),"utf-8"),t=JSON.parse(i);return t&&typeof t==="object"?t:{}}catch{return{}}}function Cn(e,i){try{Q.mkdirSync(Z.dirname(We(e)),{recursive:!0}),Q.writeFileSync(We(e),JSON.stringify(i))}catch{}}function St(e){try{let i=Q.statSync(e);return{mtimeMs:i.mtimeMs,size:i.size}}catch{return}}function kt(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let i=e.split(/[?#]/,1)[0];if(!i)return;try{return`/${i.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function jo(e){let i=kt(e);return i?be().catalog.get(i):void 0}function Bo(e){let i=kt(e);return i?be().transparent.has(i):!1}function Fo(e){let i=(o)=>e.variants.filter((a)=>a.format===o).reduce((a,c)=>a+c.bytes,0),t=i(e.fallback.format);return["avif","webp"].map((o)=>({format:o,srcset:e.sources[o]||"",bytes:i(o)})).filter((o)=>o.srcset&&o.bytes>0&&o.bytes<t).sort((o,a)=>o.bytes-a.bytes).map(({format:o,srcset:a})=>({format:o,srcset:a}))}function Nh(e){let i=jo(e);if(!i)return;return{src:i.fallback.url,srcset:i.sources[i.fallback.format]||"",sources:Fo(i).map(({format:t,srcset:o})=>({type:`image/${t}`,srcset:o})),width:i.source.width,height:i.source.height,placeholder:Bo(e)?void 0:i.placeholder?.dataUrl}}function us(){let e=be();e.catalog=new Map,e.transparent=new Set}function Rn(e){let i=be();i.catalog=new Map(e.entries),i.transparent=new Set(e.transparent)}async function Mh(e,i,t={}){if(!e||!Q.existsSync(e))return us(),{count:0,fingerprint:""};if(t.offThread){let v=await Fe("delivery",{publicDir:e,outputDir:i});if(v!==Pe)return Rn(v.state),v.result}let o=await Rt(e);if(o.length===0)return us(),{count:0,fingerprint:""};let a=Sn(i),c=o.filter((v)=>{let b=a[v.relativePath];if(!b)return!0;let S=St(v.absolutePath);return!S||S.mtimeMs!==b.mtimeMs||S.size!==b.size});if(c.length===0)return us(),{count:0,fingerprint:""};let l=wt(Z.join(i,"_stx","images"),`${un}:${bt()}`),m={outDir:Z.join(i,"_stx","images"),storage:wt(Z.join(i,"_stx","images"),`${dn}:${bt()}`),baseUrl:ye,widths:ln,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},u=c,x;try{x=await yt({...m,entries:$t(c,l)})}catch(v){if(u=await $n(c),u.length===c.length)throw v;let b=new Set(u.map((k)=>k.relativePath)),S=!1;for(let k of c){if(b.has(k.relativePath))continue;let A=St(k.absolutePath);if(!A)continue;a[k.relativePath]=A,S=!0}if(S)Cn(i,a);if(u.length===0)return us(),{count:0,fingerprint:""};x=await yt({...m,entries:$t(u,l)})}let y=await vn(x.entries),h=wn(x.entries,y),C=be();C.catalog=new Map(Object.entries(x.entries)),C.transparent=y;let w=y.size===0&&h.length===0?x.fingerprint:Ct("sha256").update(x.fingerprint).update(JSON.stringify({transparent:[...y].sort(),droppedWebp:h.sort()})).digest("hex");return{count:u.length,fingerprint:w}}class At{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let i of e.aliases)this.builtins.set(i.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,i,t,o){let a=ai(e,o);if(a!==void 0)return a;for(let c of ci(e,i,t,o))if(await s(c))return c;return null}}var de=new At;var re="\x00stx-boolean-attribute";function He(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var kn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function qe(e){let i=e.toLowerCase();return i.startsWith("aria-")||i.startsWith("data-")||kn.has(i)}function se(e,i){let t=[];for(let[o,a]of Object.entries(e.static)){if(i.has(o))continue;let c=e.staticNames?.[o]??o;if(typeof a==="boolean"){if(a)t.push(p(c));continue}if(a===re){t.push(p(c));continue}t.push(`${p(c)}="${xn(c,He(String(a)))}"`)}return t}function ae(e,i){let t=[];for(let[o,a]of Object.entries(e.serverDynamic??{})){if(i.has(o))continue;if(a===null||a===void 0||a===!1)continue;let c=e.serverDynamicNames?.[o]??o;if(a===!0){t.push(p(c));continue}if(typeof a==="object")continue;t.push(`${p(c)}="${xn(c,He(String(a)))}"`)}return t}function An(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var Xe={name:"StxLink",aliases:["stx-link"],render(e,i,t){let o=An(e),a=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),c=typeof e.static.activeClass==="string"?e.static.activeClass:"active",l=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",m=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,u=[];if(o.reactive)u.push(`:href="${n(o.value)}"`);else u.push(`href="${n(vr(o.value,"navigable"))}"`);if(a)u.push(`class="${n(a)}"`);if(u.push("data-stx-link"),u.push(`data-stx-active-class="${n(c)}"`),u.push(`data-stx-exact-active-class="${n(l)}"`),m)u.push("data-stx-prefetch");let x=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(x)u.push(`data-stx-active-match="${n(x)}"`);let y=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return u.push(...se(e,y)),u.push(...ae(e,y)),`<a ${u.join(" ")}>${i}</a>`}};var Pn=new Map;function Ve(e){if(!e)return;let i=e.split("?")[0].split("#")[0];return Pn.get(i)}var In={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ze=[320,640,768,1024,1280,1536,1920];function V(e,i){if(e.serverDynamic[i]!==void 0)return String(e.serverDynamic[i]);let t=e.static[i];if(typeof t==="string")return t;return}function _e(e,i,t=!1){let o=e.serverDynamic[i];if(o!==void 0)return o!==!1&&o!=="false";let a=e.static[i];if(a!==void 0)return a!=="false"&&a!==!1;return t}function Ge(e){if(e.includes("(")||e.includes(","))return e;let i=e.trim().split(/\s+/),t=[];for(let o of i)if(o.includes(":")){let[a,c]=o.split(":"),l=In[a];if(l)t.push(`(max-width: ${l}px) ${c}`);else{let m=Number.parseInt(a);if(!Number.isNaN(m))t.push(`(max-width: ${m}px) ${c}`)}}else t.push(o);return t.join(", ")}function Ke(e,i,t,o){return i.map((a)=>`${ve(e,a,void 0,t,o)} ${a}w`).join(", ")}function _n(e,i,t,o,a){return i.map((c)=>{let l=t?t*c:void 0;return`${ve(e,l,void 0,o,a)} ${c}x`}).join(", ")}function ve(e,i,t,o,a){if(!o||o==="local"||o==="static")return e;if(o==="cloudinary"){let c=[];if(i)c.push(`w_${i}`);if(t)c.push(`h_${t}`);if(a)c.push(`f_${a}`);c.push("q_auto");let l=c.join(",");return e.replace("/upload/",`/upload/${l}/`)}if(o==="imgix"){let c=new URLSearchParams;if(i)c.set("w",String(i));if(t)c.set("h",String(t));if(a)c.set("fm",a);c.set("auto","format");let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}if(o==="bunny"){let c=new URLSearchParams;if(i)c.set("width",String(i));if(t)c.set("height",String(t));if(a)c.set("format",a);let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}return e}function En(e){return`var s=this.style;${e.map((i)=>`s.${i}=''`).join(";")}`}function Nn(e,i,t="#e5e7eb"){let o=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${i}"><rect width="100%" height="100%" fill="${t}"/></svg>`;return`data:image/svg+xml;base64,${btoa(o)}`}var Je={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,i,t){let o=V(e,"src")||"",a=jo(o),c=V(e,"alt")||"",l=V(e,"width")||(a?String(a.source.width):void 0),m=V(e,"height")||(a?String(a.source.height):void 0),u=V(e,"sizes"),x=V(e,"srcset"),y=V(e,"densities"),h=V(e,"format"),C=Bo(o)||Ve(o)?.transparent===!0,w=V(e,"placeholder")||(a&&!C?"thumbhash":void 0),v=V(e,"placeholderColor")||"#e5e7eb",b=V(e,"provider"),S=V(e,"class")||V(e,"className")||"",k=V(e,"style")||"",A=V(e,"objectFit")||V(e,"fit"),R=V(e,"objectPosition")||V(e,"position"),B=V(e,"quality"),G=_e(e,"lazy",!0),M=_e(e,"preload",!1),F=_e(e,"priority",!1),H=V(e,"loading"),E=V(e,"decoding")||"async",D=!!a||_e(e,"picture",!1)||!!h,O=l?Number.parseInt(l):void 0,q=m?Number.parseInt(m):void 0,z=x||"",X="";if(a)z=a.sources[a.fallback.format]||"",X=u?Ge(u):"100vw";else if(!z&&u&&b&&b!=="local"&&b!=="static")z=Ke(o,Ze,b,h),X=Ge(u);else if(!z&&y){let I=y.split(/\s+/).map((_)=>Number.parseFloat(_.replace("x","")));z=_n(o,I,O,b,h)}else if(u)X=Ge(u);let L=[];if(k)L.push(k);if(A)L.push(`object-fit:${A}`);if(R)L.push(`object-position:${R}`);if(O&&q)L.push(`aspect-ratio:${O}/${q}`);let T=[],ce=w==="blur"||w==="color"||w==="thumbhash";if(ce&&!C){let I=a?.placeholder?{dataUrl:a.placeholder.dataUrl,color:v}:Ve(o);if(I&&w==="color")L.push(`background-color:${I.color}`),T.push("backgroundColor");else if(I)L.push(`background-color:${I.color}`),L.push(`background-image:url(${I.dataUrl})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundColor","backgroundImage");else{let _=Nn(O||16,q||9,v);L.push(`background-image:url(${_})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundImage")}}else if(!ce&&w&&w!=="empty"&&w!=="none")L.push(`background-image:url(${n(w)})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundImage");let $e=a?.fallback.url||ve(o,O,q,b,h),K=[];if(K.push(`src="${n(vr($e,"fetched"))}"`),K.push(`alt="${n(c)}"`),l)K.push(`width="${n(l)}"`);if(m)K.push(`height="${n(m)}"`);let le=H||(F||M?"eager":G?"lazy":"");if(le)K.push(`loading="${n(le)}"`);if(F)K.push('fetchpriority="high"');if(K.push(`decoding="${n(E)}"`),S)K.push(`class="${n(S)}"`);if(L.length>0)K.push(`style="${n(L.join(";"))}"`);if(z)K.push(`srcset="${n(vr(z,"fetched"))}"`);if(X)K.push(`sizes="${n(X)}"`);let te=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(T.length>0){let I=typeof e.static.onload==="string"?e.static.onload:"",_=En(T)+(I?`;${I}`:"");K.push(`onload="${n(_)}"`),te.add("onload")}K.push(...se(e,te)),K.push(...ae(e,te));let Te=`<img ${K.join(" ")} />`,j="";if(M){let _=h==="webp"?"image/webp":h==="avif"?"image/avif":"";j=`<link rel="preload" as="image" href="${n($e)}"${_?` type="${_}"`:""}${z?` imagesrcset="${n(z)}"`:""}${X?` imagesizes="${n(X)}"`:""} />
2
+ import{ml,hl}from"./chunk-4ntm3dtk.js";import{f,P,ot,d}from"./chunk-txd2js5v.js";import{U,br,Ns,Ms,ai,ci,Ds,vr,fn,Me,fe,J,Sr,ie,Y,N,st,kr,di,Er,ze,s,p,W,xn}from"./chunk-7kzxmm80.js";import{n}from"./chunk-xg852k9h.js";import{oe}from"./chunk-3bjnrmha.js";import{r}from"./chunk-fwktw49p.js";import{g}from"./chunk-0dve54ne.js";import{createHash as Ct}from"crypto";import Q from"fs";import Z from"path";import{decode as on,generateThumbHash as an}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import je from"fs";function Ce(e,i,t){let o=Buffer.alloc(t),a=je.readSync(e,o,0,t,i);return o.subarray(0,a)}function Le(e){if(e.length<25)return!1;let i=(o,a)=>String.fromCharCode(...e.subarray(o,a));if(i(0,4)!=="RIFF"||i(8,12)!=="WEBP")return!1;let t=i(12,16);if(t==="VP8X")return(e[20]&16)!==0;if(t==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Ue(e){let i;try{i=je.openSync(e,"r");let t=Ce(i,0,33);if(t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255)return"none";if(t.length>=26&&t[0]===137&&t.toString("latin1",1,4)==="PNG"){let o=t[25];if(o===4||o===6)return"possible";let a=8;for(let c=0;c<64;c++){let l=Ce(i,a,8);if(l.length<8)return"unknown";let m=l.toString("latin1",4,8);if(m==="tRNS")return"possible";if(m==="IDAT"||m==="IEND")return"none";a+=12+l.readUInt32BE(0)}return"unknown"}if(t.length>=25&&t.toString("latin1",0,4)==="RIFF"&&t.toString("latin1",8,12)==="WEBP"){if(Le(t))return"possible";let o=t.toString("latin1",12,16);return o==="VP8 "||o==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(i!==void 0)je.closeSync(i)}}import Yt from"fs";import ke from"os";import{join as gt}from"path";import{fileURLToPath as pt}from"url";var Pe=Symbol("stx.image-worker.unavailable");function Qt(e=typeof ke.availableParallelism==="function"?ke.availableParallelism():ke.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function en(){if(Ae<Qt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function tn(){Ae--,ht.shift()?.()}var nn="@stacksjs/stx/builtins/image-warmup-worker";function rn(e=process.cwd()){let i=import.meta.url.endsWith(".ts")?"ts":"js";try{let t=new URL(`./image-warmup-worker.${i}`,import.meta.url);if(t.protocol==="file:"&&Yt.existsSync(pt(t)))return pt(t)}catch{}try{let t=typeof Bun<"u"?Bun.resolveSync(nn,e):void 0;return t&&sn(t)?t:void 0}catch{return}}function sn(e,i=process.env){let t=e.replace(/\\/g,"/");if(t.split("/").some((a)=>/@\d[^/]*@@@\d+$/.test(a)))return!1;return![i.BUN_INSTALL_CACHE_DIR,gt(i.BUN_INSTALL||gt(ke.homedir(),".bun"),"install","cache")].filter((a)=>!!a).map((a)=>`${a.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((a)=>t.startsWith(a))}var mt=!1;function ue(e){if(!mt)mt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return Pe}function Re(e){return e instanceof Error?e.message:String(e)}async function Fe(e,i){let t;try{t=(await import("worker_threads")).Worker}catch(a){return ue(`could not load node:worker_threads: ${Re(a)}`)}if(typeof t!=="function")return ue("node:worker_threads has no Worker in this runtime");let o=rn();if(!o)return ue("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await en();try{return await new Promise((a,c)=>{let l;try{l=new t(o)}catch(y){a(ue(`could not start ${o}: ${Re(y)}`));return}let m=!1,u=!1,x=(y)=>{if(u)return;u=!0,y(),l.terminate()};l.on("message",(y)=>{if(y.type==="ready"){m=!0,l.postMessage({task:e,args:i});return}if(y.type==="result"){x(()=>a(y.value));return}let h=Error(y.error?.message??"image worker failed");if(y.error?.name)h.name=y.error.name;if(y.error?.stack)h.stack=y.error.stack;x(()=>c(h))}),l.on("error",(y)=>{x(()=>m?c(y instanceof Error?y:Error(Re(y)||"image worker crashed")):a(ue(`the worker failed before it was ready: ${Re(y)}`)))}),l.on("exit",(y)=>{x(()=>m?c(Error("image worker exited before it finished")):a(ue(`the worker exited with code ${y} before it was ready`)))})})}finally{tn()}}var cn=new Set([".avif",".jpeg",".jpg",".png",".webp"]),ln=[320,640,960,1280,1920],ye="/_stx/images",un=`stx:${ye}:alpha-1`,dn=`stx:${ye}:opaque-1`,gn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Ie;function pn(e,i){let t=Z.dirname(Bun.resolveSync(e,i));while(t!==Z.dirname(t)){let o=Z.join(t,"package.json");if(Q.existsSync(o)){let a=JSON.parse(Q.readFileSync(o,"utf8"));if(a.name===e)return a.version}t=Z.dirname(t)}return}function bt(){if(Ie!==void 0)return Ie;let e;try{e=Z.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Ie=gn.map((i)=>{let t;try{t=e?pn(i,e):void 0}catch{}return`${i.replace("@stacksjs/","")}@${t??"unknown"}`}).join("+"),Ie}var vt=Symbol.for("stx.image-delivery");function be(){let e=globalThis;return e[vt]??={catalog:new Map,transparent:new Set},e[vt]}var xt=new Set;function mn(e){return`/${e.split(Z.sep).map(encodeURIComponent).join("/")}`}function hn(e){let i=Z.extname(e),t=e.slice(0,-i.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),o=Ct("sha256").update(e).digest("hex").slice(0,8);return`${t||"image"}-${o}`}function wt(e,i=`stx:${ye}`){let t=(o)=>`${ye}/${o.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:i,async stat(o){let a=Z.join(e,o);try{let c=await Q.promises.stat(a);return c.size>0?{bytes:c.size,path:a,url:t(o)}:null}catch{return null}},async write(o,a){let c=Z.join(e,o);await Q.promises.mkdir(Z.dirname(c),{recursive:!0});let l=`${c}.${process.pid}.tmp`;return await Q.promises.writeFile(l,a),await Q.promises.rename(l,c),{bytes:a.byteLength,path:c,url:t(o)}},url:t}}async function Rt(e,i=e){let t=await Q.promises.readdir(i,{withFileTypes:!0});t.sort((a,c)=>a.name.localeCompare(c.name));let o=[];for(let a of t){let c=Z.join(i,a.name);if(a.isDirectory()){o.push(...await Rt(e,c));continue}if(!a.isFile()||!cn.has(Z.extname(a.name).toLowerCase()))continue;o.push({absolutePath:c,relativePath:Z.relative(e,c)})}return o}function $t(e,i){return e.map((t)=>({key:mn(t.relativePath),input:t.absolutePath,name:hn(t.relativePath),...yn(t.absolutePath)?{options:{storage:i}}:{}}))}function yn(e){return Ue(e)==="possible"}function bn(e){for(let i=3;i<e.length;i+=4)if(e[i]!==255)return!0;return!1}async function vn(e){let i=Object.entries(e).filter(([,a])=>a.fallback.format==="png"),t=new Set,o=8;for(let a=0;a<i.length;a+=8)await Promise.all(i.slice(a,a+8).map(async([c,l])=>{let m=l.variants.filter((u)=>u.format==="png").sort((u,x)=>u.width-x.width)[0];try{let u=await on(new Uint8Array(await Q.promises.readFile(m?.path??l.fallback.path)));if(bn(u.data))t.add(c)}catch{t.add(c)}}));return t}function wn(e,i){let t=[];for(let o of i){let a=e[o],c=a?.variants.filter((m)=>m.format==="webp")??[];if(!a||c.length===0)continue;if(!c.some((m)=>{let u;try{return u=Q.openSync(m.path,"r"),!Le(Ce(u,0,32))}catch{return!0}finally{if(u!==void 0)Q.closeSync(u)}}))continue;if(a.variants=a.variants.filter((m)=>m.format!=="webp"),delete a.sources.webp,t.push(o),!xt.has(o))xt.add(o),console.warn(`[stx-images] ${o} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return t}async function $n(e){let i=[],t=8;for(let o=0;o<e.length;o+=8){let a=e.slice(o,o+8),c=await Promise.all(a.map(async(l)=>{try{return await an(l.absolutePath),l}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${l.relativePath}`),null}}));i.push(...c.filter((l)=>l!==null))}return i}function We(e){return Z.join(e,"undecodable.json")}function Sn(e){try{let i=Q.readFileSync(We(e),"utf-8"),t=JSON.parse(i);return t&&typeof t==="object"?t:{}}catch{return{}}}function Cn(e,i){try{Q.mkdirSync(Z.dirname(We(e)),{recursive:!0}),Q.writeFileSync(We(e),JSON.stringify(i))}catch{}}function St(e){try{let i=Q.statSync(e);return{mtimeMs:i.mtimeMs,size:i.size}}catch{return}}function kt(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let i=e.split(/[?#]/,1)[0];if(!i)return;try{return`/${i.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function jo(e){let i=kt(e);return i?be().catalog.get(i):void 0}function Bo(e){let i=kt(e);return i?be().transparent.has(i):!1}function Fo(e){let i=(o)=>e.variants.filter((a)=>a.format===o).reduce((a,c)=>a+c.bytes,0),t=i(e.fallback.format);return["avif","webp"].map((o)=>({format:o,srcset:e.sources[o]||"",bytes:i(o)})).filter((o)=>o.srcset&&o.bytes>0&&o.bytes<t).sort((o,a)=>o.bytes-a.bytes).map(({format:o,srcset:a})=>({format:o,srcset:a}))}function Nh(e){let i=jo(e);if(!i)return;return{src:i.fallback.url,srcset:i.sources[i.fallback.format]||"",sources:Fo(i).map(({format:t,srcset:o})=>({type:`image/${t}`,srcset:o})),width:i.source.width,height:i.source.height,placeholder:Bo(e)?void 0:i.placeholder?.dataUrl}}function us(){let e=be();e.catalog=new Map,e.transparent=new Set}function Rn(e){let i=be();i.catalog=new Map(e.entries),i.transparent=new Set(e.transparent)}async function Mh(e,i,t={}){if(!e||!Q.existsSync(e))return us(),{count:0,fingerprint:""};if(t.offThread){let v=await Fe("delivery",{publicDir:e,outputDir:i});if(v!==Pe)return Rn(v.state),v.result}let o=await Rt(e);if(o.length===0)return us(),{count:0,fingerprint:""};let a=Sn(i),c=o.filter((v)=>{let b=a[v.relativePath];if(!b)return!0;let S=St(v.absolutePath);return!S||S.mtimeMs!==b.mtimeMs||S.size!==b.size});if(c.length===0)return us(),{count:0,fingerprint:""};let l=wt(Z.join(i,"_stx","images"),`${un}:${bt()}`),m={outDir:Z.join(i,"_stx","images"),storage:wt(Z.join(i,"_stx","images"),`${dn}:${bt()}`),baseUrl:ye,widths:ln,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},u=c,x;try{x=await yt({...m,entries:$t(c,l)})}catch(v){if(u=await $n(c),u.length===c.length)throw v;let b=new Set(u.map((k)=>k.relativePath)),S=!1;for(let k of c){if(b.has(k.relativePath))continue;let A=St(k.absolutePath);if(!A)continue;a[k.relativePath]=A,S=!0}if(S)Cn(i,a);if(u.length===0)return us(),{count:0,fingerprint:""};x=await yt({...m,entries:$t(u,l)})}let y=await vn(x.entries),h=wn(x.entries,y),C=be();C.catalog=new Map(Object.entries(x.entries)),C.transparent=y;let w=y.size===0&&h.length===0?x.fingerprint:Ct("sha256").update(x.fingerprint).update(JSON.stringify({transparent:[...y].sort(),droppedWebp:h.sort()})).digest("hex");return{count:u.length,fingerprint:w}}class At{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let i of e.aliases)this.builtins.set(i.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,i,t,o){let a=ai(e,o);if(a!==void 0)return a;for(let c of ci(e,i,t,o))if(await s(c))return c;return null}}var de=new At;var re="\x00stx-boolean-attribute";function He(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var kn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function qe(e){let i=e.toLowerCase();return i.startsWith("aria-")||i.startsWith("data-")||kn.has(i)}function se(e,i){let t=[];for(let[o,a]of Object.entries(e.static)){if(i.has(o))continue;let c=e.staticNames?.[o]??o;if(typeof a==="boolean"){if(a)t.push(p(c));continue}if(a===re){t.push(p(c));continue}t.push(`${p(c)}="${xn(c,He(String(a)))}"`)}return t}function ae(e,i){let t=[];for(let[o,a]of Object.entries(e.serverDynamic??{})){if(i.has(o))continue;if(a===null||a===void 0||a===!1)continue;let c=e.serverDynamicNames?.[o]??o;if(a===!0){t.push(p(c));continue}if(typeof a==="object")continue;t.push(`${p(c)}="${xn(c,He(String(a)))}"`)}return t}function An(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var Xe={name:"StxLink",aliases:["stx-link"],render(e,i,t){let o=An(e),a=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),c=typeof e.static.activeClass==="string"?e.static.activeClass:"active",l=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",m=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,u=[];if(o.reactive)u.push(`:href="${n(o.value)}"`);else u.push(`href="${n(vr(o.value,"navigable"))}"`);if(a)u.push(`class="${n(a)}"`);if(u.push("data-stx-link"),u.push(`data-stx-active-class="${n(c)}"`),u.push(`data-stx-exact-active-class="${n(l)}"`),m)u.push("data-stx-prefetch");let x=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(x)u.push(`data-stx-active-match="${n(x)}"`);let y=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return u.push(...se(e,y)),u.push(...ae(e,y)),`<a ${u.join(" ")}>${i}</a>`}};var Pn=new Map;function Ve(e){if(!e)return;let i=e.split("?")[0].split("#")[0];return Pn.get(i)}var In={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ze=[320,640,768,1024,1280,1536,1920];function V(e,i){if(e.serverDynamic[i]!==void 0)return String(e.serverDynamic[i]);let t=e.static[i];if(typeof t==="string")return t;return}function _e(e,i,t=!1){let o=e.serverDynamic[i];if(o!==void 0)return o!==!1&&o!=="false";let a=e.static[i];if(a!==void 0)return a!=="false"&&a!==!1;return t}function Ge(e){if(e.includes("(")||e.includes(","))return e;let i=e.trim().split(/\s+/),t=[];for(let o of i)if(o.includes(":")){let[a,c]=o.split(":"),l=In[a];if(l)t.push(`(max-width: ${l}px) ${c}`);else{let m=Number.parseInt(a);if(!Number.isNaN(m))t.push(`(max-width: ${m}px) ${c}`)}}else t.push(o);return t.join(", ")}function Ke(e,i,t,o){return i.map((a)=>`${ve(e,a,void 0,t,o)} ${a}w`).join(", ")}function _n(e,i,t,o,a){return i.map((c)=>{let l=t?t*c:void 0;return`${ve(e,l,void 0,o,a)} ${c}x`}).join(", ")}function ve(e,i,t,o,a){if(!o||o==="local"||o==="static")return e;if(o==="cloudinary"){let c=[];if(i)c.push(`w_${i}`);if(t)c.push(`h_${t}`);if(a)c.push(`f_${a}`);c.push("q_auto");let l=c.join(",");return e.replace("/upload/",`/upload/${l}/`)}if(o==="imgix"){let c=new URLSearchParams;if(i)c.set("w",String(i));if(t)c.set("h",String(t));if(a)c.set("fm",a);c.set("auto","format");let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}if(o==="bunny"){let c=new URLSearchParams;if(i)c.set("width",String(i));if(t)c.set("height",String(t));if(a)c.set("format",a);let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}return e}function En(e){return`var s=this.style;${e.map((i)=>`s.${i}=''`).join(";")}`}function Nn(e,i,t="#e5e7eb"){let o=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${i}"><rect width="100%" height="100%" fill="${t}"/></svg>`;return`data:image/svg+xml;base64,${btoa(o)}`}var Je={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,i,t){let o=V(e,"src")||"",a=jo(o),c=V(e,"alt")||"",l=V(e,"width")||(a?String(a.source.width):void 0),m=V(e,"height")||(a?String(a.source.height):void 0),u=V(e,"sizes"),x=V(e,"srcset"),y=V(e,"densities"),h=V(e,"format"),C=Bo(o)||Ve(o)?.transparent===!0,w=V(e,"placeholder")||(a&&!C?"thumbhash":void 0),v=V(e,"placeholderColor")||"#e5e7eb",b=V(e,"provider"),S=V(e,"class")||V(e,"className")||"",k=V(e,"style")||"",A=V(e,"objectFit")||V(e,"fit"),R=V(e,"objectPosition")||V(e,"position"),B=V(e,"quality"),G=_e(e,"lazy",!0),M=_e(e,"preload",!1),F=_e(e,"priority",!1),H=V(e,"loading"),E=V(e,"decoding")||"async",D=!!a||_e(e,"picture",!1)||!!h,O=l?Number.parseInt(l):void 0,q=m?Number.parseInt(m):void 0,z=x||"",X="";if(a)z=a.sources[a.fallback.format]||"",X=u?Ge(u):"100vw";else if(!z&&u&&b&&b!=="local"&&b!=="static")z=Ke(o,Ze,b,h),X=Ge(u);else if(!z&&y){let I=y.split(/\s+/).map((_)=>Number.parseFloat(_.replace("x","")));z=_n(o,I,O,b,h)}else if(u)X=Ge(u);let L=[];if(k)L.push(k);if(A)L.push(`object-fit:${A}`);if(R)L.push(`object-position:${R}`);if(O&&q)L.push(`aspect-ratio:${O}/${q}`);let T=[],ce=w==="blur"||w==="color"||w==="thumbhash";if(ce&&!C){let I=a?.placeholder?{dataUrl:a.placeholder.dataUrl,color:v}:Ve(o);if(I&&w==="color")L.push(`background-color:${I.color}`),T.push("backgroundColor");else if(I)L.push(`background-color:${I.color}`),L.push(`background-image:url(${I.dataUrl})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundColor","backgroundImage");else{let _=Nn(O||16,q||9,v);L.push(`background-image:url(${_})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundImage")}}else if(!ce&&w&&w!=="empty"&&w!=="none")L.push(`background-image:url(${n(w)})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),T.push("backgroundImage");let $e=a?.fallback.url||ve(o,O,q,b,h),K=[];if(K.push(`src="${n(vr($e,"fetched"))}"`),K.push(`alt="${n(c)}"`),l)K.push(`width="${n(l)}"`);if(m)K.push(`height="${n(m)}"`);let le=H||(F||M?"eager":G?"lazy":"");if(le)K.push(`loading="${n(le)}"`);if(F)K.push('fetchpriority="high"');if(K.push(`decoding="${n(E)}"`),S)K.push(`class="${n(S)}"`);if(L.length>0)K.push(`style="${n(L.join(";"))}"`);if(z)K.push(`srcset="${n(vr(z,"fetched"))}"`);if(X)K.push(`sizes="${n(X)}"`);let te=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(T.length>0){let I=typeof e.static.onload==="string"?e.static.onload:"",_=En(T)+(I?`;${I}`:"");K.push(`onload="${n(_)}"`),te.add("onload")}K.push(...se(e,te)),K.push(...ae(e,te));let Te=`<img ${K.join(" ")} />`,j="";if(M){let _=h==="webp"?"image/webp":h==="avif"?"image/avif":"";j=`<link rel="preload" as="image" href="${n($e)}"${_?` type="${_}"`:""}${z?` imagesrcset="${n(z)}"`:""}${X?` imagesizes="${n(X)}"`:""} />
3
3
  `}if(D){let I=[];if(a)for(let _ of Fo(a))I.push(`<source type="image/${_.format}" srcset="${n(_.srcset)}"${X?` sizes="${n(X)}"`:""} />`);if(!a&&(h==="avif"||h==="auto")){let _=ve(o,O,q,b,"avif"),ee=z?Ke(o,Ze,b,"avif"):`${_}`;I.push(`<source type="image/avif" srcset="${n(ee)}"${X?` sizes="${n(X)}"`:""} />`)}if(!a&&(h==="webp"||h==="auto")){let _=ve(o,O,q,b,"webp"),ee=z?Ke(o,Ze,b,"webp"):`${_}`;I.push(`<source type="image/webp" srcset="${n(ee)}"${X?` sizes="${n(X)}"`:""} />`)}return`${j}<picture>
4
4
  ${I.join(`
5
5
  `)}