@stacksjs/stx 0.2.788 → 0.2.789

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 (86) hide show
  1. package/dist/{chunk-yrqy4vka.js → chunk-05vb0qc8.js} +1 -1
  2. package/dist/{chunk-4dd0yecs.js → chunk-06fej0jb.js} +4 -4
  3. package/dist/{chunk-4vxz57e1.js → chunk-1d8zapw4.js} +1 -1
  4. package/dist/{chunk-7w3p07yp.js → chunk-2cdpkbar.js} +1 -1
  5. package/dist/{chunk-ebxmj4q2.js → chunk-348zcmgq.js} +2 -2
  6. package/dist/{chunk-3772atqp.js → chunk-3654413v.js} +2 -2
  7. package/dist/{chunk-67ezpess.js → chunk-4jqtj07m.js} +1 -1
  8. package/dist/{chunk-zd6cygn3.js → chunk-4n1z8qha.js} +1 -1
  9. package/dist/chunk-4pd6yk12.js +2 -0
  10. package/dist/{chunk-ns1hpm7x.js → chunk-4r9c6b95.js} +2 -2
  11. package/dist/{chunk-qadv0nrt.js → chunk-5kwy36hj.js} +18 -18
  12. package/dist/{chunk-fgz2kbwb.js → chunk-5q9nn7dg.js} +1 -1
  13. package/dist/{chunk-j10mdh4g.js → chunk-5qghq1c9.js} +2 -2
  14. package/dist/{chunk-khndcwxy.js → chunk-67prgz52.js} +1 -1
  15. package/dist/chunk-6btgrn1h.js +2 -0
  16. package/dist/chunk-6pnbee90.js +2 -0
  17. package/dist/{chunk-a1kvc52k.js → chunk-6rzdz82t.js} +1 -1
  18. package/dist/{chunk-9pkx13hy.js → chunk-6tyxze52.js} +1 -1
  19. package/dist/{chunk-t271s8p9.js → chunk-70266pbx.js} +1 -1
  20. package/dist/{chunk-shmm7135.js → chunk-73smt7ft.js} +1 -1
  21. package/dist/chunk-8x3jekrk.js +2 -0
  22. package/dist/chunk-968gy66p.js +2 -0
  23. package/dist/{chunk-05taafth.js → chunk-9rk5xcvc.js} +1 -1
  24. package/dist/{chunk-6vqz4qqy.js → chunk-9rvm6wfm.js} +1 -1
  25. package/dist/{chunk-ee2jz9xp.js → chunk-a8pbhdhr.js} +1 -1
  26. package/dist/{chunk-s14v17b5.js → chunk-adjkcbcy.js} +4 -4
  27. package/dist/chunk-b1d3z51x.js +2 -0
  28. package/dist/{chunk-epg3gkc6.js → chunk-cgjf0zdk.js} +1 -1
  29. package/dist/{chunk-dwrjs05v.js → chunk-ch2f7hf7.js} +1 -1
  30. package/dist/{chunk-9dzgkt5x.js → chunk-dk5jzps7.js} +1 -1
  31. package/dist/{chunk-9h532cqf.js → chunk-f2t4dfk0.js} +3 -3
  32. package/dist/{chunk-y38rxnrr.js → chunk-frthfvrd.js} +1 -1
  33. package/dist/{chunk-9pkazxn1.js → chunk-hp0y7jr3.js} +1 -1
  34. package/dist/{chunk-vrw1qs1j.js → chunk-jxzgph88.js} +1 -1
  35. package/dist/{chunk-kbaay11r.js → chunk-kn83cqxy.js} +1 -1
  36. package/dist/chunk-kvjv3abv.js +2 -0
  37. package/dist/{chunk-nb8czvz1.js → chunk-mm3n41p0.js} +5 -5
  38. package/dist/{chunk-8p65gzw0.js → chunk-n49bv3mg.js} +1 -1
  39. package/dist/{chunk-8qex68bk.js → chunk-neztwp5f.js} +1 -1
  40. package/dist/{chunk-gp5japjb.js → chunk-pr71c7t1.js} +2 -2
  41. package/dist/{chunk-9ppsnerc.js → chunk-q340jjzk.js} +1 -1
  42. package/dist/chunk-q54ptm6h.js +2 -0
  43. package/dist/{chunk-y8wer7e1.js → chunk-qpqg82qv.js} +57 -57
  44. package/dist/{chunk-gwzp463h.js → chunk-qvtx0kzs.js} +1 -1
  45. package/dist/chunk-r4ne3cvw.js +3 -0
  46. package/dist/{chunk-6sgqa52q.js → chunk-r4r91hs9.js} +1 -1
  47. package/dist/{chunk-mymnmr1m.js → chunk-rn23wa1x.js} +1 -1
  48. package/dist/{chunk-2hm4nmt9.js → chunk-s4wysh3z.js} +2 -2
  49. package/dist/{chunk-bwvnstrd.js → chunk-s63n6fc1.js} +1 -1
  50. package/dist/{chunk-kb2xxmxp.js → chunk-se6p0wsk.js} +1 -1
  51. package/dist/chunk-sq7zsdx9.js +2 -0
  52. package/dist/{chunk-wjcph0yf.js → chunk-svvqscdk.js} +1 -1
  53. package/dist/{chunk-2yexd919.js → chunk-tch1wqny.js} +4 -4
  54. package/dist/{chunk-p2r6rbs4.js → chunk-tqc24ep4.js} +1 -1
  55. package/dist/{chunk-h88p9w9x.js → chunk-tzy4xpsx.js} +1 -1
  56. package/dist/{chunk-hexa0j1j.js → chunk-vhyw1zak.js} +1 -1
  57. package/dist/{chunk-z9h2s292.js → chunk-w869yz2r.js} +1 -1
  58. package/dist/{chunk-c7e78z00.js → chunk-whpb8p6x.js} +1 -1
  59. package/dist/{chunk-se44k8bp.js → chunk-wyc31w66.js} +1 -1
  60. package/dist/{chunk-4yhsmwcc.js → chunk-xb2576xg.js} +1 -1
  61. package/dist/{chunk-jf4kesf8.js → chunk-xxd1ywkf.js} +1 -1
  62. package/dist/chunk-yx5qq570.js +2 -0
  63. package/dist/{chunk-yehq3z73.js → chunk-yxgx0c2g.js} +1 -1
  64. package/dist/{chunk-w1xzkkk3.js → chunk-zgf7gpeh.js} +1 -1
  65. package/dist/cli.js +7 -7
  66. package/dist/craft-entry.js +1 -1
  67. package/dist/craft.js +1 -1
  68. package/dist/native/compiler/style-variables.js +7 -0
  69. package/dist/native/runtime/binding-tree.js +14 -9
  70. package/dist/native/runtime/native-host.js +5 -2
  71. package/dist/native/testing.js +7 -0
  72. package/dist/pwa.js +1 -1
  73. package/dist/ssg.js +2 -2
  74. package/dist/utils.js +13 -1
  75. package/package.json +5 -5
  76. package/dist/chunk-5d2dnhsf.js +0 -2
  77. package/dist/chunk-5jqcs1fz.js +0 -2
  78. package/dist/chunk-9cyfq8mn.js +0 -2
  79. package/dist/chunk-dk53ytvr.js +0 -3
  80. package/dist/chunk-fd572s2h.js +0 -2
  81. package/dist/chunk-fpvhmwqj.js +0 -2
  82. package/dist/chunk-gkqx3p8n.js +0 -2
  83. package/dist/chunk-hb7phtn2.js +0 -2
  84. package/dist/chunk-npm22znd.js +0 -2
  85. package/dist/chunk-p45s8mwh.js +0 -2
  86. package/dist/chunk-qbmy60z0.js +0 -2
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  import{ue}from"./chunk-q14d714d.js";import{ze,O}from"./chunk-27rzdq3n.js";import{bc}from"./chunk-605b93pe.js";import{l}from"./chunk-jdj1358b.js";import v from"fs";import m from"path";import{pathToFileURL as I}from"url";var P=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],R=new Set;function on(s,c={}){let o=m.resolve(s,c.dir??"server/api"),i=[],f=new Map;if(!v.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let p=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=p.pop(),u=n.lastIndexOf("."),d=u>=0?n.slice(u+1):"get",g=d.toUpperCase();if(!P.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${P.map((A)=>A.toLowerCase()).join(", ")}`);if(u>=0)n=n.slice(0,u);if(n!=="index")p.push(n);let r=new Set,h=p.map((A,j)=>{let y=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(A);if(y){if(r.has(y[2])||y[1]&&j!==p.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(y[2]),`:${y[2]}${y[1]?"*":""}`}if(!/^[\w-]+$/.test(A))throw Error(`Unsupported API path segment ${A} in ${e}`);return A}),w=`/api${h.length?`/${h.join("/")}`:""}`,S=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(S))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(S)} and ${e}`);f.set(S,e);let x=m.join(o,e);R.add(m.resolve(x)),R.add(v.realpathSync(x)),i.push({pattern:w,method:g,filePath:x})}return i.sort((e,a)=>{let p=e.pattern.split("/"),n=a.pattern.split("/"),u=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(p.length,n.length);d++){let g=u(n[d])-u(p[d]);if(g)return g}return e.pattern.localeCompare(a.pattern)||e.method.localeCompare(a.method)})}async function $o(s,c){let o=l(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of c){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:a}=ue(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${a.map((p)=>`${JSON.stringify(p)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
3
3
  `);if(!await Bun.file(o).exists()||await Bun.file(o).text()!==f)await Bun.write(o,f);return o}async function Ro(s,c,o={}){let i=on(s,o);await $o(s,i);let f=[];for(let t of i){let e=await Bun.build({entrypoints:[t.filePath],target:"bun",format:"esm",minify:!1,splitting:!1});if(!e.success)throw Error(`API build failed for ${t.filePath}: ${e.logs.join(`
4
- `)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(c,n),a),f.push({...t,filePath:n})}return f}function E(s,c){let o=s.map((i)=>({route:i,...ue(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await c(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Ao(s,c){return E(c,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function xh(s,c){if(!c)return async()=>null;let o=c===!0?{}:c,i=on(s,o);return await $o(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=on(s,o);await $o(s,t);let{loadStxConfig:e}=await import("./chunk-wjcph0yf.js"),a=O((await e(s)).runtimeConfig);return await ze(a,()=>E(t,async(p)=>{let n=await Bun.build({entrypoints:[p.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
4
+ `)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(c,n),a),f.push({...t,filePath:n})}return f}function E(s,c){let o=s.map((i)=>({route:i,...ue(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await c(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Ao(s,c){return E(c,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function xh(s,c){if(!c)return async()=>null;let o=c===!0?{}:c,i=on(s,o);return await $o(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=on(s,o);await $o(s,t);let{loadStxConfig:e}=await import("./chunk-svvqscdk.js"),a=O((await e(s)).runtimeConfig);return await ze(a,()=>E(t,async(p)=>{let n=await Bun.build({entrypoints:[p.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
5
5
  `));let u=n.outputs.find((d)=>d.kind==="entry-point");if(!u||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${p.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await u.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function Po(s,c,o){if(bc(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(v.realpathSync(s))))return!0}catch{}if(R.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(c,typeof o==="object"?o.dir??"server/api":"server/api"),t=(a)=>{try{return v.realpathSync(a)}catch{return m.resolve(a)}},e=t(s);return[f,m.resolve(c,"server"),m.resolve(c,".output/server")].some((a)=>{let p=t(a);return e===p||e.startsWith(`${p}${m.sep}`)})}
6
6
  export{on,$o,Ro,Ao,xh,Po};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Sh,nc,kh,rc,Ef,Tf,cn,sr,_h,$f,Rf,Ch,y}from"./chunk-ebxmj4q2.js";import"./chunk-epg3gkc6.js";import"./chunk-y8wer7e1.js";import"./chunk-kb2xxmxp.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{cn as buildCss,$f as extractClassNames,Tf as fingerprintConfig,Rf as generateCss,_h as getCachedCSS,Sh as getCssServeAsset,y as injectCss,nc as loadCssEngine,rc as loadCssEngineConfig,sr as rebuildCss,kh as resetCssCache,Ef as resolveUserCssConfig,Ch as withLinkedModuleBundles};
2
+ import{Sh,nc,kh,rc,Ef,Tf,cn,sr,_h,$f,Rf,Ch,y}from"./chunk-348zcmgq.js";import"./chunk-cgjf0zdk.js";import"./chunk-qpqg82qv.js";import"./chunk-se6p0wsk.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{cn as buildCss,$f as extractClassNames,Tf as fingerprintConfig,Rf as generateCss,_h as getCachedCSS,Sh as getCssServeAsset,y as injectCss,nc as loadCssEngine,rc as loadCssEngineConfig,sr as rebuildCss,kh as resetCssCache,Ef as resolveUserCssConfig,Ch as withLinkedModuleBundles};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{k}from"./chunk-gb65t4n1.js";import{xe,It,ii,ai,Rc,Ac,Pc,Ic,Ds,li,Oc,Nc,Mc,hn}from"./chunk-y8wer7e1.js";import{a}from"./chunk-2hm4nmt9.js";import{yo}from"./chunk-bwvnstrd.js";import{l}from"./chunk-jdj1358b.js";import{existsSync as M,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=hn.filter((e)=>!ge.has(e)).sort(),te=[...k].sort(),me=[...new Set([...ee,...te])].sort(),he=new Set(ee),be=new Set(te),ye=new Set(me),Y=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function Se(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 u of t){if(u.offset===void 0)continue;let i=u.kind==="server"?he:be;Y.lastIndex=0;for(let c of u.code.matchAll(Y)){let g=c.index+c[0].indexOf("{")+1;for(let m of c[1].matchAll(/[^,]+/g)){let x=m[0];if(/^\s*type\s/.test(x))continue;let y=/^\s*([A-Za-z_$][\w$]*)/.exec(x);if(!y)continue;let r=y[1];if(!ye.has(r)||i.has(r))continue;let f=u.offset+g+m.index+y[0].length-r.length,p=e.slice(0,f),w=p.split(`
2
+ import{k}from"./chunk-gb65t4n1.js";import{xe,It,ii,ai,Rc,Ac,Pc,Ic,Ds,li,Oc,Nc,Mc,hn}from"./chunk-qpqg82qv.js";import{a}from"./chunk-s4wysh3z.js";import{yo}from"./chunk-s63n6fc1.js";import{l}from"./chunk-jdj1358b.js";import{existsSync as M,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=hn.filter((e)=>!ge.has(e)).sort(),te=[...k].sort(),me=[...new Set([...ee,...te])].sort(),he=new Set(ee),be=new Set(te),ye=new Set(me),Y=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function Se(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 u of t){if(u.offset===void 0)continue;let i=u.kind==="server"?he:be;Y.lastIndex=0;for(let c of u.code.matchAll(Y)){let g=c.index+c[0].indexOf("{")+1;for(let m of c[1].matchAll(/[^,]+/g)){let x=m[0];if(/^\s*type\s/.test(x))continue;let y=/^\s*([A-Za-z_$][\w$]*)/.exec(x);if(!y)continue;let r=y[1];if(!ye.has(r)||i.has(r))continue;let f=u.offset+g+m.index+y[0].length-r.length,p=e.slice(0,f),w=p.split(`
3
3
  `).length;s.push({line:w,column:f-(p.lastIndexOf(`
4
4
  `)+1)+1,offset:f,length:r.length,name:r,kind:u.kind,message:Se(r,u.kind)})}}}return s}import T from"path";var ke="@stacksjs/stx-typescript-plugin";function we(e,t){let s=T.resolve(e);for(;;){let u=T.join(s,"tsconfig.json");if(t(u))return u;let i=T.dirname(s);if(i===s)return;s=i}}function ie(e,t,s){let u=we(e,s);if(!u)return;let i=new Set,c=(g)=>{if(i.has(g))return;i.add(g);let m=t(g);if(!m)return;let x=m.compilerOptions?.plugins;if(Array.isArray(x)){let r=x.find((p)=>p?.name===ke),f=Array.isArray(r?.libs)?r.libs.filter((p)=>typeof p==="string"):[];return r?{configPath:g,libs:f.map((p)=>T.resolve(T.dirname(g),p))}:null}let y=typeof m.extends==="string"?[m.extends]:Array.isArray(m.extends)?m.extends:[];for(let r of[...y].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let f=T.resolve(T.dirname(g),r.endsWith(".json")?r:`${r}.json`),p=c(f);if(p!==void 0)return p}return};return c(u)??void 0}function Ml(e,t="",s=""){let u=e.startLine>1?`
5
5
  `.repeat(e.startLine-1):"",i=li(e)+ai(ii(e.code)),c=e.kind==="client"||e.kind==="plain"?Pc(t,e.code):"";return Ds(`${u+i}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{m,pi,Vc,Uc,sg,og,ig,ag,cg,zs,lg,je,Y,Be,ug,Cr,dg,Kc,Xc,hi,Fe,r,bn,Gc,h,fe,qh}from"./chunk-y8wer7e1.js";import"./chunk-kb2xxmxp.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Xc as SIGNAL_COMPOSABLE_CALL,fe as clearComponentCache,hi as componentClientSignalNames,pi as convertToCommonJS,h as createDetailedErrorMessage,cg as extractDirectiveNames,Vc as extractScriptFromTemplate,m as extractVariables,r as fileExists,qh as getComponentCacheStats,og as getPositionInfo,Y as getSharedTranspiler,Gc as getSourceLineInfo,ag as hasDirectives,Uc as hasVariables,dg as isHydrateTrigger,lg as isJavaScriptScript,Fe as renderComponentWithSlot,bn as resolveTemplatePath,ug as scopeOnRootElement,zs as scopeSequenceKey,je as shouldTranspileTypeScript,Kc as slotContentHasExpressions,Be as transpileTypeScript,Cr as userComponentFileExists,ig as validateDirective,sg as validateTemplate};
2
+ import{m,pi,Vc,Uc,sg,og,ig,ag,cg,zs,lg,je,Y,Be,ug,Cr,dg,Kc,Xc,hi,Fe,r,bn,Gc,h,fe,qh}from"./chunk-qpqg82qv.js";import"./chunk-se6p0wsk.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Xc as SIGNAL_COMPOSABLE_CALL,fe as clearComponentCache,hi as componentClientSignalNames,pi as convertToCommonJS,h as createDetailedErrorMessage,cg as extractDirectiveNames,Vc as extractScriptFromTemplate,m as extractVariables,r as fileExists,qh as getComponentCacheStats,og as getPositionInfo,Y as getSharedTranspiler,Gc as getSourceLineInfo,ag as hasDirectives,Uc as hasVariables,dg as isHydrateTrigger,lg as isJavaScriptScript,Fe as renderComponentWithSlot,bn as resolveTemplatePath,ug as scopeOnRootElement,zs as scopeSequenceKey,je as shouldTranspileTypeScript,Kc as slotContentHasExpressions,Be as transpileTypeScript,Cr as userComponentFileExists,ig as validateDirective,sg as validateTemplate};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{_l,Cl}from"./chunk-mm3n41p0.js";import"./chunk-1y9ez7nz.js";import"./chunk-6tyxze52.js";import"./chunk-9rvm6wfm.js";import"./chunk-q340jjzk.js";import"./chunk-b4r7d6me.js";import"./chunk-h0c6jtrj.js";import"./chunk-jxzgph88.js";import"./chunk-05vb0qc8.js";import"./chunk-f2t4dfk0.js";import"./chunk-5j619xgb.js";import"./chunk-v8rfeev5.js";import"./chunk-vrbcdds3.js";import"./chunk-qvtx0kzs.js";import"./chunk-0r61tkfe.js";import"./chunk-vkn133cs.js";import"./chunk-2p4yad7w.js";import"./chunk-rrb9m2q2.js";import"./chunk-6v4b0xc1.js";import"./chunk-pa9zfbh6.js";import"./chunk-70266pbx.js";import"./chunk-ch2f7hf7.js";import"./chunk-agtvdtx4.js";import"./chunk-tnn0br4w.js";import"./chunk-gv3bfkdm.js";import"./chunk-tnkxww7b.js";import"./chunk-5q9nn7dg.js";import"./chunk-s63n6fc1.js";import"./chunk-59tbk9qj.js";import"./chunk-5qghq1c9.js";import"./chunk-c0ejyxfj.js";import"./chunk-d18xd9x5.js";import{Qt}from"./chunk-wyc31w66.js";import"./chunk-w869yz2r.js";import"./chunk-frthfvrd.js";import"./chunk-7sh9fa3q.js";import{Re,i}from"./chunk-adjkcbcy.js";import"./chunk-348zcmgq.js";import"./chunk-tch1wqny.js";import"./chunk-2gqhfge6.js";import"./chunk-9rk5xcvc.js";import"./chunk-r4ne3cvw.js";import"./chunk-n49bv3mg.js";import"./chunk-qv85c3qy.js";import"./chunk-3654413v.js";import{we}from"./chunk-06fej0jb.js";import"./chunk-w5hhqjwr.js";import{lr,ur}from"./chunk-cgjf0zdk.js";import{vs,j,a}from"./chunk-s4wysh3z.js";import"./chunk-xb2576xg.js";import"./chunk-h0jnatd4.js";import"./chunk-605b93pe.js";import"./chunk-w9nwb8r3.js";import"./chunk-q14d714d.js";import{m,Le}from"./chunk-qpqg82qv.js";import"./chunk-se6p0wsk.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";import"./chunk-5a92srn2.js";import"./chunk-e3wmnjz8.js";export{vs as buildWebComponents,ur as cacheTemplate,lr as checkCache,Qt as classifyAllScripts,_l as createMiddleware,Cl as createRoute,j as defaultConfig,m as extractVariables,we as injectRouterScript,a as loadStxConfig,Le as processClientScript,i as processDirectives,Re as readMarkdownFile};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-y8wer7e1.js";import{yt,Re,tc,ss,Io,Oo,i}from"./chunk-s14v17b5.js";import{ae,Er,ke,B,Sn}from"./chunk-94gyfwpz.js";import{St,pr,Es,Ts,$s,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-q14d714d.js";import{vs,a,P}from"./chunk-2hm4nmt9.js";import{ft,An,Ce,D,oa,fo,qr,We,ia,qe,Ee}from"./chunk-9h532cqf.js";import{lr,ur}from"./chunk-epg3gkc6.js";import{$n}from"./chunk-9ppsnerc.js";import{e,cn,sr,y}from"./chunk-ebxmj4q2.js";import{Je}from"./chunk-2yexd919.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-4dd0yecs.js";import{l}from"./chunk-jdj1358b.js";import{K}from"./chunk-bmfk3b29.js";async function Nn(t){try{let n=await Bun.file(t).text(),o=Un(n),d=Wn(n,t),s=Vn(n,o),c=qn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:c}}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{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-qpqg82qv.js";import{yt,Re,tc,ss,Io,Oo,i}from"./chunk-adjkcbcy.js";import{ae,Er,ke,B,Sn}from"./chunk-94gyfwpz.js";import{St,pr,Es,Ts,$s,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-q14d714d.js";import{vs,a,P}from"./chunk-s4wysh3z.js";import{ft,An,Ce,D,oa,fo,qr,We,ia,qe,Ee}from"./chunk-f2t4dfk0.js";import{lr,ur}from"./chunk-cgjf0zdk.js";import{$n}from"./chunk-q340jjzk.js";import{e,cn,sr,y}from"./chunk-348zcmgq.js";import{Je}from"./chunk-tch1wqny.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-06fej0jb.js";import{l}from"./chunk-jdj1358b.js";import{K}from"./chunk-bmfk3b29.js";async function Nn(t){try{let n=await Bun.file(t).text(),o=Un(n),d=Wn(n,t),s=Vn(n,o),c=qn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:c}}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
  `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
4
4
  `).length,c={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};c.total=c.conditionals+c.loops+c.includes+c.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,b=Math.min(10,Math.ceil(c.total*0.5+h*0.1+x*0.3+(s>10?s*0.05:0)+w));return{lines:n.length,characters:t.length,directives:c,expressions:h,components:x,layouts:v,scriptLines:s,complexity:b}}function Wn(t,n){let o=[],d=Xt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let s=Xt(t,"foreach","endforeach");if(s>0)o.push({type:"error",category:"syntax",message:`Found ${s} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let c=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(c&&c.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)o.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)o.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)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Vn(t,n){let o=[];if(n.complexity>7)o.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)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function qn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=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 s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Xt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,c=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-c)}async function Ki(t=["**/*.stx"],n){let o=[],d=[];for(let c of t){let u=await Array.fromAsync(new Bun.Glob(c).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let c of d)try{let u=await Nn(c);o.push(u)}catch(u){console.warn(`Failed to analyze ${c}:`,u)}let s=Kn(o);return{results:o,summary:s}}function Kn(t){let n=t.length,o=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,s=t.reduce((h,x)=>h+x.issues.length,0),c={};t.forEach((h)=>{h.issues.forEach((x)=>{c[x.category]=(c[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(s>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(c.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:s,issuesByCategory:c,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function o(d){let s=await Jn(d,{withFileTypes:!0});s.sort((c,u)=>c.name.localeCompare(u.name));for(let c of s){let u=Te.join(d,c.name);if(c.isDirectory()){if(!c.name.startsWith(".")&&c.name!=="node_modules")await o(u)}else if(c.isFile()&&c.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(c.name))n.push(u)}}return await o(t),n}function nr(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(s){throw Error(`${n}: <script component> must contain JSON metadata (${s.message})`)}}function rr(t,n){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let s of d){if(!/\bclient\b/i.test(s[1])||/\bcomponent\b|\bstx:component\b/i.test(s[1]))continue;let c;try{c=new Bun.Transpiler({loader:"ts"}).transformSync(s[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(c)){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<c.length&&x>0;T++){let b=c[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";o[g]=`${w}${g}(${f[2]}) {${c.slice(h,T-1)}}`,u.lastIndex=T}}return o}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,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.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 o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let M=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=M;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-h88p9w9x.js"),k=b(v.join(`
890
+ `}function Ne(t,n,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.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 o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let M=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=M;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-tzy4xpsx.js"),k=b(v.join(`
891
891
  `),S),_=w.search(/<\/body>/i);if(_!==-1)w=w.slice(0,_)+k+`
892
892
  `+w.slice(_);else w+=`
893
893
  ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await ur(u,w,f,o),o.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(B.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:o.debug||K()?`<!DOCTYPE html>
@@ -950,7 +950,7 @@ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await u
950
950
  <h1>Something went wrong</h1>
951
951
  <p>An internal error occurred. Please try again later.</p>
952
952
  </body>
953
- </html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let M={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[M,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let M=n.hmrPort||T+1;c=vt({wsPort:M,verbose:!1}),u=c.start(M)}let w={},b=null,k;try{let{loadStxConfig:M}=await import("./chunk-fd572s2h.js"),I=await M();if(k=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)b=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){w=I.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-d9p7xaj7.js"),xe=I.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:_,isServerApiSource:E}=await import("./chunk-p2r6rbs4.js"),R=await _(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Nr({port:T,async fetch(M){return $n(M,await(async()=>{let I=new URL(M.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,I.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(M);if(ne.status!==404)return ne}catch{}if(w[I.pathname])try{return await w[I.pathname](M)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(M);if(V)return V;if(I.pathname==="/")return(async()=>{let z=await y(h||"");if(s)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let xe=ge.dirname(f),le=ge.join(xe,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Oe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),L="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
953
+ </html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let M={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[M,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let M=n.hmrPort||T+1;c=vt({wsPort:M,verbose:!1}),u=c.start(M)}let w={},b=null,k;try{let{loadStxConfig:M}=await import("./chunk-kvjv3abv.js"),I=await M();if(k=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)b=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){w=I.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-d9p7xaj7.js"),xe=I.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:_,isServerApiSource:E}=await import("./chunk-tqc24ep4.js"),R=await _(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Nr({port:T,async fetch(M){return $n(M,await(async()=>{let I=new URL(M.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,I.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(M);if(ne.status!==404)return ne}catch{}if(w[I.pathname])try{return await w[I.pathname](M)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(M);if(V)return V;if(I.pathname==="/")return(async()=>{let z=await y(h||"");if(s)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let xe=ge.dirname(f),le=ge.join(xe,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Oe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),L="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
954
954
  ${M.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
955
955
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
956
956
  ${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
1437
1437
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1438
1438
  ${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
1439
1439
  ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let _=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${_}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=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"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-fd572s2h.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-p2r6rbs4.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,M=null;if(n.stxOptions?.shell!==!1){if(M=await oa(f,n.stxOptions?.shell),M){if(C=await fo(M,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-fd572s2h.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-d9p7xaj7.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-fd572s2h.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-w1xzkkk3.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-fd572s2h.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-h88p9w9x.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-9dzgkt5x.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-43ynckvh.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...D(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-9dzgkt5x.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
1440
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=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"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-kvjv3abv.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-tqc24ep4.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,M=null;if(n.stxOptions?.shell!==!1){if(M=await oa(f,n.stxOptions?.shell),M){if(C=await fo(M,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-kvjv3abv.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-d9p7xaj7.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-kvjv3abv.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-zgf7gpeh.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-kvjv3abv.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-tzy4xpsx.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-dk5jzps7.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-43ynckvh.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...D(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-dk5jzps7.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
1441
1441
  ${O.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}`),s)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
1444
  ${e.yellow}Routes:${e.reset}`);let Dt=[...$s(_,f)];for(let{route:O}of R)Dt.push(`${O.pattern}`);if(Dt.forEach((O,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${O}`)}),console.log(`
1445
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-w1xzkkk3.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(M&&W){if(te.resolve(U,W)===M||te.basename(M)===W){let G=await fo(M,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-w1xzkkk3.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),s&&c)c.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&c)c.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(c)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],c=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=c.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1445
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-zgf7gpeh.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(M&&W){if(te.resolve(U,W)===M||te.basename(M)===W){let G=await fo(M,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-zgf7gpeh.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),s&&c)c.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&c)c.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(c)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],c=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=c.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(),s.push(h)}if(s.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)s.push({name:v})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Kr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
1447
1447
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,o){let d=at.basename(t,".stx"),s=await Vr(t),c=await Kr(t),u="";if(n&&o)u=`<${o}></${o}>`;else{let f=s.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{xi,Ws,u,f,R,st,d,qs,t,c,w}from"./chunk-94gyfwpz.js";import{ve,Pt,J,I,Dt,Z,_}from"./chunk-y8wer7e1.js";import{ir}from"./chunk-3772atqp.js";import{se}from"./chunk-qv85c3qy.js";import{ys}from"./chunk-w5hhqjwr.js";var de=1000,pe=!1;function he(n,r){let l=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,i;while((i=l.exec(n))!==null){let g=i.index+i[0].length,x=i.index+i[0].indexOf("("),b=w(n,"(",")",x);if(b===-1)continue;let p=n.slice(g,b).trim();if(!p)continue;if(!Object.keys(r).some((a)=>new RegExp(`(?:^|[^\\w$.])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(p)))continue;let m;try{let a=R(p,r);if(!a||typeof a!=="object")continue;m=JSON.stringify(a)}catch{continue}e+=n.slice(o,g)+m,o=b,l.lastIndex=b}return o===0?n:e+n.slice(o)}function me(n,r){let l=/@component\s*\(/g,e=n,o,i=[];while((o=l.exec(e))!==null){let g=o.index,x=g+o[0].length-1,b=1,p=x+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 s=e.substring(x+1,p),m=p+1,a=s.match(/^\s*['"]([^'"]+)['"]/);if(!a)continue;let y=a[1],h=s.slice(a[0].length),O=h.match(/^\s*,\s*/);if(!O)continue;let S=h.slice(O[0].length).trim();if(!S)continue;try{let v=R(S,r),W=JSON.stringify(v),F=`@component('${y}', ${W})`;i.push({start:g,end:m,replacement:F})}catch{continue}}for(let g=i.length-1;g>=0;g--){let{start:x,end:b,replacement:p}=i[g];e=e.substring(0,x)+p+e.substring(b)}return e}function oe(n,r,l){let e=n,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),i;while((i=o.exec(e))!==null){let g=i.index,x=g+i[0].length-1,b=1,p=x+1,s=null,m=!1;while(p<e.length&&b>0){let h=e[p];if(m){m=!1,p++;continue}if(h==="\\"&&s){m=!0,p++;continue}if(s){if(h===s)s=null;p++;continue}if(h==='"'||h==="'"||h==="`"){s=h,p++;continue}if(h==="(")b++;else if(h===")"){if(b--,b===0)break}p++}if(b!==0)break;let a=e.substring(x+1,p),y=l(a);e=e.substring(0,g)+y+e.substring(p+1)}return e}function be(n,r){let l=n;return l=l.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),l=l.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,i)=>{try{if(I(i,r.__stx_client_signal_names||[]))return e;let g=Object.keys(r),x=Object.values(r);xi(i);let b=!1,s=d(i,g,()=>{b=!0})(...x);if(b)return e;let m=JSON.stringify(s);if(m===void 0){if(!st(i).some((h)=>!(h in r)))return"";return e}let a=Buffer.from(m,"utf8").toString("base64");return`__stx_${o}="${a}"`}catch(g){return e}}),l}var ee="<!--__STX_BREAK__-->",ne="<!--__STX_CONTINUE__-->";function le(n,r){let l=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let i=l.exec(n);i;i=l.exec(n)){if(!i[1]){let p=i[0].length===3&&i[0]==="{{{"?3:2,s=i[0]==="{!!"?n.indexOf("!!}",l.lastIndex):ve(n,i.index,p);if(s<0)break;l.lastIndex=s+(i[0]==="{!!"?3:p);continue}let g=l.lastIndex,x=!0,b=/^\s*\(/.exec(n.slice(g));if(b){let p=g+b[0].length-1,s=w(n,"(",")",p);if(s<0)break;g=s+1;try{let m=`!!(${n.slice(p+1,s).trim()})`;x=f(m)?Boolean(d(m,Object.keys(r))(...Object.values(r))):Boolean(u(m,r))}catch{x=!1}}if(e+=n.slice(o,i.index),x)return e+(i[1]==="break"?ee:ne);o=g,l.lastIndex=g}return e+n.slice(o)}function ae(n){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),l="",e=0;return Dt(n,(o,i,g)=>(l+=ie(r(n.slice(e,g))),l+=`\${__stxRenderLoopValue(${g}, (${i}), ${o.length})}`,e=g+o.length,o)),l+ie(r(n.slice(e)))}function ue(n,r,l,e){return Z(n,r,l==null?"":String(l),!1,e)}function ie(n){let r=n;return r=oe(r,"@break",(l)=>{let e=l.trim();if(!qs(e))return"";return`\`; if (${e}) { break; } result += \``}),r=oe(r,"@continue",(l)=>{let e=l.trim();if(!qs(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function xe(n){let r=/@forelse\s*\(/g,l,e=[],o=/@foreach\s*\(/g,i=/@endforeach/g,g;while((g=o.exec(n))!==null)e.push({pos:g.index,delta:1});while((g=i.exec(n))!==null)e.push({pos:g.index,delta:-1});e.sort((s,m)=>s.pos-m.pos);let x=[],b=0;for(let s of e)b+=s.delta,x.push({pos:s.pos,depth:b});function p(s){let m=0,a=x.length-1,y=0;while(m<=a){let h=m+a>>1;if(x[h].pos<=s)y=x[h].depth,m=h+1;else a=h-1}return y}while((l=r.exec(n))!==null){if(p(l.index)>0)continue;let s=l.index,m=l.index+l[0].length-1,a=1,y=m+1,h=-1;while(y<n.length&&a>0){if(n[y]==="(")a++;else if(n[y]===")"){if(a--,a===0){h=y;break}}y++}if(h===-1)continue;let O=n.substring(m+1,h),S=Pt(O);if(!S)continue;let{arrayExpr:v,itemVar:W}=S,F=h+1,A=1,B=F,D=/@forelse\s*\(/g,L=/@endforelse/g,V=-1;while(A>0&&B<n.length){D.lastIndex=B,L.lastIndex=B;let P=D.exec(n),E=L.exec(n);if(!E)break;if(P&&P.index<E.index)A++,B=P.index+P[0].length;else{if(A--,A===0){V=E.index;break}B=E.index+11}}if(V===-1)continue;let k=n.substring(F,V),K=V+11,U=-1,z=0,N=0;while(N<k.length){let P=k.indexOf("@",N);if(P===-1)break;let E=k.substring(P);if(/^@forelse\s*\(/.test(E))z++,N=P+1;else if(E.startsWith("@endforelse"))z--,N=P+11;else if(z===0&&E.startsWith("@empty")){if(k.length<=P+6||!/[a-z]/i.test(k[P+6])){U=P;break}N=P+1}else N=P+1}if(U===-1)continue;return{start:s,end:K,arrayExpr:v,itemVar:W,foreachContent:k.substring(0,U),emptyContent:k.substring(U+6)}}return null}function ce(n,r){let l=n;while(!0){let e=xe(l);if(!e)break;let{start:o,end:i,arrayExpr:g,itemVar:x,foreachContent:b,emptyContent:p}=e;try{let s;if(f(g))s=d(g,Object.keys(r))(...Object.values(r));else s=u(g,r);let m;if(!Array.isArray(s)||s.length===0)m=p;else m=`@foreach (${g} as ${x})${b}@endforeach`;l=l.substring(0,o)+m+l.substring(i)}catch(s){let m=s instanceof Error?s.message:String(s),a=c("Forelse",`Error in @forelse(${g} as ${x}): ${m}`,t.EVALUATION_ERROR);l=l.substring(0,o)+a+l.substring(i)}}return l}var fe="<!--stx:foreach-not-iterable:",ye=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function Ee(n,r){return`${fe}${encodeURIComponent(n)}|${encodeURIComponent(r)}-->`}function _e(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 us(n){if(!n.includes(fe))return n;return n.replace(ye,(r,l,e)=>(_e(decodeURIComponent(l),decodeURIComponent(e)),""))}function or(n,r,l,e,o=!1){let i=n,g=new Set(r.__stx_client_signal_names||[]);for(let s of ir(n))g.add(s);if(g.size)r={...r,__stx_client_signal_names:[...g]};i=ce(i,r);function x(s){let m=/@foreach\s*\(/g,a;while((a=m.exec(s))!==null){let y=a.index,h=a.index+a[0].length-1,O=1,S=h+1,v=-1;while(S<s.length&&O>0){if(s[S]==="(")O++;else if(s[S]===")"){if(O--,O===0){v=S;break}}S++}if(v===-1)continue;let W=s.substring(h+1,v),F=Pt(W);if(!F)continue;let A=y,{arrayExpr:B,itemVar:D}=F,L=v+1,V=1,k=L,K=/@foreach\s*\(/g,U=/@endforeach/g;while(V>0&&k<s.length){K.lastIndex=k,U.lastIndex=k;let z=K.exec(s),N=U.exec(s);if(!N)break;if(z&&z.index<N.index)V++,k=z.index+z[0].length;else{if(V--,V===0){let P=s.substring(L,N.index),E=N.index+11;return{start:A,end:E,arrayExpr:B,itemVar:D,content:P}}k=N.index+11}}}return null}function b(s,m){let a=s;while(!0){let y=x(a);if(!y)break;let{start:h,end:O,arrayExpr:S,itemVar:v,content:W}=y;try{let F=S.trim(),A;if(f(F))A=d(F,Object.keys(m))(...Object.values(m));else A=u(F,m);let B=!1;if(!Array.isArray(A))if(A instanceof Map)A=Array.from(A),B=!0;else if(A instanceof Set)A=Array.from(A);else if(typeof A==="string")A=Array.from(A);else if(A&&typeof A==="object"&&!(A instanceof Date)&&!(A instanceof RegExp))A=Object.entries(A),B=!0;else{let E=Ee(F,l)+c("Foreach",`Error in @foreach: ${F} is not iterable`,t.TYPE_ERROR);a=a.substring(0,h)+E+a.substring(O);continue}let D=e?.loops?.useAltLoopVariable??pe,L=v.trim(),V=null,k,K=!1;if(L.includes("=>")){let E=L.split("=>").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])V=E[0],k=E[1];else k=L}else if(!L.startsWith("[")&&!L.startsWith("{")&&L.includes(",")){let E=L.split(",").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])k=E[0],V=E[1],K=!0;else k=L}else k=L;let U="",z=new Set(J(`${S} as ${v}`)),N=A,P=m[Ws]??new WeakMap;for(let E=0;E<N.length;E++){let j=N[E],te={index:E,iteration:E+1,first:E===0,last:E===N.length-1,count:N.length},M={...m,loop:te,$loop:te,[Ws]:P};if(Array.isArray(m.__stx_client_signal_names))M.__stx_client_signal_names=m.__stx_client_signal_names.filter((H)=>!z.has(H));if(k.startsWith("[")&&k.endsWith("]")){let H=k.slice(1,-1).split(",").map((T)=>T.trim());if(Array.isArray(j))H.forEach((T,X)=>{if(T)M[T]=j[X]});else M[k]=j}else if(k.startsWith("{")&&k.endsWith("}")){let H=k.slice(1,-1).split(",").map((T)=>T.trim()).filter(Boolean);if(j!==null&&typeof j==="object")H.forEach((T)=>{let X=T.indexOf(":"),Q=(X===-1?T:T.slice(0,X)).trim(),re=X===-1?Q:T.slice(X+1).trim();if(Q&&re)M[re]=j[Q]});else M[k]=j}else M[k]=j;if(V)if(!K&&B&&Array.isArray(j)&&j.length===2)M[V]=j[0],M[k]=j[1];else M[V]=E;let C=ce(W,M);C=or(C,M,l,e,!0),C=se(C,M,l),C=le(C,M);let q=C.indexOf(ee),G=C.indexOf(ne),Y=q<0?G:G<0?q:Math.min(q,G);if(Y>=0)C=C.slice(0,Y);if(C=_(C,M,l),C=be(C,M),C=me(C,M),C=he(C,M),U+=C,Y>=0&&Y===q)break}a=a.substring(0,h)+U+a.substring(O)}catch(F){let A=c("Foreach",`Error in @foreach(${S.trim()} as ${v.trim()}): ${F instanceof Error?F.message:String(F)}`,t.EVALUATION_ERROR);a=a.substring(0,h)+A+a.substring(O)}}return a}i=b(i,r),i=$e(i,r,l,e);let p=e?.loops?.maxWhileIterations??de;return i=we(i,r,p),o?i:us(i)}function If(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 ge(n){return qs(n)}function $e(n,r,l,e){let o=n,i=!0;while(i){i=!1;let g=o.match(/@for\s*\(/);if(!g||g.index===void 0)break;let x=g.index,b=x+g[0].length-1,p=w(o,"(",")",b);if(p===-1)break;let s=If(o.slice(b+1,p)),m=p+1,a=ys(o.slice(x),"for","endfor");if(a.length===0)break;let y=a[0].content,h=x+a[0].end;if(!ge(s)){let O=c("For",`Unsafe expression in @for: ${s}`,t.UNSAFE_EXPRESSION);o=o.substring(0,x)+O+o.substring(h),i=!0;continue}try{let O=Ae(s),S=/@(?:for|foreach|if|unless)\s*\(/.test(y);if(O.length>0&&S){let D=Re({forExpr:s,content:y,iterVarNames:O,context:r,filePath:l,options:e});o=o.substring(0,x)+D+o.substring(h),i=!0;continue}let v=Object.keys(r),W=Object.values(r),F=ae(y),B=Function(...v,"__stxRenderLoopValue",`
2
+ import{xi,Ws,u,f,R,st,d,qs,t,c,w}from"./chunk-94gyfwpz.js";import{ve,Pt,J,I,Dt,Z,_}from"./chunk-qpqg82qv.js";import{ir}from"./chunk-3654413v.js";import{se}from"./chunk-qv85c3qy.js";import{ys}from"./chunk-w5hhqjwr.js";var de=1000,pe=!1;function he(n,r){let l=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,i;while((i=l.exec(n))!==null){let g=i.index+i[0].length,x=i.index+i[0].indexOf("("),b=w(n,"(",")",x);if(b===-1)continue;let p=n.slice(g,b).trim();if(!p)continue;if(!Object.keys(r).some((a)=>new RegExp(`(?:^|[^\\w$.])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(p)))continue;let m;try{let a=R(p,r);if(!a||typeof a!=="object")continue;m=JSON.stringify(a)}catch{continue}e+=n.slice(o,g)+m,o=b,l.lastIndex=b}return o===0?n:e+n.slice(o)}function me(n,r){let l=/@component\s*\(/g,e=n,o,i=[];while((o=l.exec(e))!==null){let g=o.index,x=g+o[0].length-1,b=1,p=x+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 s=e.substring(x+1,p),m=p+1,a=s.match(/^\s*['"]([^'"]+)['"]/);if(!a)continue;let y=a[1],h=s.slice(a[0].length),O=h.match(/^\s*,\s*/);if(!O)continue;let S=h.slice(O[0].length).trim();if(!S)continue;try{let v=R(S,r),W=JSON.stringify(v),F=`@component('${y}', ${W})`;i.push({start:g,end:m,replacement:F})}catch{continue}}for(let g=i.length-1;g>=0;g--){let{start:x,end:b,replacement:p}=i[g];e=e.substring(0,x)+p+e.substring(b)}return e}function oe(n,r,l){let e=n,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),i;while((i=o.exec(e))!==null){let g=i.index,x=g+i[0].length-1,b=1,p=x+1,s=null,m=!1;while(p<e.length&&b>0){let h=e[p];if(m){m=!1,p++;continue}if(h==="\\"&&s){m=!0,p++;continue}if(s){if(h===s)s=null;p++;continue}if(h==='"'||h==="'"||h==="`"){s=h,p++;continue}if(h==="(")b++;else if(h===")"){if(b--,b===0)break}p++}if(b!==0)break;let a=e.substring(x+1,p),y=l(a);e=e.substring(0,g)+y+e.substring(p+1)}return e}function be(n,r){let l=n;return l=l.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),l=l.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,i)=>{try{if(I(i,r.__stx_client_signal_names||[]))return e;let g=Object.keys(r),x=Object.values(r);xi(i);let b=!1,s=d(i,g,()=>{b=!0})(...x);if(b)return e;let m=JSON.stringify(s);if(m===void 0){if(!st(i).some((h)=>!(h in r)))return"";return e}let a=Buffer.from(m,"utf8").toString("base64");return`__stx_${o}="${a}"`}catch(g){return e}}),l}var ee="<!--__STX_BREAK__-->",ne="<!--__STX_CONTINUE__-->";function le(n,r){let l=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let i=l.exec(n);i;i=l.exec(n)){if(!i[1]){let p=i[0].length===3&&i[0]==="{{{"?3:2,s=i[0]==="{!!"?n.indexOf("!!}",l.lastIndex):ve(n,i.index,p);if(s<0)break;l.lastIndex=s+(i[0]==="{!!"?3:p);continue}let g=l.lastIndex,x=!0,b=/^\s*\(/.exec(n.slice(g));if(b){let p=g+b[0].length-1,s=w(n,"(",")",p);if(s<0)break;g=s+1;try{let m=`!!(${n.slice(p+1,s).trim()})`;x=f(m)?Boolean(d(m,Object.keys(r))(...Object.values(r))):Boolean(u(m,r))}catch{x=!1}}if(e+=n.slice(o,i.index),x)return e+(i[1]==="break"?ee:ne);o=g,l.lastIndex=g}return e+n.slice(o)}function ae(n){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),l="",e=0;return Dt(n,(o,i,g)=>(l+=ie(r(n.slice(e,g))),l+=`\${__stxRenderLoopValue(${g}, (${i}), ${o.length})}`,e=g+o.length,o)),l+ie(r(n.slice(e)))}function ue(n,r,l,e){return Z(n,r,l==null?"":String(l),!1,e)}function ie(n){let r=n;return r=oe(r,"@break",(l)=>{let e=l.trim();if(!qs(e))return"";return`\`; if (${e}) { break; } result += \``}),r=oe(r,"@continue",(l)=>{let e=l.trim();if(!qs(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function xe(n){let r=/@forelse\s*\(/g,l,e=[],o=/@foreach\s*\(/g,i=/@endforeach/g,g;while((g=o.exec(n))!==null)e.push({pos:g.index,delta:1});while((g=i.exec(n))!==null)e.push({pos:g.index,delta:-1});e.sort((s,m)=>s.pos-m.pos);let x=[],b=0;for(let s of e)b+=s.delta,x.push({pos:s.pos,depth:b});function p(s){let m=0,a=x.length-1,y=0;while(m<=a){let h=m+a>>1;if(x[h].pos<=s)y=x[h].depth,m=h+1;else a=h-1}return y}while((l=r.exec(n))!==null){if(p(l.index)>0)continue;let s=l.index,m=l.index+l[0].length-1,a=1,y=m+1,h=-1;while(y<n.length&&a>0){if(n[y]==="(")a++;else if(n[y]===")"){if(a--,a===0){h=y;break}}y++}if(h===-1)continue;let O=n.substring(m+1,h),S=Pt(O);if(!S)continue;let{arrayExpr:v,itemVar:W}=S,F=h+1,A=1,B=F,D=/@forelse\s*\(/g,L=/@endforelse/g,V=-1;while(A>0&&B<n.length){D.lastIndex=B,L.lastIndex=B;let P=D.exec(n),E=L.exec(n);if(!E)break;if(P&&P.index<E.index)A++,B=P.index+P[0].length;else{if(A--,A===0){V=E.index;break}B=E.index+11}}if(V===-1)continue;let k=n.substring(F,V),K=V+11,U=-1,z=0,N=0;while(N<k.length){let P=k.indexOf("@",N);if(P===-1)break;let E=k.substring(P);if(/^@forelse\s*\(/.test(E))z++,N=P+1;else if(E.startsWith("@endforelse"))z--,N=P+11;else if(z===0&&E.startsWith("@empty")){if(k.length<=P+6||!/[a-z]/i.test(k[P+6])){U=P;break}N=P+1}else N=P+1}if(U===-1)continue;return{start:s,end:K,arrayExpr:v,itemVar:W,foreachContent:k.substring(0,U),emptyContent:k.substring(U+6)}}return null}function ce(n,r){let l=n;while(!0){let e=xe(l);if(!e)break;let{start:o,end:i,arrayExpr:g,itemVar:x,foreachContent:b,emptyContent:p}=e;try{let s;if(f(g))s=d(g,Object.keys(r))(...Object.values(r));else s=u(g,r);let m;if(!Array.isArray(s)||s.length===0)m=p;else m=`@foreach (${g} as ${x})${b}@endforeach`;l=l.substring(0,o)+m+l.substring(i)}catch(s){let m=s instanceof Error?s.message:String(s),a=c("Forelse",`Error in @forelse(${g} as ${x}): ${m}`,t.EVALUATION_ERROR);l=l.substring(0,o)+a+l.substring(i)}}return l}var fe="<!--stx:foreach-not-iterable:",ye=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function Ee(n,r){return`${fe}${encodeURIComponent(n)}|${encodeURIComponent(r)}-->`}function _e(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 us(n){if(!n.includes(fe))return n;return n.replace(ye,(r,l,e)=>(_e(decodeURIComponent(l),decodeURIComponent(e)),""))}function or(n,r,l,e,o=!1){let i=n,g=new Set(r.__stx_client_signal_names||[]);for(let s of ir(n))g.add(s);if(g.size)r={...r,__stx_client_signal_names:[...g]};i=ce(i,r);function x(s){let m=/@foreach\s*\(/g,a;while((a=m.exec(s))!==null){let y=a.index,h=a.index+a[0].length-1,O=1,S=h+1,v=-1;while(S<s.length&&O>0){if(s[S]==="(")O++;else if(s[S]===")"){if(O--,O===0){v=S;break}}S++}if(v===-1)continue;let W=s.substring(h+1,v),F=Pt(W);if(!F)continue;let A=y,{arrayExpr:B,itemVar:D}=F,L=v+1,V=1,k=L,K=/@foreach\s*\(/g,U=/@endforeach/g;while(V>0&&k<s.length){K.lastIndex=k,U.lastIndex=k;let z=K.exec(s),N=U.exec(s);if(!N)break;if(z&&z.index<N.index)V++,k=z.index+z[0].length;else{if(V--,V===0){let P=s.substring(L,N.index),E=N.index+11;return{start:A,end:E,arrayExpr:B,itemVar:D,content:P}}k=N.index+11}}}return null}function b(s,m){let a=s;while(!0){let y=x(a);if(!y)break;let{start:h,end:O,arrayExpr:S,itemVar:v,content:W}=y;try{let F=S.trim(),A;if(f(F))A=d(F,Object.keys(m))(...Object.values(m));else A=u(F,m);let B=!1;if(!Array.isArray(A))if(A instanceof Map)A=Array.from(A),B=!0;else if(A instanceof Set)A=Array.from(A);else if(typeof A==="string")A=Array.from(A);else if(A&&typeof A==="object"&&!(A instanceof Date)&&!(A instanceof RegExp))A=Object.entries(A),B=!0;else{let E=Ee(F,l)+c("Foreach",`Error in @foreach: ${F} is not iterable`,t.TYPE_ERROR);a=a.substring(0,h)+E+a.substring(O);continue}let D=e?.loops?.useAltLoopVariable??pe,L=v.trim(),V=null,k,K=!1;if(L.includes("=>")){let E=L.split("=>").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])V=E[0],k=E[1];else k=L}else if(!L.startsWith("[")&&!L.startsWith("{")&&L.includes(",")){let E=L.split(",").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])k=E[0],V=E[1],K=!0;else k=L}else k=L;let U="",z=new Set(J(`${S} as ${v}`)),N=A,P=m[Ws]??new WeakMap;for(let E=0;E<N.length;E++){let j=N[E],te={index:E,iteration:E+1,first:E===0,last:E===N.length-1,count:N.length},M={...m,loop:te,$loop:te,[Ws]:P};if(Array.isArray(m.__stx_client_signal_names))M.__stx_client_signal_names=m.__stx_client_signal_names.filter((H)=>!z.has(H));if(k.startsWith("[")&&k.endsWith("]")){let H=k.slice(1,-1).split(",").map((T)=>T.trim());if(Array.isArray(j))H.forEach((T,X)=>{if(T)M[T]=j[X]});else M[k]=j}else if(k.startsWith("{")&&k.endsWith("}")){let H=k.slice(1,-1).split(",").map((T)=>T.trim()).filter(Boolean);if(j!==null&&typeof j==="object")H.forEach((T)=>{let X=T.indexOf(":"),Q=(X===-1?T:T.slice(0,X)).trim(),re=X===-1?Q:T.slice(X+1).trim();if(Q&&re)M[re]=j[Q]});else M[k]=j}else M[k]=j;if(V)if(!K&&B&&Array.isArray(j)&&j.length===2)M[V]=j[0],M[k]=j[1];else M[V]=E;let C=ce(W,M);C=or(C,M,l,e,!0),C=se(C,M,l),C=le(C,M);let q=C.indexOf(ee),G=C.indexOf(ne),Y=q<0?G:G<0?q:Math.min(q,G);if(Y>=0)C=C.slice(0,Y);if(C=_(C,M,l),C=be(C,M),C=me(C,M),C=he(C,M),U+=C,Y>=0&&Y===q)break}a=a.substring(0,h)+U+a.substring(O)}catch(F){let A=c("Foreach",`Error in @foreach(${S.trim()} as ${v.trim()}): ${F instanceof Error?F.message:String(F)}`,t.EVALUATION_ERROR);a=a.substring(0,h)+A+a.substring(O)}}return a}i=b(i,r),i=$e(i,r,l,e);let p=e?.loops?.maxWhileIterations??de;return i=we(i,r,p),o?i:us(i)}function If(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 ge(n){return qs(n)}function $e(n,r,l,e){let o=n,i=!0;while(i){i=!1;let g=o.match(/@for\s*\(/);if(!g||g.index===void 0)break;let x=g.index,b=x+g[0].length-1,p=w(o,"(",")",b);if(p===-1)break;let s=If(o.slice(b+1,p)),m=p+1,a=ys(o.slice(x),"for","endfor");if(a.length===0)break;let y=a[0].content,h=x+a[0].end;if(!ge(s)){let O=c("For",`Unsafe expression in @for: ${s}`,t.UNSAFE_EXPRESSION);o=o.substring(0,x)+O+o.substring(h),i=!0;continue}try{let O=Ae(s),S=/@(?:for|foreach|if|unless)\s*\(/.test(y);if(O.length>0&&S){let D=Re({forExpr:s,content:y,iterVarNames:O,context:r,filePath:l,options:e});o=o.substring(0,x)+D+o.substring(h),i=!0;continue}let v=Object.keys(r),W=Object.values(r),F=ae(y),B=Function(...v,"__stxRenderLoopValue",`
3
3
  let result = '';
4
4
  for (${s}) {
5
5
  result += \`${F}\`;
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ug}from"./chunk-6vqz4qqy.js";import"./chunk-2hm4nmt9.js";import"./chunk-4yhsmwcc.js";import"./chunk-h0jnatd4.js";import"./chunk-605b93pe.js";import"./chunk-w9nwb8r3.js";import"./chunk-q14d714d.js";import"./chunk-y8wer7e1.js";import"./chunk-kb2xxmxp.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Ug as buildApp};
2
+ import{Ug}from"./chunk-9rvm6wfm.js";import"./chunk-s4wysh3z.js";import"./chunk-xb2576xg.js";import"./chunk-h0jnatd4.js";import"./chunk-605b93pe.js";import"./chunk-w9nwb8r3.js";import"./chunk-q14d714d.js";import"./chunk-qpqg82qv.js";import"./chunk-se6p0wsk.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Ug as buildApp};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-y8wer7e1.js";import"./chunk-94gyfwpz.js";import"./chunk-27rzdq3n.js";import"./chunk-kb2xxmxp.js";import{Vt,eo,Ut,Hi,ct,Vi,to,Wt,Wi,qt}from"./chunk-7gdwvnwc.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{Vi("Config file changed, restarting...");try{await e.onChange()}catch(p){ct(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",pt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:pt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:mt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function mt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
2
+ import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-qpqg82qv.js";import"./chunk-94gyfwpz.js";import"./chunk-27rzdq3n.js";import"./chunk-se6p0wsk.js";import{Vt,eo,Ut,Hi,ct,Vi,to,Wt,Wi,qt}from"./chunk-7gdwvnwc.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{Vi("Config file changed, restarting...");try{await e.onChange()}catch(p){ct(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",pt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:pt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:mt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function mt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
3
3
  <script>
4
4
  (function() {
5
5
  const ws = new WebSocket('${t}');
@@ -556,7 +556,7 @@ window.__stxPerformance = {
556
556
 
557
557
  window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
558
558
  </script>
559
- `}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-hb7phtn2.js"),p={},g=h(n);if(g)try{await m(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),u=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:u,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await m(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-hb7phtn2.js"),c={...r},n=h(e);if(n)try{await m(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
559
+ `}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-sq7zsdx9.js"),p={},g=h(n);if(g)try{await m(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),u=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:u,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await m(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-sq7zsdx9.js"),c={...r},n=h(e);if(n)try{await m(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
560
560
  `)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
561
561
  `)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function rt(t,e){let r=await Wt(t);ut(t,r);let s=qt(t.config,r);dt(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),g=`http://${o}:${e.port}`,y=Wi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let u=await Wt(t);ut(t,u);let f=qt(t.config,u);if(dt(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=g;try{let{exec:l}=await import("child_process"),u=process.platform;l(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:g,close:async()=>{y(),p.stop()}}}async function xt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],g=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((u)=>u.id===p);if(!l)return new Response("Story not found",{status:404});try{let u=await Y(t,l,g,y);return Response.json({html:u.html,css:u.css,js:u.js,errors:u.errors,duration:u.duration})}catch(u){return Response.json({html:"",css:"",js:"",errors:[u instanceof Error?u.message:String(u)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((g)=>g.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function wt(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
562
562
  <html lang="en" class="${r.darkClass||"dark"}">
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{U}from"./chunk-y8wer7e1.js";import{ze,O,Lt}from"./chunk-27rzdq3n.js";import{ft,Ce,D,qe,Ee,la,go,ua,In}from"./chunk-9h532cqf.js";import{St,ue,et}from"./chunk-q14d714d.js";import{Ao}from"./chunk-y38rxnrr.js";import{On}from"./chunk-985afhhy.js";import{be}from"./chunk-4dd0yecs.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import V from"zlib";import{promisify as Q}from"util";var K=Q(V.brotliCompress),ee=Q(V.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((a)=>e.startsWith(a)))return!1;return te.some((a)=>e.startsWith(a))}function oe(t){let e=new Map;for(let a of t.split(",")){let[r,...i]=a.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of i){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),a=e.get("*"),r=(i)=>e.get(i)??a??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,k=new Map,z=0;function ie(t,e){if(e.length>Y/8)return;k.set(t,e),z+=e.length;for(let[a,r]of k){if(z<=Y)break;k.delete(a),z-=r.length}}async function $n(t,e,a={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let i;try{i=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(i,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(i.length<(a.threshold??re))return f();try{let h=a.quality??5,g=`${r}:${h}:${i.length}:${Bun.hash(i)}`,l=k.get(g);if(!l)l=r==="br"?await K(i,{params:{[V.constants.BROTLI_PARAM_QUALITY]:h,[V.constants.BROTLI_PARAM_SIZE_HINT]:i.length}}):await ee(i),ie(g,l);if(l.length>=i.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),a=e.get("Vary");if(!a)return e.set("Vary","Accept-Encoding"),e;if(!a.split(",").some((i)=>i.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${a}, Accept-Encoding`);return e}class G{now;entries=new U(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,a){let r,i=async()=>{let s=r??await a();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",D(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return i();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${Ce(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,X=async()=>{let s=await a();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let M=await s.clone().arrayBuffer();if(M.byteLength>1048576)return null;s.headers.set("Vary",D(s.headers.get("Vary")).Vary);let n={body:M,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return i();x=X().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let A=await x;return A?l(A):i()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function Wg(t={}){let e=T.resolve(t.outputDir||".output"),a=t.port??3000,r=la(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let i=On(r.routeRules),f=new G,h=Ao(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?O(l):void 0,v=new Map,X=new Map,x=new Map,A=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),c=JSON.parse(await Bun.file(y).text());if(m)c.html=Lt(c.html,m);v.set(n.pattern,c),x.set(n.pattern,et(c.html)),A.set(n.pattern,be(c.html));let L=T.join(e,n.fragmentPath);if(qe(c.html,r.routerContainer||"main")&&await Bun.file(L).exists()){let P=await Bun.file(L).text();X.set(n.pattern,m?Lt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:c}=ue(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:c})}else s.set(n.pattern,n);let M=ce({port:a,async fetch(n){return $n(n,await ze(m??O(),async()=>{let c=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[c])return t.apiRoutes[c](n);let L=await h(n);if(L)return L;if((n.method==="GET"||n.method==="HEAD")&&c!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(c)}catch{d=c}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),E=pe[R]||"application/octet-stream",j=c.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(c);return new Response(Bun.file(u),{headers:{"Content-Type":E,"Cache-Control":j?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=Ce(n),C=null,q={};if(C=s.get(c)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let o=c.match(p);if(o){C=d,u.forEach((R,E)=>{q[R]=o[E+1]});break}}if(!C){let p=St(c)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let _=i(c),W=Object.keys(_).length>0;return f.respond(n,_.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let o=X.get(C.pattern);if(o){let R=x.get(C.pattern);return new Response(o,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...A.has(C.pattern)?{"X-STX-Runtime":A.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...D(),..._.cache?{}:{"Cache-Control":ft}}})}}let d=go(n.method),u=v.get(C.pattern);if(!u){let o=s.get("/500")||null;if(o){let R=v.get(o.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"public, max-age=60"}});try{let{html:o,boundaries:R,redirect:E,cookies:j,status:H,headers:F}=await In(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(E)return ua(E,j,F);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:I}=await import("./chunk-9dzgkt5x.js"),B=new Headers({...D(),...F,"Cache-Control":"private, no-store"});for(let N of j??[])B.append("Set-Cookie",N);if(P&&!d&&qe(o,r.routerContainer||"main")){let N=et(o);B.set("X-STX-Fragment","true"),B.set("X-STX-Runtime",be(o)?"true":"false"),B.set("X-STX-Layout",N.layout),B.set("X-STX-Layout-Group",N.group)}return I(S(P&&!d&&qe(o,r.routerContainer||"main")?Ee(o,r.routerContainer||"main",!0):o,R,{timeoutMs:30000}),{status:H??u.status??200,headers:B})}let w=new Headers({"Content-Type":"text/html",...D(),..._.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of j??[])w.append("Set-Cookie",S);for(let[S,I]of Object.entries(F??{}))w.set(S,I);if(w.set("Vary",D(w.get("Vary")).Vary),P&&!d&&qe(o,r.routerContainer||"main")){let S=et(o);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",be(o)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(Ee(o,r.routerContainer||"main",!0),{status:H??u.status??200,headers:w})}return new Response(o,{status:H??u.status??200,headers:w})}catch(o){if(console.error(`[stx] Hydration error for ${c}:`,o),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${M.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:M.port,stop:()=>{f.invalidate(),M.stop()},invalidate:(n)=>f.invalidate(n)}}
2
+ import{U}from"./chunk-qpqg82qv.js";import{ze,O,Lt}from"./chunk-27rzdq3n.js";import{ft,Ce,D,qe,Ee,la,go,ua,In}from"./chunk-f2t4dfk0.js";import{St,ue,et}from"./chunk-q14d714d.js";import{Ao}from"./chunk-frthfvrd.js";import{On}from"./chunk-985afhhy.js";import{be}from"./chunk-06fej0jb.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import V from"zlib";import{promisify as Q}from"util";var K=Q(V.brotliCompress),ee=Q(V.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((a)=>e.startsWith(a)))return!1;return te.some((a)=>e.startsWith(a))}function oe(t){let e=new Map;for(let a of t.split(",")){let[r,...i]=a.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of i){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),a=e.get("*"),r=(i)=>e.get(i)??a??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,k=new Map,z=0;function ie(t,e){if(e.length>Y/8)return;k.set(t,e),z+=e.length;for(let[a,r]of k){if(z<=Y)break;k.delete(a),z-=r.length}}async function $n(t,e,a={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let i;try{i=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(i,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(i.length<(a.threshold??re))return f();try{let h=a.quality??5,g=`${r}:${h}:${i.length}:${Bun.hash(i)}`,l=k.get(g);if(!l)l=r==="br"?await K(i,{params:{[V.constants.BROTLI_PARAM_QUALITY]:h,[V.constants.BROTLI_PARAM_SIZE_HINT]:i.length}}):await ee(i),ie(g,l);if(l.length>=i.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),a=e.get("Vary");if(!a)return e.set("Vary","Accept-Encoding"),e;if(!a.split(",").some((i)=>i.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${a}, Accept-Encoding`);return e}class G{now;entries=new U(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,a){let r,i=async()=>{let s=r??await a();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",D(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return i();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${Ce(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,X=async()=>{let s=await a();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let M=await s.clone().arrayBuffer();if(M.byteLength>1048576)return null;s.headers.set("Vary",D(s.headers.get("Vary")).Vary);let n={body:M,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return i();x=X().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let A=await x;return A?l(A):i()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function Wg(t={}){let e=T.resolve(t.outputDir||".output"),a=t.port??3000,r=la(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let i=On(r.routeRules),f=new G,h=Ao(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?O(l):void 0,v=new Map,X=new Map,x=new Map,A=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),c=JSON.parse(await Bun.file(y).text());if(m)c.html=Lt(c.html,m);v.set(n.pattern,c),x.set(n.pattern,et(c.html)),A.set(n.pattern,be(c.html));let L=T.join(e,n.fragmentPath);if(qe(c.html,r.routerContainer||"main")&&await Bun.file(L).exists()){let P=await Bun.file(L).text();X.set(n.pattern,m?Lt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:c}=ue(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:c})}else s.set(n.pattern,n);let M=ce({port:a,async fetch(n){return $n(n,await ze(m??O(),async()=>{let c=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[c])return t.apiRoutes[c](n);let L=await h(n);if(L)return L;if((n.method==="GET"||n.method==="HEAD")&&c!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(c)}catch{d=c}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),E=pe[R]||"application/octet-stream",j=c.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(c);return new Response(Bun.file(u),{headers:{"Content-Type":E,"Cache-Control":j?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=Ce(n),C=null,q={};if(C=s.get(c)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let o=c.match(p);if(o){C=d,u.forEach((R,E)=>{q[R]=o[E+1]});break}}if(!C){let p=St(c)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let _=i(c),W=Object.keys(_).length>0;return f.respond(n,_.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let o=X.get(C.pattern);if(o){let R=x.get(C.pattern);return new Response(o,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...A.has(C.pattern)?{"X-STX-Runtime":A.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...D(),..._.cache?{}:{"Cache-Control":ft}}})}}let d=go(n.method),u=v.get(C.pattern);if(!u){let o=s.get("/500")||null;if(o){let R=v.get(o.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"public, max-age=60"}});try{let{html:o,boundaries:R,redirect:E,cookies:j,status:H,headers:F}=await In(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(E)return ua(E,j,F);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:I}=await import("./chunk-dk5jzps7.js"),B=new Headers({...D(),...F,"Cache-Control":"private, no-store"});for(let N of j??[])B.append("Set-Cookie",N);if(P&&!d&&qe(o,r.routerContainer||"main")){let N=et(o);B.set("X-STX-Fragment","true"),B.set("X-STX-Runtime",be(o)?"true":"false"),B.set("X-STX-Layout",N.layout),B.set("X-STX-Layout-Group",N.group)}return I(S(P&&!d&&qe(o,r.routerContainer||"main")?Ee(o,r.routerContainer||"main",!0):o,R,{timeoutMs:30000}),{status:H??u.status??200,headers:B})}let w=new Headers({"Content-Type":"text/html",...D(),..._.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of j??[])w.append("Set-Cookie",S);for(let[S,I]of Object.entries(F??{}))w.set(S,I);if(w.set("Vary",D(w.get("Vary")).Vary),P&&!d&&qe(o,r.routerContainer||"main")){let S=et(o);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",be(o)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(Ee(o,r.routerContainer||"main",!0),{status:H??u.status??200,headers:w})}return new Response(o,{status:H??u.status??200,headers:w})}catch(o){if(console.error(`[stx] Hydration error for ${c}:`,o),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${M.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:M.port,stop:()=>{f.invalidate(),M.stop()},invalidate:(n)=>f.invalidate(n)}}
3
3
  export{$n,Wg};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{eh,ho,th,nh,rh,sh}from"./chunk-5q9nn7dg.js";import"./chunk-w869yz2r.js";import"./chunk-frthfvrd.js";import"./chunk-7sh9fa3q.js";import"./chunk-3654413v.js";import"./chunk-06fej0jb.js";import"./chunk-w5hhqjwr.js";import"./chunk-s4wysh3z.js";import"./chunk-xb2576xg.js";import"./chunk-h0jnatd4.js";import"./chunk-605b93pe.js";import"./chunk-w9nwb8r3.js";import"./chunk-q14d714d.js";import"./chunk-qpqg82qv.js";import"./chunk-se6p0wsk.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{sh as clearStoreCache,eh as getStoreScript,rh as getStoreScriptFor,nh as pageStoresAll,ho as storesRead,th as storesReadInFiles};