@stacksjs/stx 0.2.832 → 0.2.833
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.
- package/dist/chunk-09fbj9b4.js +2 -0
- package/dist/{chunk-asqznjzg.js → chunk-17h13201.js} +1 -1
- package/dist/{chunk-qm2t1ftx.js → chunk-1b1crd5a.js} +1 -1
- package/dist/{chunk-any1jha4.js → chunk-1c62mrad.js} +2 -2
- package/dist/{chunk-kts0wcxn.js → chunk-28z6pq6w.js} +2 -2
- package/dist/{chunk-q1nbsj9p.js → chunk-293fnyc2.js} +1 -1
- package/dist/{chunk-zgf3nss0.js → chunk-38wq4ttd.js} +6 -6
- package/dist/{chunk-6cayjtgq.js → chunk-3grrmmrg.js} +1 -1
- package/dist/{chunk-k58rsprz.js → chunk-3sqay5jm.js} +1 -1
- package/dist/chunk-437wgphe.js +2 -0
- package/dist/{chunk-8z2g630g.js → chunk-46yyc2sf.js} +1 -1
- package/dist/{chunk-6m58mesb.js → chunk-4xw22xqd.js} +3 -3
- package/dist/{chunk-32xv3q66.js → chunk-503ppv77.js} +1 -1
- package/dist/{chunk-jxjmbwb9.js → chunk-5e7abvtz.js} +1 -1
- package/dist/{chunk-hn3qmkx2.js → chunk-6b1g5a6a.js} +1 -1
- package/dist/{chunk-ec45m14s.js → chunk-6kk8p766.js} +1 -1
- package/dist/{chunk-fgreefqz.js → chunk-6qbatp72.js} +4 -4
- package/dist/{chunk-egmxf96v.js → chunk-7b105hww.js} +1 -1
- package/dist/{chunk-9vvvp4g3.js → chunk-7nnep25t.js} +1 -1
- package/dist/chunk-83hwrh5n.js +2 -0
- package/dist/{chunk-npk6j7a9.js → chunk-95d5qy7d.js} +1 -1
- package/dist/{chunk-atbzg7vw.js → chunk-9jvpyq5h.js} +1 -1
- package/dist/{chunk-eaeyemgp.js → chunk-a395a3dt.js} +2 -2
- package/dist/{chunk-7kzmfpcf.js → chunk-a7j451hn.js} +1 -1
- package/dist/{chunk-gj33636j.js → chunk-a9d14beh.js} +1 -1
- package/dist/chunk-abh791bh.js +2 -0
- package/dist/{chunk-f9yqvq9t.js → chunk-aqjcqnex.js} +1 -1
- package/dist/chunk-awd0dvjb.js +2 -0
- package/dist/chunk-b39g02k9.js +2 -0
- package/dist/{chunk-7qgegnxh.js → chunk-ba499a3p.js} +1 -1
- package/dist/{chunk-nd7z3syn.js → chunk-bgqbvf1w.js} +2 -2
- package/dist/{chunk-hdedvppk.js → chunk-c6gr71fg.js} +1 -1
- package/dist/{chunk-27r7e2pv.js → chunk-cfqz4bd6.js} +1 -1
- package/dist/{chunk-dnx152fg.js → chunk-dzm9g76x.js} +1 -1
- package/dist/{chunk-a5kd0r75.js → chunk-e7yejx6x.js} +1 -1
- package/dist/chunk-f8g0sgs0.js +2 -0
- package/dist/{chunk-7zzz8r0d.js → chunk-fby81k5g.js} +1 -1
- package/dist/{chunk-xwjsbewa.js → chunk-g00nhj1d.js} +4 -4
- package/dist/{chunk-v856z21j.js → chunk-g0vz0ch5.js} +2 -2
- package/dist/{chunk-7jazxycb.js → chunk-ggnzezrn.js} +1 -1
- package/dist/{chunk-5hm3aq74.js → chunk-gy59sm92.js} +1 -1
- package/dist/{chunk-ke0w29sz.js → chunk-hfktzsat.js} +1 -1
- package/dist/chunk-jny0vbmt.js +2 -0
- package/dist/{chunk-d6qkykt6.js → chunk-kn3pknzt.js} +1 -1
- package/dist/chunk-kr6x19z0.js +2 -0
- package/dist/{chunk-9pjmza44.js → chunk-m6q2vedz.js} +2 -2
- package/dist/chunk-ns23fv15.js +3 -0
- package/dist/{chunk-q2zsy8vk.js → chunk-pc4xah5j.js} +1 -1
- package/dist/{chunk-yw9g1ag1.js → chunk-q2tbbtqn.js} +1 -1
- package/dist/{chunk-9fw647px.js → chunk-qws72sn9.js} +5 -5
- package/dist/{chunk-cnf9r95x.js → chunk-qym44qqd.js} +1 -1
- package/dist/{chunk-44wcgf44.js → chunk-r2fwxtke.js} +1 -1
- package/dist/{chunk-zx85qm3n.js → chunk-s67pnfvz.js} +2 -2
- package/dist/{chunk-0cwn420q.js → chunk-shzkz2az.js} +1 -1
- package/dist/{chunk-8nf8244n.js → chunk-tchz2m2v.js} +1 -1
- package/dist/{chunk-7b3wjek8.js → chunk-vce1js6z.js} +1 -1
- package/dist/{chunk-8ew4a7vy.js → chunk-vhehb6eh.js} +1 -1
- package/dist/{chunk-kmss70d5.js → chunk-vhmzkhy4.js} +1 -1
- package/dist/{chunk-v88bnrwx.js → chunk-w7m9pecb.js} +1 -1
- package/dist/{chunk-tdq1bq8x.js → chunk-xdqv5yq4.js} +1 -1
- package/dist/{chunk-hr4rd0rr.js → chunk-y34ayg61.js} +4 -4
- package/dist/{chunk-5jkx1t6c.js → chunk-yd1j88kp.js} +4 -4
- package/dist/{chunk-b5rxc6p1.js → chunk-z58dr234.js} +1 -1
- package/dist/{chunk-kqhq31nh.js → chunk-zy41xhc4.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/component-processing.js +1 -1
- package/dist/component-renderer.js +1 -1
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-39k5bfmk.js +0 -2
- package/dist/chunk-8hhkqfb7.js +0 -3
- package/dist/chunk-8q6qp36z.js +0 -2
- package/dist/chunk-9maxchrj.js +0 -2
- package/dist/chunk-asf2d722.js +0 -2
- package/dist/chunk-bkf2z7zt.js +0 -2
- package/dist/chunk-dafwt7tk.js +0 -2
- package/dist/chunk-hmnzsdc9.js +0 -2
- package/dist/chunk-qez22va2.js +0 -2
- package/dist/chunk-wbmh106x.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pe,mn,Ot,Nt,m,s,ge,p}from"./chunk-
|
|
2
|
+
import{pe,mn,Ot,Nt,m,s,ge,p}from"./chunk-38wq4ttd.js";import{bt,Ae,oc,os,No,Mo,i}from"./chunk-y34ayg61.js";import{ae,ce,Er,_e,z,kn}from"./chunk-c9mdvpf5.js";import{kt,pr,Ts,$s,Rs,_t,Ct,Et,Tt,$t,Rt,tt}from"./chunk-mxvevxb8.js";import{xs,a,O}from"./chunk-a395a3dt.js";import{gt,Pn,Ee,j,la,mo,qr,qe,ua,Ke,Te}from"./chunk-4xw22xqd.js";import{lr,ur}from"./chunk-fby81k5g.js";import{Rn}from"./chunk-gy59sm92.js";import{e,ln,or,b}from"./chunk-bgqbvf1w.js";import{Ye}from"./chunk-g00nhj1d.js";import{Re}from"./chunk-6k26n0sj.js";import{G,we,ve}from"./chunk-yd1j88kp.js";import{c}from"./chunk-k6ye0159.js";import{X}from"./chunk-t59bc7na.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
|
|
3
3
|
`),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
|
|
4
4
|
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:y}}function Wn(t,n){let r=[],d=Xt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Xt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
|
|
5
5
|
`).filter((x)=>x.length>120);if(g.length>0)r.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function Ji(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import ke from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";r[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function sr(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
@@ -887,7 +887,7 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await xs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await lr(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let g=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ae.time("script-extraction",()=>{let y=g,k=pe(g);if(k)y=k.content.trim();let M=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await _e(()=>m(h,S,u),void 0,(y)=>{let k=new ce(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ae.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-
|
|
890
|
+
`}function Ne(t,n,r={}){let d=Br(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await xs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await lr(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let g=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ae.time("script-extraction",()=>{let y=g,k=pe(g);if(k)y=k.content.trim();let M=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await _e(()=>m(h,S,u),void 0,(y)=>{let k=new ce(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ae.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-r2fwxtke.js"),k=y(v.join(`
|
|
891
891
|
`),S),M=w.search(/<\/body>/i);if(M!==-1)w=w.slice(0,M)+k+`
|
|
892
892
|
`+w.slice(M);else w+=`
|
|
893
893
|
${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await ur(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ce(`Plugin processing failed: ${String(f)}`,u);if(z.log(g,{filePath:u,buildConfig:t.config}),kn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:r.debug||X()?`<!DOCTYPE html>
|
|
@@ -950,7 +950,7 @@ ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await 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 r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await ln(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=vt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Fr(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await ln(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=vt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-awd0dvjb.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-db1c0c3c.js"),be=L.broadcasting;await V(be);let le=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Ce=me.join(process.cwd(),"channels.ts");if(Be.existsSync(Ce))try{let ne=await Y(Ce);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-46yyc2sf.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Nr({port:T,async fetch(D){return Rn(D,await(async()=>{let L=new URL(D.url);if([g,me.dirname(f),me.join(process.cwd(),"public")].some((ne)=>E(me.join(ne,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let ne=await y.handleRequest(D);if(ne.status!==404)return ne}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=me.join(g,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=me.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let be=me.dirname(f),le=me.join(be,L.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=me.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let Ce=me.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ce)&&Be.statSync(Ce).isFile()){let ne=Bun.file(Ce),F=me.extname(Ce).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
|
|
954
954
|
${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
955
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
956
|
${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
|
|
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1437
1437
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1438
1438
|
${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
|
|
1439
1439
|
${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:$e.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:$e.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import fe from"fs";import te from"path";async function dn(t){try{return mn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Hr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-39k5bfmk.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-8z2g630g.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await la(f,n.stxOptions?.shell),D){if(C=await mo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-39k5bfmk.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-db1c0c3c.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=$s(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-39k5bfmk.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-kmss70d5.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=mn(Z),{classifyAllScripts:ue}=await import("./chunk-39k5bfmk.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-44wcgf44.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-7b3wjek8.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=r;try{if(Ge=await We(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Mo(N,os()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-m9dj8pgb.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=pr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&ua(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?Pn(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[oc]:os(),...j(),"Cache-Control":gt}})}if(C)B=qr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-7b3wjek8.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=qr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=qr(C,ue);if(ue=await b(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1440
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import fe from"fs";import te from"path";async function dn(t){try{return mn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),r=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function Hr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-awd0dvjb.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-46yyc2sf.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await la(f,n.stxOptions?.shell),D){if(C=await mo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-awd0dvjb.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-db1c0c3c.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=$s(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-awd0dvjb.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-vhmzkhy4.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=mn(Z),{classifyAllScripts:ue}=await import("./chunk-awd0dvjb.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-r2fwxtke.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-vce1js6z.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=r;try{if(Ge=await We(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===No&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Mo(N,os()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-m9dj8pgb.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=pr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),o)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&ua(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?Pn(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[oc]:os(),...j(),"Cache-Control":gt}})}if(C)B=qr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-vce1js6z.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=qr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),o)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=qr(C,ue);if(ue=await b(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1441
1441
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1442
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
1443
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1444
1444
|
${e.yellow}Routes:${e.reset}`);let Dt=[...Rs(M,f)];for(let{route:P}of R)Dt.push(`${P.pattern}`);if(Dt.forEach((P,I)=>{let Q=I===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-
|
|
1445
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(At.url.toString(),()=>{if(l)it();At.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-vhmzkhy4.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(D&&W){if(te.resolve(U,W)===D||te.basename(D)===W){let K=await mo(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await or(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-vhmzkhy4.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
|
|
1446
1446
|
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Kr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
|
|
1447
1447
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Vr(t),l=await Kr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
|
|
1448
1448
|
`);u=`<${d}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Se,It,ui,Ls,Oc,Nc,Mc,Dc,js,pi,Lc,jc,fi,yn}from"./chunk-
|
|
2
|
+
import{Se,It,ui,Ls,Oc,Nc,Mc,Dc,js,pi,Lc,jc,fi,yn}from"./chunk-38wq4ttd.js";import{k}from"./chunk-04z1xyrb.js";import{a}from"./chunk-a395a3dt.js";import{wo}from"./chunk-3sqay5jm.js";import{c}from"./chunk-k6ye0159.js";import{existsSync as B,readFileSync as K}from"fs";import h from"path";var ge=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),ee=yn.filter((e)=>!ge.has(e)).sort(),te=[...k].sort(),he=[...new Set([...ee,...te])].sort(),be=new Set(ee),xe=new Set(te),ye=new Set(he),Y=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function ke(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ne(e,t){let s=[];for(let f of t){if(f.offset===void 0)continue;let i=f.kind==="server"?be:xe;Y.lastIndex=0;for(let p of f.code.matchAll(Y)){let g=p.index+p[0].indexOf("{")+1;for(let d of p[1].matchAll(/[^,]+/g)){let y=d[0];if(/^\s*type\s/.test(y))continue;let b=/^\s*([A-Za-z_$][\w$]*)/.exec(y);if(!b)continue;let r=b[1];if(!ye.has(r)||i.has(r))continue;let o=f.offset+g+d.index+b[0].length-r.length,u=e.slice(0,o),S=u.split(`
|
|
3
3
|
`).length;s.push({line:S,column:o-(u.lastIndexOf(`
|
|
4
4
|
`)+1)+1,offset:o,length:r.length,name:r,kind:f.kind,message:ke(r,f.kind)})}}}return s}import E from"path";var we="@stacksjs/stx-typescript-plugin";function $e(e,t){let s=E.resolve(e);for(;;){let f=E.join(s,"tsconfig.json");if(t(f))return f;let i=E.dirname(s);if(i===s)return;s=i}}function ie(e,t,s){let f=$e(e,s);if(!f)return;let i=new Set,p=(g)=>{if(i.has(g))return;i.add(g);let d=t(g);if(!d)return;let y=d.compilerOptions?.plugins;if(Array.isArray(y)){let r=y.find((u)=>u?.name===we),o=Array.isArray(r?.libs)?r.libs.filter((u)=>typeof u==="string"):[];return r?{configPath:g,libs:o.map((u)=>E.resolve(E.dirname(g),u))}:null}let b=typeof d.extends==="string"?[d.extends]:Array.isArray(d.extends)?d.extends:[];for(let r of[...b].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let o=E.resolve(E.dirname(g),r.endsWith(".json")?r:`${r}.json`),u=p(o);if(u!==void 0)return u}return};return p(f)??void 0}function aa(e,t="",s=""){let f=e.startLine>1?`
|
|
5
5
|
`.repeat(e.startLine-1):"",i=ui(pi(e)+e.code,t),p=Ls(i.code),g=e.kind==="client"||e.kind==="plain"?Mc(t,e.code):"",d=(f+p).split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xe,Us,bg,Qh,wg,ey,Dt,p,W,Q,vn,ke,vg,xi,xg,ty,_,Sg,ny,R,ry}from"./chunk-
|
|
2
|
+
import{xe,Us,bg,Qh,wg,ey,Dt,p,W,Q,vn,ke,vg,xi,xg,ty,_,Sg,ny,R,ry}from"./chunk-38wq4ttd.js";import"./chunk-xdqv5yq4.js";import"./chunk-2qngyyaz.js";import"./chunk-c9mdvpf5.js";import"./chunk-8y8kgw9s.js";import"./chunk-04z1xyrb.js";export{Sg as applyFilters,ey as clearCustomFilters,vg as clientLoopScopes,Us as defaultFilters,vn as escapeAttributeValue,p as escapeHtml,W as escapeHtmlValue,Q as escapeInterpolatedHtmlValue,R as evaluateExpression,xe as findMustacheEnd,wg as getAllFilters,xg as interpolateScriptAttributes,xi as interpolateScriptExpressions,ty as interpolateScriptsInTemplate,_ as processExpressions,bg as registerFilter,Qh as registerFilters,Dt as replaceInterpolations,ny as resetRejectedExpressionWarnings,ry as unescapeHtml,ke as usesSignalsInScript};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ut,dt,pt}from"./chunk-ema1c29k.js";import"./chunk-04z1xyrb.js";import"./chunk-8y8kgw9s.js";import"./chunk-c9mdvpf5.js";import{m}from"./chunk-
|
|
2
|
+
import{ut,dt,pt}from"./chunk-ema1c29k.js";import"./chunk-04z1xyrb.js";import"./chunk-8y8kgw9s.js";import"./chunk-c9mdvpf5.js";import{m}from"./chunk-38wq4ttd.js";import"./chunk-2qngyyaz.js";import"./chunk-xdqv5yq4.js";import{Ut,no,Wt,Wi,lt,qi,ro,qt,Xi,Kt}from"./chunk-qnrgfm9v.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()=>{qi("Config file changed, restarting...");try{await e.onChange()}catch(p){lt(`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",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id: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-
|
|
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-09fbj9b4.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-09fbj9b4.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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await qt(t);dt(t,r);let s=Kt(t.config,r);pt(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=Xi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let u=await qt(t);dt(t,u);let f=Kt(t.config,u);if(pt(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,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xn,Si}from"./chunk-
|
|
2
|
+
import{xn,Si}from"./chunk-xdqv5yq4.js";import"./chunk-2qngyyaz.js";export{Si as generateRuntimeConfigTypes,xn as prepareRuntimeConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{q,Me}from"./chunk-
|
|
2
|
+
import{q,Me}from"./chunk-38wq4ttd.js";var o=/\b(?:state|derived|effect|batch|ref|reactive|computed|watch|watchEffect)\s*(?:<[^>]*>)?\s*\(/;function u(t,e,r){let i={fullTag:r,content:e,attrs:t};if(/\bserver\b/.test(t))return{...i,type:"server"};if(/\bdata-stx-scoped\b/.test(t))return{...i,type:"client"};if(o.test(e))return{...i,type:"signals"};if(/\bclient\b/.test(t)||/\btype\s*=\s*["']module["']/.test(t)||/\bsrc\s*=/.test(t))return{...i,type:"client"};return{...i,type:"server"}}var S=/^<script\b([^>]*)>([\s\S]*)<\/script\s*>$/i;function en(t){let e=[],r=[],i=[],c=0;while(c<t.length){let s=t.indexOf("<",c);if(s===-1)break;let p=Me(t,s);if(p>s){c=p;continue}let a=q(t,s);if(a>s){let f=t.slice(s,a),l=S.exec(f);if(l){let n=u(l[1],l[2],f);switch(n.type){case"signals":e.push(n);break;case"client":r.push(n);break;case"server":i.push(n);break}}c=a;continue}c=s+(t.startsWith("<!--",s)?4:1)}return{signals:e,client:r,server:i}}
|
|
3
3
|
export{en};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Lm,va,pu,jm,Bm,Fm,zm,Hm,fu,gu,Vm,Um,Wm,qm}from"./chunk-
|
|
2
|
+
import{Lm,va,pu,jm,Bm,Fm,zm,Hm,fu,gu,Vm,Um,Wm,qm}from"./chunk-dzm9g76x.js";import"./chunk-y34ayg61.js";import"./chunk-bgqbvf1w.js";import"./chunk-g00nhj1d.js";import"./chunk-c84pxd2k.js";import"./chunk-28z6pq6w.js";import"./chunk-ns23fv15.js";import"./chunk-kn3pknzt.js";import"./chunk-ekh3mxyp.js";import"./chunk-g0vz0ch5.js";import"./chunk-yd1j88kp.js";import"./chunk-qadce16v.js";import"./chunk-fby81k5g.js";import"./chunk-a395a3dt.js";import"./chunk-a7j451hn.js";import"./chunk-cv1zc9dg.js";import"./chunk-7p8m82pj.js";import"./chunk-rkdsgfhd.js";import"./chunk-mxvevxb8.js";import"./chunk-38wq4ttd.js";import"./chunk-xdqv5yq4.js";import"./chunk-2qngyyaz.js";import"./chunk-c9mdvpf5.js";import"./chunk-8y8kgw9s.js";import"./chunk-04z1xyrb.js";export{pu as SUSPENSE_RESOLVER_RUNTIME,va as buildSuspenseResolveScript,Hm as createStreamRenderer,Fm as extractStreamBoundaries,qm as generateHydrationRuntime,gu as islandDirective,Um as processSectionDirectives,Bm as processStreamDirectives,Vm as registerStreamingDirectives,jm as renderStreamingPage,Lm as streamTemplate,zm as streamTemplateSimple,Wm as streamToResponse,fu as streamingSuspenseDirective};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a}from"./chunk-
|
|
2
|
+
import{a}from"./chunk-a395a3dt.js";import{yo}from"./chunk-wr7bmkne.js";import p from"path";async function Jg(t={}){let l=performance.now(),s=t.root||process.cwd(),e=await a(s),o=t.ssr?.routeRules??e.routeRules??{};if(yo(o),!e.ssr&&Object.keys(o).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let u,n;if(r==="ssg"){let{generateStaticSite:i}=await import("./ssg.js");u=await i({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:i}=await import("./chunk-437wgphe.js");n=await i({root:s,outputDir:".output",debug:t.debug,...t.ssr})}let d=Math.round(performance.now()-l);return{mode:r,ssg:u,ssr:n,duration:d}}
|
|
3
3
|
export{Jg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ff,Lh,jh,Bh,Fh,zf,Hf,zh,Hh,Go,Vh,lr,ur,ws}from"./chunk-
|
|
2
|
+
import{Ff,Lh,jh,Bh,Fh,zf,Hf,zh,Hh,Go,Vh,lr,ur,ws}from"./chunk-fby81k5g.js";import{rt}from"./chunk-car6nhfe.js";import"./chunk-38wq4ttd.js";import"./chunk-xdqv5yq4.js";import"./chunk-2qngyyaz.js";import"./chunk-c9mdvpf5.js";import"./chunk-8y8kgw9s.js";import"./chunk-04z1xyrb.js";export{Fh as __setSignalsGeneratorsForTest,rt as cacheEngineFingerprint,ur as cacheTemplate,lr as checkCache,Vh as clearDevCaches,Hf as getCachedRouterScript,zf as getCachedSignalsRuntime,zh as getServeClientAsset,Go as getServeModuleBundle,ws as hashFilePath,jh as invalidateFileCache,Bh as invalidateFileCacheByDir,Lh as readFileCached,Hh as registerServeModuleBundle,Ff as templateCache};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{de}from"./chunk-mxvevxb8.js";import{He,M}from"./chunk-2qngyyaz.js";import{Sc}from"./chunk-7p8m82pj.js";import{c}from"./chunk-k6ye0159.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 an(s,l={}){let o=m.resolve(s,l.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 Ao(s,l){let o=c(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 l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:a}=de(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 Po(s,l,o={}){let i=an(s,o);await Ao(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(l,n),a),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...de(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 l(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 Io(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function $h(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=an(s,o);return await Ao(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=an(s,o);await Ao(s,t);let{loadStxConfig:e}=await import("./chunk-
|
|
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(l,n),a),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...de(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 l(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 Io(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function $h(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=an(s,o);return await Ao(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=an(s,o);await Ao(s,t);let{loadStxConfig:e}=await import("./chunk-7b105hww.js"),a=M((await e(s)).runtimeConfig);return await He(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 Oo(s,l,o){if(Sc(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(l,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(l,"server"),m.resolve(l,".output/server")].some((a)=>{let p=t(a);return e===p||e.startsWith(`${p}${m.sep}`)})}
|
|
6
6
|
export{an,Ao,Po,Io,$h,Oo};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sn,M}from"./chunk-2qngyyaz.js";import m from"fs";import e from"path";async function xn(r,o,i){if(r.__stx_runtime_config)return;let n=Sn();if(n||i){r.__stx_runtime_config=n??M(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-
|
|
2
|
+
import{Sn,M}from"./chunk-2qngyyaz.js";import m from"fs";import e from"path";async function xn(r,o,i){if(r.__stx_runtime_config)return;let n=Sn();if(n||i){r.__stx_runtime_config=n??M(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-7b105hww.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=M(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Si(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
|
|
3
3
|
declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${i(o.public??{})} }
|
|
4
4
|
`),await Bun.write(e.join(r,".stx/runtime-config-server.d.ts"),`import '@stacksjs/stx/runtime-config-server'
|
|
5
5
|
declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${i(o.private??{})} }
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{jt,ae,A,u,f,P,t,ce,K,l,_e,Ci,z,kn,Ei,zt,Ti,il,$r,al,at,cl,Rr,ll,_n,$i,ul,Ar,Ir,Ce,Ri}from"./chunk-c9mdvpf5.js";import{ci,Ac,o,C,Ne,fn,Me,fe,J,vr,gn,Bs,Fc,zc,hn,_r,zs,Hs,Hc,mi,Vc,Uc,Wc,qc,Le,je,Vs,ze,s,wn,h,p,W,Q,ke,_}from"./chunk-
|
|
2
|
+
import{jt,ae,A,u,f,P,t,ce,K,l,_e,Ci,z,kn,Ei,zt,Ti,il,$r,al,at,cl,Rr,ll,_n,$i,ul,Ar,Ir,Ce,Ri}from"./chunk-c9mdvpf5.js";import{ci,Ac,o,C,Ne,fn,Me,fe,J,vr,gn,Bs,Fc,zc,hn,_r,zs,Hs,Hc,mi,Vc,Uc,Wc,qc,Le,je,Vs,ze,s,wn,h,p,W,Q,ke,_}from"./chunk-38wq4ttd.js";import{Lt}from"./chunk-2qngyyaz.js";import{xn}from"./chunk-xdqv5yq4.js";import{b}from"./chunk-bgqbvf1w.js";import{gr,As}from"./chunk-mxvevxb8.js";import{gc,mc,dr,et,hc,O}from"./chunk-a395a3dt.js";import{Qo,ei,ti,ni}from"./chunk-rkdsgfhd.js";import{lc,us}from"./chunk-28z6pq6w.js";import{is,as,cs}from"./chunk-g00nhj1d.js";import{gs,Wo,qo,ms,hs,Ko}from"./chunk-g0vz0ch5.js";import{ds,Fo}from"./chunk-kn3pknzt.js";import{Do}from"./chunk-c84pxd2k.js";import{oe,zo,Ho,Vo}from"./chunk-ekh3mxyp.js";import{ar,we,dc,cr,pc}from"./chunk-yd1j88kp.js";import{B,Ze}from"./chunk-ybq56wam.js";import{yc,bc}from"./chunk-a7j451hn.js";import{E,Cn,Ai}from"./chunk-t59bc7na.js";import Xn from"fs";import ie from"path";function dt(){return`
|
|
3
3
|
// STX Lifecycle Runtime
|
|
4
4
|
(function() {
|
|
5
5
|
if (typeof window === 'undefined') return;
|
|
@@ -1293,7 +1293,7 @@ ${R}
|
|
|
1293
1293
|
</style>`;a=a.replace(x,D),y.lastIndex=0}catch(R){}}}return a}import it from"path";var qn=/(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.\.?\/[^'"]*)\2/g,Vn=/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/gi;function Wn(n,e){if(!e||!n.includes("/"))return n;let c=it.dirname(e);return n.replace(qn,(a,g,r,d)=>{let y=it.resolve(c,d);return`${g}${r}${y.split(it.sep).join("/")}${r}`})}function lr(n,e){if(!e||!n.includes("<script"))return n;return n.replace(Vn,(c,a,g,r)=>`${a}${Wn(g,e)}${r}`)}var Ee="<!--PARENT_CONTENT_PLACEHOLDER-->";function ur(n){return n.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function wr(n,e){let c=n.length,a=e,g=!0,r=[],d=(y)=>y+9<=c&&n[y]==="<"&&n[y+1]==="/"&&(n[y+2]==="s"||n[y+2]==="S")&&(n[y+3]==="c"||n[y+3]==="C")&&(n[y+4]==="r"||n[y+4]==="R")&&(n[y+5]==="i"||n[y+5]==="I")&&(n[y+6]==="p"||n[y+6]==="P")&&(n[y+7]==="t"||n[y+7]==="T")&&(n[y+8]===">"||/\s/.test(n[y+8]));while(a<c){let y=n[a];if(d(a))return a;if(y==="/"&&n[a+1]==="/"){if(a=n.indexOf(`
|
|
1294
1294
|
`,a+2),a===-1)return-1;a+=1,g=!0;continue}if(y==="/"&&n[a+1]==="*"){let m=n.indexOf("*/",a+2);if(m===-1)return-1;a=m+2,g=!0;continue}if(y==="/"&&g){let m=a+1,x=!1;while(m<c){let w=n[m];if(w==="\\"){m+=2;continue}if(w==="[")x=!0;else if(w==="]")x=!1;else if(w==="/"&&!x){m++;break}else if(w===`
|
|
1295
1295
|
`){m=-1;break}m++}if(m===-1){a++,g=!1;continue}while(m<c&&/[a-z]/.test(n[m]))m++;a=m,g=!1;continue}if(y==="'"||y==='"'){let m=y;a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]===m){a++;break}if(n[a]===`
|
|
1296
|
-
`)break;a++}g=!1;continue}if(y==="`"){a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}if(r.length===0)g=!1;continue}if(y==="}"&&r.length>0){r.pop(),a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++,g=!1;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}continue}if(/\s/.test(y));else if(/[)\].\w$]/.test(y))g=!1;else g=!0;a++}return-1}function xr(n,e){let c=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`<script\\b(?=[^>]*\\b${c}(?:\\s|=|/?>))[^>]*>`,"i").exec(n);if(!a)return null;let g=a.index+a[0].length,r=n.indexOf("</script>",g);if(r===-1)return null;let d=n.indexOf(">",r);if(d===-1)return null;return{start:a.index,end:d+1}}var zn=4096;async function ot(n,e,c){if(c.buildMode!=="serve"||e.length<zn)return null;let{registerServeModuleBundle:a}=await import("./chunk-
|
|
1296
|
+
`)break;a++}g=!1;continue}if(y==="`"){a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}if(r.length===0)g=!1;continue}if(y==="}"&&r.length>0){r.pop(),a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++,g=!1;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}continue}if(/\s/.test(y));else if(/[)\].\w$]/.test(y))g=!1;else g=!0;a++}return-1}function xr(n,e){let c=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`<script\\b(?=[^>]*\\b${c}(?:\\s|=|/?>))[^>]*>`,"i").exec(n);if(!a)return null;let g=a.index+a[0].length,r=n.indexOf("</script>",g);if(r===-1)return null;let d=n.indexOf(">",r);if(d===-1)return null;return{start:a.index,end:d+1}}var zn=4096;async function ot(n,e,c){if(c.buildMode!=="serve"||e.length<zn)return null;let{registerServeModuleBundle:a}=await import("./chunk-vhmzkhy4.js");return`<script ${n} src="${a(e)}"></script>`}async function nr(n,e,c,a){try{let{registeredModuleIdsIn:g,buildModuleRegistryScript:r}=await o("stx/client-module-registry",()=>import("./chunk-293fnyc2.js")),d=[],y=await r(g(...n),{minify:Ai(e.buildMode,e.minifyClient),collectInputs:d});for(let m of d)c?.add(m);if(a)a.inputs=d,a.code=y??void 0;if(!y)return null;if(e.buildMode==="serve"){let{registerServeModuleBundle:m}=await import("./chunk-vhmzkhy4.js");return`<script data-stx-scoped data-stx-run="always" data-stx-modules src="${m(y)}"></script>`}return`<script data-stx-scoped data-stx-run="always" data-stx-modules>${y.replace(/<\/script/gi,"<\\/script")}</script>`}catch{return null}}async function Kn(n,e,c,a){let g={modulesTag:null,modulesCode:null,storeTag:null,storeCode:null,composableTag:null,composableCode:null,frameworkScript:null};try{let{getFrameworkComposableScript:k}=await o("stx/framework-composables",()=>import("./chunk-cfqz4bd6.js"));g.frameworkScript=await k(n)}catch{}let r=null;try{r=await o("stx/store-loader",()=>import("./chunk-kr6x19z0.js"))}catch{}let d=e.storesDir,y=!!a.__stx_native_screen||(r?.pageStoresAll()??!0),m=y?"":n.replace(/<script\b[^>]*\bdata-stx-(?:runtime|router|hmr)\b[^>]*>[\s\S]*?<\/script>/gi,""),x=[],w=[],v=null;for(let k=0;k<8;k++){let S=null,M="",T=!1;try{if(r){let j=y?await r.getStoreScript(d).then((F)=>F?{code:F,stores:["*"],functions:null}:null):await r.getStoreScriptFor(d,[m],{reads:r.storesReadInFiles([...x,...w]),runOnce:!0});if(j)S=j.code,M=j.stores.join(","),T=!!j.functions&&!y}}catch{}if(v!==null&&M===v)break;v=M;let R=T?'data-stx-scoped data-stx-run="always" data-stx-stores':"data-stx-stores",D=S?`<script ${R}>${S}</script>`:null;g.storeCode=S,g.storeTag=S?await ot(R,S,e)??D:null;let N={};g.modulesTag=await nr([n,D],e,c,N),g.modulesCode=N.code??null,x=N.inputs??[],g.composableTag=null,g.composableCode=null,w=[];try{let{getComposableScript:j}=await o("stx/composable-loader",()=>import("./chunk-83hwrh5n.js")),F=e.composablesDir,I=[g.modulesCode??g.modulesTag,D,g.frameworkScript].filter((H)=>H!==null),L=await j(e._layerComposableDirs??F,n,I,w);if(L)g.composableCode=L,g.composableTag=await ot('data-stx-scoped data-stx-run="always" data-stx-composables',L,e)??`<script data-stx-scoped data-stx-run="always" data-stx-composables>${L}</script>`}catch{}if(y||!r)break}return g}async function Gn(n,e,c,a={}){let{withModuleSubstitutes:g,moduleSubstitutionKey:r}=await import("./chunk-503ppv77.js"),d=await import("./chunk-jp6sbk05.js"),{messages:y,webModules:m}=e,x=null,w=null,v=r()===""&&!a.__stx_native_screen;if(y&&d.pageMessagesEnabled(e)&&v)try{x=await d.loadPageMessages(process.cwd(),y)}catch(R){Zn(R)}if(m&&Object.keys(m).length&&v)try{w=await(await import("./chunk-hd378dgy.js")).loadWebModules(process.cwd(),m)}catch(R){Jn(R)}let k=new Map([...w??[],...x?.stubs??[]]),S=()=>Kn(n,e,c,a),M=k.size?await g(k,S):await S(),T=null;if(x){let R=d.messageAreasIn(M.modulesCode,M.storeCode,M.composableCode),D=d.pageMessagesScript(x,d.pageLanguages(n,x),R);if(D)T=await ot('data-stx-scoped data-stx-run="always" data-stx-messages',D,e)??`<script data-stx-scoped data-stx-run="always" data-stx-messages>${D.replace(/<\/script/gi,"<\\/script")}</script>`}return[T,M.modulesTag,M.storeTag,M.composableTag,M.frameworkScript].filter((R)=>R!==null)}var pr=!1;function Zn(n){if(pr)return;pr=!0,console.warn(`[stx] messages: ${n instanceof Error?n.message:String(n)}; pages ship every language`)}var fr=!1;function Jn(n){if(fr)return;fr=!0,console.warn(`[stx] ${n instanceof Error?n.message:String(n)}; pages bundle the real modules`)}function Qn(n,e=""){let c=xr(n,"data-stx-runtime");if(!c)return n;let a=ar(n);if(a===-1||a===c.start){if(!e)return n;return n.slice(0,c.end)+e+n.slice(c.end)}if(a<c.start)return n.slice(0,a)+n.slice(c.start,c.end)+e+`
|
|
1297
1297
|
`+n.slice(a,c.start)+n.slice(c.end);let g=n.slice(c.start,c.end),r=n.slice(0,c.start)+n.slice(c.end),d=ar(r);if(d===-1)return g+e+`
|
|
1298
1298
|
`+r;return r.slice(0,d)+g+e+`
|
|
1299
1299
|
`+r.slice(d)}function Yn(n){let e=/\x00STX_ESC_MUSTACHE_OPEN\x00([\s\S]*?)\x00STX_ESC_MUSTACHE_CLOSE\x00/g;return n.replace(e,(c,a,g)=>{let r=n.slice(0,g);return r.lastIndexOf("<")>r.lastIndexOf(">")?`{{${a}}}`:`{<!--stx-literal-->{${a}}}`})}async function i(n,e,c,a,g){if(await A(),a.ssr===!1&&!a.autoShell&&a.buildMode==="spa")return n;if(e.__stx_signals_gate===void 0)e.__stx_signals_gate=ke(n,c);let r=!e.__stxProcessingDepth;hn(e);for(let d of a._layerGraph?.configDependencies??[])g.add(d);if(r&&a.runtimeConfig)await xn(e,c,a.runtimeConfig);if(r)Wc(e),e.__stx_scope_seq??={n:0,key:Vs(String(e.__filename??c))},e.__stx_head_injections=Ti(),e.__stx_seo_staged=!1;if(!e.__stxProcessingDepth)e.__stxProcessingDepth=0;if(e.__stxProcessingDepth++,!e.__onceStore)e.__onceStore=new Set;if((a.debug||!E()&&!Cn())&&c&&c.endsWith(".stx"))Do(n,c);try{return await ae.timeAsync("template-processing",async()=>{let d=await es(n,e,c,a,g);if(r)d=mi(d);if(r&&a.autoShell&&a.buildMode!=="compile"){let y=Ce(a.app?.head,{known:Ir,source:"app.head"}),x=(e.__stx_runtime_head||null)??Ri(),w=(e.__stx_head_raw||"").trim(),v,k=w.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(k)v=k[1].trim(),w=w.replace(k[0],"").trim();let S=e.__sections?.title,M=S?_(S,e,c):void 0,T=x.title||v||M,R=!x.title&&(!!v||!!M),D=x.meta||[],N=new Set(D.map((V)=>at(V)).filter(Boolean)),j={...y,...T&&{title:T},meta:[...(y.meta||[]).filter((V)=>!N.has(at(V))),...D],link:[...y.link||[],...x.link||[]],script:[...y.script||[],...x.script||[]],headRaw:[y.headRaw,w].filter(Boolean).join(`
|
|
@@ -1308,7 +1308,7 @@ ${m.trim()}
|
|
|
1308
1308
|
@endsection`}}if(D&&m.includes("<script")){let I=J(m),L=I.scripts.map((H)=>mr(H,c)??H);m=vr(I.output,L)}if(m=m.replace(/@section\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(I,L,H)=>(R[L]=H,"")),m=m.replace(/@section\(\s*['"]([^'"]+)['"]\s*,\s*([^)]+?)\s*\)/g,(I,L,H)=>{if(/^(['"]).*\1$/.test(H.trim()))return I;try{let V=u(H.trim(),e);if(V===void 0)return I;let ee=(e.__stx_inline_section_values??=[]).push(V)-1;return R[L]=`{{ __stx_inline_section_values[${ee}] }}`,""}catch{return I}}),m=m.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@endsection|@show)/g,(I,L,H)=>{if(H.includes("@parent"))R[L]=H.replace("@parent",Ee);else R[L]=H.trim();return""}),e.__sections=R,m=m.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/g,(I,L,H)=>R[L]||H||""),!("slot"in e)||e.slot===void 0)m=m.replace(/\{\{\s*slot\s*\}\}/g,()=>R.content||"");if(m=cs(m,T),D){let I=[],L=J(m),H=fe(L.output,fn,(V,X)=>`\x00STX_ORPHAN_STYLE_${X}\x00`);if(m=H.output.replace(/\x00STX_(SCRIPT|ORPHAN_STYLE)_(\d+)\x00/g,(V,X,ee)=>{let te=X==="SCRIPT"?mr(L.scripts[Number(ee)],c):H.tokens[Number(ee)];if(te)I.push(te);return""}),I.length>0){let V=I.join(`
|
|
1309
1309
|
`);R.content=R.content?`${R.content}
|
|
1310
1310
|
${V}`:V,e.__sections=R}}if(D)try{let I;if(ie.isAbsolute(D))I=D,g.add(D);else I=await _e(()=>wn(D,c,d,g),null,()=>{throw new ce(`Failed to resolve layout path: ${D}`,c,void 0,void 0,`Layout referenced from ${c}`)});if(!I){let te=(G)=>{if(!G)return[];try{let me=ie.isAbsolute(G)?G:ie.resolve(process.cwd(),G);return Xn.readdirSync(me).filter((ve)=>ve.endsWith(".stx")).map((ve)=>ve.replace(/\.stx$/,""))}catch{return[]}},re=[...te(d.layoutsDir),...te(d.fallbackLayoutsDir)].filter((G,me,ve)=>ve.indexOf(G)===me).sort(),le=[d.layoutsDir,d.fallbackLayoutsDir].filter((G)=>typeof G==="string"&&G.length>0),de=le.length>0?` Searched: ${le.join(", ")} (set \`layoutsDir\` to look elsewhere).`:"",se=`Layout not found: ${D} (referenced from ${c})`+(re.length>0?`. Available layouts: ${re.join(", ")}`:d.layoutsDir?`. No .stx layouts found in ${d.layoutsDir}`:"")+de;if(z.log(Error(se),{layoutPath:D,filePath:c,available:re},"error"),console.error(`[stx] ${se}`),d.debug)throw new ce(se,c);return m}let L=await _e(()=>Bun.file(I).text(),"",()=>{throw new ce(`Failed to read layout file: ${I}`,c,void 0,void 0,"Layout content could not be loaded")});L=lr(L,I);let H=L.match(/@(?:layout|extends)\(\s*['"]([^'"]+)['"]\s*\)/);if(H){if(d.debug)console.log(`Found nested layout: ${H[1]} in ${I}`);let te={},re=L.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(se,G,me)=>(te[G]=me.trim(),""));for(let[se,G]of Object.entries(te))if(R[se]&&R[se].includes(Ee)){let me=R[se].indexOf(Ee);R[se]=R[se].slice(0,me)+G+R[se].slice(me+Ee.length)}else if(!R[se])R[se]=G;let le={...e,__sections:R},de=`@layout('${H[1]}')${re}`;return await i(de,le,I,d,g)}let V=L.replace(/\{\{--[\s\S]*?--\}\}/g,""),X=as(V,T),ee={};return X=X.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(te,re,le)=>(ee[re]=le.trim(),`@slot('${re}')`)),X=X.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(te,re,le)=>{if(R[re]){let de=R[re];if(de.includes(Ee)){let se=ee[re]||"",G=de.indexOf(Ee);de=de.slice(0,G)+se+de.slice(G+Ee.length)}return de}return le||""}),X=ts(X,R),X=X.replace(/\{\{\s*slot\s*\}\}/g,()=>R.content||""),X=cs(X,T),e.__originalFilePath=c,m=await br(X,e,I,d,g),m=`<!-- stx-layout: ${D} -->
|
|
1311
|
-
${m}`,v(m)}catch(I){if(I instanceof K)throw I;throw new ce(`Error processing layout ${D}: ${I instanceof Error?I.message:String(I)}`,c)}return v(await br(m,e,c,d,g))}function ts(n,e){return n.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(c,a,g)=>{let r=e[a];if(r!==void 0){if(!new RegExp(`@(?:yield|slot)\\(\\s*['"]${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"]`).test(r))return r}return g||""})}function rs(n,e){if(n.__stx_sfc_mode=!0,n.__stx_options=e,e.buildMode)n.__stx_buildMode=e.buildMode;let c=e.envPrefix||"STX_PUBLIC_",a={};for(let[g,r]of Object.entries(process.env))if(g.startsWith(c)&&r!==void 0)a[g]=r;n.$env=a}async function ns(n,e){await _e(()=>Xt(n,e),void 0,(c)=>{z.log(c,{filePath:n,phase:"view-composer"},"warning"),console.warn(`[stx] view composer failed for ${n}: ${c.message}`)})}var ct="data-stx-source";function mr(n,e){if(!n)return n;let c=/^<script\b([^>]*)>/i.exec(n);if(!c||!/\bserver\b/.test(c[1])||c[1].includes(ct))return n;return`<script ${ct}="${encodeURIComponent(e)}"${n.slice(7)}`}function ss(n){let e=new RegExp(`${ct}="([^"]*)"`).exec(n);return e?decodeURIComponent(e[1]):void 0}function hr(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function yr(n,e,c){return`<div data-stx-server-script-error role="alert" style="padding:12px 14px;border:1px solid #f0b4b4;border-left-width:4px;background:#fff5f5;color:#7a1f1f;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace"><strong style="display:block;margin-bottom:4px">stx: a <script server> ${e==="module-resolution"?"imports a module that does not resolve":e==="syntax"?"does not parse":"names something that does not exist"}, so this component rendered nothing.</strong><span style="display:block;opacity:.85">${hr(n)}</span><span style="display:block;margin-top:4px">${hr(c)}</span></div>`}async function ls(n,e,c,a){let{scanScriptTags:g}=await o("stx/signal-processing",()=>import("./chunk-
|
|
1311
|
+
${m}`,v(m)}catch(I){if(I instanceof K)throw I;throw new ce(`Error processing layout ${D}: ${I instanceof Error?I.message:String(I)}`,c)}return v(await br(m,e,c,d,g))}function ts(n,e){return n.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(c,a,g)=>{let r=e[a];if(r!==void 0){if(!new RegExp(`@(?:yield|slot)\\(\\s*['"]${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"]`).test(r))return r}return g||""})}function rs(n,e){if(n.__stx_sfc_mode=!0,n.__stx_options=e,e.buildMode)n.__stx_buildMode=e.buildMode;let c=e.envPrefix||"STX_PUBLIC_",a={};for(let[g,r]of Object.entries(process.env))if(g.startsWith(c)&&r!==void 0)a[g]=r;n.$env=a}async function ns(n,e){await _e(()=>Xt(n,e),void 0,(c)=>{z.log(c,{filePath:n,phase:"view-composer"},"warning"),console.warn(`[stx] view composer failed for ${n}: ${c.message}`)})}var ct="data-stx-source";function mr(n,e){if(!n)return n;let c=/^<script\b([^>]*)>/i.exec(n);if(!c||!/\bserver\b/.test(c[1])||c[1].includes(ct))return n;return`<script ${ct}="${encodeURIComponent(e)}"${n.slice(7)}`}function ss(n){let e=new RegExp(`${ct}="([^"]*)"`).exec(n);return e?decodeURIComponent(e[1]):void 0}function hr(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function yr(n,e,c){return`<div data-stx-server-script-error role="alert" style="padding:12px 14px;border:1px solid #f0b4b4;border-left-width:4px;background:#fff5f5;color:#7a1f1f;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace"><strong style="display:block;margin-bottom:4px">stx: a <script server> ${e==="module-resolution"?"imports a module that does not resolve":e==="syntax"?"does not parse":"names something that does not exist"}, so this component rendered nothing.</strong><span style="display:block;opacity:.85">${hr(n)}</span><span style="display:block;margin-top:4px">${hr(c)}</span></div>`}async function ls(n,e,c,a){let{scanScriptTags:g}=await o("stx/signal-processing",()=>import("./chunk-9jvpyq5h.js")),r=[],d=!E()&&!Cn();for(let m of g(n)){let x=m.attrs;if(!/\bserver\b/.test(x))continue;let w=m.start+m.fullMatch.indexOf(">")+1,v=wr(n,w);if(v===-1)continue;let k=n.slice(w,v);if(!k.trim())continue;let S=ss(x)??c,M={index:m.start,length:v+9-m.start};try{let{extractVariables:T}=await o("stx/variable-extractor",()=>import("./chunk-3grrmmrg.js"));await T(k,e,S,{preserveExisting:!0,onFailure:(R)=>{if(R.kind==="unknown")return;if(a?.onServerScriptError?.({sourcePath:S,kind:R.kind,message:R.message}),!d)return;r.push({...M,markup:yr(S,R.kind,R.message)})}})}catch(T){let R=T instanceof Error?T:Error(String(T));if(z.log(R,{filePath:S,phase:"server-script-extraction"},"warning"),console.warn(`[stx] server <script> extraction failed in ${S}: ${R.message}`),d)r.push({...M,markup:yr(S,"unknown",R.message)})}}if(r.length===0)return n;let y=n;for(let m of r.sort((x,w)=>w.index-x.index))y=y.slice(0,m.index)+m.markup+y.slice(m.index+m.length);return y}async function ps(n,e,c){try{let{interpolateScriptsInTemplate:a}=await o("stx/expressions",()=>import("./chunk-r2fwxtke.js"));return a(n,e,{skipServer:!0})}catch(a){let g=a instanceof Error?a:Error(String(a));return z.log(g,{filePath:c,phase:"script-expression-interpolation"},"warning"),console.warn(`[stx] script expression interpolation failed in ${c}: ${g.message}`),n}}async function br(n,e,c,a,g){let r=n;await A();let d=a;if(r=await ls(r,e,c,a),r=await Nt(r,e,c),r=await Ht(r,e,c),r=await ps(r,e,c),await A(),r=await _t(r,e,c,d),ke(r))r=Wo(r,e),r=hs(r,e),r=ms(r,e);r=qo(r),await A();let{processStreamDirectives:y}=await o("stx/streaming",()=>import("./chunk-vce1js6z.js"));r=y(r,e),r=await Fo(r,e,c,d,!0),await A(),r=await Yt(r,e,c,d,g),r=await us(r,e,c,d,g),await A(),r=gc(r,e,c,d);let{processDeferDirectives:m}=await o("stx/defer",()=>import("./chunk-ay7ggc4k.js"));r=m(r,e,c);let{processTeleportDirectives:x}=await o("stx/teleport",()=>import("./chunk-1bpx9b0m.js"));r=x(r,e,c);let{processTransitionDirectives:w,processTransitionAttributes:v}=await o("stx/transitions",()=>import("./chunk-72n804gy.js"));r=w(r,e,c),r=v(r);let{processErrorBoundaryDirectives:k,stripRenderFailedMarkers:S}=await o("stx/error-boundaries",()=>import("./chunk-h85hrwkq.js"));r=k(r,e,c),r=S(r);let{processSuspenseDirectives:M}=await o("stx/suspense",()=>import("./chunk-txzap6yn.js"));r=M(r,e,c);let{processAsyncDirectives:T}=await o("stx/async-components",()=>import("./chunk-m3tnxk01.js"));r=T(r,e,c);let{processKeepAliveDirectives:R}=await o("stx/keep-alive",()=>import("./chunk-6aak0b7c.js"));r=R(r,e,c);let{processVirtualListDirectives:D,processVirtualGridDirectives:N,processInfiniteListDirectives:j}=await o("stx/virtual-scrolling",()=>import("./chunk-cw8vpk41.js"));r=D(r,e,c),r=N(r,e,c),r=j(r,e,c),await A();let{processPartialHydrationDirectives:F,processStaticDirectives:I}=await o("stx/partial-hydration",()=>import("./chunk-pe5qqem0.js"));r=F(r,e,c),r=I(r);let{processComputedDirectives:L,processWatchDirectives:H}=await o("stx/computed",()=>import("./chunk-1xdzcy9d.js"));r=L(r,e,c),r=H(r,e,c);let{processFormValidationDirectives:V}=await o("stx/forms-validation",()=>import("./chunk-zy41xhc4.js"));r=V(r,e,c);let{processHeadDirective:X,processTitleDirective:ee,processMetaDirective:te,resetHead:re}=await o("stx/head",()=>import("./chunk-67nq6csk.js"));if(!e.__stx_head_preset&&!e.__stx_runtime_head)re();let le=X(r);if(r=le.content,le.headContent)e.__stx_head_raw=`${e.__stx_head_raw||""}${le.headContent}
|
|
1312
1312
|
`;if(r=ee(r,e),r=te(r,e,c),r=Wt(r),r=zo(r,e),r=Tt(r),r=Ft(r),r=await is(r,e,c,d,g),r=await us(r,e,c,d,g),await A(),r=r.replace(/@push\s*\(\s*['"][^'"]+['"]\s*\)[\s\S]*?@endpush/g,""),r=mi(r),r=oe(r,e,c),r=ds(r),await A(),e.__stxProcessingDepth===1)r=qc(r,e);if(r=Fc(r,e,{filePath:c,buildMode:d.buildMode}),r=Ho(r,e),r=Vo(r,e),r=We(r,e),r=Ot(r,e),r=Pt(r,e),r=await yt(r,e,c,d),r=await hc(r,e,c),r=await yc(r,e,c,d),await A(),r=bc(r,e,c,d),r=Qo(r,e,c,d),r=ei(r,e,c),r=ti(r,e,c,d),r=$t(r,e,c,d),r=zs(r,e),r=Hs(r),r=Hc(r),!d.skipEventDirectives)r=Ac(r,e,c);if(r=zc(r,e,c,a.skipSignalsRuntime===!0&&Number(e.__stxProcessingDepth)>0),await A(),d.debug){let U=/\bx-data\s*=/.test(r),q=gs(n);if(U&&q)console.warn(`[stx] ${c}: Template mixes Alpine-style (x-data) and signals (state/derived/effect) reactivity.
|
|
1313
1313
|
Both work on the same page, but they manage separate scopes.
|
|
1314
1314
|
Prefer signals (state/derived/effect) for new components.`)}r=lc(r,e),r=await _(r,e,c),await A(),r=Vc(r),r=Uc(r),r=gt(r);let{processXElementDirectives:de}=await o("stx/x-element",()=>import("./chunk-zhxdpzga.js"));r=de(r);let se=e.__originalFilePath||c,G=Le(e);if(r=await Ko(r,d,se,G),await A(),r=Mt(r,e),r=await Vt(r,e,c,d),await A(),d.media?.image?.autoSiblings){let U=d.publicDir||"public",{rewriteImagesWithSiblings:q}=await o("stx/image-optimization/auto-sibling",()=>import("./chunk-xrspzeqx.js"));r=await q(r,{publicDir:U})}if(d.seo?.enabled)r=ni(r,e,d);let me=(U,q,Z=!0)=>{if(!q)return U;let he=q.match(/<title\b[^>]*>[\s\S]*?<\/title>/i),ne=/<head\b[^>]*>[\s\S]*?(?:<\/head\s*>|<body\b|$)/i.exec(U),pe=ne?/<title\b[^>]*>[\s\S]*?<\/title>/i.exec(ne[0]):null;if(he&&ne&&pe){if(Z){let Te=ne.index+pe.index;U=U.slice(0,Te)+he[0]+U.slice(Te+pe[0].length)}if(q=q.replace(he[0],"").trim(),!q)return U}if(/<\/head>/i.test(U))return U.replace(/<\/head>/i,`${q}
|
|
@@ -1322,6 +1322,6 @@ ${dt()}
|
|
|
1322
1322
|
`+Te}else r=r.replace("</head>",`${q}
|
|
1323
1323
|
</head>`)}else if(r.includes("<body"))r=r.replace(/<body([^>]*)>/,`<body$1>
|
|
1324
1324
|
${q}`);else r=q+`
|
|
1325
|
-
`+r}{let{scanScriptTags:U}=await o("stx/signal-processing",()=>import("./chunk-
|
|
1325
|
+
`+r}{let{scanScriptTags:U}=await o("stx/signal-processing",()=>import("./chunk-9jvpyq5h.js")),q=[];for(let Z of U(r)){if(!/\bserver\b/i.test(Z.attrs))continue;let he=Z.start+Z.fullMatch.indexOf(">")+1,ne=wr(r,he);if(ne===-1)continue;let pe=ne+9;while(pe<r.length&&/\s/.test(r[pe]))pe++;q.push({start:Z.start,end:pe})}if(q.length>0){let Z=Array(q.length+1),he=0;for(let ne=0;ne<q.length;ne++){let{start:pe,end:Te}=q[ne];Z[ne]=r.slice(he,pe),he=Te}Z[q.length]=r.slice(he),r=Z.join("")}}let lt=Bs(r,c);if(lt.hasScoped)r=lt.html;let Cr=e.__stx_event_bindings||[],Ke=!1,ut=[],Mr=/\s:[a-z][\w.-]*\s*=/.test(r),{scanScriptTags:Dr}=await o("stx/signal-processing",()=>import("./chunk-9jvpyq5h.js"));for(let U of Dr(r,{skipAttrs:/\bserver\b|\bsrc\s*=|\bdata-stx-scoped\b|\bdata-stx-router\b|\btype\s*=\s*["'](?!(?:text\/javascript|application\/javascript|module)["'])[^"']*["']/}))ut.push({match:U.fullMatch,attrs:U.attrs,content:U.body});for(let{match:U,attrs:q,content:Z}of ut){Ke=!0;let he=Z;Ne(Z,c,a.strict,e.__originalFilePath);let ne=await je(Z,{eventBindings:Cr,attrs:q,hasColonDirectives:Mr,templateContent:n,filePath:c,projectRoot:process.cwd(),production:Ai(a.buildMode,a.minifyClient),serverData:G});r=r.replace(U,()=>ne)}if(Ke)e.__stx_event_bindings=[];if(!Ke&&e.__stxProcessingDepth===1){let U=e.__stx_event_bindings||[];if(U.length>0){let q=ci(U);if(q){let Z=r.lastIndexOf("</body>");r=Z===-1?r+q:r.slice(0,Z)+q+`
|
|
1326
1326
|
`+r.slice(Z)}e.__stx_event_bindings=[]}}if(!d.skipSignalsRuntime&&!we(r)&&dc(r))r=await cr(r,d);if(r=pc(r),d.csp?.enabled&&d.csp.useNonce&&typeof e.cspNonce==="string")r=St(r,e.cspNonce);return r}
|
|
1327
1327
|
export{bt,Ae,oc,os,No,Mo,nr,i};
|