@stacksjs/stx 0.2.685 → 0.2.686
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-2ajbhefk.js → chunk-078as147.js} +1 -1
- package/dist/{chunk-r8cn9qhr.js → chunk-0nt17nas.js} +1 -1
- package/dist/{chunk-9wd31tc6.js → chunk-0y2hkbc6.js} +1 -1
- package/dist/{chunk-mxbp4vyy.js → chunk-1rgjy80j.js} +2 -2
- package/dist/{chunk-6nhsvb9x.js → chunk-1x0pf3sw.js} +1 -1
- package/dist/chunk-31jvtxpx.js +2 -0
- package/dist/{chunk-jsac71cy.js → chunk-4cksc4n3.js} +1 -1
- package/dist/{chunk-ppxfsqwh.js → chunk-4dzh6g52.js} +1 -1
- package/dist/{chunk-9xp9hs7t.js → chunk-4j9p27kn.js} +1 -1
- package/dist/chunk-4ntt6d6q.js +2 -0
- package/dist/{chunk-7st0prz9.js → chunk-51fqvchq.js} +2 -2
- package/dist/{chunk-fbdmsw5j.js → chunk-58m0kfb3.js} +1 -1
- package/dist/{chunk-kgcwx6nt.js → chunk-5ahrdnm0.js} +1 -1
- package/dist/{chunk-fb84n8kz.js → chunk-67v3rh14.js} +2 -2
- package/dist/{chunk-7grjwpdq.js → chunk-6te346zf.js} +1 -1
- package/dist/chunk-71d927c6.js +2 -0
- package/dist/{chunk-xpch3mq8.js → chunk-7gprzmd9.js} +1 -1
- package/dist/chunk-7w7e24e9.js +2 -0
- package/dist/{chunk-f5s2h2y8.js → chunk-840waqpm.js} +1 -1
- package/dist/{chunk-km6ggz8n.js → chunk-90ggz2m1.js} +1 -1
- package/dist/{chunk-px7ryjd9.js → chunk-9c3x72qy.js} +1 -1
- package/dist/{chunk-6qn368e7.js → chunk-a7hcwkjz.js} +2 -2
- package/dist/{chunk-yhba2f9d.js → chunk-av02901t.js} +1 -1
- package/dist/{chunk-8x34g2ad.js → chunk-bg6t69qq.js} +1 -1
- package/dist/chunk-c0fkhe6t.js +2 -0
- package/dist/{chunk-d0g4zndy.js → chunk-cge9pgyb.js} +1 -1
- package/dist/{chunk-dpghx4z6.js → chunk-d26nb6zy.js} +1 -1
- package/dist/{chunk-nsvnxkyb.js → chunk-d9esaahz.js} +2 -2
- package/dist/{chunk-qjmvcqfh.js → chunk-dbxq6fd7.js} +1 -1
- package/dist/{chunk-4k3jx9mm.js → chunk-dnbdxbkb.js} +6 -6
- package/dist/{chunk-gn98ha90.js → chunk-dv8a3gp8.js} +1 -1
- package/dist/{chunk-qgs69nds.js → chunk-dxcn65hq.js} +1 -1
- package/dist/chunk-ebmcecyh.js +2 -0
- package/dist/chunk-ejphs9fs.js +2 -0
- package/dist/chunk-em77nd40.js +2 -0
- package/dist/chunk-exbs8qm6.js +2 -0
- package/dist/{chunk-bnggav14.js → chunk-f4fxj7xg.js} +1 -1
- package/dist/{chunk-6zzg889q.js → chunk-ffwvbqkp.js} +1 -1
- package/dist/{chunk-eykbcntx.js → chunk-fndg9ar3.js} +1 -1
- package/dist/{chunk-4ht54p3j.js → chunk-fw12pvmr.js} +4 -4
- package/dist/chunk-gyye3mcb.js +2 -0
- package/dist/{chunk-wt6f9pk9.js → chunk-hx787tfa.js} +1 -1
- package/dist/{chunk-mf8yzpyy.js → chunk-hxnvcvkz.js} +1 -1
- package/dist/{chunk-bxr4c8rg.js → chunk-j7phk6kh.js} +1 -1
- package/dist/chunk-jdhdae0h.js +2 -0
- package/dist/{chunk-5t9ndqfm.js → chunk-jgxzbthg.js} +1 -1
- package/dist/{chunk-gwqw8r2e.js → chunk-jq4h969v.js} +1 -1
- package/dist/chunk-k8b4fme9.js +2 -0
- package/dist/{chunk-6e60jp4a.js → chunk-kq1hmpgb.js} +1 -1
- package/dist/{chunk-4r8c96a0.js → chunk-kqzrm2ym.js} +5 -5
- package/dist/{chunk-4rj9746b.js → chunk-n4qp4q2x.js} +1 -1
- package/dist/{chunk-49c5v5fh.js → chunk-n93krbsx.js} +1 -1
- package/dist/{chunk-e5kz0y03.js → chunk-pf25jb54.js} +4 -4
- package/dist/chunk-q4jpjjdc.js +2 -0
- package/dist/{chunk-3tp7r57c.js → chunk-r0ys9aqa.js} +1 -1
- package/dist/{chunk-9wa3t87n.js → chunk-r21m7gsd.js} +1 -1
- package/dist/chunk-rz0kkfd3.js +2 -0
- package/dist/{chunk-718rkxa7.js → chunk-s84zv8ky.js} +1 -1
- package/dist/chunk-t2eadw9a.js +2 -0
- package/dist/{chunk-nqvex98n.js → chunk-v6wa51js.js} +3 -3
- package/dist/{chunk-zhcb33s1.js → chunk-vewm4kr8.js} +1 -1
- package/dist/{chunk-gccwjjzw.js → chunk-vnnwp1cg.js} +1 -1
- package/dist/{chunk-zf6kmw9q.js → chunk-w0zrp51m.js} +1 -1
- package/dist/{chunk-w6frg42f.js → chunk-x828kq22.js} +1 -1
- package/dist/{chunk-jrche9k7.js → chunk-xp2cn23j.js} +1 -1
- package/dist/{chunk-t3e5tv4h.js → chunk-xw0cqb5m.js} +6 -6
- package/dist/{chunk-gkmh0xys.js → chunk-ydad3kq5.js} +1 -1
- package/dist/{chunk-w3q5czk5.js → chunk-yf42bhjw.js} +2 -2
- package/dist/{chunk-r7csb300.js → chunk-ygb33q5w.js} +1 -1
- package/dist/{chunk-cnvwrv5a.js → chunk-ymjpqt50.js} +1 -1
- package/dist/{chunk-01bd9hrj.js → chunk-yqgrjf9q.js} +1 -1
- package/dist/{chunk-qz314za9.js → chunk-ywpyxqn5.js} +1 -1
- package/dist/chunk-z0r4vm2m.js +2 -0
- package/dist/{chunk-244tyyhx.js → chunk-z10ffhzy.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/env.d.ts +1 -1
- package/dist/env.js +2 -2
- package/dist/process.js +2 -2
- package/dist/pwa.js +2 -2
- package/dist/ssg.js +5 -5
- package/dist/types/config-types.d.ts +1 -0
- package/package.json +5 -5
- package/dist/chunk-42c308vk.js +0 -2
- package/dist/chunk-8y7tpjfs.js +0 -2
- package/dist/chunk-bhm9sdnv.js +0 -2
- package/dist/chunk-bpk0qy53.js +0 -2
- package/dist/chunk-cxvka6g3.js +0 -2
- package/dist/chunk-fzfa35ft.js +0 -2
- package/dist/chunk-kxqvfdm9.js +0 -2
- package/dist/chunk-m1cwgzqy.js +0 -2
- package/dist/chunk-mn9xw0fe.js +0 -2
- package/dist/chunk-sy19th0w.js +0 -2
- package/dist/chunk-t8djd28a.js +0 -2
- package/dist/chunk-tfhhxpda.js +0 -2
- package/dist/chunk-v3mmxk1y.js +0 -2
- package/dist/chunk-x519ewtq.js +0 -2
- package/dist/chunk-xe40yhcw.js +0 -2
- package/dist/chunk-xs8228sa.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-
|
|
2
|
+
import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-xw0cqb5m.js";import{gt,$e,oa,Lr,to,no,o}from"./chunk-dnbdxbkb.js";import{ie,fr,xe,D,bn}from"./chunk-r0ys9aqa.js";import{vt,tr,ns,rs,ss,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-kypwg2ws.js";import{Jr,i,R}from"./chunk-1rgjy80j.js";import{ut,Ri,ke,O,Ai,Hs,Pr,Ve,Pi,_e}from"./chunk-d9esaahz.js";import{Zn,Qn}from"./chunk-58m0kfb3.js";import{kn}from"./chunk-9c3x72qy.js";import{e,nn,Kn,h}from"./chunk-67v3rh14.js";import{Ke}from"./chunk-pf25jb54.js";import{Te}from"./chunk-374nhgyf.js";import{q,he,ye}from"./chunk-fw12pvmr.js";import{c}from"./chunk-xvs84gas.js";import{W}from"./chunk-078as147.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
|
|
3
3
|
`),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(s?s[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 f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let s=[],p=Kt(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=Kt(t,"foreach","endforeach");if(a>0)s.push({type:"error",category:"syntax",message:`Found ${a} 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)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)s.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.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 y=t.split(`
|
|
5
5
|
`).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)s.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function Un(t,r){let s=[];if(r.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)s.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(r.directives.total===0&&r.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function Wn(t,r){let s=1;if(s+=r.directives.conditionals*0.1,s+=r.directives.loops*0.5,s+=r.directives.includes*2,s+=r.expressions*0.05,s+=r.components*1,r.scriptLines>10)s+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(s>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function Kt(t,r,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function yi(t=["**/*.stx"],r){let s=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);s.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=Vn(s);return{results:s,summary:a}}function Vn(t){let r=t.length,s=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as qn,readFile as Xn,readdir as Gn,stat as Xt,writeFile as Jn}from"fs/promises";import Re from"path";function en(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 tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function er(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let r=[];async function s(p){let a=await Gn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=Re.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await s(t),r}function or(t,r){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(tn.has(y))throw Error(`${r}: client ${en(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return s}function ir(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Gt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
|
|
@@ -876,7 +876,7 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-
|
|
879
|
+
`}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-dbxq6fd7.js"),T=x(w.join(`
|
|
880
880
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
881
881
|
`+v.slice(k);else v+=`
|
|
882
882
|
${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qn(f,v,u,s),s.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new ie(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),bn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:s.debug||W()?`<!DOCTYPE html>
|
|
@@ -939,7 +939,7 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Q
|
|
|
939
939
|
<h1>Something went wrong</h1>
|
|
940
940
|
<p>An internal error occurred. Please try again later.</p>
|
|
941
941
|
</body>
|
|
942
|
-
</html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-
|
|
942
|
+
</html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-4ntt6d6q.js"),j=await _();if(T=r.stxOptions?.serverApi??j.serverApi,j?.apiRouter)x=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){v=j.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-9rv27cdd.js"),we=j.broadcasting;await K(we);let le=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);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(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:I}=await import("./chunk-w0zrp51m.js"),A=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let M=Nr({port:C,async fetch(_){return kn(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>I(ge.join(ne,j.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[j.pathname])try{return await v[j.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await A(_);if(K)return K;if(j.pathname==="/")return(async()=>{let F=await h(m||"");if(a)F=Ne(F,f);if(r.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(r.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(y,j.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),L="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":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let we=ge.dirname(u),le=ge.join(we,j.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),L="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":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Pe=ge.join(process.cwd(),"public",j.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),L="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":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
943
943
|
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${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(`
|
|
945
945
|
${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
|
|
@@ -1426,12 +1426,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1426
1426
|
${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(`
|
|
1427
1427
|
${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
|
|
1428
1428
|
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",I=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${I}`)}),console.log(`
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".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(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-bhm9sdnv.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-zf6kmw9q.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${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 ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-bhm9sdnv.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);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 we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.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,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-bhm9sdnv.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-bxr4c8rg.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-bhm9sdnv.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-qjmvcqfh.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-mn9xw0fe.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).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 Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.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:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.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(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{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",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-mn9xw0fe.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);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 I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.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;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1429
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".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(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-4ntt6d6q.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-w0zrp51m.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${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 ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-4ntt6d6q.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);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 we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.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,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-4ntt6d6q.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-j7phk6kh.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-4ntt6d6q.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-dbxq6fd7.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-ejphs9fs.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).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 Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.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:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.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(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{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",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-ejphs9fs.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);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 I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.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;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1430
1430
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1431
1431
|
${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(`
|
|
1432
1432
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
|
|
1433
1433
|
${e.yellow}Routes:${e.reset}`);let Mt=[...ss(k,u)];for(let{route:P}of A)Mt.push(`${P.pattern}`);if(Mt.forEach((P,H)=>{let Q=H===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
|
|
1434
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}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,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}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,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-j7phk6kh.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(_&&V){if(te.resolve(N,V)===_||te.basename(_)===V){let G=await Hs(_,r.stxOptions||{});if(G)E=G}}if(await ze(),await Kn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-j7phk6kh.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await ze(),a&&l)l.reload(V)}}else if(yt(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(l)st();Dt.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Vr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
|
|
1435
1435
|
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function qr(t){try{let r=await Bun.file(t).text(),s=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
|
|
1436
1436
|
`).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,r=!1,s){let p=it.basename(t,".stx"),a=await Vr(t),l=await qr(t),f="";if(r&&s)f=`<${s}></${s}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
|
|
1437
1437
|
`);f=`<${p}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gc,mc}from"./chunk-gtktv6nn.js";import{j,cs,ls,us,To,$o,ar,Ie,de,G,ps,oe,X,H,et,lr,Io,pr,je,n,d,V,mn}from"./chunk-t3e5tv4h.js";import{p,E,tt,u}from"./chunk-3tp7r57c.js";import{re}from"./chunk-wt6f9pk9.js";import{r}from"./chunk-9tg4995v.js";import{f}from"./chunk-b7e07ybq.js";import{createHash as Ct}from"crypto";import ee from"fs";import Q from"path";import{decode as sn,generateThumbHash as on}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import Te from"fs";function Ce(e,t,s){let i=Buffer.alloc(s),o=Te.readSync(e,i,0,s,t);return i.subarray(0,o)}function De(e){if(e.length<25)return!1;let t=(i,o)=>String.fromCharCode(...e.subarray(i,o));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let s=t(12,16);if(s==="VP8X")return(e[20]&16)!==0;if(s==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Me(e){let t;try{t=Te.openSync(e,"r");let s=Ce(t,0,33);if(s.length>=3&&s[0]===255&&s[1]===216&&s[2]===255)return"none";if(s.length>=26&&s[0]===137&&s.toString("latin1",1,4)==="PNG"){let i=s[25];if(i===4||i===6)return"possible";let o=8;for(let a=0;a<64;a++){let c=Ce(t,o,8);if(c.length<8)return"unknown";let g=c.toString("latin1",4,8);if(g==="tRNS")return"possible";if(g==="IDAT"||g==="IEND")return"none";o+=12+c.readUInt32BE(0)}return"unknown"}if(s.length>=25&&s.toString("latin1",0,4)==="RIFF"&&s.toString("latin1",8,12)==="WEBP"){if(De(s))return"possible";let i=s.toString("latin1",12,16);return i==="VP8 "||i==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)Te.closeSync(t)}}import Jt from"fs";import Re from"os";import{join as dt}from"path";import{fileURLToPath as gt}from"url";import{Worker as mt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Yt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function Qt(){if(Ae<Yt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function en(){Ae--,ht.shift()?.()}var tn="@stacksjs/stx/builtins/image-warmup-worker";function nn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let s=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(s.protocol==="file:"&&Jt.existsSync(gt(s)))return gt(s)}catch{}try{let s=typeof Bun<"u"?Bun.resolveSync(tn,e):void 0;return s&&rn(s)?s:void 0}catch{return}}function rn(e,t=process.env){let s=e.replace(/\\/g,"/");if(s.split("/").some((o)=>/@\d[^/]*@@@\d+$/.test(o)))return!1;return![t.BUN_INSTALL_CACHE_DIR,dt(t.BUN_INSTALL||dt(Re.homedir(),".bun"),"install","cache")].filter((o)=>!!o).map((o)=>`${o.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((o)=>s.startsWith(o))}var pt=!1;function pe(e){if(!pt)pt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return ke}function Le(e){return e instanceof Error?e.message:String(e)}async function ze(e,t){if(typeof mt!=="function")return pe("node:worker_threads has no Worker in this runtime");let s=nn();if(!s)return pe("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await Qt();try{return await new Promise((i,o)=>{let a;try{a=new mt(s)}catch(h){i(pe(`could not start ${s}: ${Le(h)}`));return}let c=!1,g=!1,l=(h)=>{if(g)return;g=!0,h(),a.terminate()};a.on("message",(h)=>{if(h.type==="ready"){c=!0,a.postMessage({task:e,args:t});return}if(h.type==="result"){l(()=>i(h.value));return}let v=Error(h.error?.message??"image worker failed");if(h.error?.name)v.name=h.error.name;if(h.error?.stack)v.stack=h.error.stack;l(()=>o(v))}),a.on("error",(h)=>{l(()=>c?o(h instanceof Error?h:Error(Le(h)||"image worker crashed")):i(pe(`the worker failed before it was ready: ${Le(h)}`)))}),a.on("exit",(h)=>{l(()=>c?o(Error("image worker exited before it finished")):i(pe(`the worker exited with code ${h} before it was ready`)))})})}finally{en()}}var an=new Set([".avif",".jpeg",".jpg",".png",".webp"]),cn=[320,640,960,1280,1920],he="/_stx/images",ln=`stx:${he}:alpha-1`,un=`stx:${he}:opaque-1`,fn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function dn(e,t){let s=Q.dirname(Bun.resolveSync(e,t));while(s!==Q.dirname(s)){let i=Q.join(s,"package.json");if(ee.existsSync(i)){let o=JSON.parse(ee.readFileSync(i,"utf8"));if(o.name===e)return o.version}s=Q.dirname(s)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=Q.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=fn.map((t)=>{let s;try{s=e?dn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${s??"unknown"}`}).join("+"),Pe}var bt=Symbol.for("stx.image-delivery");function ye(){let e=globalThis;return e[bt]??={catalog:new Map,transparent:new Set},e[bt]}var vt=new Set;function gn(e){return`/${e.split(Q.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=Q.extname(e),s=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),i=Ct("sha256").update(e).digest("hex").slice(0,8);return`${s||"image"}-${i}`}function wt(e,t=`stx:${he}`){let s=(i)=>`${he}/${i.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(i){let o=Q.join(e,i);try{let a=await ee.promises.stat(o);return a.size>0?{bytes:a.size,path:o,url:s(i)}:null}catch{return null}},async write(i,o){let a=Q.join(e,i);await ee.promises.mkdir(Q.dirname(a),{recursive:!0});let c=`${a}.${process.pid}.tmp`;return await ee.promises.writeFile(c,o),await ee.promises.rename(c,a),{bytes:o.byteLength,path:a,url:s(i)}},url:s}}async function Rt(e,t=e){let s=await ee.promises.readdir(t,{withFileTypes:!0});s.sort((o,a)=>o.name.localeCompare(a.name));let i=[];for(let o of s){let a=Q.join(t,o.name);if(o.isDirectory()){i.push(...await Rt(e,a));continue}if(!o.isFile()||!an.has(Q.extname(o.name).toLowerCase()))continue;i.push({absolutePath:a,relativePath:Q.relative(e,a)})}return i}function $t(e,t){return e.map((s)=>({key:gn(s.relativePath),input:s.absolutePath,name:pn(s.relativePath),...hn(s.absolutePath)?{options:{storage:t}}:{}}))}function hn(e){return Me(e)==="possible"}function yn(e){for(let t=3;t<e.length;t+=4)if(e[t]!==255)return!0;return!1}async function xn(e){let t=Object.entries(e).filter(([,o])=>o.fallback.format==="png"),s=new Set,i=8;for(let o=0;o<t.length;o+=8)await Promise.all(t.slice(o,o+8).map(async([a,c])=>{let g=c.variants.filter((l)=>l.format==="png").sort((l,h)=>l.width-h.width)[0];try{let l=await sn(new Uint8Array(await ee.promises.readFile(g?.path??c.fallback.path)));if(yn(l.data))s.add(a)}catch{s.add(a)}}));return s}function bn(e,t){let s=[];for(let i of t){let o=e[i],a=o?.variants.filter((g)=>g.format==="webp")??[];if(!o||a.length===0)continue;if(!a.some((g)=>{let l;try{return l=ee.openSync(g.path,"r"),!De(Ce(l,0,32))}catch{return!0}finally{if(l!==void 0)ee.closeSync(l)}}))continue;if(o.variants=o.variants.filter((g)=>g.format!=="webp"),delete o.sources.webp,s.push(i),!vt.has(i))vt.add(i),console.warn(`[stx-images] ${i} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return s}async function vn(e){let t=[],s=8;for(let i=0;i<e.length;i+=8){let o=e.slice(i,i+8),a=await Promise.all(o.map(async(c)=>{try{return await on(c.absolutePath),c}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${c.relativePath}`),null}}));t.push(...a.filter((c)=>c!==null))}return t}function Ue(e){return Q.join(e,"undecodable.json")}function wn(e){try{let t=ee.readFileSync(Ue(e),"utf-8"),s=JSON.parse(t);return s&&typeof s==="object"?s:{}}catch{return{}}}function $n(e,t){try{ee.mkdirSync(Q.dirname(Ue(e)),{recursive:!0}),ee.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function St(e){try{let t=ee.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function At(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let t=e.split(/[?#]/,1)[0];if(!t)return;try{return`/${t.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function so(e){let t=At(e);return t?ye().catalog.get(t):void 0}function oo(e){let t=At(e);return t?ye().transparent.has(t):!1}function io(e){let t=(i)=>e.variants.filter((o)=>o.format===i).reduce((o,a)=>o+a.bytes,0),s=t(e.fallback.format);return["avif","webp"].map((i)=>({format:i,srcset:e.sources[i]||"",bytes:t(i)})).filter((i)=>i.srcset&&i.bytes>0&&i.bytes<s).sort((i,o)=>i.bytes-o.bytes).map(({format:i,srcset:o})=>({format:i,srcset:o}))}function hp(e){let t=so(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:io(t).map(({format:s,srcset:i})=>({type:`image/${s}`,srcset:i})),width:t.source.width,height:t.source.height,placeholder:oo(e)?void 0:t.placeholder?.dataUrl}}function Hr(){let e=ye();e.catalog=new Map,e.transparent=new Set}function Sn(e){let t=ye();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function yp(e,t,s={}){if(!e||!ee.existsSync(e))return Hr(),{count:0,fingerprint:""};if(s.offThread){let m=await ze("delivery",{publicDir:e,outputDir:t});if(m!==ke)return Sn(m.state),m.result}let i=await Rt(e);if(i.length===0)return Hr(),{count:0,fingerprint:""};let o=wn(t),a=i.filter((m)=>{let b=o[m.relativePath];if(!b)return!0;let w=St(m.absolutePath);return!w||w.mtimeMs!==b.mtimeMs||w.size!==b.size});if(a.length===0)return Hr(),{count:0,fingerprint:""};let c=wt(Q.join(t,"_stx","images"),`${ln}:${xt()}`),g={outDir:Q.join(t,"_stx","images"),storage:wt(Q.join(t,"_stx","images"),`${un}:${xt()}`),baseUrl:he,widths:cn,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},l=a,h;try{h=await yt({...g,entries:$t(a,c)})}catch(m){if(l=await vn(a),l.length===a.length)throw m;let b=new Set(l.map((C)=>C.relativePath)),w=!1;for(let C of a){if(b.has(C.relativePath))continue;let k=St(C.absolutePath);if(!k)continue;o[C.relativePath]=k,w=!0}if(w)$n(t,o);if(l.length===0)return Hr(),{count:0,fingerprint:""};h=await yt({...g,entries:$t(l,c)})}let v=await xn(h.entries),y=bn(h.entries,v),S=ye();S.catalog=new Map(Object.entries(h.entries)),S.transparent=v;let x=v.size===0&&y.length===0?h.fingerprint:Ct("sha256").update(h.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:y.sort()})).digest("hex");return{count:l.length,fingerprint:x}}class kt{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let t of e.aliases)this.builtins.set(t.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,t,s,i){let o=To(e,i);if(o!==void 0)return o;for(let a of $o(e,t,s,i))if(await n(a))return a;return null}}var le=new kt;function R(e){return V(e)}var se="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Cn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function Fe(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Cn.has(t)}function ie(e,t){let s=[];for(let[i,o]of Object.entries(e.static)){if(t.has(i))continue;let a=e.staticNames?.[i]??i;if(typeof o==="boolean"){if(o)s.push(d(a));continue}if(o===se){s.push(d(a));continue}s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function ae(e,t){let s=[];for(let[i,o]of Object.entries(e.serverDynamic??{})){if(t.has(i))continue;if(o===null||o===void 0||o===!1)continue;let a=e.serverDynamicNames?.[i]??i;if(o===!0){s.push(d(a));continue}if(typeof o==="object")continue;s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function Rn(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var He={name:"StxLink",aliases:["stx-link"],render(e,t,s){let i=Rn(e),o=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),a=typeof e.static.activeClass==="string"?e.static.activeClass:"active",c=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",g=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,l=[];if(i.reactive)l.push(`:href="${R(i.value)}"`);else l.push(`href="${R(ar(i.value,"navigable"))}"`);if(o)l.push(`class="${R(o)}"`);if(l.push("data-stx-link"),l.push(`data-stx-active-class="${R(a)}"`),l.push(`data-stx-exact-active-class="${R(c)}"`),g)l.push("data-stx-prefetch");let h=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(h)l.push(`data-stx-active-match="${R(h)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return l.push(...ie(e,v)),l.push(...ae(e,v)),`<a ${l.join(" ")}>${t}</a>`}};var An=new Map;function qe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return An.get(t)}var kn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Xe=[320,640,768,1024,1280,1536,1920];function J(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let s=e.static[t];if(typeof s==="string")return s;return}function _e(e,t,s=!1){let i=e.serverDynamic[t];if(i!==void 0)return i!==!1&&i!=="false";let o=e.static[t];if(o!==void 0)return o!=="false"&&o!==!1;return s}function Ze(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),s=[];for(let i of t)if(i.includes(":")){let[o,a]=i.split(":"),c=kn[o];if(c)s.push(`(max-width: ${c}px) ${a}`);else{let g=Number.parseInt(o);if(!Number.isNaN(g))s.push(`(max-width: ${g}px) ${a}`)}}else s.push(i);return s.join(", ")}function Ve(e,t,s,i){return t.map((o)=>`${xe(e,o,void 0,s,i)} ${o}w`).join(", ")}function Pn(e,t,s,i,o){return t.map((a)=>{let c=s?s*a:void 0;return`${xe(e,c,void 0,i,o)} ${a}x`}).join(", ")}function xe(e,t,s,i,o){if(!i||i==="local"||i==="static")return e;if(i==="cloudinary"){let a=[];if(t)a.push(`w_${t}`);if(s)a.push(`h_${s}`);if(o)a.push(`f_${o}`);a.push("q_auto");let c=a.join(",");return e.replace("/upload/",`/upload/${c}/`)}if(i==="imgix"){let a=new URLSearchParams;if(t)a.set("w",String(t));if(s)a.set("h",String(s));if(o)a.set("fm",o);a.set("auto","format");let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}if(i==="bunny"){let a=new URLSearchParams;if(t)a.set("width",String(t));if(s)a.set("height",String(s));if(o)a.set("format",o);let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function In(e,t,s="#e5e7eb"){let i=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${s}"/></svg>`;return`data:image/svg+xml;base64,${btoa(i)}`}var Ge={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,s){let i=J(e,"src")||"",o=so(i),a=J(e,"alt")||"",c=J(e,"width")||(o?String(o.source.width):void 0),g=J(e,"height")||(o?String(o.source.height):void 0),l=J(e,"sizes"),h=J(e,"srcset"),v=J(e,"densities"),y=J(e,"format"),S=oo(i)||qe(i)?.transparent===!0,x=J(e,"placeholder")||(o&&!S?"thumbhash":void 0),m=J(e,"placeholderColor")||"#e5e7eb",b=J(e,"provider"),w=J(e,"class")||J(e,"className")||"",C=J(e,"style")||"",k=J(e,"objectFit")||J(e,"fit"),A=J(e,"objectPosition")||J(e,"position"),I=J(e,"quality"),U=_e(e,"lazy",!0),M=_e(e,"preload",!1),L=_e(e,"priority",!1),q=J(e,"loading"),N=J(e,"decoding")||"async",_=!!o||_e(e,"picture",!1)||!!y,O=c?Number.parseInt(c):void 0,B=g?Number.parseInt(g):void 0,z=h||"",K="";if(o)z=o.sources[o.fallback.format]||"",K=l?Ze(l):"100vw";else if(!z&&l&&b&&b!=="local"&&b!=="static")z=Ve(i,Xe,b,y),K=Ze(l);else if(!z&&v){let P=v.split(/\s+/).map((F)=>Number.parseFloat(F.replace("x","")));z=Pn(i,P,O,b,y)}else if(l)K=Ze(l);let D=[];if(C)D.push(C);if(k)D.push(`object-fit:${k}`);if(A)D.push(`object-position:${A}`);if(O&&B)D.push(`aspect-ratio:${O}/${B}`);let W=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!S){let P=o?.placeholder?{dataUrl:o.placeholder.dataUrl,color:m}:qe(i);if(P&&x==="color")D.push(`background-color:${P.color}`),W.push("backgroundColor");else if(P)D.push(`background-color:${P.color}`),D.push(`background-image:url(${P.dataUrl})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundColor","backgroundImage");else{let F=In(O||16,B||9,m);D.push(`background-image:url(${F})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")D.push(`background-image:url(${R(x)})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage");let we=o?.fallback.url||xe(i,O,B,b,y),Y=[];if(Y.push(`src="${R(ar(we,"fetched"))}"`),Y.push(`alt="${R(a)}"`),c)Y.push(`width="${R(c)}"`);if(g)Y.push(`height="${R(g)}"`);let ne=q||(L||M?"eager":U?"lazy":"");if(ne)Y.push(`loading="${R(ne)}"`);if(L)Y.push('fetchpriority="high"');if(Y.push(`decoding="${R(N)}"`),w)Y.push(`class="${R(w)}"`);if(D.length>0)Y.push(`style="${R(D.join(";"))}"`);if(z)Y.push(`srcset="${R(ar(z,"fetched"))}"`);if(K)Y.push(`sizes="${R(K)}"`);let $e=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(W.length>0){let P=typeof e.static.onload==="string"?e.static.onload:"",F=_n(W)+(P?`;${P}`:"");Y.push(`onload="${R(F)}"`),$e.add("onload")}Y.push(...ie(e,$e)),Y.push(...ae(e,$e));let T=`<img ${Y.join(" ")} />`,Z="";if(M){let F=y==="webp"?"image/webp":y==="avif"?"image/avif":"";Z=`<link rel="preload" as="image" href="${R(we)}"${F?` type="${F}"`:""}${z?` imagesrcset="${R(z)}"`:""}${K?` imagesizes="${R(K)}"`:""} />
|
|
2
|
+
import{gc,mc}from"./chunk-gtktv6nn.js";import{j,cs,ls,us,To,$o,ar,Ie,de,G,ps,oe,X,H,et,lr,Io,pr,je,n,d,V,mn}from"./chunk-xw0cqb5m.js";import{p,E,tt,u}from"./chunk-r0ys9aqa.js";import{re}from"./chunk-hx787tfa.js";import{r}from"./chunk-9tg4995v.js";import{f}from"./chunk-b7e07ybq.js";import{createHash as Ct}from"crypto";import ee from"fs";import Q from"path";import{decode as sn,generateThumbHash as on}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import Te from"fs";function Ce(e,t,s){let i=Buffer.alloc(s),o=Te.readSync(e,i,0,s,t);return i.subarray(0,o)}function De(e){if(e.length<25)return!1;let t=(i,o)=>String.fromCharCode(...e.subarray(i,o));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let s=t(12,16);if(s==="VP8X")return(e[20]&16)!==0;if(s==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Me(e){let t;try{t=Te.openSync(e,"r");let s=Ce(t,0,33);if(s.length>=3&&s[0]===255&&s[1]===216&&s[2]===255)return"none";if(s.length>=26&&s[0]===137&&s.toString("latin1",1,4)==="PNG"){let i=s[25];if(i===4||i===6)return"possible";let o=8;for(let a=0;a<64;a++){let c=Ce(t,o,8);if(c.length<8)return"unknown";let g=c.toString("latin1",4,8);if(g==="tRNS")return"possible";if(g==="IDAT"||g==="IEND")return"none";o+=12+c.readUInt32BE(0)}return"unknown"}if(s.length>=25&&s.toString("latin1",0,4)==="RIFF"&&s.toString("latin1",8,12)==="WEBP"){if(De(s))return"possible";let i=s.toString("latin1",12,16);return i==="VP8 "||i==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)Te.closeSync(t)}}import Jt from"fs";import Re from"os";import{join as dt}from"path";import{fileURLToPath as gt}from"url";import{Worker as mt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Yt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function Qt(){if(Ae<Yt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function en(){Ae--,ht.shift()?.()}var tn="@stacksjs/stx/builtins/image-warmup-worker";function nn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let s=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(s.protocol==="file:"&&Jt.existsSync(gt(s)))return gt(s)}catch{}try{let s=typeof Bun<"u"?Bun.resolveSync(tn,e):void 0;return s&&rn(s)?s:void 0}catch{return}}function rn(e,t=process.env){let s=e.replace(/\\/g,"/");if(s.split("/").some((o)=>/@\d[^/]*@@@\d+$/.test(o)))return!1;return![t.BUN_INSTALL_CACHE_DIR,dt(t.BUN_INSTALL||dt(Re.homedir(),".bun"),"install","cache")].filter((o)=>!!o).map((o)=>`${o.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((o)=>s.startsWith(o))}var pt=!1;function pe(e){if(!pt)pt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return ke}function Le(e){return e instanceof Error?e.message:String(e)}async function ze(e,t){if(typeof mt!=="function")return pe("node:worker_threads has no Worker in this runtime");let s=nn();if(!s)return pe("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await Qt();try{return await new Promise((i,o)=>{let a;try{a=new mt(s)}catch(h){i(pe(`could not start ${s}: ${Le(h)}`));return}let c=!1,g=!1,l=(h)=>{if(g)return;g=!0,h(),a.terminate()};a.on("message",(h)=>{if(h.type==="ready"){c=!0,a.postMessage({task:e,args:t});return}if(h.type==="result"){l(()=>i(h.value));return}let v=Error(h.error?.message??"image worker failed");if(h.error?.name)v.name=h.error.name;if(h.error?.stack)v.stack=h.error.stack;l(()=>o(v))}),a.on("error",(h)=>{l(()=>c?o(h instanceof Error?h:Error(Le(h)||"image worker crashed")):i(pe(`the worker failed before it was ready: ${Le(h)}`)))}),a.on("exit",(h)=>{l(()=>c?o(Error("image worker exited before it finished")):i(pe(`the worker exited with code ${h} before it was ready`)))})})}finally{en()}}var an=new Set([".avif",".jpeg",".jpg",".png",".webp"]),cn=[320,640,960,1280,1920],he="/_stx/images",ln=`stx:${he}:alpha-1`,un=`stx:${he}:opaque-1`,fn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function dn(e,t){let s=Q.dirname(Bun.resolveSync(e,t));while(s!==Q.dirname(s)){let i=Q.join(s,"package.json");if(ee.existsSync(i)){let o=JSON.parse(ee.readFileSync(i,"utf8"));if(o.name===e)return o.version}s=Q.dirname(s)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=Q.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=fn.map((t)=>{let s;try{s=e?dn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${s??"unknown"}`}).join("+"),Pe}var bt=Symbol.for("stx.image-delivery");function ye(){let e=globalThis;return e[bt]??={catalog:new Map,transparent:new Set},e[bt]}var vt=new Set;function gn(e){return`/${e.split(Q.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=Q.extname(e),s=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),i=Ct("sha256").update(e).digest("hex").slice(0,8);return`${s||"image"}-${i}`}function wt(e,t=`stx:${he}`){let s=(i)=>`${he}/${i.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(i){let o=Q.join(e,i);try{let a=await ee.promises.stat(o);return a.size>0?{bytes:a.size,path:o,url:s(i)}:null}catch{return null}},async write(i,o){let a=Q.join(e,i);await ee.promises.mkdir(Q.dirname(a),{recursive:!0});let c=`${a}.${process.pid}.tmp`;return await ee.promises.writeFile(c,o),await ee.promises.rename(c,a),{bytes:o.byteLength,path:a,url:s(i)}},url:s}}async function Rt(e,t=e){let s=await ee.promises.readdir(t,{withFileTypes:!0});s.sort((o,a)=>o.name.localeCompare(a.name));let i=[];for(let o of s){let a=Q.join(t,o.name);if(o.isDirectory()){i.push(...await Rt(e,a));continue}if(!o.isFile()||!an.has(Q.extname(o.name).toLowerCase()))continue;i.push({absolutePath:a,relativePath:Q.relative(e,a)})}return i}function $t(e,t){return e.map((s)=>({key:gn(s.relativePath),input:s.absolutePath,name:pn(s.relativePath),...hn(s.absolutePath)?{options:{storage:t}}:{}}))}function hn(e){return Me(e)==="possible"}function yn(e){for(let t=3;t<e.length;t+=4)if(e[t]!==255)return!0;return!1}async function xn(e){let t=Object.entries(e).filter(([,o])=>o.fallback.format==="png"),s=new Set,i=8;for(let o=0;o<t.length;o+=8)await Promise.all(t.slice(o,o+8).map(async([a,c])=>{let g=c.variants.filter((l)=>l.format==="png").sort((l,h)=>l.width-h.width)[0];try{let l=await sn(new Uint8Array(await ee.promises.readFile(g?.path??c.fallback.path)));if(yn(l.data))s.add(a)}catch{s.add(a)}}));return s}function bn(e,t){let s=[];for(let i of t){let o=e[i],a=o?.variants.filter((g)=>g.format==="webp")??[];if(!o||a.length===0)continue;if(!a.some((g)=>{let l;try{return l=ee.openSync(g.path,"r"),!De(Ce(l,0,32))}catch{return!0}finally{if(l!==void 0)ee.closeSync(l)}}))continue;if(o.variants=o.variants.filter((g)=>g.format!=="webp"),delete o.sources.webp,s.push(i),!vt.has(i))vt.add(i),console.warn(`[stx-images] ${i} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return s}async function vn(e){let t=[],s=8;for(let i=0;i<e.length;i+=8){let o=e.slice(i,i+8),a=await Promise.all(o.map(async(c)=>{try{return await on(c.absolutePath),c}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${c.relativePath}`),null}}));t.push(...a.filter((c)=>c!==null))}return t}function Ue(e){return Q.join(e,"undecodable.json")}function wn(e){try{let t=ee.readFileSync(Ue(e),"utf-8"),s=JSON.parse(t);return s&&typeof s==="object"?s:{}}catch{return{}}}function $n(e,t){try{ee.mkdirSync(Q.dirname(Ue(e)),{recursive:!0}),ee.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function St(e){try{let t=ee.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function At(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let t=e.split(/[?#]/,1)[0];if(!t)return;try{return`/${t.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function so(e){let t=At(e);return t?ye().catalog.get(t):void 0}function oo(e){let t=At(e);return t?ye().transparent.has(t):!1}function io(e){let t=(i)=>e.variants.filter((o)=>o.format===i).reduce((o,a)=>o+a.bytes,0),s=t(e.fallback.format);return["avif","webp"].map((i)=>({format:i,srcset:e.sources[i]||"",bytes:t(i)})).filter((i)=>i.srcset&&i.bytes>0&&i.bytes<s).sort((i,o)=>i.bytes-o.bytes).map(({format:i,srcset:o})=>({format:i,srcset:o}))}function hp(e){let t=so(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:io(t).map(({format:s,srcset:i})=>({type:`image/${s}`,srcset:i})),width:t.source.width,height:t.source.height,placeholder:oo(e)?void 0:t.placeholder?.dataUrl}}function Hr(){let e=ye();e.catalog=new Map,e.transparent=new Set}function Sn(e){let t=ye();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function yp(e,t,s={}){if(!e||!ee.existsSync(e))return Hr(),{count:0,fingerprint:""};if(s.offThread){let m=await ze("delivery",{publicDir:e,outputDir:t});if(m!==ke)return Sn(m.state),m.result}let i=await Rt(e);if(i.length===0)return Hr(),{count:0,fingerprint:""};let o=wn(t),a=i.filter((m)=>{let b=o[m.relativePath];if(!b)return!0;let w=St(m.absolutePath);return!w||w.mtimeMs!==b.mtimeMs||w.size!==b.size});if(a.length===0)return Hr(),{count:0,fingerprint:""};let c=wt(Q.join(t,"_stx","images"),`${ln}:${xt()}`),g={outDir:Q.join(t,"_stx","images"),storage:wt(Q.join(t,"_stx","images"),`${un}:${xt()}`),baseUrl:he,widths:cn,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},l=a,h;try{h=await yt({...g,entries:$t(a,c)})}catch(m){if(l=await vn(a),l.length===a.length)throw m;let b=new Set(l.map((C)=>C.relativePath)),w=!1;for(let C of a){if(b.has(C.relativePath))continue;let k=St(C.absolutePath);if(!k)continue;o[C.relativePath]=k,w=!0}if(w)$n(t,o);if(l.length===0)return Hr(),{count:0,fingerprint:""};h=await yt({...g,entries:$t(l,c)})}let v=await xn(h.entries),y=bn(h.entries,v),S=ye();S.catalog=new Map(Object.entries(h.entries)),S.transparent=v;let x=v.size===0&&y.length===0?h.fingerprint:Ct("sha256").update(h.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:y.sort()})).digest("hex");return{count:l.length,fingerprint:x}}class kt{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let t of e.aliases)this.builtins.set(t.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,t,s,i){let o=To(e,i);if(o!==void 0)return o;for(let a of $o(e,t,s,i))if(await n(a))return a;return null}}var le=new kt;function R(e){return V(e)}var se="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Cn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function Fe(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Cn.has(t)}function ie(e,t){let s=[];for(let[i,o]of Object.entries(e.static)){if(t.has(i))continue;let a=e.staticNames?.[i]??i;if(typeof o==="boolean"){if(o)s.push(d(a));continue}if(o===se){s.push(d(a));continue}s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function ae(e,t){let s=[];for(let[i,o]of Object.entries(e.serverDynamic??{})){if(t.has(i))continue;if(o===null||o===void 0||o===!1)continue;let a=e.serverDynamicNames?.[i]??i;if(o===!0){s.push(d(a));continue}if(typeof o==="object")continue;s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function Rn(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var He={name:"StxLink",aliases:["stx-link"],render(e,t,s){let i=Rn(e),o=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),a=typeof e.static.activeClass==="string"?e.static.activeClass:"active",c=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",g=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,l=[];if(i.reactive)l.push(`:href="${R(i.value)}"`);else l.push(`href="${R(ar(i.value,"navigable"))}"`);if(o)l.push(`class="${R(o)}"`);if(l.push("data-stx-link"),l.push(`data-stx-active-class="${R(a)}"`),l.push(`data-stx-exact-active-class="${R(c)}"`),g)l.push("data-stx-prefetch");let h=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(h)l.push(`data-stx-active-match="${R(h)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return l.push(...ie(e,v)),l.push(...ae(e,v)),`<a ${l.join(" ")}>${t}</a>`}};var An=new Map;function qe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return An.get(t)}var kn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Xe=[320,640,768,1024,1280,1536,1920];function J(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let s=e.static[t];if(typeof s==="string")return s;return}function _e(e,t,s=!1){let i=e.serverDynamic[t];if(i!==void 0)return i!==!1&&i!=="false";let o=e.static[t];if(o!==void 0)return o!=="false"&&o!==!1;return s}function Ze(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),s=[];for(let i of t)if(i.includes(":")){let[o,a]=i.split(":"),c=kn[o];if(c)s.push(`(max-width: ${c}px) ${a}`);else{let g=Number.parseInt(o);if(!Number.isNaN(g))s.push(`(max-width: ${g}px) ${a}`)}}else s.push(i);return s.join(", ")}function Ve(e,t,s,i){return t.map((o)=>`${xe(e,o,void 0,s,i)} ${o}w`).join(", ")}function Pn(e,t,s,i,o){return t.map((a)=>{let c=s?s*a:void 0;return`${xe(e,c,void 0,i,o)} ${a}x`}).join(", ")}function xe(e,t,s,i,o){if(!i||i==="local"||i==="static")return e;if(i==="cloudinary"){let a=[];if(t)a.push(`w_${t}`);if(s)a.push(`h_${s}`);if(o)a.push(`f_${o}`);a.push("q_auto");let c=a.join(",");return e.replace("/upload/",`/upload/${c}/`)}if(i==="imgix"){let a=new URLSearchParams;if(t)a.set("w",String(t));if(s)a.set("h",String(s));if(o)a.set("fm",o);a.set("auto","format");let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}if(i==="bunny"){let a=new URLSearchParams;if(t)a.set("width",String(t));if(s)a.set("height",String(s));if(o)a.set("format",o);let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function In(e,t,s="#e5e7eb"){let i=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${s}"/></svg>`;return`data:image/svg+xml;base64,${btoa(i)}`}var Ge={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,s){let i=J(e,"src")||"",o=so(i),a=J(e,"alt")||"",c=J(e,"width")||(o?String(o.source.width):void 0),g=J(e,"height")||(o?String(o.source.height):void 0),l=J(e,"sizes"),h=J(e,"srcset"),v=J(e,"densities"),y=J(e,"format"),S=oo(i)||qe(i)?.transparent===!0,x=J(e,"placeholder")||(o&&!S?"thumbhash":void 0),m=J(e,"placeholderColor")||"#e5e7eb",b=J(e,"provider"),w=J(e,"class")||J(e,"className")||"",C=J(e,"style")||"",k=J(e,"objectFit")||J(e,"fit"),A=J(e,"objectPosition")||J(e,"position"),I=J(e,"quality"),U=_e(e,"lazy",!0),M=_e(e,"preload",!1),L=_e(e,"priority",!1),q=J(e,"loading"),N=J(e,"decoding")||"async",_=!!o||_e(e,"picture",!1)||!!y,O=c?Number.parseInt(c):void 0,B=g?Number.parseInt(g):void 0,z=h||"",K="";if(o)z=o.sources[o.fallback.format]||"",K=l?Ze(l):"100vw";else if(!z&&l&&b&&b!=="local"&&b!=="static")z=Ve(i,Xe,b,y),K=Ze(l);else if(!z&&v){let P=v.split(/\s+/).map((F)=>Number.parseFloat(F.replace("x","")));z=Pn(i,P,O,b,y)}else if(l)K=Ze(l);let D=[];if(C)D.push(C);if(k)D.push(`object-fit:${k}`);if(A)D.push(`object-position:${A}`);if(O&&B)D.push(`aspect-ratio:${O}/${B}`);let W=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!S){let P=o?.placeholder?{dataUrl:o.placeholder.dataUrl,color:m}:qe(i);if(P&&x==="color")D.push(`background-color:${P.color}`),W.push("backgroundColor");else if(P)D.push(`background-color:${P.color}`),D.push(`background-image:url(${P.dataUrl})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundColor","backgroundImage");else{let F=In(O||16,B||9,m);D.push(`background-image:url(${F})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")D.push(`background-image:url(${R(x)})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage");let we=o?.fallback.url||xe(i,O,B,b,y),Y=[];if(Y.push(`src="${R(ar(we,"fetched"))}"`),Y.push(`alt="${R(a)}"`),c)Y.push(`width="${R(c)}"`);if(g)Y.push(`height="${R(g)}"`);let ne=q||(L||M?"eager":U?"lazy":"");if(ne)Y.push(`loading="${R(ne)}"`);if(L)Y.push('fetchpriority="high"');if(Y.push(`decoding="${R(N)}"`),w)Y.push(`class="${R(w)}"`);if(D.length>0)Y.push(`style="${R(D.join(";"))}"`);if(z)Y.push(`srcset="${R(ar(z,"fetched"))}"`);if(K)Y.push(`sizes="${R(K)}"`);let $e=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(W.length>0){let P=typeof e.static.onload==="string"?e.static.onload:"",F=_n(W)+(P?`;${P}`:"");Y.push(`onload="${R(F)}"`),$e.add("onload")}Y.push(...ie(e,$e)),Y.push(...ae(e,$e));let T=`<img ${Y.join(" ")} />`,Z="";if(M){let F=y==="webp"?"image/webp":y==="avif"?"image/avif":"";Z=`<link rel="preload" as="image" href="${R(we)}"${F?` type="${F}"`:""}${z?` imagesrcset="${R(z)}"`:""}${K?` imagesizes="${R(K)}"`:""} />
|
|
3
3
|
`}if(_){let P=[];if(o)for(let F of io(o))P.push(`<source type="image/${F.format}" srcset="${R(F.srcset)}"${K?` sizes="${R(K)}"`:""} />`);if(!o&&(y==="avif"||y==="auto")){let F=xe(i,O,B,b,"avif"),te=z?Ve(i,Xe,b,"avif"):`${F}`;P.push(`<source type="image/avif" srcset="${R(te)}"${K?` sizes="${R(K)}"`:""} />`)}if(!o&&(y==="webp"||y==="auto")){let F=xe(i,O,B,b,"webp"),te=z?Ve(i,Xe,b,"webp"):`${F}`;P.push(`<source type="image/webp" srcset="${R(te)}"${K?` sizes="${R(K)}"`:""} />`)}return`${Z}<picture>
|
|
4
4
|
${P.join(`
|
|
5
5
|
`)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Bt}from"./chunk-
|
|
2
|
+
import{Bt}from"./chunk-kq1hmpgb.js";function Rs(e){let n=e.pwa;if(!n?.enabled)return"";let r=n.manifest,t=n.icons?.outputDir?`/${n.icons.outputDir}`:"/pwa-icons",o=Bt(e),i=`
|
|
3
3
|
<!-- stx PWA Meta Tags -->
|
|
4
4
|
<link rel="manifest" href="/manifest.json">
|
|
5
5
|
<meta name="theme-color" content="${a(r?.themeColor||"#000000")}">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{l,p,E,u,U}from"./chunk-
|
|
2
|
+
import{l,p,E,u,U}from"./chunk-r0ys9aqa.js";import{L,is,B,Pe,ue,ur,Me,Le,n,m,we,x}from"./chunk-xw0cqb5m.js";import{st}from"./chunk-gtktv6nn.js";import{T}from"./chunk-6beg47t4.js";import{re}from"./chunk-hx787tfa.js";import{K,Ge}from"./chunk-yft8yn6y.js";import{C,wn}from"./chunk-078as147.js";import A from"path";import{existsSync as St}from"fs";function at(a,t){let c=0;for(let i=t;i<a.length;i++){let S=a[i];if(S==="("||S==="["||S==="{")c++;else if(S===")"||S==="]"||S==="}")c--;else if(S===","&&c===0)return i}return-1}function yt(a,t,c){let i=a,S=new RegExp(`${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\(`,"g"),s=S.exec(i);while(s){let f=s.index,e=f+s[0].length-1,D=1,Z=e+1;while(Z<i.length&&D>0){if(i[Z]==="(")D++;else if(i[Z]===")")D--;Z++}if(D!==0)break;let it=i.substring(e+1,Z-1),j=`${c}(${it})`;i=i.substring(0,f)+j+i.substring(Z),S.lastIndex=f+j.length,s=S.exec(i)}return i}function $t(a){return/\b(state|derived|effect)\s*(?:<[^<>()]*>)?\s*\(/.test(a)}function mt(a){let t=a,c=[],i=new Set,S=0,s=0,f=t.length,e=(j)=>{s++;while(s<f){if(t[s]==="\\"){s+=2;continue}if(t[s]===j){s++;return}s++}},D=()=>{s++;while(s<f){if(t[s]==="\\"){s+=2;continue}if(t[s]==="`"){s++;return}if(t[s]==="$"&&t[s+1]==="{"){s+=2;let j=1;while(s<f&&j>0)if(t[s]==="{")j++,s++;else if(t[s]==="}")j--,s++;else if(t[s]==="'"||t[s]==='"')e(t[s]);else if(t[s]==="`")D();else s++;continue}s++}},Z=()=>{if(t[s]==="/"&&t[s+1]==="/"){while(s<f&&t[s]!==`
|
|
3
3
|
`)s++;return!0}if(t[s]==="/"&&t[s+1]==="*"){s+=2;while(s<f-1&&!(t[s]==="*"&&t[s+1]==="/"))s++;return s+=2,!0}return!1},it=()=>{if(S!==0)return;let j=t.slice(s).match(/^(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=/);if(j){let H=j[2];if(!i.has(H))c.push(H),i.add(H);return}let et=t.slice(s).match(/^function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/);if(et){let H=et[1];if(!i.has(H))c.push(H),i.add(H);return}let Y=t.slice(s).match(/^async\s+function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/);if(Y){let H=Y[1];if(!i.has(H))c.push(H),i.add(H)}};while(s<f){if(Z())continue;if(t[s]==="'"||t[s]==='"'){e(t[s]);continue}if(t[s]==="`"){D();continue}if(t[s]==="{"){S++,s++;continue}if(t[s]==="}"){S--,s++;continue}if(S===0&&/[a-z]/i.test(t[s])&&(s===0||/\s|[;{}()]/.test(t[s-1])))it();s++}return c.join(", ")}function Et(a,t=""){let c=mt(a).split(",").map((i)=>i.trim()).filter(Boolean);return`
|
|
4
4
|
(function() {
|
|
5
5
|
${st("var",c)}
|
|
@@ -44,10 +44,10 @@ ${s}
|
|
|
44
44
|
}
|
|
45
45
|
if (typeof window !== 'undefined') window.__STX_CURRENT_ELEMENT__ = __stxPrevEl;
|
|
46
46
|
}
|
|
47
|
-
})();`;return c+a+i}function It(a,t){if(K(a)){let S=K(a).tag.match(/data-stx-scope="([^"]*)"/);if(S)return{html:a,mergedIntoExisting:S[1],stamped:!0,root:"body"};return{html:Ge(a,(s,f)=>`<body${f} data-stx-scope="${t}">`),mergedIntoExisting:null,stamped:!0,root:"body"}}let c=a.match(/^(\s*(?:(?:<!--[\s\S]*?-->|\x00STX_HTML_COMMENT_\d+\x00)\s*)*)(<[a-zA-Z][a-zA-Z0-9-]*)(\s[^>]*>|>)/s);if(c){let i=c[2]+c[3],S=c[2].slice(1),s=i.match(/data-stx-scope="([^"]*)"/);if(s)return{html:a,mergedIntoExisting:s[1],stamped:!0,root:S};let f=c[1],e=c[2],D=c[3];return{html:`${f}${e} data-stx-scope="${t}"${D}${a.slice(c[0].length)}`,mergedIntoExisting:null,stamped:!0,root:S}}return{html:a,mergedIntoExisting:null,stamped:!1,root:null}}var Mt=0;function ut(a,t){let c=A.basename(a,".stx").replace(/[^a-zA-Z0-9]/g,"_"),i=t.__stx_scope_seq;return i?`stx_scope_${c}_${++i.n}_${i.key}`:`stx_scope_${c}_${++Mt}`}var lt=new Set,pt=new Set;function gp(){lt.clear(),pt.clear()}var Tt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Tl(a){let t=(e)=>e.replace(/[^\n]/g," "),c=a.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,t).replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,t).replace(/<!--[\s\S]*?-->/g,t).replace(/\x00STX_HTML_COMMENT_\d+\x00/g,t).replace(/\{\{[\s\S]*?\}\}/g,t).replace(/\{!![\s\S]*?!!\}/g,t),i=[],S=0,s=/<(\/?)([A-Za-z][\w-]*)\b(?:[^<>"']|"[^"]*"|'[^']*')*?(\/?)>/g,f;while((f=s.exec(c))!==null){let e=f[1]==="/",D=f[2],Z=f[3]==="/"||Tt.has(D.toLowerCase());if(e){S=Math.max(0,S-1);continue}if(S===0)i.push(D);if(!Z)S++}return i}function ft(a){return/\btype\s*=\s*["'](?!(?:text\/javascript|application\/javascript|module)["'])[^"']*["']/i.test(a)}var Ke=new B(500),ca=new Set;function mp(){ca.clear()}function Ct(a){if(a.__onceStore instanceof Set)return a.__onceStore;return ca}async function Br(a,t,c,i,S,s=new Set){let f=i.partialsDir||A.join(A.dirname(c),"partials");if(f&&!A.isAbsolute(f))f=A.resolve(process.cwd(),f);let e=yt(a,"@partial","@include"),D=Ct(t);e=e.replace(/@once([\s\S]*?)@endonce/g,(h,k,_)=>{let g=k.trim(),r=`${c}:${g}`;if(D.has(r))return"";return D.add(r),k});{let h=/@includeIf\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")")r--;w++}if(r!==0)break;let d=e.substring(g+1,w-1),o=d.match(/^\s*['"]([^'"]+)['"]/);if(!o){h.lastIndex=w;continue}let O=o[1],W=Z(O,f,c),R="";if(W&&await Bun.file(W).exists())S.add(W),R=`@include(${d})`;e=e.substring(0,_)+R+e.substring(w),h.lastIndex=0}}for(let[h,k]of[["@includeWhen",!1],["@includeUnless",!0]]){let _=new RegExp(`${h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\(`,"g"),g;while((g=_.exec(e))!==null){let r=g.index,w=r+g[0].length-1,d=1,o=w+1;while(o<e.length&&d>0){if(e[o]==="(")d++;else if(e[o]===")")d--;o++}if(d!==0)break;let O=e.substring(w+1,o-1),W=at(O,0);if(W===-1){_.lastIndex=o;continue}let R=O.substring(0,W).trim(),V=O.substring(W+1).trim(),z=V.match(/^\s*['"]([^'"]+)['"]/);if(!z){_.lastIndex=o;continue}let b=z[1],J=V.substring(z[0].length),N,I=at(J,0);if(I!==-1)N=J.substring(I+1).trim();try{let M=`Boolean(${R})`,P;if(p(M)){let ot=u(M,Object.keys(t));P=Boolean(ot(...Object.values(t)))}else P=Boolean(l(M,t));let tt=k?!P:P,rt="";if(tt){let ot=Z(b,f,c);if(ot&&await Bun.file(ot).exists())S.add(ot);rt=`@include('${b}'${N?`, ${N}`:""})`}e=e.substring(0,r)+rt+e.substring(o),_.lastIndex=0}catch(M){let P=M instanceof Error?M.message:String(M),tt=m("Include",`Error evaluating ${h} condition: ${P}`,c,a,r);e=e.substring(0,r)+tt+e.substring(o),_.lastIndex=0}}}{let h=/@each\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")"){if(r--,r===0)break}w++}if(r!==0)break;let d=e.substring(g+1,w),o=e.substring(_,w+1),O=d.match(/^\s*['"]([^'"]+)['"]\s*,\s*([^,]+)\s*,\s*['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?\s*$/);if(!O){h.lastIndex=0,e=e.replace(o,"");continue}let[,W,R,V,z]=O;try{let b,J=R.trim();if(p(J))b=u(J,Object.keys(t))(...Object.values(t));else b=l(J,t);let N="";if(Array.isArray(b)&&b.length>0)for(let I of b){let M={...t,[V]:I},P=await et(W,M,a,_);N+=P}else if(z)N=await et(z,{},a,_);e=e.substring(0,_)+N+e.substring(w+1),h.lastIndex=0}catch(b){let J=b instanceof Error?b.message:String(b);e=e.substring(0,_)+m("Each",`Error in @each: ${J}`,c,a,_)+e.substring(w+1),h.lastIndex=0}}}{let h=/@includeFirst\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")"){if(r--,r===0)break}w++}if(r!==0)break;let d=e.substring(g+1,w),o=e.substring(_,w+1),O=d.match(/^\s*(\[[^\]]+\])/);if(!O){h.lastIndex=0,e=e.replace(o,"");continue}let W=O[1],R=d.slice(O[0].length),V,z=R.match(/^\s*,\s*\{/);if(z){R=R.slice(z[0].length-1);let N=1,I=1;while(I<R.length&&N>0){if(R[I]==="{")N++;else if(R[I]==="}"){if(N--,N===0)break}I++}V=R.substring(0,I+1),R=R.slice(I+1)}let b,J=R.match(/^\s*,\s*['"]([^'"]*)['"]\s*$/);if(J)b=J[1];try{let N=JSON.parse(W.replace(/'/g,'"')),I={};if(V)try{I=E(V,t)}catch(P){let tt=P instanceof Error?P.message:String(P);if(i.debug){let rt=m("Include",`Error parsing includeFirst variables: ${tt}`,c,a,_,o);e=e.replace(o,()=>rt)}else e=e.replace(o,()=>b||"");continue}let M=!1;for(let P of N){let tt=Z(P,f,c);if(!tt)continue;if(await n(tt)){let rt=await et(P,I,a,_);e=e.replace(o,()=>rt),M=!0;break}}if(!M)if(b!==void 0)e=e.replace(o,()=>b);else if(i.debug){let P=m("Include",`None of the includeFirst paths exist: ${W}`,c,a,_,o);e=e.replace(o,()=>P)}else e=e.replace(o,"")}catch(N){let I=N instanceof Error?N.message:String(N),M=m("Include",`Error processing @includeFirst: ${I}`,c,a,_,o);e=e.replace(o,()=>M)}h.lastIndex=0}}function Z(h,k,_){try{let g=h;if(!h.endsWith(".stx"))g=`${h}.stx`;let r=A.resolve(k),w=A.resolve(A.dirname(_)),d;if(!g.startsWith("./")&&!g.startsWith("../")){for(let z of i._layerPartialDirs??[]){let b=A.resolve(z,g);if(b.startsWith(`${A.resolve(z)}${A.sep}`)&&St(b))return b}d=A.resolve(k,g)}else d=A.resolve(w,g);let o=A.normalize(d),O=o.startsWith(r+A.sep)||o===r,W=o.startsWith(w+A.sep)||o===w,R=!1,V=A.dirname(w);if(o.startsWith(V+A.sep)){if(!A.relative(V,o).split(A.sep).some((N)=>N.startsWith(".")&&N!=="."&&N!==".."))R=!0}if(!O&&!W&&!R)return console.error(`Security: Path traversal attempt blocked for include path: ${h}`),console.error(` Resolved to: ${o}`),console.error(` Allowed dirs: ${r}, ${w}`),null;return o}catch(g){return console.error(`Error resolving path ${h}: ${g}`),null}}let it=A.resolve(c);s.add(it);function j(h,k,_,g){return i.onIncludeError?.({includePath:h,templatePath:c,message:k,partialsDir:f}),m("Include",k,c,_,g)}async function et(h,k={},_,g){let r=Z(h,f,c);if(!r)return j(h,`Could not resolve path for include: ${h}`,_,g);let w=A.resolve(r);if(s.has(w)){let d=[...s,w].map((o)=>A.basename(o)).join(" -> ");return j(h,`Circular include detected: ${d}`,_,g)}try{S.add(r);let d;if(!d)try{d=await Bun.file(r).text()}catch(v){let q=v instanceof Error?v.message:String(v);return j(h,`Error loading include file ${h}: ${q}`,_,g)}if(d)d=d.replace(/\{\{--[\s\S]*?--\}\}/g,"");if(d&&d.includes("@stream")){let{processStreamDirectives:v}=await import("./chunk-
|
|
47
|
+
})();`;return c+a+i}function It(a,t){if(K(a)){let S=K(a).tag.match(/data-stx-scope="([^"]*)"/);if(S)return{html:a,mergedIntoExisting:S[1],stamped:!0,root:"body"};return{html:Ge(a,(s,f)=>`<body${f} data-stx-scope="${t}">`),mergedIntoExisting:null,stamped:!0,root:"body"}}let c=a.match(/^(\s*(?:(?:<!--[\s\S]*?-->|\x00STX_HTML_COMMENT_\d+\x00)\s*)*)(<[a-zA-Z][a-zA-Z0-9-]*)(\s[^>]*>|>)/s);if(c){let i=c[2]+c[3],S=c[2].slice(1),s=i.match(/data-stx-scope="([^"]*)"/);if(s)return{html:a,mergedIntoExisting:s[1],stamped:!0,root:S};let f=c[1],e=c[2],D=c[3];return{html:`${f}${e} data-stx-scope="${t}"${D}${a.slice(c[0].length)}`,mergedIntoExisting:null,stamped:!0,root:S}}return{html:a,mergedIntoExisting:null,stamped:!1,root:null}}var Mt=0;function ut(a,t){let c=A.basename(a,".stx").replace(/[^a-zA-Z0-9]/g,"_"),i=t.__stx_scope_seq;return i?`stx_scope_${c}_${++i.n}_${i.key}`:`stx_scope_${c}_${++Mt}`}var lt=new Set,pt=new Set;function gp(){lt.clear(),pt.clear()}var Tt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Tl(a){let t=(e)=>e.replace(/[^\n]/g," "),c=a.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,t).replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,t).replace(/<!--[\s\S]*?-->/g,t).replace(/\x00STX_HTML_COMMENT_\d+\x00/g,t).replace(/\{\{[\s\S]*?\}\}/g,t).replace(/\{!![\s\S]*?!!\}/g,t),i=[],S=0,s=/<(\/?)([A-Za-z][\w-]*)\b(?:[^<>"']|"[^"]*"|'[^']*')*?(\/?)>/g,f;while((f=s.exec(c))!==null){let e=f[1]==="/",D=f[2],Z=f[3]==="/"||Tt.has(D.toLowerCase());if(e){S=Math.max(0,S-1);continue}if(S===0)i.push(D);if(!Z)S++}return i}function ft(a){return/\btype\s*=\s*["'](?!(?:text\/javascript|application\/javascript|module)["'])[^"']*["']/i.test(a)}var Ke=new B(500),ca=new Set;function mp(){ca.clear()}function Ct(a){if(a.__onceStore instanceof Set)return a.__onceStore;return ca}async function Br(a,t,c,i,S,s=new Set){let f=i.partialsDir||A.join(A.dirname(c),"partials");if(f&&!A.isAbsolute(f))f=A.resolve(process.cwd(),f);let e=yt(a,"@partial","@include"),D=Ct(t);e=e.replace(/@once([\s\S]*?)@endonce/g,(h,k,_)=>{let g=k.trim(),r=`${c}:${g}`;if(D.has(r))return"";return D.add(r),k});{let h=/@includeIf\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")")r--;w++}if(r!==0)break;let d=e.substring(g+1,w-1),o=d.match(/^\s*['"]([^'"]+)['"]/);if(!o){h.lastIndex=w;continue}let O=o[1],W=Z(O,f,c),R="";if(W&&await Bun.file(W).exists())S.add(W),R=`@include(${d})`;e=e.substring(0,_)+R+e.substring(w),h.lastIndex=0}}for(let[h,k]of[["@includeWhen",!1],["@includeUnless",!0]]){let _=new RegExp(`${h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\(`,"g"),g;while((g=_.exec(e))!==null){let r=g.index,w=r+g[0].length-1,d=1,o=w+1;while(o<e.length&&d>0){if(e[o]==="(")d++;else if(e[o]===")")d--;o++}if(d!==0)break;let O=e.substring(w+1,o-1),W=at(O,0);if(W===-1){_.lastIndex=o;continue}let R=O.substring(0,W).trim(),V=O.substring(W+1).trim(),z=V.match(/^\s*['"]([^'"]+)['"]/);if(!z){_.lastIndex=o;continue}let b=z[1],J=V.substring(z[0].length),N,I=at(J,0);if(I!==-1)N=J.substring(I+1).trim();try{let M=`Boolean(${R})`,P;if(p(M)){let ot=u(M,Object.keys(t));P=Boolean(ot(...Object.values(t)))}else P=Boolean(l(M,t));let tt=k?!P:P,rt="";if(tt){let ot=Z(b,f,c);if(ot&&await Bun.file(ot).exists())S.add(ot);rt=`@include('${b}'${N?`, ${N}`:""})`}e=e.substring(0,r)+rt+e.substring(o),_.lastIndex=0}catch(M){let P=M instanceof Error?M.message:String(M),tt=m("Include",`Error evaluating ${h} condition: ${P}`,c,a,r);e=e.substring(0,r)+tt+e.substring(o),_.lastIndex=0}}}{let h=/@each\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")"){if(r--,r===0)break}w++}if(r!==0)break;let d=e.substring(g+1,w),o=e.substring(_,w+1),O=d.match(/^\s*['"]([^'"]+)['"]\s*,\s*([^,]+)\s*,\s*['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?\s*$/);if(!O){h.lastIndex=0,e=e.replace(o,"");continue}let[,W,R,V,z]=O;try{let b,J=R.trim();if(p(J))b=u(J,Object.keys(t))(...Object.values(t));else b=l(J,t);let N="";if(Array.isArray(b)&&b.length>0)for(let I of b){let M={...t,[V]:I},P=await et(W,M,a,_);N+=P}else if(z)N=await et(z,{},a,_);e=e.substring(0,_)+N+e.substring(w+1),h.lastIndex=0}catch(b){let J=b instanceof Error?b.message:String(b);e=e.substring(0,_)+m("Each",`Error in @each: ${J}`,c,a,_)+e.substring(w+1),h.lastIndex=0}}}{let h=/@includeFirst\s*\(/g,k;while((k=h.exec(e))!==null){let _=k.index,g=_+k[0].length-1,r=1,w=g+1;while(w<e.length&&r>0){if(e[w]==="(")r++;else if(e[w]===")"){if(r--,r===0)break}w++}if(r!==0)break;let d=e.substring(g+1,w),o=e.substring(_,w+1),O=d.match(/^\s*(\[[^\]]+\])/);if(!O){h.lastIndex=0,e=e.replace(o,"");continue}let W=O[1],R=d.slice(O[0].length),V,z=R.match(/^\s*,\s*\{/);if(z){R=R.slice(z[0].length-1);let N=1,I=1;while(I<R.length&&N>0){if(R[I]==="{")N++;else if(R[I]==="}"){if(N--,N===0)break}I++}V=R.substring(0,I+1),R=R.slice(I+1)}let b,J=R.match(/^\s*,\s*['"]([^'"]*)['"]\s*$/);if(J)b=J[1];try{let N=JSON.parse(W.replace(/'/g,'"')),I={};if(V)try{I=E(V,t)}catch(P){let tt=P instanceof Error?P.message:String(P);if(i.debug){let rt=m("Include",`Error parsing includeFirst variables: ${tt}`,c,a,_,o);e=e.replace(o,()=>rt)}else e=e.replace(o,()=>b||"");continue}let M=!1;for(let P of N){let tt=Z(P,f,c);if(!tt)continue;if(await n(tt)){let rt=await et(P,I,a,_);e=e.replace(o,()=>rt),M=!0;break}}if(!M)if(b!==void 0)e=e.replace(o,()=>b);else if(i.debug){let P=m("Include",`None of the includeFirst paths exist: ${W}`,c,a,_,o);e=e.replace(o,()=>P)}else e=e.replace(o,"")}catch(N){let I=N instanceof Error?N.message:String(N),M=m("Include",`Error processing @includeFirst: ${I}`,c,a,_,o);e=e.replace(o,()=>M)}h.lastIndex=0}}function Z(h,k,_){try{let g=h;if(!h.endsWith(".stx"))g=`${h}.stx`;let r=A.resolve(k),w=A.resolve(A.dirname(_)),d;if(!g.startsWith("./")&&!g.startsWith("../")){for(let z of i._layerPartialDirs??[]){let b=A.resolve(z,g);if(b.startsWith(`${A.resolve(z)}${A.sep}`)&&St(b))return b}d=A.resolve(k,g)}else d=A.resolve(w,g);let o=A.normalize(d),O=o.startsWith(r+A.sep)||o===r,W=o.startsWith(w+A.sep)||o===w,R=!1,V=A.dirname(w);if(o.startsWith(V+A.sep)){if(!A.relative(V,o).split(A.sep).some((N)=>N.startsWith(".")&&N!=="."&&N!==".."))R=!0}if(!O&&!W&&!R)return console.error(`Security: Path traversal attempt blocked for include path: ${h}`),console.error(` Resolved to: ${o}`),console.error(` Allowed dirs: ${r}, ${w}`),null;return o}catch(g){return console.error(`Error resolving path ${h}: ${g}`),null}}let it=A.resolve(c);s.add(it);function j(h,k,_,g){return i.onIncludeError?.({includePath:h,templatePath:c,message:k,partialsDir:f}),m("Include",k,c,_,g)}async function et(h,k={},_,g){let r=Z(h,f,c);if(!r)return j(h,`Could not resolve path for include: ${h}`,_,g);let w=A.resolve(r);if(s.has(w)){let d=[...s,w].map((o)=>A.basename(o)).join(" -> ");return j(h,`Circular include detected: ${d}`,_,g)}try{S.add(r);let d;if(!d)try{d=await Bun.file(r).text()}catch(v){let q=v instanceof Error?v.message:String(v);return j(h,`Error loading include file ${h}: ${q}`,_,g)}if(d)d=d.replace(/\{\{--[\s\S]*?--\}\}/g,"");if(d&&d.includes("@stream")){let{processStreamDirectives:v}=await import("./chunk-ejphs9fs.js");d=v(d,t)}if(d&&(i.debug||!C()&&!wn()))try{let{warnUnbalancedTags:v}=await import("./chunk-23efje42.js");v(d,r)}catch{}try{let{processESImports:v}=await import("./chunk-em77nd40.js");d=await v(d,t,r,i,S)}catch(v){if(i.debug)console.warn(`[stx] partial ES import extraction skipped for ${r}:`,v instanceof Error?v.message:v)}let o=d,O=ue(o);if(O)o=O.content.trim();let R=d.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").match(/<style\b([^>]*)>([\s\S]*?)<\/style>/i),V="";if(R)V=`<style${R[1]}>${R[2]}</style>`;let z=[];o=o.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(v,q,y)=>{if(!ft(q))return"";return z.push({attrs:q,body:y}),`__STX_DATA_BLOCK_${z.length-1}__`}),o=o.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let b={...t};b.__stx_signals_gate=we(d,r);for(let[v,q]of Object.entries(k))b[v]=q;let J=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,N=[...d.matchAll(J)].sort((v,q)=>{let y=(v[1]||"").includes("server"),X=(q[1]||"").includes("server");return Number(X)-Number(y)}),I="",M=null,P=!1,tt=!1;for(let v of N){let q=v[1]||"",y=v[2]||"";if(ft(q))continue;let X=q.includes("server"),wt=Me(q);if(!X&&!/\bsrc\s*=/i.test(q))Pe(y,r,i.strict);if(!X&&y.trim()){let{interpolateScriptExpressions:F}=await import("./chunk-dbxq6fd7.js");y=F(y,b,h)}let ct="";try{let{extractAndStripCssImports:F,renderVendorStyleTags:Q}=await import("./chunk-4cksc4n3.js"),nt=F(y,{filePath:r,projectRoot:process.cwd()});y=nt.code,ct=Q(nt.styles)}catch(F){if(i.debug)console.warn(`[stx] vendor-css extractor skipped for ${r}:`,F instanceof Error?F.message:F)}if(wt&&y.trim())y=Le(y);if(!X){try{let{injectBrowserCoreAutoImports:Q}=await import("./chunk-4cksc4n3.js");y=Q(y).code;let{hasUserImports:nt,bundleClientScript:bt}=await import("./chunk-yqgrjf9q.js");if(nt(y))y=await bt(y,r,{projectRoot:process.cwd()})}catch(Q){if(i.debug)console.warn(`[stx] bundler skipped for ${r}:`,Q instanceof Error?Q.message:Q)}let{stripStxRuntimeImports:F}=await import("./chunk-4j9p27kn.js");y=F(y)}let dt=$t(y);if(!X){let{extractBridgeData:F,generateServerDataBridge:Q}=await import("./chunk-4cksc4n3.js"),nt=Q(y,F(b));if(nt)y=`${nt}
|
|
48
48
|
${y}`}if(dt&&!X){P=!0,M=ut(r,t);let F=T(y),Q=gt(F,M);I+=`${ct}<script data-stx-scoped data-stx-run="always" data-stx-owner="${M}">${Q}</script>
|
|
49
|
-
`;continue}if(X)try{let{extractVariables:F}=await import("./chunk-
|
|
50
|
-
`}}if(z.length>0){let{interpolateScriptExpressions:v}=await import("./chunk-
|
|
49
|
+
`;continue}if(X)try{let{extractVariables:F}=await import("./chunk-7gprzmd9.js");await F(y,b,r)}catch(F){if(i.debug)console.warn(`Warning: Could not extract variables from server script in ${r}:`,F)}if(!X&&!dt){let F=q.replace(/\bclient\b/i,"").trim();M=ut(r,t);let Q=T(y),nt=gt(Q,M);if(/__scopeRegistration\["(?!__stx)[^"]+"\]\s*=|Object\.defineProperty\(__scopeRegistration, "(?!__stx)/.test(nt))tt=!0;I+=`${ct}<script data-stx-scoped data-stx-run="always" data-stx-owner="${M}"${F?` ${F}`:""}>${nt}</script>
|
|
50
|
+
`}}if(z.length>0){let{interpolateScriptExpressions:v}=await import("./chunk-dbxq6fd7.js");o=o.replace(/__STX_DATA_BLOCK_(\d+)__/g,(q,y)=>{let X=z[Number(y)];return`<script${X.attrs}>${v(X.body,b,h)}</script>`})}if(M){let v=It(o,M);if(o=v.html,v.mergedIntoExisting){let y=M,X=v.mergedIntoExisting;I=I.split(`'${y}'`).join(`'${X}'`).split(`"${y}"`).join(`"${X}"`),M=X}else if(!v.stamped&&P&&!lt.has(r))lt.add(r),console.warn(`[stx] ${A.relative(process.cwd(),r)} declares signals but has no element to scope them to, so nothing in it will hydrate. Wrap the partial's markup in a single root element.`);if(v.stamped&&v.root!=="body"&&(P||tt)&&!pt.has(r)){let y=Tl(o);if(y.length>1)pt.add(r),console.warn(`[stx] ${A.relative(process.cwd(),r)} declares ${P?"signals":"bindings"} and has ${y.length} top-level elements (${y.map((X)=>`<${X}>`).join(", ")}). Only the first is scoped, so bindings in the others cannot see what this partial's script declares. Wrap the partial's markup in a single root element.`)}let q=v.stamped&&v.root!==null&&ur(v.root);I=Rt(I,q?M:null)}if(o.includes("@include")||o.includes("@partial"))o=await Br(o,b,r,i,S,s);let{processLoops:rt,reportDeferredLoopWarnings:ot}=await import("./chunk-gyye3mcb.js"),G=rt(o,b,r,void 0,!0);G=re(G,b,r),G=ot(G);let{processMetaDirectives:ht,processSeoDirective:xt,processStructuredData:_t}=await import("./chunk-d26nb6zy.js");if(G=ht(G,b,r,i),G=_t(G,b,r),G=xt(G,b,r,i),G=x(G,b,r),V)G+=`
|
|
51
51
|
`+V;if(I)G+=`
|
|
52
52
|
`+I;return G}catch(d){if(d instanceof U)throw d;let o=d instanceof Error?d.message:String(d);return j(h,`Error processing include ${h}: ${o}`,_,g)}}let Y=/@include\s*\(/g,H;while((H=Y.exec(e))!==null){let h=H.index,k=h+H[0].length-1,_=1,g=k+1;while(g<e.length&&_>0){if(e[g]==="(")_++;else if(e[g]===")")_--;g++}if(_!==0)break;let r=e.substring(h,g),w=e.substring(k+1,g-1),d=w.match(/^\s*['"]([^'"]+)['"]/);if(!d){Y.lastIndex=g;continue}let o=d[1],O,W=w.substring(d[0].length),R=at(W,0);if(R!==-1)O=W.substring(R+1).trim();let V={};if(O)try{V=E(O,t)}catch(b){let J=b instanceof Error?b.message:String(b);e=e.replace(r,m("Include",`Error parsing include variables for ${o}: ${J}`,c,a,h)),Y.lastIndex=0;continue}let z=await et(o,V,a,h);e=e.substring(0,h)+z+e.substring(g),Y.lastIndex=0}return e}function Fr(a,t){let c=a;function i(S,s,f,e){let D=S,Z=!0;while(Z){Z=!1;let it=new RegExp(`@${s}\\(['"]([^'"]+)['"]\\)`),j=D.match(it);if(!j||j.index===void 0)break;let et=j.index,Y=j[1],H=et+j[0].length,h=new RegExp(`@${s}\\(`),k=new RegExp(`@${f}(?![a-z])`),_=1,g=H,r=-1;while(_>0&&g<D.length){let d=D.slice(g),o=d.match(h),O=d.match(k),W=o?g+o.index:1/0,R=O?g+O.index:1/0;if(W<R)_++,g=W+(o[0].length||1);else if(R<1/0){if(_--,_===0){r=R;break}g=R+f.length+1}else break}if(r===-1)break;let w=D.slice(H,r);if(!t[Y])t[Y]=[];if(e)t[Y].unshift(w);else t[Y].push(w);D=D.substring(0,et)+D.substring(r+`@${f}`.length),Z=!0}return D}return c=i(c,"push","endpush",!1),c=i(c,"prepend","endprepend",!0),c}function zr(a,t){return a.replace(/@stack\(['"]([^'"]+)['"]\)/g,(c,i)=>{if(!t[i]||t[i].length===0)return"";return t[i].join(`
|
|
53
53
|
`)})}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ou}from"./chunk-9c3x72qy.js";import"./chunk-d9esaahz.js";import"./chunk-cge9pgyb.js";import"./chunk-0nt17nas.js";import"./chunk-fw12pvmr.js";import"./chunk-1rgjy80j.js";import"./chunk-0y2hkbc6.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import"./chunk-xw0cqb5m.js";import"./chunk-bg6t69qq.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{Ou as startProductionServer};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W}from"./chunk-
|
|
2
|
+
import{W}from"./chunk-078as147.js";import Oe from"path";var t={UNCLOSED_DIRECTIVE:1001,UNCLOSED_EXPRESSION:1002,INVALID_DIRECTIVE_SYNTAX:1003,MALFORMED_EXPRESSION:1004,UNEXPECTED_TOKEN:1005,UNDEFINED_VARIABLE:1101,TYPE_ERROR:1102,EVALUATION_ERROR:1103,INFINITE_LOOP:1104,CIRCULAR_REFERENCE:1105,UNSAFE_EXPRESSION:1201,PATH_TRAVERSAL:1202,XSS_ATTEMPT:1203,CODE_INJECTION:1204,DOM_API_VIOLATION:1205,FILE_NOT_FOUND:1301,FILE_READ_ERROR:1302,INVALID_FILE_PATH:1303,PERMISSION_DENIED:1304,INVALID_CONFIG:1401,MISSING_REQUIRED_CONFIG:1402,DEPRECATED_CONFIG:1403,COMPONENT_NOT_FOUND:1501,INVALID_PROPS:1502,COMPONENT_RENDER_ERROR:1503,FILTER_NOT_FOUND:1601,INVALID_FILTER_ARGS:1602,EXPRESSION_TIMEOUT:1603};function G(e){for(let[n,r]of Object.entries(t))if(r===e)return n;return}import st from"path";var ot={showRelativePaths:!1,enableAutoRecovery:W(),logRecoveryWarnings:!0},Y={...ot};function N(){return{...Y}}function M(e){if(!Y.showRelativePaths||!e)return e;let n=Y.baseDir||process.cwd();try{let r=st.relative(n,e);return r.startsWith("..")?e:r}catch{return e}}class L extends Error{code;filePath;line;column;context;numericCode;constructor(e,n,r,i,s,o,c){super(e);this.code=n;this.filePath=r;this.line=i;this.column=s;this.context=o;if(this.name="StxError",this.numericCode=c||t.EVALUATION_ERROR,this.filePath)this.filePath=M(this.filePath)}}class ie extends L{constructor(e,n,r,i,s,o){super(e,"stx_RUNTIME_ERROR",n,r,i,s,o||t.EVALUATION_ERROR);this.name="StxRuntimeError"}}class fr extends L{constructor(e,n,r,i,s,o){super(e,"stx_FILE_ERROR",n,r,i,s,o||t.FILE_NOT_FOUND);this.name="StxFileError"}}class U extends L{isFatal=!0;constructor(e,n,r,i,s,o){super(e,"stx_VALIDATION_ERROR",n,r,i,s,o||t.DOM_API_VIOLATION);this.name="StxValidationError"}}function me(e){let{type:n,message:r,code:i,filePath:s,line:o,column:c,template:g,offset:d,snippet:f,suggestion:h,format:m="text"}=e,b=o,w=c;if(!b&&g&&d!==void 0){let K=pt(g,d);b=K.line,w=K.column}let k=s?M(s):void 0,S=i?G(i):void 0,C={type:n,code:i,codeName:S,message:r,filePath:k,line:b,column:w,snippet:f,suggestion:h,timestamp:new Date().toISOString()},T;switch(m){case"html":T=ct(C);break;case"json":T=JSON.stringify(C,null,2);break;case"console":T=lt(C,g,d);break;case"text":default:T=at(C,g,d);break}return{formatted:T,data:C}}function at(e,n,r){let i=[],s=e.code?` [${e.codeName||e.code}]`:"";if(i.push(`[${e.type} Error${s}]`),e.filePath){let o=e.filePath;if(e.line){if(o+=`:${e.line}`,e.column)o+=`:${e.column}`}i.push(`at ${o}`)}if(i.push(`
|
|
3
3
|
${e.message}`),n&&e.line){let o=ut(n,e.line,2);if(o)i.push(`
|
|
4
4
|
${o}`)}if(e.snippet)i.push(`
|
|
5
5
|
Snippet: ${e.snippet}`);if(e.suggestion)i.push(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{C}from"./chunk-
|
|
2
|
+
import{C}from"./chunk-078as147.js";import{He,Sn}from"./chunk-e26pxzjj.js";function m(e){let t={"cache-first":{className:"CacheFirst",importFrom:"workbox-strategies"},"network-first":{className:"NetworkFirst",importFrom:"workbox-strategies"},"stale-while-revalidate":{className:"StaleWhileRevalidate",importFrom:"workbox-strategies"},"network-only":{className:"NetworkOnly",importFrom:"workbox-strategies"},"cache-only":{className:"CacheOnly",importFrom:"workbox-strategies"}};return t[e]||t["network-first"]}function g(e){return m(e).className}function d(e){let t=e.pwa;if(!t?.enabled)return"";let r=t.routes||[],n=t.cacheStorage,c=[];for(let a of r){let i=g(a.strategy),s=[];if(a.maxAgeSeconds||a.maxEntries||n?.maxEntries){let o=a.maxEntries||n?.maxEntries||100,u=a.maxAgeSeconds||(n?.maxAge?n.maxAge*24*60*60:void 0);s.push(`new ExpirationPlugin({
|
|
3
3
|
maxEntries: ${o},
|
|
4
4
|
${u?`maxAgeSeconds: ${u},`:""}
|
|
5
5
|
purgeOnQuotaError: true,
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ws,qd,Kd}from"./chunk-ywpyxqn5.js";import"./chunk-ffwvbqkp.js";import"./chunk-0nt17nas.js";import"./chunk-374nhgyf.js";import"./chunk-51fqvchq.js";import"./chunk-fw12pvmr.js";import"./chunk-jgxzbthg.js";import"./chunk-1rgjy80j.js";import"./chunk-0y2hkbc6.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import"./chunk-xw0cqb5m.js";import"./chunk-bg6t69qq.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{Kd as clearComposableCache,qd as getComposableScript,Ws as listComposableModules};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{g,Mo,Ka,Ga,eu,tu,nu,ru,su,vs,ou,Me,J,Le,iu,pr,au,Ya,Fo,je,n,gn,Za,m,pe,Np}from"./chunk-
|
|
2
|
+
import{g,Mo,Ka,Ga,eu,tu,nu,ru,su,vs,ou,Me,J,Le,iu,pr,au,Ya,Fo,je,n,gn,Za,m,pe,Np}from"./chunk-xw0cqb5m.js";import"./chunk-bg6t69qq.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{pe as clearComponentCache,Fo as componentClientSignalNames,Mo as convertToCommonJS,m as createDetailedErrorMessage,su as extractDirectiveNames,Ka as extractScriptFromTemplate,g as extractVariables,n as fileExists,Np as getComponentCacheStats,tu as getPositionInfo,J as getSharedTranspiler,Za as getSourceLineInfo,ru as hasDirectives,Ga as hasVariables,au as isHydrateTrigger,ou as isJavaScriptScript,je as renderComponentWithSlot,gn as resolveTemplatePath,iu as scopeOnRootElement,vs as scopeSequenceKey,Me as shouldTranspileTypeScript,Ya as slotContentHasExpressions,Le as transpileTypeScript,pr as userComponentFileExists,nu as validateDirective,eu as validateTemplate};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{qi,Ki,Gi,Xi,ip}from"./chunk-z10ffhzy.js";import"./chunk-yf42bhjw.js";import"./chunk-03xn8244.js";import"./chunk-dnbdxbkb.js";import"./chunk-67v3rh14.js";import"./chunk-9bgb9n12.js";import"./chunk-dxcn65hq.js";import"./chunk-pf25jb54.js";import"./chunk-n4qp4q2x.js";import"./chunk-hx787tfa.js";import"./chunk-51fqvchq.js";import"./chunk-fw12pvmr.js";import"./chunk-jgxzbthg.js";import"./chunk-58m0kfb3.js";import"./chunk-1rgjy80j.js";import"./chunk-0y2hkbc6.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import"./chunk-xw0cqb5m.js";import"./chunk-bg6t69qq.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{qi as buildNative,ip as default,Ki as findCraftBinary,Xi as getAvailableFormats,Gi as getAvailableTargets};
|