@stacksjs/stx 0.2.896 → 0.2.898
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-h19fp8g8.js → chunk-051r7ebx.js} +2 -2
- package/dist/chunk-0hgetg3j.js +2 -0
- package/dist/{chunk-knhf7dkn.js → chunk-0vrt55pp.js} +6 -6
- package/dist/{chunk-18gfzvn5.js → chunk-0yh33smh.js} +1 -1
- package/dist/chunk-0yycygry.js +2 -0
- package/dist/{chunk-m136gh80.js → chunk-2s0q8mjx.js} +1 -1
- package/dist/{chunk-n2d0jzyv.js → chunk-2shw0j2q.js} +1 -1
- package/dist/{chunk-jrbkvptj.js → chunk-3hd73qqj.js} +1 -1
- package/dist/{chunk-zkq66keq.js → chunk-3jxmnnef.js} +1 -1
- package/dist/{chunk-5zztnr63.js → chunk-4wh71ddp.js} +1 -1
- package/dist/{chunk-xwrjre34.js → chunk-5eq2e6p3.js} +1 -1
- package/dist/{chunk-142n73c3.js → chunk-5v4e2a02.js} +1 -1
- package/dist/{chunk-9tngkmry.js → chunk-5xq6eky7.js} +4 -4
- package/dist/{chunk-66qwkxrv.js → chunk-66qfr6b0.js} +1 -1
- package/dist/{chunk-s5xfmr87.js → chunk-6kn2vwtn.js} +1 -1
- package/dist/{chunk-fjpaxmvv.js → chunk-7h52e87j.js} +2 -2
- package/dist/{chunk-3jrn01rc.js → chunk-8cs8jckk.js} +1 -1
- package/dist/{chunk-gxpcdhr3.js → chunk-a0jhmkpd.js} +1 -1
- package/dist/chunk-a1s0tfcd.js +3 -0
- package/dist/chunk-a2bstyq1.js +2 -0
- package/dist/{chunk-p1wqyf10.js → chunk-b9npgke0.js} +6 -6
- package/dist/{chunk-6yqeqesa.js → chunk-bh2j50cy.js} +1 -1
- package/dist/{chunk-rvn63nv2.js → chunk-bj8pv8m9.js} +5 -5
- package/dist/{chunk-38gz54d6.js → chunk-bjmkyead.js} +4 -4
- package/dist/chunk-cgxmgjk4.js +2 -0
- package/dist/{chunk-xzj4jyhy.js → chunk-dd074gp5.js} +3 -3
- package/dist/{chunk-6s81gd2p.js → chunk-ezpk14gs.js} +1 -1
- package/dist/{chunk-6shfk0tt.js → chunk-fsehzmg8.js} +1 -1
- package/dist/chunk-g0p2n9tm.js +2 -0
- package/dist/{chunk-z3kvxk73.js → chunk-g5axctr0.js} +1 -1
- package/dist/{chunk-9v2bpwgb.js → chunk-g8p4sjy4.js} +2 -2
- package/dist/chunk-ggnhr4r3.js +2 -0
- package/dist/{chunk-n8mfvqqz.js → chunk-hmpmvf5c.js} +1 -1
- package/dist/{chunk-q671arjn.js → chunk-htvft92j.js} +1 -1
- package/dist/{chunk-xbqt53jj.js → chunk-j1cgj6z2.js} +1 -1
- package/dist/{chunk-b35t77m0.js → chunk-j1ncsbk2.js} +1 -1
- package/dist/{chunk-3sc1w0dz.js → chunk-jm9rbxj4.js} +1 -1
- package/dist/{chunk-srsb2zvm.js → chunk-jnwj14eq.js} +1 -1
- package/dist/chunk-jvc2qb1n.js +2 -0
- package/dist/{chunk-fnpq78k3.js → chunk-jytqf6p6.js} +1 -1
- package/dist/{chunk-t6sdtsf8.js → chunk-mr34w48c.js} +4 -4
- package/dist/{chunk-hn679t1s.js → chunk-mx5twaps.js} +1 -1
- package/dist/{chunk-w5kq4k7f.js → chunk-n0jfwsz1.js} +1 -1
- package/dist/{chunk-snbhzrfy.js → chunk-nd2bhjdw.js} +1 -1
- package/dist/{chunk-3wz8eys3.js → chunk-ns2d6pb9.js} +1 -1
- package/dist/{chunk-h91ry9p1.js → chunk-nw2zjwcg.js} +2 -2
- package/dist/{chunk-1y4ad3ma.js → chunk-q4dcchrt.js} +1 -1
- package/dist/{chunk-g71ppt0e.js → chunk-qcbj1m21.js} +2 -2
- package/dist/{chunk-8ccgty8s.js → chunk-qe0t0m38.js} +3 -1
- package/dist/{chunk-xvmd0aja.js → chunk-qfxy34d4.js} +1 -1
- package/dist/chunk-qwt94yh2.js +2 -0
- package/dist/chunk-rarsjcs4.js +2 -0
- package/dist/{chunk-jyd9trff.js → chunk-rryzw9x7.js} +1 -1
- package/dist/chunk-ryj1srqn.js +2 -0
- package/dist/{chunk-exb4wc0c.js → chunk-s5j4fpdr.js} +1 -1
- package/dist/{chunk-xtq8swr2.js → chunk-s94gqce0.js} +1 -1
- package/dist/{chunk-avn3panj.js → chunk-taeqm3nc.js} +2 -2
- package/dist/chunk-tsz03zc9.js +2 -0
- package/dist/{chunk-er0hgd96.js → chunk-v8ewgs1y.js} +1 -1
- package/dist/{chunk-rr0wvqa3.js → chunk-w2qct5kq.js} +1 -1
- package/dist/{chunk-7vr7nw7p.js → chunk-wbp6jgcr.js} +1 -1
- package/dist/{chunk-c8hyr9vb.js → chunk-x8yne6s5.js} +1 -1
- package/dist/{chunk-19v28wj2.js → chunk-xdrp6d7e.js} +2 -2
- package/dist/{chunk-7xk40zsm.js → chunk-ykax1thr.js} +1 -1
- package/dist/{chunk-tspz0z7d.js → chunk-zrbyvyn2.js} +1 -1
- package/dist/{chunk-54dk6rbc.js → chunk-zy97etqx.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/offline/app-service-worker.js +2 -2
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-55w7a5tt.js +0 -3
- package/dist/chunk-8abrg1v2.js +0 -2
- package/dist/chunk-8e38dzxv.js +0 -2
- package/dist/chunk-9vpcsn2f.js +0 -2
- package/dist/chunk-jre984qm.js +0 -2
- package/dist/chunk-qe3z3x39.js +0 -2
- package/dist/chunk-rspsbhcv.js +0 -2
- package/dist/chunk-t31twwh0.js +0 -2
- package/dist/chunk-tznd1egg.js +0 -2
- package/dist/chunk-x57p5bay.js +0 -2
- package/dist/chunk-ycge4wfk.js +0 -2
- package/dist/chunk-z1dym2re.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B,$n,Kt,Gt,y,s,Ce,g}from"./chunk-
|
|
2
|
+
import{B,$n,Kt,Gt,y,s,Ce,g}from"./chunk-0vrt55pp.js";import{Pt,He,Rc,ks,ti,ni,i}from"./chunk-b9npgke0.js";import{we}from"./chunk-0jdz31q1.js";import{ce,Hr,Me,K,Dn}from"./chunk-xmg6bmh6.js";import{Dt,Tr,Us,Ws,qs,Lt,jt,Bt,Ft,zt,Ht,pt}from"./chunk-qe0t0m38.js";import{js,a,j}from"./chunk-qcbj1m21.js";import{Tt,cn,je,U,Ia,Do,ls,rt,Oa,st,Be}from"./chunk-dd074gp5.js";import{_r,Cr}from"./chunk-s94gqce0.js";import{e,Sn,wr,S}from"./chunk-nw2zjwcg.js";import{ct}from"./chunk-5xq6eky7.js";import{ze}from"./chunk-115bb91s.js";import{Vn}from"./chunk-2s0q8mjx.js";import{re,Re,Ae}from"./chunk-mr34w48c.js";import{l}from"./chunk-zxjdfgdx.js";import{ne}from"./chunk-a0aqs5a8.js";import{c,f}from"./chunk-hxws025y.js";async function Pn(n){try{let t=await Bun.file(n).text(),o=En(t),d=On(t,n),r=An(t,o),p=Mn(t,o);return{file:n,metrics:o,issues:d,suggestions:r,performance:p}}catch(t){throw Error(`Failed to analyze template ${n}: ${t instanceof Error?t.message:String(t)}`)}}function En(n){let t=n.split(`
|
|
3
3
|
`),o=n.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),r=(o?o[1]:"").split(`
|
|
4
4
|
`).length,p={conditionals:(n.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(n.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(n.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};p.total=p.conditionals+p.loops+p.includes+p.custom;let u=(n.match(/\{\{[\s\S]*?\}\}/g)||[]).length,m=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length,x=(n.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+m+x,b=(n.match(/<[A-Z][^>]*>/g)||[]).length,C=(n.match(/@(?:layout|extends)\(/g)||[]).length,R=0,O=0;for(let A of t)if(/@(?:if|unless|foreach|for|while|section)\b/.test(A)&&!/@end/.test(A)&&!/@else/.test(A))O++,R=Math.max(R,O);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(A))O--;let v=R>=4?3:0,w=Math.min(10,Math.ceil(p.total*0.5+h*0.1+b*0.3+(r>10?r*0.05:0)+v));return{lines:t.length,characters:n.length,directives:p,expressions:h,components:b,layouts:C,scriptLines:r,complexity:w}}function On(n,t){let o=[],d=Ut(n,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let r=Ut(n,"foreach","endforeach");if(r>0)o.push({type:"error",category:"syntax",message:`Found ${r} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let p=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let m=n.match(/<img[^>]*>/g);if(m){let b=m.filter((C)=>!C.includes("alt="));if(b.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let x=n.split(`
|
|
5
5
|
`).filter((b)=>b.length>120);if(x.length>0)o.push({type:"info",category:"maintainability",message:`Found ${x.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(n.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function An(n,t){let o=[];if(t.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(t.complexity>5&&t.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(t.lines>100&&t.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(t.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(t.directives.total===0&&t.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(t.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Mn(n,t){let o=1;if(o+=t.directives.conditionals*0.1,o+=t.directives.loops*0.5,o+=t.directives.includes*2,o+=t.expressions*0.05,o+=t.components*1,t.scriptLines>10)o+=t.scriptLines*0.1;let d;if(t.expressions===0&&t.directives.total===0)d="high";else if(t.expressions<5&&t.directives.total<3)d="medium";else d="low";let r=[];if(o>10)r.push("Consider optimizing template complexity");if(d==="low"&&t.directives.total>5)r.push("Reduce dynamic content for better caching");if(t.components===0&&t.lines>40)r.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:t.complexity,cacheability:d,recommendations:r}}function Ut(n,t,o){let d=n.replace(/<!--[\s\S]*?-->/g,""),r=(d.match(new RegExp(`@${t}\\b`,"g"))||[]).length,p=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(r-p)}async function xa(n=["**/*.stx"],t){let o=[],d=[];for(let p of n){let u=await Array.fromAsync(new Bun.Glob(p).scan({cwd:t||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((m)=>m.endsWith(".stx")))}for(let p of d)try{let u=await Pn(p);o.push(u)}catch(u){console.warn(`Failed to analyze ${p}:`,u)}let r=_n(o);return{results:o,summary:r}}function _n(n){let t=n.length,o=n.reduce((h,b)=>h+b.metrics.lines,0),d=t>0?n.reduce((h,b)=>h+b.metrics.complexity,0)/t:0,r=n.reduce((h,b)=>h+b.issues.length,0),p={};n.forEach((h)=>{h.issues.forEach((b)=>{p[b.category]=(p[b.category]||0)+1})});let u=t>0?n.reduce((h,b)=>h+b.performance.estimatedRenderTime,0)/t:0,m=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),x=[];if(d>6)x.push("Project has high average complexity. Consider refactoring complex templates.");if(r>t*2)x.push("High number of issues detected. Run detailed analysis on individual files.");if(p.security>0)x.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:t,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:r,issuesByCategory:p,performanceScore:m,recommendations:x}}var{serve:Un}=globalThis.Bun;import Rt from"fs";import Qe from"path";function dt(){return`
|
|
@@ -454,7 +454,7 @@ else {
|
|
|
454
454
|
};
|
|
455
455
|
})();
|
|
456
456
|
</script>
|
|
457
|
-
`}function Ue(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function ht(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function yt(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function xt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var Ze=null;function bt(n){if(!Ze)Ze=new Wt(n);return Ze}function ot(){if(Ze)Ze.stop(),Ze=null}import vt from"path";var et={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${vt.relative(vt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await js(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let w=await _r(u,o);if(w){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:w,loader:"html"}}}let x=await Me(()=>Bun.file(u).text(),"",(w)=>{throw new Hr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${w.message}`)});if(!x)throw new Hr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:b,allScripts:C}=we.time("script-extraction",()=>{let w=x,A=B(x);if(A)w=A.content.trim();let W=x.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],oe="",I=[];for(let k of W){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),q=D?D[1]:"";if(/\bserver\b/i.test(q))oe=P;else I.push(k)}let L=w.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:oe,templateContent:L,allScripts:I}}),R={__filename:u,__dirname:vt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await Me(()=>y(h,R,u),void 0,(w)=>{let A=new ce(`Script execution failed in ${u}: ${w.message}`,u,void 0,void 0,h.substring(0,100));if(K.log(A,{filePath:u,scriptContent:h}),o.debug)throw A});let v=await we.timeAsync("directive-processing",async()=>await i(b,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:w}=await import("./chunk-
|
|
457
|
+
`}function Ue(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function ht(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function yt(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function xt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var Ze=null;function bt(n){if(!Ze)Ze=new Wt(n);return Ze}function ot(){if(Ze)Ze.stop(),Ze=null}import vt from"path";var et={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${vt.relative(vt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await js(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let w=await _r(u,o);if(w){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:w,loader:"html"}}}let x=await Me(()=>Bun.file(u).text(),"",(w)=>{throw new Hr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${w.message}`)});if(!x)throw new Hr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:b,allScripts:C}=we.time("script-extraction",()=>{let w=x,A=B(x);if(A)w=A.content.trim();let W=x.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],oe="",I=[];for(let k of W){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),q=D?D[1]:"";if(/\bserver\b/i.test(q))oe=P;else I.push(k)}let L=w.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:oe,templateContent:L,allScripts:I}}),R={__filename:u,__dirname:vt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await Me(()=>y(h,R,u),void 0,(w)=>{let A=new ce(`Script execution failed in ${u}: ${w.message}`,u,void 0,void 0,h.substring(0,100));if(K.log(A,{filePath:u,scriptContent:h}),o.debug)throw A});let v=await we.timeAsync("directive-processing",async()=>await i(b,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:w}=await import("./chunk-fsehzmg8.js"),A=w(C.join(`
|
|
458
458
|
`),R),W=v.search(/<\/body>/i);if(W!==-1)v=v.slice(0,W)+A+`
|
|
459
459
|
`+v.slice(W);else v+=`
|
|
460
460
|
${A}`}if(v=await Ae(v),m.forEach((w)=>d.add(w)),o.cache&&o.cachePath){if(await Cr(u,v,m,o),o.debug)console.log(`Cached template ${u} with ${m.size} dependencies`)}return{contents:v,loader:"html"}}catch(m){let x=m instanceof Error?m:new ce(`Plugin processing failed: ${String(m)}`,u);if(K.log(x,{filePath:u,buildConfig:n.config}),Dn.logDetailedError(x,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",x);let h=x,b=h.line||null,C=h.context||null;return{contents:o.debug||ne()?`<!DOCTYPE html>
|
|
@@ -517,7 +517,7 @@ ${A}`}if(v=await Ae(v),m.forEach((w)=>d.add(w)),o.cache&&o.cachePath){if(await C
|
|
|
517
517
|
<h1>Something went wrong</h1>
|
|
518
518
|
<p>An internal error occurred. Please try again later.</p>
|
|
519
519
|
</body>
|
|
520
|
-
</html>`,loader:"html"}}})}};async function rs(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Et(m,t);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let x=l(process.cwd(),"output");Ie.mkdirSync(x,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let h=null,b=async()=>{try{let P={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:x,plugins:[P,et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let q=D.outputs.find((xe)=>xe.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(q.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await b())return!1;let R=ge.dirname(m);await Sn(R);let O=o;try{if(O=await Ve(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=bt({wsPort:P,verbose:!1}),u=p.start(P)}let v={},w=null,A;try{let{loadStxConfig:P}=await import("./chunk-
|
|
520
|
+
</html>`,loader:"html"}}})}};async function rs(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Et(m,t);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let x=l(process.cwd(),"output");Ie.mkdirSync(x,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let h=null,b=async()=>{try{let P={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:x,plugins:[P,et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let q=D.outputs.find((xe)=>xe.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(q.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await b())return!1;let R=ge.dirname(m);await Sn(R);let O=o;try{if(O=await Ve(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=bt({wsPort:P,verbose:!1}),u=p.start(P)}let v={},w=null,A;try{let{loadStxConfig:P}=await import("./chunk-tsz03zc9.js"),D=await P();if(A=t.stxOptions?.serverApi??D.serverApi,D?.apiRouter)w=D?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(D?.apiRoutes){v=D.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(D?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Y}=await import("./chunk-0k437z3q.js"),xe=D.broadcasting;await q(xe);let pe=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${pe}/ws${e.reset}`);let ke=ge.join(process.cwd(),"channels.ts");if(Ie.existsSync(ke))try{let se=await Y(ke);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:W,isServerApiSource:oe}=await import("./chunk-3hd73qqj.js"),I=await W(process.cwd(),A);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${O}/${e.reset}...`),r)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let L=Kn({port:O,async fetch(P){return Vn(P,await(async()=>{let D=new URL(P.url);if([x,ge.dirname(m),ge.join(process.cwd(),"public")].some((se)=>oe(ge.join(se,D.pathname),process.cwd(),A)))return new Response("Not Found",{status:404});if(w)try{let se=await w.handleRequest(P);if(se.status!==404)return se}catch{}if(v[D.pathname])try{return await v[D.pathname](P)}catch(se){return new Response(JSON.stringify({error:se.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await I(P);if(q)return q;if(D.pathname==="/")return(async()=>{let F=await S(h||"");if(r)F=Ue(F,u);if(t.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(t.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(x,D.pathname);if(Ie.existsSync(Y)&&Ie.statSync(Y).isFile()){let se=Bun.file(Y),F=ge.extname(Y).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Ne=await se.text(),Ge=Fe.transformSync(Ne);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":E}})}let xe=ge.dirname(m),pe=ge.join(xe,D.pathname);if(Ie.existsSync(pe)&&Ie.statSync(pe).isFile()){let se=Bun.file(pe),F=ge.extname(pe).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Ne=await se.text(),Ge=Fe.transformSync(Ne);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":E}})}let ke=ge.join(process.cwd(),"public",D.pathname);if(Ie.existsSync(ke)&&Ie.statSync(ke).isFile()){let se=Bun.file(ke),F=ge.extname(ke).toLowerCase(),E="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Ne=await se.text(),Ge=Fe.transformSync(Ne);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":E}})}return new Response("Not Found",{status:404})})())},error(P){return new Response(`<pre>${P}
|
|
521
521
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
522
522
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
523
523
|
${e.bright}\u2192 ${e.cyan}http://localhost:${O}/${e.reset}`),console.log(`
|
|
@@ -1002,12 +1002,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1002
1002
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1003
1003
|
${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
|
|
1004
1004
|
${e.yellow}Routes:${e.reset}`);let R=new Set(m.map((v)=>v.routeTemplate)),O=Object.entries(u).filter(([v])=>!R.has(v)).sort(([v],[w])=>v.localeCompare(w)).map(([v,w])=>({route:v==="/"?"/":v,filePath:Se.relative(process.cwd(),w.filePath),fileType:w.fileType}));for(let v of m){let w=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");O.push({route:w,filePath:Se.relative(process.cwd(),v.filePath),fileType:"stx"})}if(O.sort((v,w)=>v.route.localeCompare(w.route)),O.forEach((v,w)=>{let W=w===O.length-1?"\u2514\u2500 ":"\u251C\u2500 ",oe=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${W}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${oe}`)}),console.log(`
|
|
1005
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(C.url.toString(),()=>{if(d)Ke.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ke.watch(p,{recursive:!0},async(w,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),ct.clear(),Ce(),await x()});process.on("SIGINT",()=>{v.close(),C.stop(),process.exit(0)})}return!0}function qt(n){return String(n??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Gn}=globalThis.Bun;import me from"fs";import te from"path";async function Jt(n){try{return $n(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=te.extname(n).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function os(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=te.resolve(n),{loadStxConfig:x}=await import("./chunk-tznd1egg.js"),h=await x(m),{createServerApi:b,isServerApiSource:C}=await import("./chunk-jrbkvptj.js"),R=t.stxOptions?.serverApi??h.serverApi,O=await b(m,R),v=h.root&&h.root!=="."?te.join(m,h.root):m,w=t.pagesDir||h.pagesDir||"pages",A=te.join(v,w);if(!me.existsSync(A)&&!h._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${w}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${w}/index.stx for the homepage.${e.reset}`),!1;let W=re(v,{pagesDir:w,pagesDirs:h._layerPageDirs?[A,...h._layerPageDirs.slice(1)]:void 0});if(W.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${W.length}${e.blue} routes${e.reset}`);let oe=h?._pluginPageDirs||[],I=[];for(let{dir:T,prefix:M}of oe)if(me.existsSync(T)){let z=re(te.dirname(T),{pagesDir:te.basename(T)});for(let Q of z){let X=M==="/"?Q.pattern:`${M}${Q.pattern==="/"?"":Q.pattern}`;I.push({route:{...Q,pattern:X},prefix:M})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${M}${e.reset}`)}let L=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Ia(m,t.stxOptions?.shell),P){if(k=await Do(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Lt(),await Bt(m);let D=jt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let q={},Y=null;try{let{loadStxConfig:T}=await import("./chunk-tznd1egg.js"),M=await T(m);if(M?.apiRouter)Y=M?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(M?.apiRoutes){q=M.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(M?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-0k437z3q.js"),X=M.broadcasting;await z(X);let Te=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Te}/ws${e.reset}`);let be=te.join(process.cwd(),"channels.ts");if(me.existsSync(be))try{let N=await Q(be);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let xe=l(m,"output");me.mkdirSync(xe,{recursive:!0});let pe=new Map,ke=new Set,se=async(T)=>{let M=Ws(A,T);if(!M)return null;try{let z=await Bun.build({entrypoints:[M],outdir:xe,plugins:[et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,E=async(T,M)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Te,injectRouterScript:be}=await import("./chunk-tznd1egg.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:ue}=await import("./chunk-3jrn01rc.js"),G=await Te(m),We=(le)=>{if(!le)return le;if(te.isAbsolute(le))return le;return te.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=We(de.partialsDir),de.componentsDir=We(de.componentsDir),de.layoutsDir=We(de.layoutsDir),de.storesDir=We(de.storesDir||"stores"),de.cachePath=We(de.cachePath)??l(m,"cache");let _=!M&&!t.profile,ie=de.cache!==!1;if(ie&&_){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let Le=!0;for(let ve of le.dependencies){if(!me.existsSync(ve)){Le=!1;break}if((await me.promises.stat(ve)).mtime.getTime()>le.mtime){Le=!1;break}}if(Le){let ve=le.output;if(k)ve=rt(ve,{preserveHead:!0});let nt=F.get(T.filePath);return{route:T,content:ve,status:nt?.status??await Jt(T.filePath),headers:nt?.headers}}}}catch{}let De=await N(T.filePath,de);if(De){let _e=De;if(k)_e=rt(_e,{preserveHead:!0});let Le=F.get(T.filePath);return{route:T,content:_e,status:Le?.status??await Jt(T.filePath),headers:Le?.headers}}}let Z=ie?await V(T.filePath):await Bun.file(T.filePath).text(),ae=$n(Z),{classifyAllScripts:fe}=await import("./chunk-tznd1egg.js"),H=fe(Z),Oe=H.server.map((le)=>le.content),Pe=Z;for(let le of H.server)Pe=Pe.replace(le.fullTag,"");let ee={__filename:T.filePath,__dirname:te.dirname(T.filePath),__stx_options:de,params:M??{},__stx_runtime_head:{}};for(let le of Oe)try{await Q(le,ee,T.filePath)}catch(De){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,De?.message||De)}let $e=new Set,he;if(t.profile){let le=performance.now();he=await z(Pe,ee,T.filePath,de,$e);let De=performance.now()-le,_e=te.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${_e} \u2192 ${De.toFixed(2)}ms`)}else he=await z(Pe,ee,T.filePath,de,$e);if(!k)he=await be(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-6shfk0tt.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(De,_e,Le)=>{if(!/function\s+__stx_setup_/.test(Le))return De;return`<script${_e}>${le(Le,ee)}</script>`})}if(k)he=rt(he,{preserveHead:!0});if(ie&&_)await J(T.filePath,he,$e,de);let{extractStreamBoundaries:lt}=await import("./chunk-8abrg1v2.js"),Je=lt(ee),tt=ee.__streamTemplates;if(tt&&typeof tt==="object"&&Object.keys(tt).length>0){let le=ee.streamBoundaries||{},De={...de,autoShell:!1},_e=Object.keys(tt).map((ve)=>({id:ve,render:async()=>{let nt=typeof le[ve]==="function"?await le[ve]():void 0;return z(tt[ve],{...ee,$boundary:nt},T.filePath,De,new Set)}})),Le=new Set(_e.map((ve)=>ve.id));Je=[...(Je||[]).filter((ve)=>!Le.has(ve.id)),..._e]}if(Je&&Je.length>0)ke.add(T.pattern);else Je=void 0;let _t=Kt(ee),It=Gt(ee);if(_)F.set(T.filePath,{status:_t,headers:It});return{route:T,content:he,status:_t??ae,headers:It,boundaries:Je}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},Fe=8,Ne=async()=>{let T=new Set(pe.keys()),M=new Set(L.keys());pe.clear(),L.clear();let z=t.prebuild===!1?W.filter((X)=>T.has(X.pattern)):W,Q=t.prebuild===!1?I.filter(({route:X})=>M.has(X.pattern)):I;for(let X=0;X<z.length;X+=Fe){let Te=z.slice(X,X+Fe),be=await Promise.all(Te.map((N)=>E(N)));for(let N of be)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Te=Q.slice(X,X+Fe),be=await Promise.all(Te.map(({route:N})=>E(N)));for(let N of be)if(N)L.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?W.length+I.length>0:await Ne()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Sn(m);let Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Xe+1;p=bt({wsPort:T,verbose:!1}),u=p.start(T)}let St=(T,M)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(M).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(T.includes("</head>"))return f(T,Q,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+T};console.log(`${e.blue}Starting server...${e.reset}`);let kt=Gn({port:Xe,hostname:t.hostname,async fetch(T){let M=new URL(T.url),z=t.stxOptions?.offline??h.offline;if(M.pathname===ti&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(T.method==="HEAD"?null:ni(z,ks()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",X=te.join(m,Q,M.pathname),Te=te.join(m,M.pathname),be=te.join(xe,M.pathname);if([X,Te,be].some((_)=>C(_,m,R)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Te).catch(()=>null),me.promises.stat(be).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(J?.isFile()&&!C(Te,m,R))return Ot(Te);if(V?.isFile()&&!C(be,m,R))return Ot(be);if(M.pathname.startsWith("/_stx/component/")){let _=decodeURIComponent(M.pathname.slice(16));if(_)try{let ie=`<${_} />`,Z={...buildConfig,autoShell:!1},ae=await processDirectives(ie,{},te.join(m,"components",`${_}.stx`),Z,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(ie){return new Response(`<div class="stx-async-error">${ie.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(M.pathname==="/_stx/img"){let{handleImageRequest:_}=await import("./chunk-1a7a8cjs.js"),ie=await _(T,{publicDir:te.join(m,Q),cacheDir:l(m,"cache","img")});if(ie)return ie}if(Y)try{let _=await Y.handleRequest(T);if(_.status!==404)return _}catch{}if(q[M.pathname])try{return await q[M.pathname](T)}catch(_){return new Response(JSON.stringify({error:_.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Tr(M.pathname,W);if(G){let _=pe.get(G.route.pattern),ie=ke.has(G.route.pattern);if(!_||G.route.isDynamic&&Object.keys(G.params).length>0||ie){let Z=await E(G.route,G.params);if(Z){if(_=Z,!G.route.isDynamic&&!ie)pe.set(G.route.pattern,Z)}}if(_){let Z=_.status??200,ae=_.headers??{},fe=(G.route.filePath?Pt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Pe=await se(404);if(Pe){let ee=Pe;if(ee=await S(ee,m),r)ee=Ue(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Oe=Ft(M.pathname,G.params,fe,M.search),Pe=zt(Oe,null,T,{isServer:!0}),ee=await Ht(fe.middleware,Pe);if(ee.redirect){let $e=ee.redirect.path,he=ee.redirect.options.redirectCode||302,lt=new Headers(ee.responseHeaders);return lt.set("Location",$e),new Response(null,{status:he,headers:lt})}if(ee.abort){let{statusCode:$e,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${$e}</title></head><body><h1>Error ${$e}</h1><p>${he}</p></body></html>`,{status:$e,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let $e=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;_.content=f(_.content,$e,"")}}let H=_.content;if(k&&Oa(T)&&st(H,h?.router?.container||"main")){let Oe=pt(H),Pe=Re(H),ee=H.match(/<title[^>]*>([\s\S]*?)<\/title>/i),$e=ee?cn(ee[1].trim()):"";if(Object.keys(G.params).length>0)H=St(H,G.params);H=await S(H,m);let he=h?.router?.container||"main";return H=Be(H,he,!0),new Response(H,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Oe.layout,"X-STX-Layout-Group":Oe.group,"X-STX-Runtime":Pe?"true":"false",...$e&&{"X-STX-Title":encodeURIComponent($e)},[Rc]:ks(),...U(),"Cache-Control":Tt}})}if(k)H=ls(k,H);if(Object.keys(G.params).length>0)H=St(H,G.params);if(H=await S(H,m),r)H=Ue(H,u);if(t.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;if(t.titlebarHidden)if(H.includes("<head>"))H=H.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else H=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${H}`;if(_.boundaries&&_.boundaries.length>0){let{renderStreamingPage:Oe,streamToResponse:Pe}=await import("./chunk-8abrg1v2.js");return Pe(Oe(H,_.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(H,{status:Z,headers:{"Content-Type":"text/html",...U(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(I.length>0){let _=I.map((Z)=>Z.route),ie=Tr(M.pathname,_);if(ie){let Z=L.get(ie.route.pattern);if(!Z||ie.route.isDynamic){let ae=await E(ie.route,ie.params);if(ae){if(Z=ae,!ie.route.isDynamic)L.set(ie.route.pattern,ae)}}if(Z){let ae=Z.content;if(k)ae=ls(k,ae);if(Object.keys(ie.params).length>0)ae=St(ae,ie.params);if(ae=await S(ae,m),r)ae=Ue(ae,u);return new Response(ae,{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 oe)if(Z!=="/"&&M.pathname.startsWith(Z)){let ae=L.get(Z)||L.get(Z+"/");if(!ae){let fe=I.find(({route:H})=>H.pattern===Z||H.pattern===`${Z}/`);if(fe){let H=await E(fe.route);if(H)ae=H,L.set(fe.route.pattern,H)}}if(ae){let fe=ae.content;if(k)fe=ls(k,fe);if(fe=await S(fe,m),r)fe=Ue(fe,u);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Dt(M.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=pe.get("/");if(We){let _=We.content;if(_=await S(_,m),r)_=Ue(_,u);if(t.native)if(_.includes("<head>"))_=_.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 _="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+_;return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await se(404);if(de){let _=de;if(_=await S(_,m),r)_=Ue(_,u);return new Response(_,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let M=await se(500);if(M)return new Response(M,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
|
|
1005
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(C.url.toString(),()=>{if(d)Ke.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ke.watch(p,{recursive:!0},async(w,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),ct.clear(),Ce(),await x()});process.on("SIGINT",()=>{v.close(),C.stop(),process.exit(0)})}return!0}function qt(n){return String(n??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Gn}=globalThis.Bun;import me from"fs";import te from"path";async function Jt(n){try{return $n(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=te.extname(n).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function os(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=te.resolve(n),{loadStxConfig:x}=await import("./chunk-tsz03zc9.js"),h=await x(m),{createServerApi:b,isServerApiSource:C}=await import("./chunk-3hd73qqj.js"),R=t.stxOptions?.serverApi??h.serverApi,O=await b(m,R),v=h.root&&h.root!=="."?te.join(m,h.root):m,w=t.pagesDir||h.pagesDir||"pages",A=te.join(v,w);if(!me.existsSync(A)&&!h._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${w}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${w}/index.stx for the homepage.${e.reset}`),!1;let W=re(v,{pagesDir:w,pagesDirs:h._layerPageDirs?[A,...h._layerPageDirs.slice(1)]:void 0});if(W.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${W.length}${e.blue} routes${e.reset}`);let oe=h?._pluginPageDirs||[],I=[];for(let{dir:T,prefix:M}of oe)if(me.existsSync(T)){let z=re(te.dirname(T),{pagesDir:te.basename(T)});for(let Q of z){let X=M==="/"?Q.pattern:`${M}${Q.pattern==="/"?"":Q.pattern}`;I.push({route:{...Q,pattern:X},prefix:M})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${M}${e.reset}`)}let L=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Ia(m,t.stxOptions?.shell),P){if(k=await Do(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Lt(),await Bt(m);let D=jt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let q={},Y=null;try{let{loadStxConfig:T}=await import("./chunk-tsz03zc9.js"),M=await T(m);if(M?.apiRouter)Y=M?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(M?.apiRoutes){q=M.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(M?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-0k437z3q.js"),X=M.broadcasting;await z(X);let Te=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Te}/ws${e.reset}`);let be=te.join(process.cwd(),"channels.ts");if(me.existsSync(be))try{let N=await Q(be);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let xe=l(m,"output");me.mkdirSync(xe,{recursive:!0});let pe=new Map,ke=new Set,se=async(T)=>{let M=Ws(A,T);if(!M)return null;try{let z=await Bun.build({entrypoints:[M],outdir:xe,plugins:[et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,E=async(T,M)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Te,injectRouterScript:be}=await import("./chunk-tsz03zc9.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:ue}=await import("./chunk-8cs8jckk.js"),G=await Te(m),We=(le)=>{if(!le)return le;if(te.isAbsolute(le))return le;return te.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=We(de.partialsDir),de.componentsDir=We(de.componentsDir),de.layoutsDir=We(de.layoutsDir),de.storesDir=We(de.storesDir||"stores"),de.cachePath=We(de.cachePath)??l(m,"cache");let _=!M&&!t.profile,ie=de.cache!==!1;if(ie&&_){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let Le=!0;for(let ve of le.dependencies){if(!me.existsSync(ve)){Le=!1;break}if((await me.promises.stat(ve)).mtime.getTime()>le.mtime){Le=!1;break}}if(Le){let ve=le.output;if(k)ve=rt(ve,{preserveHead:!0});let nt=F.get(T.filePath);return{route:T,content:ve,status:nt?.status??await Jt(T.filePath),headers:nt?.headers}}}}catch{}let De=await N(T.filePath,de);if(De){let _e=De;if(k)_e=rt(_e,{preserveHead:!0});let Le=F.get(T.filePath);return{route:T,content:_e,status:Le?.status??await Jt(T.filePath),headers:Le?.headers}}}let Z=ie?await V(T.filePath):await Bun.file(T.filePath).text(),ae=$n(Z),{classifyAllScripts:fe}=await import("./chunk-tsz03zc9.js"),H=fe(Z),Oe=H.server.map((le)=>le.content),Pe=Z;for(let le of H.server)Pe=Pe.replace(le.fullTag,"");let ee={__filename:T.filePath,__dirname:te.dirname(T.filePath),__stx_options:de,params:M??{},__stx_runtime_head:{}};for(let le of Oe)try{await Q(le,ee,T.filePath)}catch(De){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,De?.message||De)}let $e=new Set,he;if(t.profile){let le=performance.now();he=await z(Pe,ee,T.filePath,de,$e);let De=performance.now()-le,_e=te.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${_e} \u2192 ${De.toFixed(2)}ms`)}else he=await z(Pe,ee,T.filePath,de,$e);if(!k)he=await be(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-fsehzmg8.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(De,_e,Le)=>{if(!/function\s+__stx_setup_/.test(Le))return De;return`<script${_e}>${le(Le,ee)}</script>`})}if(k)he=rt(he,{preserveHead:!0});if(ie&&_)await J(T.filePath,he,$e,de);let{extractStreamBoundaries:lt}=await import("./chunk-rarsjcs4.js"),Je=lt(ee),tt=ee.__streamTemplates;if(tt&&typeof tt==="object"&&Object.keys(tt).length>0){let le=ee.streamBoundaries||{},De={...de,autoShell:!1},_e=Object.keys(tt).map((ve)=>({id:ve,render:async()=>{let nt=typeof le[ve]==="function"?await le[ve]():void 0;return z(tt[ve],{...ee,$boundary:nt},T.filePath,De,new Set)}})),Le=new Set(_e.map((ve)=>ve.id));Je=[...(Je||[]).filter((ve)=>!Le.has(ve.id)),..._e]}if(Je&&Je.length>0)ke.add(T.pattern);else Je=void 0;let _t=Kt(ee),It=Gt(ee);if(_)F.set(T.filePath,{status:_t,headers:It});return{route:T,content:he,status:_t??ae,headers:It,boundaries:Je}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},Fe=8,Ne=async()=>{let T=new Set(pe.keys()),M=new Set(L.keys());pe.clear(),L.clear();let z=t.prebuild===!1?W.filter((X)=>T.has(X.pattern)):W,Q=t.prebuild===!1?I.filter(({route:X})=>M.has(X.pattern)):I;for(let X=0;X<z.length;X+=Fe){let Te=z.slice(X,X+Fe),be=await Promise.all(Te.map((N)=>E(N)));for(let N of be)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Te=Q.slice(X,X+Fe),be=await Promise.all(Te.map(({route:N})=>E(N)));for(let N of be)if(N)L.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?W.length+I.length>0:await Ne()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Sn(m);let Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Xe+1;p=bt({wsPort:T,verbose:!1}),u=p.start(T)}let St=(T,M)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(M).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(T.includes("</head>"))return f(T,Q,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+T};console.log(`${e.blue}Starting server...${e.reset}`);let kt=Gn({port:Xe,hostname:t.hostname,async fetch(T){let M=new URL(T.url),z=t.stxOptions?.offline??h.offline;if(M.pathname===ti&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(T.method==="HEAD"?null:ni(z,ks()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",X=te.join(m,Q,M.pathname),Te=te.join(m,M.pathname),be=te.join(xe,M.pathname);if([X,Te,be].some((_)=>C(_,m,R)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Te).catch(()=>null),me.promises.stat(be).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(J?.isFile()&&!C(Te,m,R))return Ot(Te);if(V?.isFile()&&!C(be,m,R))return Ot(be);if(M.pathname.startsWith("/_stx/component/")){let _=decodeURIComponent(M.pathname.slice(16));if(_)try{let ie=`<${_} />`,Z={...buildConfig,autoShell:!1},ae=await processDirectives(ie,{},te.join(m,"components",`${_}.stx`),Z,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(ie){return new Response(`<div class="stx-async-error">${ie.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(M.pathname==="/_stx/img"){let{handleImageRequest:_}=await import("./chunk-1a7a8cjs.js"),ie=await _(T,{publicDir:te.join(m,Q),cacheDir:l(m,"cache","img")});if(ie)return ie}if(Y)try{let _=await Y.handleRequest(T);if(_.status!==404)return _}catch{}if(q[M.pathname])try{return await q[M.pathname](T)}catch(_){return new Response(JSON.stringify({error:_.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Tr(M.pathname,W);if(G){let _=pe.get(G.route.pattern),ie=ke.has(G.route.pattern);if(!_||G.route.isDynamic&&Object.keys(G.params).length>0||ie){let Z=await E(G.route,G.params);if(Z){if(_=Z,!G.route.isDynamic&&!ie)pe.set(G.route.pattern,Z)}}if(_){let Z=_.status??200,ae=_.headers??{},fe=(G.route.filePath?Pt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Pe=await se(404);if(Pe){let ee=Pe;if(ee=await S(ee,m),r)ee=Ue(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Oe=Ft(M.pathname,G.params,fe,M.search),Pe=zt(Oe,null,T,{isServer:!0}),ee=await Ht(fe.middleware,Pe);if(ee.redirect){let $e=ee.redirect.path,he=ee.redirect.options.redirectCode||302,lt=new Headers(ee.responseHeaders);return lt.set("Location",$e),new Response(null,{status:he,headers:lt})}if(ee.abort){let{statusCode:$e,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${$e}</title></head><body><h1>Error ${$e}</h1><p>${he}</p></body></html>`,{status:$e,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let $e=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;_.content=f(_.content,$e,"")}}let H=_.content;if(k&&Oa(T)&&st(H,h?.router?.container||"main")){let Oe=pt(H),Pe=Re(H),ee=H.match(/<title[^>]*>([\s\S]*?)<\/title>/i),$e=ee?cn(ee[1].trim()):"";if(Object.keys(G.params).length>0)H=St(H,G.params);H=await S(H,m);let he=h?.router?.container||"main";return H=Be(H,he,!0),new Response(H,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Oe.layout,"X-STX-Layout-Group":Oe.group,"X-STX-Runtime":Pe?"true":"false",...$e&&{"X-STX-Title":encodeURIComponent($e)},[Rc]:ks(),...U(),"Cache-Control":Tt}})}if(k)H=ls(k,H);if(Object.keys(G.params).length>0)H=St(H,G.params);if(H=await S(H,m),r)H=Ue(H,u);if(t.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;if(t.titlebarHidden)if(H.includes("<head>"))H=H.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else H=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${H}`;if(_.boundaries&&_.boundaries.length>0){let{renderStreamingPage:Oe,streamToResponse:Pe}=await import("./chunk-rarsjcs4.js");return Pe(Oe(H,_.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(H,{status:Z,headers:{"Content-Type":"text/html",...U(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(I.length>0){let _=I.map((Z)=>Z.route),ie=Tr(M.pathname,_);if(ie){let Z=L.get(ie.route.pattern);if(!Z||ie.route.isDynamic){let ae=await E(ie.route,ie.params);if(ae){if(Z=ae,!ie.route.isDynamic)L.set(ie.route.pattern,ae)}}if(Z){let ae=Z.content;if(k)ae=ls(k,ae);if(Object.keys(ie.params).length>0)ae=St(ae,ie.params);if(ae=await S(ae,m),r)ae=Ue(ae,u);return new Response(ae,{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 oe)if(Z!=="/"&&M.pathname.startsWith(Z)){let ae=L.get(Z)||L.get(Z+"/");if(!ae){let fe=I.find(({route:H})=>H.pattern===Z||H.pattern===`${Z}/`);if(fe){let H=await E(fe.route);if(H)ae=H,L.set(fe.route.pattern,H)}}if(ae){let fe=ae.content;if(k)fe=ls(k,fe);if(fe=await S(fe,m),r)fe=Ue(fe,u);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Dt(M.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=pe.get("/");if(We){let _=We.content;if(_=await S(_,m),r)_=Ue(_,u);if(t.native)if(_.includes("<head>"))_=_.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 _="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+_;return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await se(404);if(de){let _=de;if(_=await S(_,m),r)_=Ue(_,u);return new Response(_,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let M=await se(500);if(M)return new Response(M,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
|
|
1006
1006
|
${T.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1007
1007
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1008
1008
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${e.reset}`),r)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1009
1009
|
${e.yellow}Routes:${e.reset}`);let Ct=[...qs(W,m)];for(let{route:T}of I)Ct.push(`${T.pattern}`);if(Ct.forEach((T,M)=>{let Q=M===Ct.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${T}`)}),console.log(`
|
|
1010
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(kt.url.toString(),()=>{if(p)ot();kt.stop()}),t.native){let T,M=te.join(A,"index.stx");if(me.existsSync(M)){let Q=await Bun.file(M).text();T=gt(Q)}let z=h?.app?.window??{};await Ye(Xe,{title:h?.app?.head?.title||te.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),M=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([m,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let ue=me.realpathSync(V);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${te.sep}`)))N.add(ue)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,ue)=>{Te(J,V,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Te=(N,J,V)=>(X=X.catch(()=>{}).then(()=>be(N,J,V)),X),be=async(N,J,V)=>{if(!V||xt(V))return;if(yt(V)){if(h._layerGraph){let ue=await x(m);Object.assign(h,ue),W.splice(0,W.length,...re(v,{pagesDir:w,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Q()}if(T(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),r&&p)p.reload(V)}else if(M(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ct.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-
|
|
1010
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(kt.url.toString(),()=>{if(p)ot();kt.stop()}),t.native){let T,M=te.join(A,"index.stx");if(me.existsSync(M)){let Q=await Bun.file(M).text();T=gt(Q)}let z=h?.app?.window??{};await Ye(Xe,{title:h?.app?.head?.title||te.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),M=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([m,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let ue=me.realpathSync(V);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${te.sep}`)))N.add(ue)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,ue)=>{Te(J,V,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Te=(N,J,V)=>(X=X.catch(()=>{}).then(()=>be(N,J,V)),X),be=async(N,J,V)=>{if(!V||xt(V))return;if(yt(V)){if(h._layerGraph){let ue=await x(m);Object.assign(h,ue),W.splice(0,W.length,...re(v,{pagesDir:w,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Q()}if(T(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),r&&p)p.reload(V)}else if(M(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ct.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-8cs8jckk.js");ue(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(P&&V){if(te.resolve(N,V)===P||te.basename(P)===V){let G=await Do(P,t.stxOptions||{});if(G)k=G}}if(await Ne(),await wr(m),r&&p)p.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ct.clear(),Ce();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-8cs8jckk.js");ue(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await Ne(),r&&p)p.reload(V)}}else if(ht(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),r&&p)p.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(p)ot();kt.stop(),process.exit(0)})}return!0}import At from"fs";import it from"path";async function Jn(n){try{let o=(await Bun.file(n).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],r=[],p=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=p.exec(d))!==null){let m=u[1],x=u[2]||u[3]||u[4];if(!x)continue;let h={name:x},b=m.match(/@type\s+\{([^}]+)\}/i);if(b)h.type=b[1].trim();if(m.match(/@required/i))h.required=!0;let R=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(R)h.default=R[1].trim();let O=m.split(`
|
|
1011
1011
|
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);h.description=O.join(" ").trim(),r.push(h)}if(r.length===0){let m=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(m){let h=m[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of h){let[C]=b.split(":").map((R)=>R.trim());if(C)r.push({name:C})}}}return r}catch(t){return console.error(`Error extracting props from ${n}:`,t),[]}}async function Yn(n){try{let t=await Bun.file(n).text(),o=t.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||t.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1012
1012
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Qn(n,t=!1,o){let d=it.basename(n,".stx"),r=await Jn(n),p=await Yn(n),u="";if(t&&o)u=`<${o}></${o}>`;else{let m=r.map((x)=>{if(x.type==="boolean")return`:${x.name}="true"`;return`${x.name}="value"`}).join(`
|
|
1013
1013
|
`);u=`<${d}
|