@stacksjs/stx 0.2.872 → 0.2.873
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-kx6y1cqw.js → chunk-0489wcvq.js} +1 -1
- package/dist/{chunk-jnj9s2yw.js → chunk-0g80km93.js} +1 -1
- package/dist/{chunk-q8d0wf0w.js → chunk-1mzfynpk.js} +1 -1
- package/dist/{chunk-y69hhxn8.js → chunk-26s2jxvn.js} +1 -1
- package/dist/{chunk-bfvr4byj.js → chunk-2drcj9wn.js} +2 -2
- package/dist/chunk-36e94whg.js +3 -0
- package/dist/{chunk-pj1znb6y.js → chunk-3t91wwbe.js} +1 -1
- package/dist/{chunk-v4ab2jzz.js → chunk-60ezkjcz.js} +1 -1
- package/dist/{chunk-v99hgmsx.js → chunk-696cdgkg.js} +1 -1
- package/dist/{chunk-tahw02kf.js → chunk-85m8nyk6.js} +1 -1
- package/dist/{chunk-ba86dkhs.js → chunk-8q8xkw02.js} +1 -1
- package/dist/{chunk-1c8j9zdp.js → chunk-8xjj7wjf.js} +1 -1
- package/dist/{chunk-jkevn2jy.js → chunk-9kghtf20.js} +1 -1
- package/dist/{chunk-dv1edvz8.js → chunk-aed45njs.js} +1 -1
- package/dist/{chunk-thyxsg54.js → chunk-are96jcb.js} +1 -1
- package/dist/{chunk-1p9rb7rt.js → chunk-b53rzbrh.js} +1 -1
- package/dist/{chunk-e549f7a9.js → chunk-ct90b523.js} +2 -2
- package/dist/{chunk-bqs9wyje.js → chunk-d3mmnzwy.js} +1 -1
- package/dist/chunk-d8zhtwnw.js +2 -0
- package/dist/{chunk-808fbm83.js → chunk-d9f7zb5p.js} +1 -1
- package/dist/{chunk-teahvty8.js → chunk-df49nnj9.js} +1 -1
- package/dist/chunk-dhjet15m.js +2 -0
- package/dist/chunk-dy1brym3.js +2 -0
- package/dist/{chunk-jf3n1f32.js → chunk-e5xfbcp7.js} +1 -1
- package/dist/{chunk-tc36b3r4.js → chunk-e631k202.js} +4 -4
- package/dist/{chunk-qvxtq5vb.js → chunk-ek5mv2h8.js} +1 -1
- package/dist/{chunk-pnqdwqw9.js → chunk-eprhhrzc.js} +6 -6
- package/dist/{chunk-kkevjppm.js → chunk-eq3mqbcn.js} +1 -1
- package/dist/{chunk-s70e5jbq.js → chunk-f30bpj7a.js} +4 -4
- package/dist/{chunk-ycb07ppz.js → chunk-fbqk2w2k.js} +1 -1
- package/dist/{chunk-9c07p1vq.js → chunk-gynvaceg.js} +2 -2
- package/dist/{chunk-bmbqr2br.js → chunk-h3j2zvms.js} +1 -1
- package/dist/chunk-h8rpk597.js +2 -0
- package/dist/{chunk-vv9anbw1.js → chunk-hmsjjw34.js} +1 -1
- package/dist/{chunk-hd4vn78w.js → chunk-hq0zqaqc.js} +1 -1
- package/dist/{chunk-kzhget9h.js → chunk-hq4d1me0.js} +1 -1
- package/dist/{chunk-rvbw12e1.js → chunk-j7f3h982.js} +1 -1
- package/dist/{chunk-6s7q8kw3.js → chunk-j7q17ws8.js} +1 -1
- package/dist/chunk-jq0zvr43.js +2 -0
- package/dist/{chunk-qk1fkfvj.js → chunk-k0ph8zr7.js} +1 -1
- package/dist/chunk-kp12tsn0.js +2 -0
- package/dist/{chunk-4ay62hs9.js → chunk-mxdapaz2.js} +1 -1
- package/dist/{chunk-832m6nwr.js → chunk-n0d4vbcv.js} +5 -5
- package/dist/{chunk-7q3ar8ay.js → chunk-natvnazg.js} +1 -1
- package/dist/{chunk-2jccw1km.js → chunk-nxqsdt89.js} +1 -1
- package/dist/chunk-p71c1wrw.js +2 -0
- package/dist/{chunk-vf91b9b9.js → chunk-qhczf1wf.js} +1 -1
- package/dist/{chunk-qt4dha3g.js → chunk-rb71xcfw.js} +3 -3
- package/dist/{chunk-pc8jnkb3.js → chunk-sb8qv9wy.js} +1 -1
- package/dist/{chunk-9bnggqhj.js → chunk-scsmp2e5.js} +1 -1
- package/dist/{chunk-jpgc0j8x.js → chunk-tny8mz6q.js} +2 -2
- package/dist/{chunk-my6tp8rn.js → chunk-ts1jwj54.js} +1 -1
- package/dist/{chunk-b8vs32dw.js → chunk-vvddndcm.js} +1 -1
- package/dist/{chunk-mm00bb1p.js → chunk-w3d7pwzg.js} +1 -1
- package/dist/{chunk-2yrd286h.js → chunk-w4a3fqf4.js} +1 -1
- package/dist/{chunk-4p51hk75.js → chunk-wa4w5bcn.js} +4 -4
- package/dist/{chunk-av2vknrs.js → chunk-xpzt4wwb.js} +2 -2
- package/dist/{chunk-jcr69v95.js → chunk-xr1yrdxy.js} +2 -2
- package/dist/{chunk-71hjqg16.js → chunk-xvj6yf0q.js} +4 -4
- package/dist/chunk-y0a8hex3.js +2 -0
- package/dist/chunk-y2ctxchq.js +2 -0
- package/dist/{chunk-f5gg0pxj.js → chunk-z347p6cg.js} +1 -1
- package/dist/{chunk-z2wfgva6.js → chunk-z3afnkan.js} +1 -1
- package/dist/{chunk-y48ykf1n.js → chunk-zktbzwkv.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-2nd3h37q.js +0 -2
- package/dist/chunk-3k5g4tbn.js +0 -2
- package/dist/chunk-3qewdhvh.js +0 -2
- package/dist/chunk-7mqnbn1x.js +0 -2
- package/dist/chunk-b2kkezey.js +0 -2
- package/dist/chunk-c63027nw.js +0 -2
- package/dist/chunk-cv9vmz5x.js +0 -2
- package/dist/chunk-tfsf9pes.js +0 -2
- package/dist/chunk-txjtd4gj.js +0 -2
- package/dist/chunk-z0qxrx9r.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{L,vn,Bt,Ft,h,s,we,g}from"./chunk-
|
|
2
|
+
import{L,vn,Bt,Ft,h,s,we,g}from"./chunk-eprhhrzc.js";import{kt,Ne,hc,ps,zo,Ho,i}from"./chunk-e631k202.js";import{ge,oe,Or,$e,W,Rn}from"./chunk-csymxc5a.js";import{$t,wr,Ns,Ds,Ms,Rt,At,Pt,It,Ot,Nt,ot}from"./chunk-hhbt8grm.js";import{$s,a,M}from"./chunk-xr1yrdxy.js";import{wt,en,Ae,H,wa,So,Qr,Je,va,Ye,Pe}from"./chunk-rb71xcfw.js";import{hr,yr}from"./chunk-b53rzbrh.js";import{e,mn,dr,x}from"./chunk-xpzt4wwb.js";import{tt}from"./chunk-f30bpj7a.js";import{Oe}from"./chunk-9zrvh3pz.js";import{Dn}from"./chunk-h3j2zvms.js";import{ee,ke,_e}from"./chunk-wa4w5bcn.js";import{l}from"./chunk-46pxmpeb.js";import{r,Y}from"./chunk-z9xe3xkg.js";import{Q}from"./chunk-9fyw1xkh.js";import{c,f}from"./chunk-fd1bpv35.js";async function qn(t){try{let n=await Bun.file(t).text(),o=Kn(n),u=Xn(n,t),d=Gn(n,o),p=Jn(n,o);return{file:t,metrics:o,issues:u,suggestions:d,performance:p}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Kn(t){let n=t.split(`
|
|
3
3
|
`),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),d=(o?o[1]:"").split(`
|
|
4
4
|
`).length,p={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};p.total=p.conditionals+p.loops+p.includes+p.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,y=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,b=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,v=m+y+b,w=(t.match(/<[A-Z][^>]*>/g)||[]).length,k=(t.match(/@(?:layout|extends)\(/g)||[]).length,R=0,E=0;for(let C of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))E++,R=Math.max(R,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))E--;let T=R>=4?3:0,S=Math.min(10,Math.ceil(p.total*0.5+v*0.1+w*0.3+(d>10?d*0.05:0)+T));return{lines:n.length,characters:t.length,directives:p,expressions:v,components:w,layouts:k,scriptLines:d,complexity:S}}function Xn(t,n){let o=[],u=Qt(t,"if","endif");if(u>0)o.push({type:"error",category:"syntax",message:`Found ${u} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let d=Qt(t,"foreach","endforeach");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)o.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let y=t.match(/<img[^>]*>/g);if(y){let w=y.filter((k)=>!k.includes("alt="));if(w.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${w.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let b=t.split(`
|
|
5
5
|
`).filter((w)=>w.length>120);if(b.length>0)o.push({type:"info",category:"maintainability",message:`Found ${b.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let v=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(v>3)o.push({type:"info",category:"maintainability",message:`Found ${v} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Gn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let u=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(u&&u.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Jn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let u;if(n.expressions===0&&n.directives.total===0)u="high";else if(n.expressions<5&&n.directives.total<3)u="medium";else u="low";let d=[];if(o>10)d.push("Consider optimizing template complexity");if(u==="low"&&n.directives.total>5)d.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)d.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:u,recommendations:d}}function Qt(t,n,o){let u=t.replace(/<!--[\s\S]*?-->/g,""),d=(u.match(new RegExp(`@${n}\\b`,"g"))||[]).length,p=(u.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(d-p)}async function ia(t=["**/*.stx"],n){let o=[],u=[];for(let p of t){let m=await Array.fromAsync(new Bun.Glob(p).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));u.push(...m.filter((y)=>y.endsWith(".stx")))}for(let p of u)try{let m=await qn(p);o.push(m)}catch(m){console.warn(`Failed to analyze ${p}:`,m)}let d=Yn(o);return{results:o,summary:d}}function Yn(t){let n=t.length,o=t.reduce((v,w)=>v+w.metrics.lines,0),u=n>0?t.reduce((v,w)=>v+w.metrics.complexity,0)/n:0,d=t.reduce((v,w)=>v+w.issues.length,0),p={};t.forEach((v)=>{v.issues.forEach((w)=>{p[w.category]=(p[w.category]||0)+1})});let m=n>0?t.reduce((v,w)=>v+w.performance.estimatedRenderTime,0)/n:0,y=Math.max(1,Math.min(10,Math.round(10-m/2-u/2))),b=[];if(u>6)b.push("Project has high average complexity. Consider refactoring complex templates.");if(d>n*2)b.push("High number of issues detected. Run detailed analysis on individual files.");if(p.security>0)b.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(u*100)/100,totalIssues:d,issuesByCategory:p,performanceScore:y,recommendations:b}}import{mkdir as Zn,readFile as Qn,readdir as er,stat as tn,writeFile as tr}from"fs/promises";import ve from"path";function cn(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 ln=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function nr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function zt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function rr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function sr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function or(t){let n=[];async function o(u){let d=await er(u,{withFileTypes:!0});d.sort((p,m)=>p.name.localeCompare(m.name));for(let p of d){let m=ve.join(u,p.name);if(p.isDirectory()){if(!p.name.startsWith(".")&&p.name!=="node_modules")await o(m)}else if(p.isFile()&&p.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(p.name))n.push(m)}}return await o(t),n}function ir(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let u=o[1].trim();if(!u)return{};try{return JSON.parse(u)}catch(d){throw Error(`${n}: <script component> must contain JSON metadata (${d.message})`)}}function ar(t){let n=r(t),o=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g,u=[],d=new Bun.Transpiler({loader:"ts"}),p;while(p=o.exec(n)){let m=o.lastIndex;while(/\s/.test(n[m]||""))m++;let y=m;if(n[m]==="<")m=Xe(n,m,"<",">");if(m<0)continue;let b=t.slice(y,m).trim();while(/\s/.test(n[m]||""))m++;if(n[m]!=="(")continue;let v=m,w=Xe(n,m,"(",")");if(w<0)continue;for(m=w;m<t.length;m++){let k=n[m];if(k!=="{"&&k!==";")continue;let R=t.slice(p.index,m).trim(),E;try{E=d.transformSync(R+(k==="{"?"{}":";"))}catch{continue}if(k==="{"&&!E.includes(`function ${p[1]}(`))continue;if(k===";"&&E.trim())continue;let T=k==="{"?Xe(n,m,"{","}"):m+1;if(T<0)break;u.push({name:p[1],header:R,generic:b,parameters:t.slice(v+1,w-1),returns:t.slice(w,m).trim().replace(/^:\s*/,""),async:/\basync\s+function/.test(p[0]),...k==="{"?{source:t.slice(p.index,T)}:{}}),o.lastIndex=T;break}}return u}function cr(t){let n=pt(t.parameters,",",!0).flatMap((o,u)=>{let d=r(o),p=0,m=-1;for(let S=0;S<d.length;S++){let C=d[S];if("([{<".includes(C))p++;else if(")]}>".includes(C)&&!(C===">"&&d[S-1]==="="))p--;if(C==="="&&p===0&&d[S+1]!==">"){m=S;break}}let y=(m<0?o:o.slice(0,m)).trim(),b=pt(y,":",!0),v=b.shift().trim();if(v==="this")return[];let w=/^[A-Za-z_$]|^\.\.\./.test(v)?v:`argument${u}`,k=m<0?"":o.slice(m+1).trim(),R=k==="true"||k==="false"?"boolean":/^-?\d+(?:\.\d+)?$/.test(k)?"number":/^['"`]/.test(k)?"string":w.startsWith("...")?"unknown[]":"unknown",E=b.join(":").trim()||R,T=m>=0&&!w.endsWith("?")&&!w.startsWith("...")?"?":"";return[`${w}${T}: ${E}`]}).join(", ");return`${t.name}${t.generic}(${n}): ${t.returns||(t.async?"Promise<unknown>":"unknown")}`}function lr(t,n){let o={},u={},d=[],p=[],m=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let w of m){if(/\bserver\b|\bcomponent\b|\bstx:component\b/i.test(w[1])||/\btype=["']application\//i.test(w[1]))continue;try{new Bun.Transpiler({loader:"ts"}).transformSync(w[2])}catch(P){throw Error(`${n}: failed to transpile <script client> (${P.message})`)}let k=/\bclient\b/i.test(w[1])?ar(w[2]):[],R=new Set(k.filter((P)=>!P.source).map((P)=>P.name));for(let P of k){if(ln.has(P.name))throw Error(`${n}: client ${cn(P.name)}`);if(P.source)o[P.name]=new Bun.Transpiler({loader:"ts"}).transformSync(P.source).trim().replace(/^(?:export\s+)?(async\s+)?function\s+/,"$1");if(!P.source||!R.has(P.name))(u[P.name]??=[]).push(cr(P))}for(let P of w[2].matchAll(/^\s*import\s+(?:type\s+)?([\s\S]*?)\s+from\s*(['"])([^'"]+)\2\s*;?/gm))p.push({binding:P[1].trim(),module:P[3]});let E=r(w[2]),T=Y(E).depths,S=/(?:export\s+)?(interface|type)\s+[A-Za-z_$][\w$]*/g,C;while(C=S.exec(E)){if(T[C.index]!==0)continue;let P=S.lastIndex,D=0;for(;P<E.length;P++){let A=E[P];if(A==="{"){let I=Xe(E,P,"{","}");if(I<0)break;if(P=I-1,C[1]==="interface"&&D===0){P++;break}continue}if("([<".includes(A))D++;else if(")]>".includes(A)&&!(A===">"&&E[P-1]==="="))D--;if(C[1]==="type"&&D===0&&(A===";"||A===`
|
|
@@ -896,7 +896,7 @@ else {
|
|
|
896
896
|
};
|
|
897
897
|
})();
|
|
898
898
|
</script>
|
|
899
|
-
`}function qe(t,n,o={}){let u=Wr(n,o),d=c(t);if(d!==-1)return t.slice(0,d)+u+t.slice(d);if(t.includes("</html>"))return t.replace("</html>",`${u}</html>`);return t+u}function St(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function Tt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((u)=>n.endsWith(u))}function Ct(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var at=null;function Et(t){if(!at)at=new dn(t);return at}function ut(){if(at)at.stop(),at=null}import Dt from"path";var ct={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},u=new Set,d=o.webComponents?.enabled?`./${Dt.relative(Dt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let m=await $s(o,u);if(p.push(...m),o.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let y=new Set;if(o.cache&&o.cachePath){let S=await hr(m,o);if(S){if(o.debug)console.log(`Using cached version of ${m}`);return{contents:S,loader:"html"}}}let b=await $e(()=>Bun.file(m).text(),"",(S)=>{throw new Or(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${S.message}`)});if(!b)throw new Or(`stx file is empty: ${m}`,m);let{scriptContent:v,templateContent:w,allScripts:k}=ge.time("script-extraction",()=>{let S=b,C=L(b);if(C)S=C.content.trim();let P=b.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],D="",A=[];for(let O of P){let j=O.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=O.match(/<script\b([^>]*)>/i),G=F?F[1]:"";if(/\bserver\b/i.test(G))D=j;else A.push(O)}let I=S.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:D,templateContent:I,allScripts:A}}),R={__filename:m,__dirname:Dt.dirname(m),__stx:{webComponentsPath:d,builtComponents:p}};await $e(()=>h(v,R,m),void 0,(S)=>{let C=new oe(`Script execution failed in ${m}: ${S.message}`,m,void 0,void 0,v.substring(0,100));if(W.log(C,{filePath:m,scriptContent:v}),o.debug)throw C});let T=await ge.timeAsync("directive-processing",async()=>await i(w,R,m,o,y));if(k.length>0){let{interpolateScriptsInTemplate:S}=await import("./chunk-
|
|
899
|
+
`}function qe(t,n,o={}){let u=Wr(n,o),d=c(t);if(d!==-1)return t.slice(0,d)+u+t.slice(d);if(t.includes("</html>"))return t.replace("</html>",`${u}</html>`);return t+u}function St(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function Tt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((u)=>n.endsWith(u))}function Ct(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var at=null;function Et(t){if(!at)at=new dn(t);return at}function ut(){if(at)at.stop(),at=null}import Dt from"path";var ct={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},u=new Set,d=o.webComponents?.enabled?`./${Dt.relative(Dt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let m=await $s(o,u);if(p.push(...m),o.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let y=new Set;if(o.cache&&o.cachePath){let S=await hr(m,o);if(S){if(o.debug)console.log(`Using cached version of ${m}`);return{contents:S,loader:"html"}}}let b=await $e(()=>Bun.file(m).text(),"",(S)=>{throw new Or(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${S.message}`)});if(!b)throw new Or(`stx file is empty: ${m}`,m);let{scriptContent:v,templateContent:w,allScripts:k}=ge.time("script-extraction",()=>{let S=b,C=L(b);if(C)S=C.content.trim();let P=b.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],D="",A=[];for(let O of P){let j=O.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=O.match(/<script\b([^>]*)>/i),G=F?F[1]:"";if(/\bserver\b/i.test(G))D=j;else A.push(O)}let I=S.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:D,templateContent:I,allScripts:A}}),R={__filename:m,__dirname:Dt.dirname(m),__stx:{webComponentsPath:d,builtComponents:p}};await $e(()=>h(v,R,m),void 0,(S)=>{let C=new oe(`Script execution failed in ${m}: ${S.message}`,m,void 0,void 0,v.substring(0,100));if(W.log(C,{filePath:m,scriptContent:v}),o.debug)throw C});let T=await ge.timeAsync("directive-processing",async()=>await i(w,R,m,o,y));if(k.length>0){let{interpolateScriptsInTemplate:S}=await import("./chunk-z347p6cg.js"),C=S(k.join(`
|
|
900
900
|
`),R),P=T.search(/<\/body>/i);if(P!==-1)T=T.slice(0,P)+C+`
|
|
901
901
|
`+T.slice(P);else T+=`
|
|
902
902
|
${C}`}if(T=await _e(T),y.forEach((S)=>u.add(S)),o.cache&&o.cachePath){if(await yr(m,T,y,o),o.debug)console.log(`Cached template ${m} with ${y.size} dependencies`)}return{contents:T,loader:"html"}}catch(y){let b=y instanceof Error?y:new oe(`Plugin processing failed: ${String(y)}`,m);if(W.log(b,{filePath:m,buildConfig:t.config}),Rn.logDetailedError(b,{filePath:m,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",b);let v=b,w=v.line||null,k=v.context||null;return{contents:o.debug||Q()?`<!DOCTYPE html>
|
|
@@ -959,7 +959,7 @@ ${C}`}if(T=await _e(T),y.forEach((S)=>u.add(S)),o.cache&&o.cachePath){if(await y
|
|
|
959
959
|
<h1>Something went wrong</h1>
|
|
960
960
|
<p>An internal error occurred. Please try again later.</p>
|
|
961
961
|
</body>
|
|
962
|
-
</html>`,loader:"html"}}})}};async function Kr(t,n={}){let o=n.port||3000,u=n.watch!==!1,d=n.hotReload!==!1&&u,p=null,m=n.hmrPort||o+1,y=be.resolve(t);if(!Ue.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(y.endsWith(".md"))return qt(y,n);else if(!y.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1;let b=l(process.cwd(),"output");Ue.mkdirSync(b,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let v=null,w=async()=>{try{let j={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(fe)=>({path:fe.path,external:!0}))}},F=await Bun.build({entrypoints:[y],outdir:b,plugins:[j,ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let G=F.outputs.find((Te)=>Te.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return v=await Bun.file(G.path).text(),!0}catch(j){return console.error(`${e.red}Error building stx file:${e.reset}`,j),!1}};if(!await w())return!1;let R=be.dirname(y);await mn(R);let E=o;try{if(E=await Ge(o),E!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(d){let j=n.hmrPort||E+1;p=Et({wsPort:j,verbose:!1}),m=p.start(j)}let T={},S=null,C;try{let{loadStxConfig:j}=await import("./chunk-
|
|
962
|
+
</html>`,loader:"html"}}})}};async function Kr(t,n={}){let o=n.port||3000,u=n.watch!==!1,d=n.hotReload!==!1&&u,p=null,m=n.hmrPort||o+1,y=be.resolve(t);if(!Ue.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(y.endsWith(".md"))return qt(y,n);else if(!y.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1;let b=l(process.cwd(),"output");Ue.mkdirSync(b,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let v=null,w=async()=>{try{let j={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(fe)=>({path:fe.path,external:!0}))}},F=await Bun.build({entrypoints:[y],outdir:b,plugins:[j,ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let G=F.outputs.find((Te)=>Te.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return v=await Bun.file(G.path).text(),!0}catch(j){return console.error(`${e.red}Error building stx file:${e.reset}`,j),!1}};if(!await w())return!1;let R=be.dirname(y);await mn(R);let E=o;try{if(E=await Ge(o),E!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(d){let j=n.hmrPort||E+1;p=Et({wsPort:j,verbose:!1}),m=p.start(j)}let T={},S=null,C;try{let{loadStxConfig:j}=await import("./chunk-p71c1wrw.js"),F=await j();if(C=n.stxOptions?.serverApi??F.serverApi,F?.apiRouter)S=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){T=F.apiRoutes;let G=Object.keys(T).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:ne}=await import("./chunk-rqa92xm4.js"),Te=F.broadcasting;await G(Te);let fe=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${fe}/ws${e.reset}`);let De=be.join(process.cwd(),"channels.ts");if(Ue.existsSync(De))try{let ce=await ne(De);console.log(`${e.blue}Loaded ${e.bright}${ce} broadcast channel${ce!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ce){console.warn(`${e.yellow}Failed to load channels.ts: ${ce.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:P,isServerApiSource:D}=await import("./chunk-hmsjjw34.js"),A=await P(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),d)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Vr({port:E,async fetch(j){return Dn(j,await(async()=>{let F=new URL(j.url);if([b,be.dirname(y),be.join(process.cwd(),"public")].some((ce)=>D(be.join(ce,F.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(S)try{let ce=await S.handleRequest(j);if(ce.status!==404)return ce}catch{}if(T[F.pathname])try{return await T[F.pathname](j)}catch(ce){return new Response(JSON.stringify({error:ce.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await A(j);if(G)return G;if(F.pathname==="/")return(async()=>{let V=await x(v||"");if(d)V=qe(V,m);if(n.native)if(V.includes("<head>"))V=V.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(V.includes("<html"))V=V.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 V="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+V;if(n.titlebarHidden)if(V.includes("<head>"))V=V.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(V.includes("<html"))V=V.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 V=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${V}`;return V})().then((V)=>new Response(V,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let ne=be.join(b,F.pathname);if(Ue.existsSync(ne)&&Ue.statSync(ne).isFile()){let ce=Bun.file(ne),V=be.extname(ne).toLowerCase(),B="text/plain";if(V===".ts"||V===".tsx"){let We=new Bun.Transpiler({loader:V===".tsx"?"tsx":"ts"}),Ve=await ce.text(),nt=We.transformSync(Ve);return new Response(nt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(V){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ce,{headers:{"Content-Type":B}})}let Te=be.dirname(y),fe=be.join(Te,F.pathname);if(Ue.existsSync(fe)&&Ue.statSync(fe).isFile()){let ce=Bun.file(fe),V=be.extname(fe).toLowerCase(),B="text/plain";if(V===".ts"||V===".tsx"){let We=new Bun.Transpiler({loader:V===".tsx"?"tsx":"ts"}),Ve=await ce.text(),nt=We.transformSync(Ve);return new Response(nt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(V){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ce,{headers:{"Content-Type":B}})}let De=be.join(process.cwd(),"public",F.pathname);if(Ue.existsSync(De)&&Ue.statSync(De).isFile()){let ce=Bun.file(De),V=be.extname(De).toLowerCase(),B="application/octet-stream";if(V===".ts"||V===".tsx"){let We=new Bun.Transpiler({loader:V===".tsx"?"tsx":"ts"}),Ve=await ce.text(),nt=We.transformSync(Ve);return new Response(nt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(V){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ce,{headers:{"Content-Type":B}})}return new Response("Not Found",{status:404})})())},error(j){return new Response(`<pre>${j}
|
|
963
963
|
${j.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
964
964
|
${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(`
|
|
965
965
|
${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
|
|
@@ -1444,12 +1444,12 @@ ${T.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1444
1444
|
${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(`
|
|
1445
1445
|
${e.bright}\u2192 ${e.cyan}http://localhost:${w}/${e.reset}`),console.log(`
|
|
1446
1446
|
${e.yellow}Routes:${e.reset}`);let R=new Set(y.map((T)=>T.routeTemplate)),E=Object.entries(m).filter(([T])=>!R.has(T)).sort(([T],[S])=>T.localeCompare(S)).map(([T,S])=>({route:T==="/"?"/":T,filePath:Ee.relative(process.cwd(),S.filePath),fileType:S.fileType}));for(let T of y){let S=T.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");E.push({route:S,filePath:Ee.relative(process.cwd(),T.filePath),fileType:"stx"})}if(E.sort((T,S)=>T.route.localeCompare(S.route)),E.forEach((T,S)=>{let P=S===E.length-1?"\u2514\u2500 ":"\u251C\u2500 ",D=T.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${P}${T.route}${e.reset} \u2192 ${e.bright}${T.filePath}${e.reset} ${D}`)}),console.log(`
|
|
1447
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(k.url.toString(),()=>{if(u)Qe.watch(p,{recursive:!0}).close();k.stop()}),u){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=Qe.watch(p,{recursive:!0},async(S,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),we(),await b()});process.on("SIGINT",()=>{T.close(),k.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Jr}=globalThis.Bun;import ye from"fs";import ae from"path";async function gn(t){try{return vn(await Bun.file(t).text())}catch{return}}function Kt(t){let n=Bun.file(t),o=ae.extname(t).toLowerCase(),u={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":u[o]||"application/octet-stream",...p}})}async function Gr(t=".",n={}){let o=n.port||3000,u=n.watch!==!1,d=n.hotReload!==!1&&u,p=null,m=n.hmrPort||o+1,y=ae.resolve(t),{loadStxConfig:b}=await import("./chunk-cv9vmz5x.js"),v=await b(y),{createServerApi:w,isServerApiSource:k}=await import("./chunk-vv9anbw1.js"),R=n.stxOptions?.serverApi??v.serverApi,E=await w(y,R),T=v.root&&v.root!=="."?ae.join(y,v.root):y,S=n.pagesDir||v.pagesDir||"pages",C=ae.join(T,S);if(!ye.existsSync(C)&&!v._layerPageDirs?.some((_)=>ye.existsSync(_)))return console.error(`${e.red}Error: No '${S}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${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 ${S}/index.stx for the homepage.${e.reset}`),!1;let P=ee(T,{pagesDir:S,pagesDirs:v._layerPageDirs?[C,...v._layerPageDirs.slice(1)]:void 0});if(P.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${P.length}${e.blue} routes${e.reset}`);let D=v?._pluginPageDirs||[],A=[];for(let{dir:_,prefix:z}of D)if(ye.existsSync(_)){let q=ee(ae.dirname(_),{pagesDir:ae.basename(_)});for(let re of q){let J=z==="/"?re.pattern:`${z}${re.pattern==="/"?"":re.pattern}`;A.push({route:{...re,pattern:J},prefix:z})}if(q.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${q.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let I=new Map,O=null,j=null;if(n.stxOptions?.shell!==!1){if(j=await wa(y,n.stxOptions?.shell),j){if(O=await So(j,n.stxOptions||{}),O)console.log(`${e.blue}Using app shell: ${e.bright}${ae.relative(y,j)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Rt(),await Pt(y);let F=At();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let G={},ne=null;try{let{loadStxConfig:_}=await import("./chunk-cv9vmz5x.js"),z=await _(y);if(z?.apiRouter)ne=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){G=z.apiRoutes;let q=Object.keys(G).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:re}=await import("./chunk-rqa92xm4.js"),J=z.broadcasting;await q(J);let Me=J.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Me}/ws${e.reset}`);let Ce=ae.join(process.cwd(),"channels.ts");if(ye.existsSync(Ce))try{let K=await re(Ce);console.log(`${e.blue}Loaded ${e.bright}${K} broadcast channel${K!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(K){console.warn(`${e.yellow}Failed to load channels.ts: ${K.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let Te=l(y,"output");ye.mkdirSync(Te,{recursive:!0});let fe=new Map,De=new Set,ce=async(_)=>{let z=Ds(C,_);if(!z)return null;try{let q=await Bun.build({entrypoints:[z],outdir:Te,plugins:[ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!q.success)return null;let re=q.outputs.find((J)=>J.path.endsWith(".html"));if(!re)return null;return await Bun.file(re.path).text()}catch{return null}},V=new Map,B=async(_,z)=>{try{let{processDirectives:q,extractVariables:re,defaultConfig:J,loadStxConfig:Me,injectRouterScript:Ce}=await import("./chunk-cv9vmz5x.js"),{checkCache:K,cacheTemplate:te,readFileCached:X,templateCache:me}=await import("./chunk-v4ab2jzz.js"),Z=await Me(y),Ke=(pe)=>{if(!pe)return pe;if(ae.isAbsolute(pe))return pe;return ae.resolve(y,pe)},ue={...J,...Z,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ue.debug=!0;ue.partialsDir=Ke(ue.partialsDir),ue.componentsDir=Ke(ue.componentsDir),ue.layoutsDir=Ke(ue.layoutsDir),ue.storesDir=Ke(ue.storesDir||"stores"),ue.cachePath=Ke(ue.cachePath)??l(y,"cache");let N=!z&&!n.profile,le=ue.cache!==!1;if(le&&N){let pe=me.get(_.filePath);if(pe)try{if((await ye.promises.stat(_.filePath)).mtime.getTime()<=pe.mtime){let ze=!0;for(let Re of pe.dependencies){if(!ye.existsSync(Re)){ze=!1;break}if((await ye.promises.stat(Re)).mtime.getTime()>pe.mtime){ze=!1;break}}if(ze){let Re=pe.output;if(O)Re=Je(Re,{preserveHead:!0});let dt=V.get(_.filePath);return{route:_,content:Re,status:dt?.status??await gn(_.filePath),headers:dt?.headers}}}}catch{}let He=await K(_.filePath,ue);if(He){let Fe=He;if(O)Fe=Je(Fe,{preserveHead:!0});let ze=V.get(_.filePath);return{route:_,content:Fe,status:ze?.status??await gn(_.filePath),headers:ze?.headers}}}let se=le?await X(_.filePath):await Bun.file(_.filePath).text(),de=vn(se),{classifyAllScripts:he}=await import("./chunk-cv9vmz5x.js"),U=he(se),Be=U.server.map((pe)=>pe.content),Ie=se;for(let pe of U.server)Ie=Ie.replace(pe.fullTag,"");let ie={__filename:_.filePath,__dirname:ae.dirname(_.filePath),__stx_options:ue,params:z??{},__stx_runtime_head:{}};for(let pe of Be)try{await re(pe,ie,_.filePath)}catch(He){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",_.filePath,He?.message||He)}let Le=new Set,xe;if(n.profile){let pe=performance.now();xe=await q(Ie,ie,_.filePath,ue,Le);let He=performance.now()-pe,Fe=ae.relative(y,_.filePath)||_.filePath;console.log(`[stx:profile] ${Fe} \u2192 ${He.toFixed(2)}ms`)}else xe=await q(Ie,ie,_.filePath,ue,Le);if(!O)xe=await Ce(xe,{router:ue.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-f5gg0pxj.js");xe=xe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(He,Fe,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return He;return`<script${Fe}>${pe(ze,ie)}</script>`})}if(O)xe=Je(xe,{preserveHead:!0});if(le&&N)await te(_.filePath,xe,Le,ue);let{extractStreamBoundaries:gt}=await import("./chunk-jkevn2jy.js"),rt=gt(ie),lt=ie.__streamTemplates;if(lt&&typeof lt==="object"&&Object.keys(lt).length>0){let pe=ie.streamBoundaries||{},He={...ue,autoShell:!1},Fe=Object.keys(lt).map((Re)=>({id:Re,render:async()=>{let dt=typeof pe[Re]==="function"?await pe[Re]():void 0;return q(lt[Re],{...ie,$boundary:dt},_.filePath,He,new Set)}})),ze=new Set(Fe.map((Re)=>Re.id));rt=[...(rt||[]).filter((Re)=>!ze.has(Re.id)),...Fe]}if(rt&&rt.length>0)De.add(_.pattern);else rt=void 0;let Jt=Bt(ie),Yt=Ft(ie);if(N)V.set(_.filePath,{status:Jt,headers:Yt});return{route:_,content:xe,status:Jt??de,headers:Yt,boundaries:rt}}catch(q){return console.error(`${e.red}Error building ${e.bright}${_.pattern}${e.reset}:`,q),null}},We=8,Ve=async()=>{let _=new Set(fe.keys()),z=new Set(I.keys());fe.clear(),I.clear();let q=n.prebuild===!1?P.filter((J)=>_.has(J.pattern)):P,re=n.prebuild===!1?A.filter(({route:J})=>z.has(J.pattern)):A;for(let J=0;J<q.length;J+=We){let Me=q.slice(J,J+We),Ce=await Promise.all(Me.map((K)=>B(K)));for(let K of Ce)if(K)fe.set(K.route.pattern,K)}for(let J=0;J<re.length;J+=We){let Me=re.slice(J,J+We),Ce=await Promise.all(Me.map(({route:K})=>B(K)));for(let K of Ce)if(K)I.set(K.route.pattern,K)}return fe.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?P.length+A.length>0:await Ve()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await mn(y);let et=o;try{if(et=await Ge(o),et!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(d){let _=n.hmrPort||et+1;p=Et({wsPort:_,verbose:!1}),m=p.start(_)}let _t=(_,z)=>{let re=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).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(_.includes("</head>"))return f(_,re,"");if(_.includes("<body"))return _.replace(/<body([^>]*)>/,`<body$1>${re}`);return re+_};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Jr({port:et,hostname:n.hostname,async fetch(_){let z=new URL(_.url),q=n.stxOptions?.offline??v.offline;if(z.pathname===zo&&q?.enabled){if(!["GET","HEAD"].includes(_.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(_.method==="HEAD"?null:Ho(q,ps()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let re=v?.publicDir||"public",J=ae.join(y,re,z.pathname),Me=ae.join(y,z.pathname),Ce=ae.join(Te,z.pathname);if([J,Me,Ce].some((N)=>k(N,y,R)))return new Response("Not Found",{status:404});let[K,te,X]=await Promise.all([ye.promises.stat(J).catch(()=>null),ye.promises.stat(Me).catch(()=>null),ye.promises.stat(Ce).catch(()=>null)]);if(K?.isFile()&&!k(J,y,R))return Kt(J);if(te?.isFile()&&!k(Me,y,R))return Kt(Me);if(X?.isFile()&&!k(Ce,y,R))return Kt(Ce);if(z.pathname.startsWith("/_stx/component/")){let N=decodeURIComponent(z.pathname.slice(16));if(N)try{let le=`<${N} />`,se={...buildConfig,autoShell:!1},de=await processDirectives(le,{},ae.join(y,"components",`${N}.stx`),se,new Set);return new Response(de,{headers:{"Content-Type":"text/html"}})}catch(le){return new Response(`<div class="stx-async-error">${le.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:N}=await import("./chunk-gc4bgven.js"),le=await N(_,{publicDir:ae.join(y,re),cacheDir:l(y,"cache","img")});if(le)return le}if(ne)try{let N=await ne.handleRequest(_);if(N.status!==404)return N}catch{}if(G[z.pathname])try{return await G[z.pathname](_)}catch(N){return new Response(JSON.stringify({error:N.message}),{status:500,headers:{"Content-Type":"application/json"}})}let me=await E(_);if(me)return me;let Z=wr(z.pathname,P);if(Z){let N=fe.get(Z.route.pattern),le=De.has(Z.route.pattern);if(!N||Z.route.isDynamic&&Object.keys(Z.params).length>0||le){let se=await B(Z.route,Z.params);if(se){if(N=se,!Z.route.isDynamic&&!le)fe.set(Z.route.pattern,se)}}if(N){let se=N.status??200,de=N.headers??{},he=(Z.route.filePath?kt(await Bun.file(Z.route.filePath).text().catch(()=>"")):null)??{};if(he.validate){if(!await he.validate({params:Z.params})){let Ie=await ce(404);if(Ie){let ie=Ie;if(ie=await x(ie,y),d)ie=qe(ie,m);return new Response(ie,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(he.middleware){let Be=It(z.pathname,Z.params,he,z.search),Ie=Ot(Be,null,_,{isServer:!0}),ie=await Nt(he.middleware,Ie);if(ie.redirect){let Le=ie.redirect.path,xe=ie.redirect.options.redirectCode||302,gt=new Headers(ie.responseHeaders);return gt.set("Location",Le),new Response(null,{status:xe,headers:gt})}if(ie.abort){let{statusCode:Le,message:xe}=ie.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Le}</title></head><body><h1>Error ${Le}</h1><p>${xe}</p></body></html>`,{status:Le,headers:{"Content-Type":"text/html"}})}if(Object.keys(ie.state).length>0){let Le=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ie.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;N.content=f(N.content,Le,"")}}let U=N.content;if(O&&va(_)&&Ye(U,v?.router?.container||"main")){let Be=ot(U),Ie=ke(U),ie=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Le=ie?en(ie[1].trim()):"";if(Object.keys(Z.params).length>0)U=_t(U,Z.params);U=await x(U,y);let xe=v?.router?.container||"main";return U=Pe(U,xe,!0),new Response(U,{status:se,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Be.layout,"X-STX-Layout-Group":Be.group,"X-STX-Runtime":Ie?"true":"false",...Le&&{"X-STX-Title":encodeURIComponent(Le)},[hc]:ps(),...H(),"Cache-Control":wt}})}if(O)U=Qr(O,U);if(Object.keys(Z.params).length>0)U=_t(U,Z.params);if(U=await x(U,y),d)U=qe(U,m);if(n.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(n.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(N.boundaries&&N.boundaries.length>0){let{renderStreamingPage:Be,streamToResponse:Ie}=await import("./chunk-jkevn2jy.js");return Ie(Be(U,N.boundaries,{timeoutMs:30000}),{status:se,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:se,headers:{"Content-Type":"text/html",...H(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...de}})}}if(A.length>0){let N=A.map((se)=>se.route),le=wr(z.pathname,N);if(le){let se=I.get(le.route.pattern);if(!se||le.route.isDynamic){let de=await B(le.route,le.params);if(de){if(se=de,!le.route.isDynamic)I.set(le.route.pattern,de)}}if(se){let de=se.content;if(O)de=Qr(O,de);if(Object.keys(le.params).length>0)de=_t(de,le.params);if(de=await x(de,y),d)de=qe(de,m);return new Response(de,{status:se.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:se}of D)if(se!=="/"&&z.pathname.startsWith(se)){let de=I.get(se)||I.get(se+"/");if(!de){let he=A.find(({route:U})=>U.pattern===se||U.pattern===`${se}/`);if(he){let U=await B(he.route);if(U)de=U,I.set(he.route.pattern,U)}}if(de){let he=de.content;if(O)he=Qr(O,he);if(he=await x(he,y),d)he=qe(he,m);return new Response(he,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if($t(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ke=fe.get("/");if(Ke){let N=Ke.content;if(N=await x(N,y),d)N=qe(N,m);if(n.native)if(N.includes("<head>"))N=N.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 N="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+N;return new Response(N,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ue=await ce(404);if(ue){let N=ue;if(N=await x(N,y),d)N=qe(N,m);return new Response(N,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(_){let z=await ce(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${_}
|
|
1447
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(k.url.toString(),()=>{if(u)Qe.watch(p,{recursive:!0}).close();k.stop()}),u){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=Qe.watch(p,{recursive:!0},async(S,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),we(),await b()});process.on("SIGINT",()=>{T.close(),k.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Jr}=globalThis.Bun;import ye from"fs";import ae from"path";async function gn(t){try{return vn(await Bun.file(t).text())}catch{return}}function Kt(t){let n=Bun.file(t),o=ae.extname(t).toLowerCase(),u={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":u[o]||"application/octet-stream",...p}})}async function Gr(t=".",n={}){let o=n.port||3000,u=n.watch!==!1,d=n.hotReload!==!1&&u,p=null,m=n.hmrPort||o+1,y=ae.resolve(t),{loadStxConfig:b}=await import("./chunk-p71c1wrw.js"),v=await b(y),{createServerApi:w,isServerApiSource:k}=await import("./chunk-hmsjjw34.js"),R=n.stxOptions?.serverApi??v.serverApi,E=await w(y,R),T=v.root&&v.root!=="."?ae.join(y,v.root):y,S=n.pagesDir||v.pagesDir||"pages",C=ae.join(T,S);if(!ye.existsSync(C)&&!v._layerPageDirs?.some((_)=>ye.existsSync(_)))return console.error(`${e.red}Error: No '${S}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${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 ${S}/index.stx for the homepage.${e.reset}`),!1;let P=ee(T,{pagesDir:S,pagesDirs:v._layerPageDirs?[C,...v._layerPageDirs.slice(1)]:void 0});if(P.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${P.length}${e.blue} routes${e.reset}`);let D=v?._pluginPageDirs||[],A=[];for(let{dir:_,prefix:z}of D)if(ye.existsSync(_)){let q=ee(ae.dirname(_),{pagesDir:ae.basename(_)});for(let re of q){let J=z==="/"?re.pattern:`${z}${re.pattern==="/"?"":re.pattern}`;A.push({route:{...re,pattern:J},prefix:z})}if(q.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${q.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let I=new Map,O=null,j=null;if(n.stxOptions?.shell!==!1){if(j=await wa(y,n.stxOptions?.shell),j){if(O=await So(j,n.stxOptions||{}),O)console.log(`${e.blue}Using app shell: ${e.bright}${ae.relative(y,j)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Rt(),await Pt(y);let F=At();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let G={},ne=null;try{let{loadStxConfig:_}=await import("./chunk-p71c1wrw.js"),z=await _(y);if(z?.apiRouter)ne=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){G=z.apiRoutes;let q=Object.keys(G).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:re}=await import("./chunk-rqa92xm4.js"),J=z.broadcasting;await q(J);let Me=J.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Me}/ws${e.reset}`);let Ce=ae.join(process.cwd(),"channels.ts");if(ye.existsSync(Ce))try{let K=await re(Ce);console.log(`${e.blue}Loaded ${e.bright}${K} broadcast channel${K!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(K){console.warn(`${e.yellow}Failed to load channels.ts: ${K.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let Te=l(y,"output");ye.mkdirSync(Te,{recursive:!0});let fe=new Map,De=new Set,ce=async(_)=>{let z=Ds(C,_);if(!z)return null;try{let q=await Bun.build({entrypoints:[z],outdir:Te,plugins:[ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!q.success)return null;let re=q.outputs.find((J)=>J.path.endsWith(".html"));if(!re)return null;return await Bun.file(re.path).text()}catch{return null}},V=new Map,B=async(_,z)=>{try{let{processDirectives:q,extractVariables:re,defaultConfig:J,loadStxConfig:Me,injectRouterScript:Ce}=await import("./chunk-p71c1wrw.js"),{checkCache:K,cacheTemplate:te,readFileCached:X,templateCache:me}=await import("./chunk-60ezkjcz.js"),Z=await Me(y),Ke=(pe)=>{if(!pe)return pe;if(ae.isAbsolute(pe))return pe;return ae.resolve(y,pe)},ue={...J,...Z,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ue.debug=!0;ue.partialsDir=Ke(ue.partialsDir),ue.componentsDir=Ke(ue.componentsDir),ue.layoutsDir=Ke(ue.layoutsDir),ue.storesDir=Ke(ue.storesDir||"stores"),ue.cachePath=Ke(ue.cachePath)??l(y,"cache");let N=!z&&!n.profile,le=ue.cache!==!1;if(le&&N){let pe=me.get(_.filePath);if(pe)try{if((await ye.promises.stat(_.filePath)).mtime.getTime()<=pe.mtime){let ze=!0;for(let Re of pe.dependencies){if(!ye.existsSync(Re)){ze=!1;break}if((await ye.promises.stat(Re)).mtime.getTime()>pe.mtime){ze=!1;break}}if(ze){let Re=pe.output;if(O)Re=Je(Re,{preserveHead:!0});let dt=V.get(_.filePath);return{route:_,content:Re,status:dt?.status??await gn(_.filePath),headers:dt?.headers}}}}catch{}let He=await K(_.filePath,ue);if(He){let Fe=He;if(O)Fe=Je(Fe,{preserveHead:!0});let ze=V.get(_.filePath);return{route:_,content:Fe,status:ze?.status??await gn(_.filePath),headers:ze?.headers}}}let se=le?await X(_.filePath):await Bun.file(_.filePath).text(),de=vn(se),{classifyAllScripts:he}=await import("./chunk-p71c1wrw.js"),U=he(se),Be=U.server.map((pe)=>pe.content),Ie=se;for(let pe of U.server)Ie=Ie.replace(pe.fullTag,"");let ie={__filename:_.filePath,__dirname:ae.dirname(_.filePath),__stx_options:ue,params:z??{},__stx_runtime_head:{}};for(let pe of Be)try{await re(pe,ie,_.filePath)}catch(He){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",_.filePath,He?.message||He)}let Le=new Set,xe;if(n.profile){let pe=performance.now();xe=await q(Ie,ie,_.filePath,ue,Le);let He=performance.now()-pe,Fe=ae.relative(y,_.filePath)||_.filePath;console.log(`[stx:profile] ${Fe} \u2192 ${He.toFixed(2)}ms`)}else xe=await q(Ie,ie,_.filePath,ue,Le);if(!O)xe=await Ce(xe,{router:ue.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-z347p6cg.js");xe=xe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(He,Fe,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return He;return`<script${Fe}>${pe(ze,ie)}</script>`})}if(O)xe=Je(xe,{preserveHead:!0});if(le&&N)await te(_.filePath,xe,Le,ue);let{extractStreamBoundaries:gt}=await import("./chunk-9kghtf20.js"),rt=gt(ie),lt=ie.__streamTemplates;if(lt&&typeof lt==="object"&&Object.keys(lt).length>0){let pe=ie.streamBoundaries||{},He={...ue,autoShell:!1},Fe=Object.keys(lt).map((Re)=>({id:Re,render:async()=>{let dt=typeof pe[Re]==="function"?await pe[Re]():void 0;return q(lt[Re],{...ie,$boundary:dt},_.filePath,He,new Set)}})),ze=new Set(Fe.map((Re)=>Re.id));rt=[...(rt||[]).filter((Re)=>!ze.has(Re.id)),...Fe]}if(rt&&rt.length>0)De.add(_.pattern);else rt=void 0;let Jt=Bt(ie),Yt=Ft(ie);if(N)V.set(_.filePath,{status:Jt,headers:Yt});return{route:_,content:xe,status:Jt??de,headers:Yt,boundaries:rt}}catch(q){return console.error(`${e.red}Error building ${e.bright}${_.pattern}${e.reset}:`,q),null}},We=8,Ve=async()=>{let _=new Set(fe.keys()),z=new Set(I.keys());fe.clear(),I.clear();let q=n.prebuild===!1?P.filter((J)=>_.has(J.pattern)):P,re=n.prebuild===!1?A.filter(({route:J})=>z.has(J.pattern)):A;for(let J=0;J<q.length;J+=We){let Me=q.slice(J,J+We),Ce=await Promise.all(Me.map((K)=>B(K)));for(let K of Ce)if(K)fe.set(K.route.pattern,K)}for(let J=0;J<re.length;J+=We){let Me=re.slice(J,J+We),Ce=await Promise.all(Me.map(({route:K})=>B(K)));for(let K of Ce)if(K)I.set(K.route.pattern,K)}return fe.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?P.length+A.length>0:await Ve()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await mn(y);let et=o;try{if(et=await Ge(o),et!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(d){let _=n.hmrPort||et+1;p=Et({wsPort:_,verbose:!1}),m=p.start(_)}let _t=(_,z)=>{let re=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).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(_.includes("</head>"))return f(_,re,"");if(_.includes("<body"))return _.replace(/<body([^>]*)>/,`<body$1>${re}`);return re+_};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Jr({port:et,hostname:n.hostname,async fetch(_){let z=new URL(_.url),q=n.stxOptions?.offline??v.offline;if(z.pathname===zo&&q?.enabled){if(!["GET","HEAD"].includes(_.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(_.method==="HEAD"?null:Ho(q,ps()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let re=v?.publicDir||"public",J=ae.join(y,re,z.pathname),Me=ae.join(y,z.pathname),Ce=ae.join(Te,z.pathname);if([J,Me,Ce].some((N)=>k(N,y,R)))return new Response("Not Found",{status:404});let[K,te,X]=await Promise.all([ye.promises.stat(J).catch(()=>null),ye.promises.stat(Me).catch(()=>null),ye.promises.stat(Ce).catch(()=>null)]);if(K?.isFile()&&!k(J,y,R))return Kt(J);if(te?.isFile()&&!k(Me,y,R))return Kt(Me);if(X?.isFile()&&!k(Ce,y,R))return Kt(Ce);if(z.pathname.startsWith("/_stx/component/")){let N=decodeURIComponent(z.pathname.slice(16));if(N)try{let le=`<${N} />`,se={...buildConfig,autoShell:!1},de=await processDirectives(le,{},ae.join(y,"components",`${N}.stx`),se,new Set);return new Response(de,{headers:{"Content-Type":"text/html"}})}catch(le){return new Response(`<div class="stx-async-error">${le.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:N}=await import("./chunk-gc4bgven.js"),le=await N(_,{publicDir:ae.join(y,re),cacheDir:l(y,"cache","img")});if(le)return le}if(ne)try{let N=await ne.handleRequest(_);if(N.status!==404)return N}catch{}if(G[z.pathname])try{return await G[z.pathname](_)}catch(N){return new Response(JSON.stringify({error:N.message}),{status:500,headers:{"Content-Type":"application/json"}})}let me=await E(_);if(me)return me;let Z=wr(z.pathname,P);if(Z){let N=fe.get(Z.route.pattern),le=De.has(Z.route.pattern);if(!N||Z.route.isDynamic&&Object.keys(Z.params).length>0||le){let se=await B(Z.route,Z.params);if(se){if(N=se,!Z.route.isDynamic&&!le)fe.set(Z.route.pattern,se)}}if(N){let se=N.status??200,de=N.headers??{},he=(Z.route.filePath?kt(await Bun.file(Z.route.filePath).text().catch(()=>"")):null)??{};if(he.validate){if(!await he.validate({params:Z.params})){let Ie=await ce(404);if(Ie){let ie=Ie;if(ie=await x(ie,y),d)ie=qe(ie,m);return new Response(ie,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(he.middleware){let Be=It(z.pathname,Z.params,he,z.search),Ie=Ot(Be,null,_,{isServer:!0}),ie=await Nt(he.middleware,Ie);if(ie.redirect){let Le=ie.redirect.path,xe=ie.redirect.options.redirectCode||302,gt=new Headers(ie.responseHeaders);return gt.set("Location",Le),new Response(null,{status:xe,headers:gt})}if(ie.abort){let{statusCode:Le,message:xe}=ie.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Le}</title></head><body><h1>Error ${Le}</h1><p>${xe}</p></body></html>`,{status:Le,headers:{"Content-Type":"text/html"}})}if(Object.keys(ie.state).length>0){let Le=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ie.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;N.content=f(N.content,Le,"")}}let U=N.content;if(O&&va(_)&&Ye(U,v?.router?.container||"main")){let Be=ot(U),Ie=ke(U),ie=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Le=ie?en(ie[1].trim()):"";if(Object.keys(Z.params).length>0)U=_t(U,Z.params);U=await x(U,y);let xe=v?.router?.container||"main";return U=Pe(U,xe,!0),new Response(U,{status:se,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Be.layout,"X-STX-Layout-Group":Be.group,"X-STX-Runtime":Ie?"true":"false",...Le&&{"X-STX-Title":encodeURIComponent(Le)},[hc]:ps(),...H(),"Cache-Control":wt}})}if(O)U=Qr(O,U);if(Object.keys(Z.params).length>0)U=_t(U,Z.params);if(U=await x(U,y),d)U=qe(U,m);if(n.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(n.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(N.boundaries&&N.boundaries.length>0){let{renderStreamingPage:Be,streamToResponse:Ie}=await import("./chunk-9kghtf20.js");return Ie(Be(U,N.boundaries,{timeoutMs:30000}),{status:se,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:se,headers:{"Content-Type":"text/html",...H(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...de}})}}if(A.length>0){let N=A.map((se)=>se.route),le=wr(z.pathname,N);if(le){let se=I.get(le.route.pattern);if(!se||le.route.isDynamic){let de=await B(le.route,le.params);if(de){if(se=de,!le.route.isDynamic)I.set(le.route.pattern,de)}}if(se){let de=se.content;if(O)de=Qr(O,de);if(Object.keys(le.params).length>0)de=_t(de,le.params);if(de=await x(de,y),d)de=qe(de,m);return new Response(de,{status:se.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:se}of D)if(se!=="/"&&z.pathname.startsWith(se)){let de=I.get(se)||I.get(se+"/");if(!de){let he=A.find(({route:U})=>U.pattern===se||U.pattern===`${se}/`);if(he){let U=await B(he.route);if(U)de=U,I.set(he.route.pattern,U)}}if(de){let he=de.content;if(O)he=Qr(O,he);if(he=await x(he,y),d)he=qe(he,m);return new Response(he,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if($t(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ke=fe.get("/");if(Ke){let N=Ke.content;if(N=await x(N,y),d)N=qe(N,m);if(n.native)if(N.includes("<head>"))N=N.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 N="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+N;return new Response(N,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ue=await ce(404);if(ue){let N=ue;if(N=await x(N,y),d)N=qe(N,m);return new Response(N,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(_){let z=await ce(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${_}
|
|
1448
1448
|
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1449
1449
|
${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(`
|
|
1450
1450
|
${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),d)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
1451
1451
|
${e.yellow}Routes:${e.reset}`);let jt=[...Ms(P,y)];for(let{route:_}of A)jt.push(`${_.pattern}`);if(jt.forEach((_,z)=>{let re=z===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${re}${e.reset}${_}`)}),console.log(`
|
|
1452
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(p)ut();Lt.stop()}),n.native){let _,z=ae.join(C,"index.stx");if(ye.existsSync(z)){let re=await Bun.file(z).text();_=vt(re)}let q=v?.app?.window??{};await st(et,{title:v?.app?.head?.title||ae.basename(y)||"stx App",width:q.width,height:q.height,darkMode:q.darkMode,hotReload:q.hotReload,titlebarHidden:q.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!_,sidebarConfig:_})}if(u){console.log(`${e.blue}Watching for changes...${e.reset}`);let _=(K)=>K.startsWith("public/")||K.startsWith("public\\"),z=(K)=>{let te=K.toLowerCase();return te.endsWith(".stx")||te.endsWith(".html")||te.endsWith(".md")},q=new Map,re=()=>{let K=new Set([y,...v._layerGraph?.layers.map((te)=>te.root)??[],...v._layerGraph?.configDependencies.map((te)=>ae.dirname(te))??[]].filter((te)=>ye.existsSync(te)).map((te)=>ye.realpathSync(te)));for(let te of v._layerGraph?.layers??[])for(let X of Object.values(te.resources)){if(!ye.existsSync(X))continue;let me=ye.realpathSync(X);if(![...K].some((Z)=>me===Z||me.startsWith(`${Z}${ae.sep}`)))K.add(me)}for(let[te,X]of q)if(!K.has(te))X.close(),q.delete(te);for(let te of K)if(!q.has(te)&&ye.existsSync(te))q.set(te,ye.watch(te,{recursive:!0},(X,me)=>{Me(te,X,me).catch((Z)=>console.error("[stx] Layer rebuild failed:",Z))}))},J=Promise.resolve(),Me=(K,te,X)=>(J=J.catch(()=>{}).then(()=>Ce(K,te,X)),J),Ce=async(K,te,X)=>{if(!X||Ct(X))return;if(Tt(X)){if(v._layerGraph){let me=await b(y);Object.assign(v,me),P.splice(0,P.length,...ee(T,{pagesDir:S,pagesDirs:me._layerPageDirs?[C,...me._layerPageDirs.slice(1)]:void 0})),re()}if(_(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),d&&p)p.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),tt.clear(),we();try{let{invalidateFileCache:me,templateCache:Z}=await import("./chunk-
|
|
1452
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(p)ut();Lt.stop()}),n.native){let _,z=ae.join(C,"index.stx");if(ye.existsSync(z)){let re=await Bun.file(z).text();_=vt(re)}let q=v?.app?.window??{};await st(et,{title:v?.app?.head?.title||ae.basename(y)||"stx App",width:q.width,height:q.height,darkMode:q.darkMode,hotReload:q.hotReload,titlebarHidden:q.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!_,sidebarConfig:_})}if(u){console.log(`${e.blue}Watching for changes...${e.reset}`);let _=(K)=>K.startsWith("public/")||K.startsWith("public\\"),z=(K)=>{let te=K.toLowerCase();return te.endsWith(".stx")||te.endsWith(".html")||te.endsWith(".md")},q=new Map,re=()=>{let K=new Set([y,...v._layerGraph?.layers.map((te)=>te.root)??[],...v._layerGraph?.configDependencies.map((te)=>ae.dirname(te))??[]].filter((te)=>ye.existsSync(te)).map((te)=>ye.realpathSync(te)));for(let te of v._layerGraph?.layers??[])for(let X of Object.values(te.resources)){if(!ye.existsSync(X))continue;let me=ye.realpathSync(X);if(![...K].some((Z)=>me===Z||me.startsWith(`${Z}${ae.sep}`)))K.add(me)}for(let[te,X]of q)if(!K.has(te))X.close(),q.delete(te);for(let te of K)if(!q.has(te)&&ye.existsSync(te))q.set(te,ye.watch(te,{recursive:!0},(X,me)=>{Me(te,X,me).catch((Z)=>console.error("[stx] Layer rebuild failed:",Z))}))},J=Promise.resolve(),Me=(K,te,X)=>(J=J.catch(()=>{}).then(()=>Ce(K,te,X)),J),Ce=async(K,te,X)=>{if(!X||Ct(X))return;if(Tt(X)){if(v._layerGraph){let me=await b(y);Object.assign(v,me),P.splice(0,P.length,...ee(T,{pagesDir:S,pagesDirs:me._layerPageDirs?[C,...me._layerPageDirs.slice(1)]:void 0})),re()}if(_(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),d&&p)p.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),tt.clear(),we();try{let{invalidateFileCache:me,templateCache:Z}=await import("./chunk-60ezkjcz.js");me(ae.resolve(K,X)),Z.delete(ae.resolve(K,X))}catch{}if(j&&X){if(ae.resolve(K,X)===j||ae.basename(j)===X){let Z=await So(j,n.stxOptions||{});if(Z)O=Z}}if(await Ve(),await dr(y),d&&p)p.reload(X)}else{console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),tt.clear(),we();try{let{invalidateFileCache:me,templateCache:Z}=await import("./chunk-60ezkjcz.js");me(ae.resolve(K,X)),Z.delete(ae.resolve(K,X))}catch{}if(await Ve(),d&&p)p.reload(X)}}else if(St(X)){if(console.log(`${e.cyan}CSS ${X} changed${e.reset}`),d&&p)p.updateCss(X)}};re(),process.on("SIGINT",()=>{for(let K of q.values())K.close();if(p)ut();Lt.stop(),process.exit(0)})}return!0}import Xt from"fs";import ft from"path";async function Yr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let u=o[1],d=[],p=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=p.exec(u))!==null){let y=m[1],b=m[2]||m[3]||m[4];if(!b)continue;let v={name:b},w=y.match(/@type\s+\{([^}]+)\}/i);if(w)v.type=w[1].trim();if(y.match(/@required/i))v.required=!0;let R=y.match(/@default\s+(.+?)(?:\s+|$)/i);if(R)v.default=R[1].trim();let E=y.split(`
|
|
1453
1453
|
`).map((T)=>T.trim().replace(/^\*\s*/,"")).filter((T)=>!T.startsWith("@")&&T.length>0);v.description=E.join(" ").trim(),d.push(v)}if(d.length===0){let y=u.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(y){let v=y[1].split(",").map((w)=>w.trim()).filter(Boolean);for(let w of v){let[k]=w.split(":").map((R)=>R.trim());if(k)d.push({name:k})}}}return d}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Zr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1454
1454
|
`).map((u)=>u.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function es(t,n=!1,o){let u=ft.basename(t,".stx"),d=await Yr(t),p=await Zr(t),m="";if(n&&o)m=`<${o}></${o}>`;else{let y=d.map((b)=>{if(b.type==="boolean")return`:${b.name}="true"`;return`${b.name}="value"`}).join(`
|
|
1455
1455
|
`);m=`<${u}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{U,rg,ri,$c,a,M,iy,ay}from"./chunk-
|
|
2
|
+
import{U,rg,ri,$c,a,M,iy,ay}from"./chunk-xr1yrdxy.js";import"./chunk-j7q17ws8.js";import"./chunk-tnp2ta5q.js";import"./chunk-rw5492e2.js";import"./chunk-6mkn81pd.js";import"./chunk-hhbt8grm.js";import"./chunk-eprhhrzc.js";import"./chunk-w3d7pwzg.js";import"./chunk-60yppcbb.js";import"./chunk-csymxc5a.js";import"./chunk-farh4p7f.js";import"./chunk-qjey0jk6.js";export{M as config,U as defaultConfig,iy as defineStxConfig,ri as discoverConfig,a as loadStxConfig,$c as resolveInstalledPackage,rg as resolveStxDirectories,ay as validateConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ee,lt,yi,Us,Wc,qc,bi,Kc,Xc,Ws,vi,Gc,Jc,xi,Sn}from"./chunk-
|
|
2
|
+
import{Ee,lt,yi,Us,Wc,qc,bi,Kc,Xc,Ws,vi,Gc,Jc,xi,Sn}from"./chunk-eprhhrzc.js";import{C}from"./chunk-qjey0jk6.js";import{a}from"./chunk-xr1yrdxy.js";import{Eo}from"./chunk-vvddndcm.js";import{l}from"./chunk-46pxmpeb.js";import{existsSync as B,readFileSync as F}from"fs";import h from"path";var ge=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),te=Sn.filter((e)=>!ge.has(e)).sort(),ne=[...C].sort(),he=[...new Set([...te,...ne])].sort(),be=new Set(te),xe=new Set(ne),ye=new Set(he),ee=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function Se(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ie(e,t){let s=[];for(let p of t){if(p.offset===void 0)continue;let i=p.kind==="server"?be:xe;ee.lastIndex=0;for(let u of p.code.matchAll(ee)){let f=u.index+u[0].indexOf("{")+1;for(let m of u[1].matchAll(/[^,]+/g)){let b=m[0];if(/^\s*type\s/.test(b))continue;let S=/^\s*([A-Za-z_$][\w$]*)/.exec(b);if(!S)continue;let r=S[1];if(!ye.has(r)||i.has(r))continue;let d=p.offset+f+m.index+S[0].length-r.length,o=e.slice(0,d),k=o.split(`
|
|
3
3
|
`).length;s.push({line:k,column:d-(o.lastIndexOf(`
|
|
4
4
|
`)+1)+1,offset:d,length:r.length,name:r,kind:p.kind,message:Se(r,p.kind)})}}}return s}import E from"path";var ke="@stacksjs/stx-typescript-plugin";function we(e,t){let s=E.resolve(e);for(;;){let p=E.join(s,"tsconfig.json");if(t(p))return p;let i=E.dirname(s);if(i===s)return;s=i}}function re(e,t,s){let p=we(e,s);if(!p)return;let i=new Set,u=(f)=>{if(i.has(f))return;i.add(f);let m=t(f);if(!m)return;let b=m.compilerOptions?.plugins;if(Array.isArray(b)){let r=b.find((o)=>o?.name===ke),d=Array.isArray(r?.libs)?r.libs.filter((o)=>typeof o==="string"):[];return r?{configPath:f,libs:d.map((o)=>E.resolve(E.dirname(f),o))}:null}let S=typeof m.extends==="string"?[m.extends]:Array.isArray(m.extends)?m.extends:[];for(let r of[...S].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let d=E.resolve(E.dirname(f),r.endsWith(".json")?r:`${r}.json`),o=u(d);if(o!==void 0)return o}return};return u(p)??void 0}function ya(e,t="",s="",p=t){let i=e.startLine>1?`
|
|
5
5
|
`.repeat(e.startLine-1):"",u=yi(vi(e)+e.code,p),f=Us(u.code),m=e.kind==="client"||e.kind==="plain"?Kc(t,e.code):"",b=(i+f).split(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Fl,zl}from"./chunk-n0d4vbcv.js";import"./chunk-v37zmez0.js";import"./chunk-mxdapaz2.js";import"./chunk-w4a3fqf4.js";import"./chunk-h3j2zvms.js";import"./chunk-nack2xs5.js";import"./chunk-bbq79tap.js";import"./chunk-nxqsdt89.js";import"./chunk-fbqk2w2k.js";import"./chunk-rb71xcfw.js";import"./chunk-6ftee542.js";import"./chunk-s584xnzx.js";import"./chunk-ew5cey88.js";import"./chunk-aed45njs.js";import"./chunk-q50x1gfd.js";import"./chunk-ysfeg3cn.js";import"./chunk-01mwbg1r.js";import"./chunk-55zq2ha8.js";import"./chunk-hev4t4d5.js";import"./chunk-8tk8yf91.js";import"./chunk-j7f3h982.js";import"./chunk-8xjj7wjf.js";import"./chunk-qcxrcypb.js";import"./chunk-gbtbfg7e.js";import"./chunk-cqhwzd9y.js";import"./chunk-j1efsjsb.js";import"./chunk-e5xfbcp7.js";import"./chunk-vvddndcm.js";import"./chunk-m131znxe.js";import"./chunk-ct90b523.js";import"./chunk-wk2rge05.js";import"./chunk-v4xes880.js";import{an}from"./chunk-696cdgkg.js";import{Ff}from"./chunk-qhczf1wf.js";import"./chunk-eq3mqbcn.js";import"./chunk-9zrvh3pz.js";import{Ne,i}from"./chunk-e631k202.js";import"./chunk-xpzt4wwb.js";import"./chunk-f30bpj7a.js";import"./chunk-q1wxgw5s.js";import"./chunk-0489wcvq.js";import"./chunk-36e94whg.js";import"./chunk-zktbzwkv.js";import"./chunk-vvxcebpn.js";import"./chunk-2drcj9wn.js";import{_e}from"./chunk-wa4w5bcn.js";import"./chunk-a8164hnf.js";import{hr,yr}from"./chunk-b53rzbrh.js";import{$s,U,a}from"./chunk-xr1yrdxy.js";import"./chunk-j7q17ws8.js";import"./chunk-tnp2ta5q.js";import"./chunk-rw5492e2.js";import"./chunk-6mkn81pd.js";import"./chunk-hhbt8grm.js";import{L,h,He}from"./chunk-eprhhrzc.js";import"./chunk-w3d7pwzg.js";import"./chunk-60yppcbb.js";import"./chunk-csymxc5a.js";import"./chunk-farh4p7f.js";import"./chunk-qjey0jk6.js";import{Ui}from"./chunk-fd1bpv35.js";import"./chunk-40h07m5w.js";import"./chunk-7cvbz4eq.js";export{$s as buildWebComponents,yr as cacheTemplate,hr as checkCache,an as classifyAllScripts,Fl as createMiddleware,zl as createRoute,U as defaultConfig,h as extractVariables,L as findSfcTemplateBlock,_e as injectRouterScript,Ui as insertBeforeBodyClose,a as loadStxConfig,He as processClientScript,i as processDirectives,Ne as readMarkdownFile,Ff as withinBundlerCallback};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ar,Oe}from"./chunk-9zrvh3pz.js";import{K,S,Cr,Vs,T}from"./chunk-pnqdwqw9.js";import{a,M}from"./chunk-jcr69v95.js";import{Fo}from"./chunk-kkevjppm.js";import{at}from"./chunk-n3jw3xpj.js";import{l}from"./chunk-46pxmpeb.js";import{r,Y}from"./chunk-z9xe3xkg.js";import d from"path";import j from"fs";import{AsyncLocalStorage as lt}from"async_hooks";import{randomUUID as $t}from"crypto";var wt=11;function J(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||Fo(t,e,n)}var ct=2;function Nf(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):l(t,"bundle-cache")}function st(t,e){let n=t;for(let i of St(e))if(i!==d.sep)n=n.split(i).join("\x00root");return n}var rt=new Map;function St(t){let e=d.resolve(t),n=rt.get(e);if(!n){let i=e;try{i=j.realpathSync(e)}catch{}n=[...new Set([e,i])].sort((c,p)=>p.length-c.length),rt.set(e,n)}return n}function vt(t,e){try{let n=j.statSync(t),i=d.resolve(e),c=t.startsWith(`${i}${d.sep}`);return{path:c?d.relative(i,t):t,...c?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(j.readFileSync(t)).toString(36)}}catch{return null}}function ut(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function Bt(t,e){for(let n of t){let i=ut(n,e);try{let c=j.statSync(i);if(c.size!==n.size)return!1;if(c.mtimeMs!==n.mtimeMs&&Bun.hash(j.readFileSync(i)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var dt=new Map,jt=100;function Df(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function Et(t){let e=G.get(t)??0;if(e>0&&e<jt){G.set(t,e+1);return}G.set(t,1);try{let n=(await j.promises.readdir(t)).filter((o)=>o.endsWith(".js")),i=Df();if(n.length<=i)return;let p=(await Promise.all(n.map(async(o)=>{try{return{name:o,at:(await j.promises.stat(d.join(t,o))).mtimeMs}}catch{return null}}))).filter((o)=>o!==null);p.sort((o,b)=>b.at-o.at);for(let o of p.slice(i)){let b=o.name.slice(0,-3);await j.promises.rm(d.join(t,`${b}.js`),{force:!0}),await j.promises.rm(d.join(t,`${b}.deps.json`),{force:!0})}N("pruned bundle cache to",i,"entries")}catch{}}function xe(t){return dt.get(t)??[]}function q(t,e){if(t)dt.set(t,e)}function Mf(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function N(...t){if(Mf())console.log("[stx:bundler]",...t)}var tt=[];function pc(t,e,n){tt.push({filePath:t||"<inline>",message:e,details:n})}function cn(){return tt.slice()}function ln(){tt.length=0}var Z;function Fh(t){Z=t}function fc(){if(Z)return Z;try{let t=M.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function un(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let c=n[1];if(!Q.some((o)=>o.test(c)))return N("detected user import:",c),!0}let i=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=i.exec(t))!==null){let c=n[1];if(/\.css(?:\?.*)?$/.test(c))continue;if(!Q.some((o)=>o.test(c)))return N("detected side-effect import:",c),!0}return!1}var ir="stx-module:",_t=/\.(?:[cm]?[jt]sx?|json)$/i;function Lf(t,e){return d.relative(t,e).split(d.sep).join("/")}function jf(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,i,c,p)=>{let o=e.get(p);return o&&!p.startsWith(ir)?`${i}${c}${o}${c}`:n})}function Bf(t,e){let n=0,i=(p)=>{let o=`__stxMod${n++}`,b=JSON.stringify(p);return e.push(`var ${o} = globalThis.__stxModules && globalThis.__stxModules[${b}];`,`if (${o} === undefined) throw new Error("[stx] module " + ${JSON.stringify(b)} + " is not registered on this page (#1957)");`),o},c=(p,o)=>{for(let b of p.split(",")){let C=b.trim();if(!C)continue;let R=C.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!R)continue;let w=R[1].startsWith('"')?JSON.parse(R[1]):R[1],f=R[2]??w;e.push(`var ${f} = ${o}[${JSON.stringify(w)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,o,b)=>{let C=b.slice(ir.length),R=i(C),w=o.trim(),f=w.match(/^([\w$]+)\s*(?:,\s*|$)/);if(f&&!w.startsWith("{")&&!w.startsWith("*"))e.push(`var ${f[1]} = ${R}.default;`),w=w.slice(f[0].length).trim();let v=w.match(/^\*\s*as\s+([\w$]+)$/);if(v)e.push(`var ${v[1]} = ${R};`);else if(w.startsWith("{"))c(w.replace(/^\{|\}$/g,""),R);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,o)=>(i(o.slice(ir.length)),"")),t}function it(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(j.existsSync(n)&&j.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var X=new lt;function ds(t,e){let n=new Bun.CryptoHasher("md5");for(let[i,c]of[...t].sort(([p],[o])=>p<o?-1:p>o?1:0))n.update(`${i}\x00${c}\x00`);return X.run({modules:t,key:n.digest("hex").slice(0,12)},e)}var pt=new lt;function Ff(t){return pt.run(!0,t)}function zf(){return pt.getStore()===!0}function gc(t){if(!zf())return;throw Error(`The client script of ${t} needs bundling, and it is being rendered inside a Bun.build loader, where Bun never finishes a second build. Make the page an entrypoint of the build (bun-plugin-stx renders entrypoints before the bundler starts), or render it once outside the build so its bundle is cached.`)}function dn(){return X.getStore()?.key??""}function ft(t,e,n,i,c,p,o=new Map,b,C,R){let w=new Map([[n,i],...R??[]]),f=(B)=>B!==void 0&&w.has(B),v=(B,s,u)=>{if(J(s,t,b))return null;if(!p||!f(B)||!_t.test(s))return null;try{if(!j.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}c.add(s);let E=`${ir}${Lf(process.cwd(),s)}`;return o.set(u,E),{path:E,external:!0}},y=(B,s)=>{let u=f(B)?e:d.dirname(B),E=d.resolve(u,s);return it(E)??E};return{name:"stx-client-bundle",setup(B){if(B.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),B.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),B.onResolve({filter:/^\//},(s)=>{if(f(s.path))return{path:s.path};let u=it(s.path);if(u){let E=v(s.importer,u,s.path);if(E)return E;if(!f(u))c.add(u);return{path:u}}return{path:s.path,external:!0}}),B.onResolve({filter:/^\.\.?\//},(s)=>{let u=y(s.importer,s.path),E=v(s.importer,u,s.path);if(E)return E;return c.add(u),{path:u}}),B.onResolve({filter:/^[@~]\//},(s)=>{let u=d.resolve(t,s.path.slice(2)),E=[u,`${u}.ts`,`${u}.tsx`,`${u}.js`,`${u}.mjs`,`${u}.jsx`,d.join(u,"index.ts"),d.join(u,"index.tsx"),d.join(u,"index.js"),d.join(u,"index.mjs")];for(let h of E)if(j.existsSync(h)&&j.statSync(h,{throwIfNoEntry:!1})?.isFile()){let D=v(s.importer,h,s.path);if(D)return D;return N(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",h),c.add(h),{path:h}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:u}}),p)B.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(!f(s.importer))return;let u=`${ir}npm:${s.path}`;return o.set(s.path,u),{path:u,external:!0}});B.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(w.has(s.path))return{contents:w.get(s.path),loader:"ts"};if(J(s.path,t,b))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let u=d.extname(s.path).toLowerCase(),E=u===".json"?"json":u===".tsx"?"tsx":u===".jsx"?"jsx":u===".ts"||u===".mts"||u===".cts"?"ts":"js";if(!f(s.path))c.add(s.path);let h=C?.get(s.path);if(h!==void 0)return{contents:h,loader:"js"};return{contents:j.readFileSync(s.path,"utf8"),loader:E}})}}}var H=new Map,z=S(64),ot=Symbol.for("stx.client-bundle-build-queue");function Hf(t){let e=globalThis,i=(e[ot]??Promise.resolve()).then(t,t);return e[ot]=i.then(()=>{return},()=>{return}),i}async function pn(t,e,n={}){let i=n.projectRoot||process.cwd(),c=(await a(i)).serverApi,p=n.minify??!1,o=n.externalizeUserModules??!0,b=n.expose?.length?[...new Set(n.expose)].sort():void 0,C=n.cacheDir||Nf(i),R=X.getStore(),w=new Bun.CryptoHasher("md5");w.update(`${wt}\x00${at()}\x00${JSON.stringify(c??!1)}\x00${o?"registry":"inline"}\x00${b?b.join(","):"*"}\x00${p?"minified":"readable"}\x00${R?.key??""}\x00${st(t,i)}\x00${st(e,i)}`);let f=w.digest("hex").slice(0,12),v=d.join(C,`${f}.js`),y=z.get(v);if(y){if(Vs(y.files)&&y.files.every((h)=>!J(h.path,i,c))){N("memo hit:",f);let h=y.files.map((D)=>D.path);return q(e,h),n.collectInputs?.push(...h),y.code}z.delete(v),N("memo invalidated by dep change:",f)}let B=d.join(C,`${f}.deps.json`),s=Bun.file(v);if(await s.exists()){let h=Bun.file(B),D=!1,k=null;if(await h.exists())try{let O=JSON.parse(await h.text());if(O.metadataVersion===ct&&Array.isArray(O.files)&&Bt(O.files,i))k=Cr(O.files.map((g)=>ut(g,i))),D=k.length===O.files.length&&!k.some((g)=>J(g.path,i,c))}catch{D=!1}if(D){if(N("cache hit:",f),k)q(e,k.map((U)=>U.path)),n.collectInputs?.push(...k.map((U)=>U.path));let O=await s.text(),g=new Date;if(j.promises.utimes(v,g,g).catch(()=>{}),k)z.set(v,{code:O,files:k});return O}N("cache invalidated by dep change:",f)}let u=H.get(f);if(u){let h=await u;if(n.collectInputs)n.collectInputs.push(...(z.get(v)?.files??[]).map((D)=>D.path));return h}gc(e);let E=Hf(()=>Mt(t,e,{projectRoot:i,minify:p,cacheDir:C,hash:f,cachePath:v,depsPath:B,collectInputs:n.collectInputs,externalizeUserModules:o,serverApi:c,expose:b,throwOnFailure:n.throwOnFailure,substitutes:R?.modules}));H.set(f,E);try{return await E}finally{H.delete(f)}}function mc(t){return`${t}-${process.pid}-${$t()}`}async function zh(t,e){let{projectRoot:n}=e,i=mc(new Bun.CryptoHasher("md5").update([...t.keys()].join("\x00")).digest("hex").slice(0,12)),c=d.join(l(n,"bundle-tmp"),"out",i);j.mkdirSync(c,{recursive:!0});let p=new Map,o=new Map,b=0;for(let[f,v]of t){let y=d.join(n,`.stx-split-${i}-${b++}.ts`);p.set(y,v),o.set(d.basename(y).replace(/\.ts$/,""),f)}let[C,R]=[...p][0],w=new Set;gc(e.filePath);try{let f=await Bun.build({entrypoints:[...p.keys()],outdir:c,target:"browser",format:"esm",splitting:!0,minify:!1,naming:{entry:"[name].js",chunk:"chunk-[hash].js"},plugins:[ft(n,d.dirname(e.filePath),C,R,w,!1,new Map,void 0,X.getStore()?.modules,p)],define:{"process.env.NODE_ENV":'"development"',...T()},root:n});if(!f.success)throw Error(f.logs.filter((y)=>y.level==="error").map((y)=>y.message).join(", ")||"Unable to bundle the entries");let v={entries:new Map,chunks:new Map};for(let y of f.outputs){let B=d.basename(y.path);if(y.kind==="entry-point"){let s=o.get(B.replace(/\.js$/,""));if(s!==void 0)v.entries.set(s,await y.text())}else if(y.kind==="chunk")v.chunks.set(B.replace(/\.js$/,""),await y.text())}return e.collectInputs?.push(...w),v}finally{try{j.rmSync(c,{recursive:!0,force:!0})}catch{}}}async function Mt(t,e,n){let{projectRoot:i,minify:c,cacheDir:p,hash:o,cachePath:b,depsPath:C,externalizeUserModules:R}=n,w=l(i,"bundle-tmp"),f=mc(o),v=d.join(i,`.stx-client-${f}.ts`),y=d.join(w,"out",f);j.mkdirSync(y,{recursive:!0});let B=d.dirname(e),s=new Set,u=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,E=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,h=r(t),{depths:D,balanced:k}=Y(h),O=(F)=>!k||D[F]===0,g;while((g=u.exec(h))!==null){if(g[1])continue;if(!O(g.index))continue;if(g[2])g[2].split(",").forEach((F)=>{let m=Rt(F);if(m)s.add(m)});else if(g[3])s.add(g[3])}while((g=E.exec(h))!==null){if(g[1])continue;if(!O(g.index))continue;s.add(g[2])}let U=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=U.exec(h))!==null){if(!O(g.index))continue;let F=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(F&&Q.some((m)=>m.test(F)))continue;if(g[1])s.add(g[1]);if(g[2])s.add(g[2]);for(let m of(g[3]??"").split(",")){let _=m.trim();if(!_||/^type\s/.test(_))continue;let L=/\bas\s+(\w+)\s*$/.exec(_)?.[1]??/^\w+$/.exec(_)?.[0];if(L)s.add(L)}}for(let F of h.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let m of F[1].split(",")){let _=/\bas\s+(\w+)\s*$/.exec(m)?.[1]??/^\s*(\w+)\s*$/.exec(m)?.[1];if(_)s.delete(_)}let mt=s.size>0?`
|
|
2
|
+
import{ar,Oe}from"./chunk-9zrvh3pz.js";import{K,S,Cr,Vs,T}from"./chunk-eprhhrzc.js";import{a,M}from"./chunk-xr1yrdxy.js";import{Fo}from"./chunk-eq3mqbcn.js";import{at}from"./chunk-n3jw3xpj.js";import{l}from"./chunk-46pxmpeb.js";import{r,Y}from"./chunk-z9xe3xkg.js";import d from"path";import j from"fs";import{AsyncLocalStorage as lt}from"async_hooks";import{randomUUID as $t}from"crypto";var wt=11;function J(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||Fo(t,e,n)}var ct=2;function Nf(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):l(t,"bundle-cache")}function st(t,e){let n=t;for(let i of St(e))if(i!==d.sep)n=n.split(i).join("\x00root");return n}var rt=new Map;function St(t){let e=d.resolve(t),n=rt.get(e);if(!n){let i=e;try{i=j.realpathSync(e)}catch{}n=[...new Set([e,i])].sort((c,p)=>p.length-c.length),rt.set(e,n)}return n}function vt(t,e){try{let n=j.statSync(t),i=d.resolve(e),c=t.startsWith(`${i}${d.sep}`);return{path:c?d.relative(i,t):t,...c?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(j.readFileSync(t)).toString(36)}}catch{return null}}function ut(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function Bt(t,e){for(let n of t){let i=ut(n,e);try{let c=j.statSync(i);if(c.size!==n.size)return!1;if(c.mtimeMs!==n.mtimeMs&&Bun.hash(j.readFileSync(i)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var dt=new Map,jt=100;function Df(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function Et(t){let e=G.get(t)??0;if(e>0&&e<jt){G.set(t,e+1);return}G.set(t,1);try{let n=(await j.promises.readdir(t)).filter((o)=>o.endsWith(".js")),i=Df();if(n.length<=i)return;let p=(await Promise.all(n.map(async(o)=>{try{return{name:o,at:(await j.promises.stat(d.join(t,o))).mtimeMs}}catch{return null}}))).filter((o)=>o!==null);p.sort((o,b)=>b.at-o.at);for(let o of p.slice(i)){let b=o.name.slice(0,-3);await j.promises.rm(d.join(t,`${b}.js`),{force:!0}),await j.promises.rm(d.join(t,`${b}.deps.json`),{force:!0})}N("pruned bundle cache to",i,"entries")}catch{}}function xe(t){return dt.get(t)??[]}function q(t,e){if(t)dt.set(t,e)}function Mf(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function N(...t){if(Mf())console.log("[stx:bundler]",...t)}var tt=[];function pc(t,e,n){tt.push({filePath:t||"<inline>",message:e,details:n})}function cn(){return tt.slice()}function ln(){tt.length=0}var Z;function Fh(t){Z=t}function fc(){if(Z)return Z;try{let t=M.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function un(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let c=n[1];if(!Q.some((o)=>o.test(c)))return N("detected user import:",c),!0}let i=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=i.exec(t))!==null){let c=n[1];if(/\.css(?:\?.*)?$/.test(c))continue;if(!Q.some((o)=>o.test(c)))return N("detected side-effect import:",c),!0}return!1}var ir="stx-module:",_t=/\.(?:[cm]?[jt]sx?|json)$/i;function Lf(t,e){return d.relative(t,e).split(d.sep).join("/")}function jf(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,i,c,p)=>{let o=e.get(p);return o&&!p.startsWith(ir)?`${i}${c}${o}${c}`:n})}function Bf(t,e){let n=0,i=(p)=>{let o=`__stxMod${n++}`,b=JSON.stringify(p);return e.push(`var ${o} = globalThis.__stxModules && globalThis.__stxModules[${b}];`,`if (${o} === undefined) throw new Error("[stx] module " + ${JSON.stringify(b)} + " is not registered on this page (#1957)");`),o},c=(p,o)=>{for(let b of p.split(",")){let C=b.trim();if(!C)continue;let R=C.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!R)continue;let w=R[1].startsWith('"')?JSON.parse(R[1]):R[1],f=R[2]??w;e.push(`var ${f} = ${o}[${JSON.stringify(w)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,o,b)=>{let C=b.slice(ir.length),R=i(C),w=o.trim(),f=w.match(/^([\w$]+)\s*(?:,\s*|$)/);if(f&&!w.startsWith("{")&&!w.startsWith("*"))e.push(`var ${f[1]} = ${R}.default;`),w=w.slice(f[0].length).trim();let v=w.match(/^\*\s*as\s+([\w$]+)$/);if(v)e.push(`var ${v[1]} = ${R};`);else if(w.startsWith("{"))c(w.replace(/^\{|\}$/g,""),R);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(p,o)=>(i(o.slice(ir.length)),"")),t}function it(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(j.existsSync(n)&&j.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var X=new lt;function ds(t,e){let n=new Bun.CryptoHasher("md5");for(let[i,c]of[...t].sort(([p],[o])=>p<o?-1:p>o?1:0))n.update(`${i}\x00${c}\x00`);return X.run({modules:t,key:n.digest("hex").slice(0,12)},e)}var pt=new lt;function Ff(t){return pt.run(!0,t)}function zf(){return pt.getStore()===!0}function gc(t){if(!zf())return;throw Error(`The client script of ${t} needs bundling, and it is being rendered inside a Bun.build loader, where Bun never finishes a second build. Make the page an entrypoint of the build (bun-plugin-stx renders entrypoints before the bundler starts), or render it once outside the build so its bundle is cached.`)}function dn(){return X.getStore()?.key??""}function ft(t,e,n,i,c,p,o=new Map,b,C,R){let w=new Map([[n,i],...R??[]]),f=(B)=>B!==void 0&&w.has(B),v=(B,s,u)=>{if(J(s,t,b))return null;if(!p||!f(B)||!_t.test(s))return null;try{if(!j.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}c.add(s);let E=`${ir}${Lf(process.cwd(),s)}`;return o.set(u,E),{path:E,external:!0}},y=(B,s)=>{let u=f(B)?e:d.dirname(B),E=d.resolve(u,s);return it(E)??E};return{name:"stx-client-bundle",setup(B){if(B.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),B.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),B.onResolve({filter:/^\//},(s)=>{if(f(s.path))return{path:s.path};let u=it(s.path);if(u){let E=v(s.importer,u,s.path);if(E)return E;if(!f(u))c.add(u);return{path:u}}return{path:s.path,external:!0}}),B.onResolve({filter:/^\.\.?\//},(s)=>{let u=y(s.importer,s.path),E=v(s.importer,u,s.path);if(E)return E;return c.add(u),{path:u}}),B.onResolve({filter:/^[@~]\//},(s)=>{let u=d.resolve(t,s.path.slice(2)),E=[u,`${u}.ts`,`${u}.tsx`,`${u}.js`,`${u}.mjs`,`${u}.jsx`,d.join(u,"index.ts"),d.join(u,"index.tsx"),d.join(u,"index.js"),d.join(u,"index.mjs")];for(let h of E)if(j.existsSync(h)&&j.statSync(h,{throwIfNoEntry:!1})?.isFile()){let D=v(s.importer,h,s.path);if(D)return D;return N(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",h),c.add(h),{path:h}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:u}}),p)B.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(!f(s.importer))return;let u=`${ir}npm:${s.path}`;return o.set(s.path,u),{path:u,external:!0}});B.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(w.has(s.path))return{contents:w.get(s.path),loader:"ts"};if(J(s.path,t,b))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let u=d.extname(s.path).toLowerCase(),E=u===".json"?"json":u===".tsx"?"tsx":u===".jsx"?"jsx":u===".ts"||u===".mts"||u===".cts"?"ts":"js";if(!f(s.path))c.add(s.path);let h=C?.get(s.path);if(h!==void 0)return{contents:h,loader:"js"};return{contents:j.readFileSync(s.path,"utf8"),loader:E}})}}}var H=new Map,z=S(64),ot=Symbol.for("stx.client-bundle-build-queue");function Hf(t){let e=globalThis,i=(e[ot]??Promise.resolve()).then(t,t);return e[ot]=i.then(()=>{return},()=>{return}),i}async function pn(t,e,n={}){let i=n.projectRoot||process.cwd(),c=(await a(i)).serverApi,p=n.minify??!1,o=n.externalizeUserModules??!0,b=n.expose?.length?[...new Set(n.expose)].sort():void 0,C=n.cacheDir||Nf(i),R=X.getStore(),w=new Bun.CryptoHasher("md5");w.update(`${wt}\x00${at()}\x00${JSON.stringify(c??!1)}\x00${o?"registry":"inline"}\x00${b?b.join(","):"*"}\x00${p?"minified":"readable"}\x00${R?.key??""}\x00${st(t,i)}\x00${st(e,i)}`);let f=w.digest("hex").slice(0,12),v=d.join(C,`${f}.js`),y=z.get(v);if(y){if(Vs(y.files)&&y.files.every((h)=>!J(h.path,i,c))){N("memo hit:",f);let h=y.files.map((D)=>D.path);return q(e,h),n.collectInputs?.push(...h),y.code}z.delete(v),N("memo invalidated by dep change:",f)}let B=d.join(C,`${f}.deps.json`),s=Bun.file(v);if(await s.exists()){let h=Bun.file(B),D=!1,k=null;if(await h.exists())try{let O=JSON.parse(await h.text());if(O.metadataVersion===ct&&Array.isArray(O.files)&&Bt(O.files,i))k=Cr(O.files.map((g)=>ut(g,i))),D=k.length===O.files.length&&!k.some((g)=>J(g.path,i,c))}catch{D=!1}if(D){if(N("cache hit:",f),k)q(e,k.map((U)=>U.path)),n.collectInputs?.push(...k.map((U)=>U.path));let O=await s.text(),g=new Date;if(j.promises.utimes(v,g,g).catch(()=>{}),k)z.set(v,{code:O,files:k});return O}N("cache invalidated by dep change:",f)}let u=H.get(f);if(u){let h=await u;if(n.collectInputs)n.collectInputs.push(...(z.get(v)?.files??[]).map((D)=>D.path));return h}gc(e);let E=Hf(()=>Mt(t,e,{projectRoot:i,minify:p,cacheDir:C,hash:f,cachePath:v,depsPath:B,collectInputs:n.collectInputs,externalizeUserModules:o,serverApi:c,expose:b,throwOnFailure:n.throwOnFailure,substitutes:R?.modules}));H.set(f,E);try{return await E}finally{H.delete(f)}}function mc(t){return`${t}-${process.pid}-${$t()}`}async function zh(t,e){let{projectRoot:n}=e,i=mc(new Bun.CryptoHasher("md5").update([...t.keys()].join("\x00")).digest("hex").slice(0,12)),c=d.join(l(n,"bundle-tmp"),"out",i);j.mkdirSync(c,{recursive:!0});let p=new Map,o=new Map,b=0;for(let[f,v]of t){let y=d.join(n,`.stx-split-${i}-${b++}.ts`);p.set(y,v),o.set(d.basename(y).replace(/\.ts$/,""),f)}let[C,R]=[...p][0],w=new Set;gc(e.filePath);try{let f=await Bun.build({entrypoints:[...p.keys()],outdir:c,target:"browser",format:"esm",splitting:!0,minify:!1,naming:{entry:"[name].js",chunk:"chunk-[hash].js"},plugins:[ft(n,d.dirname(e.filePath),C,R,w,!1,new Map,void 0,X.getStore()?.modules,p)],define:{"process.env.NODE_ENV":'"development"',...T()},root:n});if(!f.success)throw Error(f.logs.filter((y)=>y.level==="error").map((y)=>y.message).join(", ")||"Unable to bundle the entries");let v={entries:new Map,chunks:new Map};for(let y of f.outputs){let B=d.basename(y.path);if(y.kind==="entry-point"){let s=o.get(B.replace(/\.js$/,""));if(s!==void 0)v.entries.set(s,await y.text())}else if(y.kind==="chunk")v.chunks.set(B.replace(/\.js$/,""),await y.text())}return e.collectInputs?.push(...w),v}finally{try{j.rmSync(c,{recursive:!0,force:!0})}catch{}}}async function Mt(t,e,n){let{projectRoot:i,minify:c,cacheDir:p,hash:o,cachePath:b,depsPath:C,externalizeUserModules:R}=n,w=l(i,"bundle-tmp"),f=mc(o),v=d.join(i,`.stx-client-${f}.ts`),y=d.join(w,"out",f);j.mkdirSync(y,{recursive:!0});let B=d.dirname(e),s=new Set,u=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,E=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,h=r(t),{depths:D,balanced:k}=Y(h),O=(F)=>!k||D[F]===0,g;while((g=u.exec(h))!==null){if(g[1])continue;if(!O(g.index))continue;if(g[2])g[2].split(",").forEach((F)=>{let m=Rt(F);if(m)s.add(m)});else if(g[3])s.add(g[3])}while((g=E.exec(h))!==null){if(g[1])continue;if(!O(g.index))continue;s.add(g[2])}let U=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=U.exec(h))!==null){if(!O(g.index))continue;let F=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(F&&Q.some((m)=>m.test(F)))continue;if(g[1])s.add(g[1]);if(g[2])s.add(g[2]);for(let m of(g[3]??"").split(",")){let _=m.trim();if(!_||/^type\s/.test(_))continue;let L=/\bas\s+(\w+)\s*$/.exec(_)?.[1]??/^\w+$/.exec(_)?.[0];if(L)s.add(L)}}for(let F of h.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let m of F[1].split(",")){let _=/\bas\s+(\w+)\s*$/.exec(m)?.[1]??/^\s*(\w+)\s*$/.exec(m)?.[1];if(_)s.delete(_)}let mt=s.size>0?`
|
|
3
3
|
export { ${[...s].join(", ")} }`:"";N("bundling:",o,"from:",d.basename(e));let et=new Set,nt=new Map;try{let F=await Bun.build({entrypoints:[v],outdir:y,target:"browser",format:"esm",minify:c?{whitespace:!1,identifiers:!0,syntax:!0}:!1,plugins:[ft(i,B,v,t+mt,et,R,nt,n.serverApi,n.substitutes)],define:{"process.env.NODE_ENV":c?'"production"':'"development"',...T()},root:i});if(!F.success){let I=F.logs.filter((A)=>A.level==="error").map((A)=>A.message).join(", ")||`Unable to bundle ${d.basename(e)}`,P=ar(F.logs,e||void 0);if(console.warn("[stx:bundler] build failed:",I),pc(e||"",I,P),n.throwOnFailure||fc()==="error")throw Error(I);return t}let m="";for(let x of F.outputs){m=await x.text();break}let _=[];for(let x of m.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let I of x[1].split(",")){let P=I.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(P){_.push([P[2],P[1]]);continue}let A=I.trim();if(/^[A-Za-z_$][\w$]*$/.test(A))_.push([A,A])}if(n.expose){let x=new Set(n.expose);for(let I=_.length-1;I>=0;I--)if(!x.has(_[I][0]))_.splice(I,1)}let L=[];m=Bf(jf(m,nt),L);let gt=m.match(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm)||[];if(m=m.replace(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim(),c&&m)try{m=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(m)}catch{}let V=`__stxBundle_${o}`,ht=new Set(K(t,!0).split(",").map((x)=>x.trim())),xt=_.map(([x,I])=>`get ${JSON.stringify(x)}() { return ${I} }${ht.has(x)?`, set ${JSON.stringify(x)}(__stxValue_${I}) { ${I} = __stxValue_${I} }`:""}`).join(", "),yt=_.map(([x])=>`var ${x} = undefined;`).join(`
|
|
4
4
|
`),bt=_.map(([x])=>`${x} = ${V}[${JSON.stringify(x)}];`).join(`
|
|
5
5
|
`);if(m=`${gt.join(`
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{An}from"./chunk-csymxc5a.js";import{L,J,w,Bt,Ft,Pr,h,gl,$i,G,I}from"./chunk-
|
|
2
|
+
import{An}from"./chunk-csymxc5a.js";import{L,J,w,Bt,Ft,Pr,h,gl,$i,G,I}from"./chunk-eprhhrzc.js";import{an}from"./chunk-696cdgkg.js";import{n}from"./chunk-36e94whg.js";import{Q}from"./chunk-9fyw1xkh.js";import{D,c}from"./chunk-fd1bpv35.js";var K=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Y(t){let s=[],e=/<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|template)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,r;while((r=e.exec(t))!==null)s.push({start:r.index,end:r.index+r[0].length});return s}function N(t,s){return s.some((e)=>t>=e.start&&t<e.end)}function Z(t){let s=(t||"").trim();if(!s)return null;if(/[\s>+~,:]/.test(s))return null;let e={},r=s,i=r.match(/^[a-z][\w-]*/i);if(i)e.tag=i[0].toLowerCase(),r=r.slice(i[0].length);while(r.length>0){let o=r.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(o){if(e.attr=o[1],o[3]!==void 0&&o[3]!=="")e.attrValue=o[3];r=r.slice(o[0].length);continue}let l=r.match(/^#([\w-]+)/);if(l){e.id=l[1],r=r.slice(l[0].length);continue}let a=r.match(/^\.([\w-]+)/);if(a){e.className=a[1],r=r.slice(a[0].length);continue}return null}if(!e.tag&&!e.attr&&!e.id&&!e.className)return null;return e}function tt(t,s){if(s.attr){if(!(s.attrValue===void 0?new RegExp(`\\b${s.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${s.attr}\\s*=\\s*(["'])\\s*${s.attrValue}\\s*\\1`,"i")).test(t))return!1}if(s.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${s.id}\\s*\\1`,"i").test(t))return!1}if(s.className){let e=t.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!e)return!1;if(!e[2].split(/\s+/).includes(s.className))return!1}return!0}function P(t,s="main"){let e=Z(s);if(!e)return null;let r=/<([a-z][\w-]*)\b([^>]*)>/gi,i=Y(t),o;while((o=r.exec(t))!==null){if(N(o.index,i))continue;let l=o[1].toLowerCase(),a=o[2]||"";if(a.trimEnd().endsWith("/")||K.has(l))continue;if(e.tag&&e.tag!==l)continue;if(!tt(a,e))continue;let u=o[0],g=o.index+u.length,f=new RegExp(`<(/?)${l}\\b([^>]*)>`,"gi");f.lastIndex=g;let d=1,x;while((x=f.exec(t))!==null){if(N(x.index,i))continue;let y=x[1]==="/";if(!y&&(x[2]||"").trimEnd().endsWith("/"))continue;if(d+=y?-1:1,d===0)return{openTag:u,openIndex:o.index,start:g,end:x.index,tagName:l}}return null}return null}var wt="private, no-store";function en(t){return t.replace(/&#(\d+);/g,(s,e)=>F(Number(e),s)).replace(/&#x([0-9a-f]+);/gi,(s,e)=>F(Number.parseInt(e,16),s)).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}function F(t,s){if(!Number.isInteger(t)||t<0||t>1114111)return s;try{return String.fromCodePoint(t)}catch{return s}}function Ae(t){return t.headers.get("X-STX-Router")==="true"}function et(t,s){if(!t)return s;return t.split(",").some((r)=>r.trim().toLowerCase()===s.toLowerCase())?t:`${t}, ${s}`}function H(t){return{Vary:et(t,"X-STX-Router")}}function E(t){return t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function B(t){let s=/<head\b[^>]*>([\s\S]*?)<\/head\s*>/i.exec(t)?.[1]??"",e=/<(meta|link)\b(?:[^>"']|"[^"]*"|'[^']*')*>|<title\b[^>]*>[\s\S]*?<\/title\s*>/giy;return w(s,(r,i)=>(e.lastIndex=i,e.exec(r)?e.lastIndex:-1)).map(({token:r})=>r)}function V(t){let s=Object.create(null),e=t.replace(/^<\w+\b|>$/g,"");for(let r of e.matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)){let i=r[1].toLowerCase();if(!(i in s))s[i]=r[2]??r[3]??r[4]??""}return s}function Ln(t){let s=[];for(let e of B(t)){if(/^<title\b/i.test(e)){s.push(`<title>${E(e.replace(/^<title\b[^>]*>|<\/title\s*>$/gi,""))}</title>`);continue}let r=V(e);if(/^<meta\b/i.test(e)){let i=r.property?"property":"name",o=en(r[i]??"").toLowerCase();if(o==="description"||/^(?:og|twitter):[\w:]+$/.test(o))s.push(`<meta ${i}="${n(o)}" content="${E(r.content??"")}">`)}else{let i=en(r.rel??"").toLowerCase();if(i==="canonical"||i==="alternate"&&r.hreflang)s.push(`<link rel="${i}" href="${E(r.href??"")}"${i==="alternate"?` hreflang="${E(r.hreflang)}"`:""}>`)}}return`<template data-stx-page-head="1">${s.join("")}</template>
|
|
3
3
|
`}var nt=["media","crossorigin","integrity"];function jn(t){let s=[];for(let e of B(t)){if(!/^<link\b/i.test(e))continue;let r=V(e);if(en(r.rel??"").trim().toLowerCase()!=="stylesheet")continue;if(!r.href||"data-css"in r||"disabled"in r)continue;let i=nt.filter((o)=>(o in r)).map((o)=>` ${o}="${E(r[o])}"`).join("");s.push(`<link rel="stylesheet" href="${E(r.href)}"${i}>`)}return s.length?`<template data-stx-page-css="1">${s.join("")}</template>
|
|
4
|
-
`:""}import T from"path";var rt="stx-page-head:",st=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,_={dev:null,prod:null};function it(){let t=Q()?"dev":"prod",s=_[t];if(s!==null)return s;try{let e=import.meta.require("./chunk-hcaedzck.js"),r=t==="dev"&&typeof e.getRouterScriptDev==="function"?e.getRouterScriptDev:e.getRouterScript;_[t]=`<script>${r()}</script>`}catch{_[t]=""}return _[t]}async function wa(t,s){if(s===!1)return null;if(s&&typeof s==="string"){let r=T.resolve(t,s);if(await Bun.file(r).exists())return r;return null}let e=T.join(t,"app.stx");if(await Bun.file(e).exists())return e;return null}async function So(t,s){try{let e=await Bun.file(t).text(),r=e,i=L(e);if(i)r=i.content.trim();let o=an(e),l=[...o.client.map((p)=>p.fullTag),...o.signals.map((p)=>p.fullTag)],a=[],u=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,g;while((g=u.exec(e))!==null)a.push(g[0]);let f=r;for(let p of o.server)f=f.replace(p.fullTag,"");for(let p of o.client)f=f.replace(p.fullTag,"");f=f.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let d="<!--__STX_PAGE_SLOT__-->";if(f=f.replace(/<slot\s*\/>/gi,d).replace(/<slot\s*>\s*<\/slot>/gi,d),!f.includes(d))return console.warn(`[stx] Shell ${t} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:x,extractVariables:y,defaultConfig:R,loadStxConfig:b}=await import("./chunk-
|
|
4
|
+
`:""}import T from"path";var rt="stx-page-head:",st=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,_={dev:null,prod:null};function it(){let t=Q()?"dev":"prod",s=_[t];if(s!==null)return s;try{let e=import.meta.require("./chunk-hcaedzck.js"),r=t==="dev"&&typeof e.getRouterScriptDev==="function"?e.getRouterScriptDev:e.getRouterScript;_[t]=`<script>${r()}</script>`}catch{_[t]=""}return _[t]}async function wa(t,s){if(s===!1)return null;if(s&&typeof s==="string"){let r=T.resolve(t,s);if(await Bun.file(r).exists())return r;return null}let e=T.join(t,"app.stx");if(await Bun.file(e).exists())return e;return null}async function So(t,s){try{let e=await Bun.file(t).text(),r=e,i=L(e);if(i)r=i.content.trim();let o=an(e),l=[...o.client.map((p)=>p.fullTag),...o.signals.map((p)=>p.fullTag)],a=[],u=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,g;while((g=u.exec(e))!==null)a.push(g[0]);let f=r;for(let p of o.server)f=f.replace(p.fullTag,"");for(let p of o.client)f=f.replace(p.fullTag,"");f=f.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let d="<!--__STX_PAGE_SLOT__-->";if(f=f.replace(/<slot\s*\/>/gi,d).replace(/<slot\s*>\s*<\/slot>/gi,d),!f.includes(d))return console.warn(`[stx] Shell ${t} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:x,extractVariables:y,defaultConfig:R,loadStxConfig:b}=await import("./chunk-p71c1wrw.js"),k=await b(),m={__filename:t,__dirname:T.dirname(t)};for(let p of l){let A=p.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(A&&!p.includes("client")&&!p.includes('type="module"'))await y(A[1],m,t)}let S=await x(f,m,t,{...R,...k,...s},new Set),C=S.indexOf(d);if(C===-1)return console.warn("[stx] Shell slot placeholder lost during processing"),null;return{beforeSlot:S.substring(0,C),afterSlot:S.substring(C+d.length),filePath:t,shellScripts:l,shellStyles:a}}catch(e){return console.error(`[stx] Error processing shell ${t}:`,e),null}}function Qr(t,s,e){let r,i="",o=s.match(st);if(o){s=s.replace(o[0],"");try{let f=Buffer.from(o[1],"base64").toString("utf8"),d=f.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(d)r=d[1].trim();i=f.replace(/<title[^>]*>[\s\S]*?<\/title>/i,"").trim()}catch{}}let l=e||r||"stx App",a=it(),u="<script>window.__stxRouterConfig={container:'[data-stx-content]'};</script>";return`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
|
@@ -29,5 +29,5 @@ ${a}
|
|
|
29
29
|
`));if(o.length>0)m.push(o.filter((S)=>!g.has(S)).join(`
|
|
30
30
|
`));if(R.length>0)m.push(R.filter((S)=>!g.has(S)).join(`
|
|
31
31
|
`));return m.push(y),m.join(`
|
|
32
|
-
`)}import O from"fs";import z from"path";function xa(t,s,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:s,outputDir:e}}function Sa(t,s){let e=z.join(s,"manifest.json");O.writeFileSync(e,JSON.stringify(t,null,2))}function ka(t){let s=z.join(t,"manifest.json");if(!O.existsSync(s))return null;try{let e=O.readFileSync(s,"utf-8"),r=JSON.parse(e);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}function M(t,s,e={}){let r=`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(e.maxAge!==void 0)r+=`; Max-Age=${e.maxAge}`;if(e.expires)r+=`; Expires=${e.expires.toUTCString()}`;if(e.path)r+=`; Path=${e.path}`;if(e.domain)r+=`; Domain=${e.domain}`;if(e.secure)r+="; Secure";if(e.httpOnly)r+="; HttpOnly";if(e.sameSite)r+=`; SameSite=${e.sameSite}`;return r}async function at(t){let s=t.headers.get("content-type")||"",e={},r=(i,o)=>{let l=e[i];if(l===void 0)e[i]=o;else if(Array.isArray(l))l.push(o);else e[i]=[l,o]};if(s.includes("multipart/form-data")){let i=await t.formData();for(let[o,l]of i.entries())if(typeof l==="string")r(o,l);return e}if(s.includes("application/x-www-form-urlencoded")){for(let[i,o]of new URLSearchParams(await t.text()).entries())r(i,o);return e}return e}function ko(t){if(!t)return!1;let s=t.toUpperCase();return s!=="GET"&&s!=="HEAD"}async function W(t,s={}){let e=s.request,r=s.method??e?.method;if(!e||!ko(r))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let i={};try{i=await at(e)}catch{}let o=await t.action({request:e,form:i,params:s.params??{},query:t.query??{},cookies:s.cookies??{}});if(o&&typeof o==="object"){let l=o,a=ct(l.cookies),u=l.redirect;if(typeof u==="string"&&u)return{redirect:u,ran:!0,...a.length>0?{cookies:a}:{}};let{cookies:g,redirect:f,...d}=l;if(Object.assign(t,d),a.length>0)return{ran:!0,cookies:a}}return{ran:!0}}function ct(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let s=[];for(let[e,r]of Object.entries(t)){if(!e)continue;if(typeof r==="string"){s.push(M(e,r));continue}if(r&&typeof r==="object"){let i=r;if(typeof i.value!=="string")continue;s.push(M(e,i.value,i))}}return s}function _a(t,s=[],e){let r=new Headers({Location:t,"Cache-Control":"no-store"});for(let i of s)r.append("Set-Cookie",i);for(let[i,o]of Object.entries(e??{}))if(i.toLowerCase()!=="location")r.set(i,o);return new Response(null,{status:303,headers:r})}async function Bn(t,s={}){let{html:e,context:r,redirect:i,cookies:o}=await lt(t,s),l=Bt(r),a=Ft(r);if(i)return{html:e,redirect:i,cookies:o,status:l,headers:a};let{extractStreamBoundaries:u}=await import("./chunk-
|
|
32
|
+
`)}import O from"fs";import z from"path";function xa(t,s,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:s,outputDir:e}}function Sa(t,s){let e=z.join(s,"manifest.json");O.writeFileSync(e,JSON.stringify(t,null,2))}function ka(t){let s=z.join(t,"manifest.json");if(!O.existsSync(s))return null;try{let e=O.readFileSync(s,"utf-8"),r=JSON.parse(e);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}function M(t,s,e={}){let r=`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(e.maxAge!==void 0)r+=`; Max-Age=${e.maxAge}`;if(e.expires)r+=`; Expires=${e.expires.toUTCString()}`;if(e.path)r+=`; Path=${e.path}`;if(e.domain)r+=`; Domain=${e.domain}`;if(e.secure)r+="; Secure";if(e.httpOnly)r+="; HttpOnly";if(e.sameSite)r+=`; SameSite=${e.sameSite}`;return r}async function at(t){let s=t.headers.get("content-type")||"",e={},r=(i,o)=>{let l=e[i];if(l===void 0)e[i]=o;else if(Array.isArray(l))l.push(o);else e[i]=[l,o]};if(s.includes("multipart/form-data")){let i=await t.formData();for(let[o,l]of i.entries())if(typeof l==="string")r(o,l);return e}if(s.includes("application/x-www-form-urlencoded")){for(let[i,o]of new URLSearchParams(await t.text()).entries())r(i,o);return e}return e}function ko(t){if(!t)return!1;let s=t.toUpperCase();return s!=="GET"&&s!=="HEAD"}async function W(t,s={}){let e=s.request,r=s.method??e?.method;if(!e||!ko(r))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let i={};try{i=await at(e)}catch{}let o=await t.action({request:e,form:i,params:s.params??{},query:t.query??{},cookies:s.cookies??{}});if(o&&typeof o==="object"){let l=o,a=ct(l.cookies),u=l.redirect;if(typeof u==="string"&&u)return{redirect:u,ran:!0,...a.length>0?{cookies:a}:{}};let{cookies:g,redirect:f,...d}=l;if(Object.assign(t,d),a.length>0)return{ran:!0,cookies:a}}return{ran:!0}}function ct(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let s=[];for(let[e,r]of Object.entries(t)){if(!e)continue;if(typeof r==="string"){s.push(M(e,r));continue}if(r&&typeof r==="object"){let i=r;if(typeof i.value!=="string")continue;s.push(M(e,i.value,i))}}return s}function _a(t,s=[],e){let r=new Headers({Location:t,"Cache-Control":"no-store"});for(let i of s)r.append("Set-Cookie",i);for(let[i,o]of Object.entries(e??{}))if(i.toLowerCase()!=="location")r.set(i,o);return new Response(null,{status:303,headers:r})}async function Bn(t,s={}){let{html:e,context:r,redirect:i,cookies:o}=await lt(t,s),l=Bt(r),a=Ft(r);if(i)return{html:e,redirect:i,cookies:o,status:l,headers:a};let{extractStreamBoundaries:u}=await import("./chunk-9kghtf20.js"),g=u(r),f=t.streamTemplates;if(f&&Object.keys(f).length>0){let{processDirectives:d}=await import("./chunk-h8rpk597.js"),{defaultConfig:x}=await import("./chunk-natvnazg.js"),y=r.streamBoundaries||{},R={...x,autoShell:!1},b=Object.keys(f).map((m)=>({id:m,render:async()=>{let S=typeof y[m]==="function"?await y[m]():void 0;return d(f[m],{...r,$boundary:S},t.sourceFile,R,new Set)}})),k=new Set(b.map((m)=>m.id));g=[...(g||[]).filter((m)=>!k.has(m.id)),...b]}return{html:e,boundaries:g&&g.length>0?g:void 0,cookies:o,status:l,headers:a}}async function lt(t,s){let e={__filename:t.sourceFile,__dirname:t.sourceFile.replace(/[/\\][^/\\]+$/,""),...s};if(!t.hasServerScripts&&!$i(t.html))return{html:t.html,context:e};for(let l of t.serverScriptContent)try{await h(l,e,t.sourceFile)}catch(a){if(s.__stx_strict_hydration)throw a;console.warn(`[stx] Server script error in ${t.sourceFile}:`,a)}let r=await W(e,{request:s.request,method:s.method,params:s.params??{},cookies:s.cookies??{}}),i=(l)=>{let a=l.replace(/<script\b[^>]*\bdata-stx-server-data\b[^>]*>[\s\S]*?<\/script>/gi,""),u=Pr(e);if(!u)return a;let g=D(a);return g<0?u+a:a.slice(0,g)+u+a.slice(g)};if(r.redirect)return{html:t.html,context:e,redirect:r.redirect,cookies:r.cookies};if(!$i(t.html))return{html:i(t.html),context:e,cookies:r.cookies};let o=new Map;for(let[l,a]of Object.entries(t.placeholders))if(a.expression)try{let u=I(a.expression,e);if(a.type==="raw")o.set(l,u!==void 0&&u!==null?String(u):"");else o.set(l,u!==void 0&&u!==null?G(String(u)):"")}catch(u){if(s.__stx_strict_hydration)throw u;o.set(l,"")}return{html:i(gl(t.html,o)),context:e,cookies:r.cookies}}
|
|
33
33
|
export{wt,en,Ae,H,Ln,jn,wa,So,Qr,Je,va,Ye,Pe,xa,Sa,ka,ko,_a,Bn};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{tu,Im,nu,ru,Om,Nm}from"./chunk-
|
|
2
|
+
import{tu,Im,nu,ru,Om,Nm}from"./chunk-aed45njs.js";import"./chunk-eprhhrzc.js";import"./chunk-w3d7pwzg.js";import"./chunk-60yppcbb.js";import"./chunk-csymxc5a.js";import"./chunk-farh4p7f.js";import"./chunk-qjey0jk6.js";export{Nm as applySlots,Om as extractSlotContent,Im as parseSlotElement,tu as parseSlots,ru as processSlots,nu as renderSlot};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{is,as}from"./chunk-pywz8q4k.js";import{w}from"./chunk-
|
|
2
|
+
import{is,as}from"./chunk-pywz8q4k.js";import{w}from"./chunk-eprhhrzc.js";import{a}from"./chunk-xr1yrdxy.js";import{Ze,ue}from"./chunk-wk2rge05.js";import{ac}from"./chunk-ct90b523.js";import{V}from"./chunk-4068rmzv.js";import{b}from"./chunk-94mpe1ny.js";import{f}from"./chunk-fd1bpv35.js";import{existsSync as z,mkdirSync as C,copyFileSync as I,chmodSync as B,rmSync as xe}from"fs";import{join as c,basename as ye,resolve as K}from"path";import{spawn as _}from"child_process";import{platform as Se}from"os";function O(e,r,i){let n=new RegExp(`</${r}\\s*>`,"iy"),s=w(e,(t,o)=>(n.lastIndex=o,n.exec(t)?n.lastIndex:-1))[0];return s?e.slice(0,s.start)+i+e.slice(s.start):null}var Tu=`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
'use strict';
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import R from"path";var O=/__stxModules\["((?:[^"\\]|\\.)*)"\]/g;function Ur(...g){let d=new Set;for(let c of g){if(!c||!c.includes("__stxModules["))continue;for(let s of c.matchAll(O))try{d.add(JSON.parse(`"${s[1]}"`))}catch{}}return[...d].sort()}function po(...g){let d=new Map,c=(s,e)=>{let r=d.get(s);if(r===null)return;if(e===null){d.set(s,null);return}let n=r??new Set;for(let i of e)n.add(i);d.set(s,n)};for(let s of g){if(!s||!s.includes("__stxModules["))continue;let e=[];for(let n of s.matchAll(/([\w$]+)\s*=\s*globalThis\.__stxModules\s*&&\s*globalThis\.__stxModules\["((?:[^"\\]|\\.)*)"\]/g)){let i;try{i=JSON.parse(`"${n[2]}"`)}catch{continue}e.push({variable:n[1],id:i,start:n.index+n[0].length,end:s.length})}let r=s.match(/__stxModules\["(?:[^"\\]|\\.)*"\]/g)?.length??0;if(e.length===0||r!==e.length){for(let n of Ur(s))c(n,null);continue}for(let[n,i]of e.entries()){let p=e.slice(n+1).find((h)=>h.variable===i.variable);i.end=p?p.start:s.length}for(let n of e){let i=new Set,p=!1,h=n.variable.replace(/[$]/g,"\\$&"),o=s.slice(n.start,n.end);for(let l of o.matchAll(new RegExp(`(?<![\\w$.])${h}(?![\\w$])`,"g"))){let f=o.slice(l.index+n.variable.length,l.index+n.variable.length+200),a=/^\s*\[\s*(["'])([A-Za-z_$][\w$]*)\1\s*\]/.exec(f)??/^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(f);if(a){i.add(a[a.length-1]);continue}if(/^\s*[!=]==?\s*(?:undefined|void 0)\b/.test(f))continue;p=!0;break}c(n.id,p?null:i)}}return d}function v(g,d,c){let s=[],e=[];return g.forEach((r,n)=>{let i=r.startsWith("npm:")?r.slice(4):R.resolve(d,r),p=`__stxRegistered${n}`,h=JSON.stringify(r),o=c?.get(r);if(o&&[...o].every((l)=>/^[A-Za-z_$][\w$]*$/.test(l))){let l=[...o].sort(),f=l.map((m,_)=>`${m} as ${p}_${_}`);s.push(l.length>0?`import { ${f.join(", ")} } from ${JSON.stringify(i)};`:`import ${JSON.stringify(i)};`);let a=l.map((m,_)=>`get ${JSON.stringify(m)}() { return ${p}_${_}; }`).join(", ");e.push(`if (!globalThis.__stxModules[${h}]) globalThis.__stxModules[${h}] = { ${a} };`);return}s.push(`import * as ${p} from ${JSON.stringify(i)};`),e.push(`if (!globalThis.__stxModules[${h}]) globalThis.__stxModules[${h}] = ${p};`)}),[...s,"globalThis.__stxModules = globalThis.__stxModules || {};",...e].join(`
|
|
3
|
-
`)}async function nm(g,d={}){if(g.length===0)return null;let c=process.cwd(),s=v(g,c,d.names),e;try{let{bundleClientScript:l}=await import("./chunk-
|
|
3
|
+
`)}async function nm(g,d={}){if(g.length===0)return null;let c=process.cwd(),s=v(g,c,d.names),e;try{let{bundleClientScript:l}=await import("./chunk-k0ph8zr7.js"),f=()=>l(s,R.join(c,".stx-module-registry.ts"),{projectRoot:c,minify:d.minify,externalizeUserModules:!1,collectInputs:d.collectInputs,throwOnFailure:!0});try{e=await f()}catch(a){if(!d.names)throw a;s=v(g,c,void 0),e=await f()}}catch(l){let{formatBuildFailure:f}=await import("./chunk-cvgbtmxp.js"),a=f(l);console.warn(`[stx] could not build the page module registry (#1957): ${a}`);let m=`[stx] the page module registry did not build, so ${g.join(", ")} cannot load (#1957): ${a}`;return`;console.error(${JSON.stringify(m)});`}let{transformAutoImports:r,generateAutoImportDestructuring:n}=await import("./chunk-0g80km93.js"),i=r(e),p=n(i.stxImports,i.browserImports),{transformStoreImports:h}=await import("./chunk-4pr29yrx.js");e=h(i.code);let o=JSON.stringify(new Bun.CryptoHasher("md5").update(s).digest("hex").slice(0,12));return[";(function() {"," var __stxBundles = globalThis.__stxModuleBundles || (globalThis.__stxModuleBundles = {});",` if (__stxBundles[${o}]) return;`,` __stxBundles[${o}] = true;`,p,e,"})();"].join(`
|
|
4
4
|
`)}var P=/^import(?:[ \t]*(\{[^}]*\})[ \t]*from|[ \t]*\*[ \t]*as[ \t]+([\w$]+)[ \t]+from)?[ \t]*["']\.\/(chunk-[\w-]+)\.js["'][ \t]*;?[ \t]*$/gm,j=/^export\s*\{([^}]*)\}\s*;?[ \t]*$/gm,I=new Set(["__preload","__chunks"]),N=/^("[^"]*"|[\w$]+)(?:\s+as\s+("[^"]*"|[\w$]+))?$/;function J(g){let d=[],c=[],s=!0,r=g.replace(/^var __chunkGraphs;[\s\S]*?^var __chunks = [\s\S]*?^\};[ \t]*\n?/m,"").replace(/^__chunks\(import\.meta\.url,[^\n]*\);[ \t]*\n?/gm,"").replace(P,(h,o,l,f)=>{let a=`__stxChunkExports${d.length}`;if(d.push(f),c.push(`var ${a} = __stxChunk(${JSON.stringify(f)});`),l)c.push(`var ${l} = ${a};`);else if(o)for(let m of o.slice(1,-1).split(",")){let _=m.trim();if(!_)continue;let w=N.exec(_);if(!w){s=!1;continue}if(I.has(w[1]))continue;let M=w[1].startsWith('"')?JSON.parse(w[1]):w[1],t=w[2]??w[1];if(t.startsWith('"')){s=!1;continue}c.push(`var ${t} = ${a}[${JSON.stringify(M)}];`)}return""});if(!s)throw Error("an import it does not read");let n=[];r=r.replace(/\(\s*__preload\([^)]*\)\s*,\s*import\(\s*["']\.\/(chunk-[\w-]+)\.js["']\s*\)\s*\)|\bimport\(\s*["']\.\/(chunk-[\w-]+)\.js["']\s*\)/g,(h,o,l)=>{let f=o??l;return n.push(f),`Promise.resolve().then(function () { return __stxChunk(${JSON.stringify(f)}); })`});let i=[];r=r.replace(j,(h,o)=>{for(let l of o.split(",")){let f=l.trim();if(!f)continue;let a=N.exec(f);if(!a||a[1].startsWith('"')){s=!1;continue}if(I.has(a[1]))continue;let m=a[2]??a[1];i.push([a[1],m.startsWith('"')?JSON.parse(m):m])}return""});let p=[/\bimport\.meta\b/,/\b__chunks\b/,/\b__preload\b/,/^\s*export\s+(?:default\b|const\b|let\b|var\b|function\b|class\b|async\b|\*|\{)/m,/\bfrom\s*["']\.\/chunk-/,/^\s*import\s*["']\.\/chunk-/m].find((h)=>h.test(r));if(!s||p)throw Error(`${p?`${p.source} is left in it`:"an export it does not read"}`);return{reads:c.join(`
|
|
5
5
|
`),chunks:d,lazy:n,body:r,exports:i}}function Bl(g){if(/\bexport\s+(?:let|var)\b/.test(g))return!0;if(g.length/Math.max(1,g.split(`
|
|
6
|
-
`).length)>200)return!1;for(let d of g.matchAll(/\bexport\s*\{([^}]*)\}(?!\s*from\b)/g))for(let c of d[1].split(",")){let s=c.trim().split(/\s+as\s+/)[0].trim();if(!/^[A-Za-z_$][\w$]*$/.test(s))continue;let e=s.replace(/[$]/g,"\\$&");if(!new RegExp(`(?<![\\w$.])(?:let|var)\\s+${e}(?![\\w$])`,"g").test(g))continue;let n=new RegExp(`(?<![\\w$.])${e}\\s*(?:=(?![=>])|[-+*/%&|^]=|\\*\\*=|<<=|>>>?=|&&=|\\|\\|=|\\?\\?=|\\+\\+|--)|(?:\\+\\+|--)\\s*${e}(?![\\w$])`,"g"),i=new RegExp(`(?<![\\w$.])(?:let|var|const)\\s+${e}\\s*=`,"g");if((g.match(n)?.length??0)>(g.match(i)?.length??0))return!0}return!1}async function fo(g,d={}){let c=g.filter((e)=>e.ids.length>0);if(c.length===0)return{chunks:new Map,routes:new Map,reads:new Map};let s=process.cwd();try{let{bundleClientEntriesSplit:e}=await import("./chunk-
|
|
6
|
+
`).length)>200)return!1;for(let d of g.matchAll(/\bexport\s*\{([^}]*)\}(?!\s*from\b)/g))for(let c of d[1].split(",")){let s=c.trim().split(/\s+as\s+/)[0].trim();if(!/^[A-Za-z_$][\w$]*$/.test(s))continue;let e=s.replace(/[$]/g,"\\$&");if(!new RegExp(`(?<![\\w$.])(?:let|var)\\s+${e}(?![\\w$])`,"g").test(g))continue;let n=new RegExp(`(?<![\\w$.])${e}\\s*(?:=(?![=>])|[-+*/%&|^]=|\\*\\*=|<<=|>>>?=|&&=|\\|\\|=|\\?\\?=|\\+\\+|--)|(?:\\+\\+|--)\\s*${e}(?![\\w$])`,"g"),i=new RegExp(`(?<![\\w$.])(?:let|var|const)\\s+${e}\\s*=`,"g");if((g.match(n)?.length??0)>(g.match(i)?.length??0))return!0}return!1}async function fo(g,d={}){let c=g.filter((e)=>e.ids.length>0);if(c.length===0)return{chunks:new Map,routes:new Map,reads:new Map};let s=process.cwd();try{let{bundleClientEntriesSplit:e}=await import("./chunk-k0ph8zr7.js"),r=[],n=await e(new Map(c.map((t)=>[t.name,v(t.ids,s,t.names)])),{projectRoot:s,filePath:R.join(s,".stx-module-registry.ts"),collectInputs:r});d.collectInputs?.push(...r);let{transformAutoImports:i,generateAutoImportDestructuring:p}=await import("./chunk-0g80km93.js"),{transformStoreImports:h}=await import("./chunk-4pr29yrx.js"),o=new Map;for(let[t,u]of[...n.chunks,...n.entries])try{o.set(t,J(u))}catch(b){throw Error(`cannot read ${t}: ${b instanceof Error?b.message:String(b)}`)}for(let[t,u]of[...n.chunks,...n.entries])if(/\b__esm\(/.test(u))throw Error(`${t} initialises a module lazily`);for(let t of r)if(/\.(?:[cm]?[jt]sx?)$/.test(t)&&Bl(await Bun.file(t).text()))throw Error(`${t} exports a binding that changes after it is read`);let l=new Set,f=new Set,a=(t)=>{if(f.has(t))return;if(l.has(t))throw Error(`the chunks import each other (${t})`);l.add(t);for(let u of o.get(t)?.chunks??[]){if(!o.has(u))throw Error(`${t} imports ${u}, which was not built`);a(u)}for(let u of o.get(t)?.lazy??[])if(!o.has(u))throw Error(`${t} imports ${u}, which was not built`);l.delete(t),f.add(t)};for(let t of o.keys())a(t);let m=(t)=>{let u=i(t.body);return{prelude:p(u.stxImports,u.browserImports),body:h(u.code)}},_=new Map;for(let t of n.chunks.keys()){let u=o.get(t),{prelude:b,body:k}=m(u),y=u.exports.map(([S,x])=>`get ${JSON.stringify(x)}() { return ${S}; }`).join(", ");_.set(t,`function (__stxChunk) {
|
|
7
7
|
${b}
|
|
8
8
|
${u.reads}
|
|
9
9
|
${k}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ur,po,nm,Bl,fo}from"./chunk-
|
|
2
|
+
import{Ur,po,nm,Bl,fo}from"./chunk-tny8mz6q.js";export{nm as buildModuleRegistryScript,fo as buildSharedModuleRegistries,Bl as exportsMutableBinding,Ur as registeredModuleIdsIn,po as registeredModuleNamesIn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Le,S,_,T,re}from"./chunk-
|
|
2
|
+
import{Le,S,_,T,re}from"./chunk-eprhhrzc.js";import{C}from"./chunk-qjey0jk6.js";import{N,On}from"./chunk-farh4p7f.js";import{a}from"./chunk-xr1yrdxy.js";import{xe,un,dn,pn}from"./chunk-qhczf1wf.js";import{Ct}from"./chunk-2drcj9wn.js";import{xt,Xn,nn,me}from"./chunk-j89p53vx.js";import{A,In}from"./chunk-9fyw1xkh.js";import h from"path";var v=new Map,E=new Map,I=S(64),F=new Map,V=["composables","functions"];function H(e){let s=h.basename(e,".ts");return s==="index"||s==="types"||e.endsWith(".d.ts")}async function Y(e){if(e)return h.resolve(e);let s=`<default>:${process.cwd()}`,r=F.get(s);if(r!==void 0)return r;let t=await ee();if(t!==null)F.set(s,t);return t}async function ee(){let e=await a(),s=e.root||process.cwd(),r=e.composablesDir;if(r)return h.resolve(s,r);for(let t of V){let n=h.resolve(s,t);try{let c=new Bun.Glob("**/*.ts");for await(let i of c.scan({cwd:n,absolute:!0}))if(!H(i))return n}catch{}}return null}async function W(e){let s=Array.isArray(e)?e:e?[h.resolve(e)]:(await a())._layerComposableDirs??[await Y()].filter((t)=>!!t),r=new Map;for(let t of s){let n=new Bun.Glob("**/*.ts");try{for await(let c of n.scan({cwd:t,absolute:!0})){let i=h.relative(t,c);if(!H(c)&&!r.has(i))r.set(i,c)}}catch{}}return{key:s.join("\x00"),files:[...r.values()].sort()}}async function Eo(e){let{files:s}=await W(e),r=re({loader:"ts",target:"browser",define:T()}),t=[];for(let n of s)try{let c=await Bun.file(n).text(),i=r.scan(c).exports.filter((u)=>u!=="default");if(i.length>0)t.push({file:n,names:i})}catch{}return t}function te(e,s){return new RegExp(`\\b${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e)}function R(e,s){let r=new Set(e.match(/\w+/g)),t=new Set;for(let n of s)if(/^\w+$/.test(n)?r.has(n):te(e,n))t.add(n);return t}var J=S(64);function X(e,s){let r=_(e,s.size),t=J.get(r);if(t)return t;let n;try{n=Le(e,s)}catch{n=R(e,s)}let c=[...e.matchAll(/(?:const|let|var)\s*\{([^}]*)\}\s*=\s*window\.__composables\u0008/g),...e.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@composables['"]/g)];for(let i of c)for(let u of i[1].split(",")){let f=u.trim().split(/\s*(?::|\u0008as\u0008)\s*/)[0];if(f&&s.has(f))n.add(f)}return J.set(r,n),n}function ne(e){return!e||/^(?:module|(?:text|application)\/(?:java|ecma)script|application\/stx-[\w-]+)$/i.test(e)}var L=S(256);function se(e,s){let r=new Set(s),t="",n=0,c=new Set;for(let i of e.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)){t+=e.slice(n,i.index),n=i.index+i[0].length;let u=i[1]??"",f=i[2]??"",d=/\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(u),m=d?(d[1]??d[2]??d[3]??"").trim():void 0;if(!ne(m)){if(!/json/i.test(m??""))t+=` ${f} `;continue}let y=R(f,r);if(y.size===0)continue;let b=_(f,[...y].sort().join(",")),w=L.get(b);if(!w)w=X(f,y),L.set(b,w);for(let B of w)c.add(B)}t+=e.slice(n);for(let i of R(t,r))c.add(i);return c}function oe(e,s,r){let t=new Map;for(let{file:f,names:d}of e)for(let m of d)if(!t.has(m))t.set(m,f);let n=new Set(t.keys()),c=(f)=>{let d=[];for(let m of X(f,n))d.push(t.get(m));return d},i=new Set,u=r.flatMap((f,d)=>d===0?[...se(f,t.keys())].map((m)=>t.get(m)):c(f));while(u.length>0){let f=[];for(let d of u){if(i.has(d))continue;i.add(d);for(let m of c(s.get(d)??""))if(!i.has(m))f.push(m)}u=f}return i}async function Eh(e,s,r,t){let{key:n,files:c}=await W(e);if(!n)return null;let i=()=>[...new Set([...c,...c.flatMap((o)=>xe(o))])],u=xt(i());if(c.length===0)return me(v,n,u,""),null;c.sort();let f=re({loader:"ts",target:"browser",define:T()}),d=nn(E,n,u);if(!d){let o=new Map,l=[];for(let p of c)try{let x=await Bun.file(p).text();o.set(p,x);let g=f.scan(x).exports.filter((Q)=>Q!=="default");if(g.length>0)l.push({file:p,names:g})}catch{o.set(p,"")}d=me(E,n,u,{codeByFile:o,modules:l})}let{codeByFile:m,modules:y}=d,b;if(s===void 0)b=new Set(c);else{let o=r?[s,...r]:[s],l=_(o.join("\x00"),n,o.length,u),p=I.get(l);if(b=p??oe(y,m,o),!p)I.set(l,b)}if(b.size===0)return null;let w=c.filter((o)=>b.has(o)),B=()=>{if(!t)return;for(let o of w)t.push(o,...xe(o))},k=`${n}\x00${w.join("\x00")}\x00${dn()}`,P=nn(v,k,u);if(P!==void 0)return B(),P||null;let D=[],M=new Set,U=new Set;for(let o of w)try{let l=m.get(o)??await Bun.file(o).text(),p=h.basename(o,".ts");for(let g of l.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(g[1])U.add(g[1]);let x=[];try{for(let g of f.scan(l).exports)if(g!=="default")M.add(g),x.push(g)}catch{}if(l=N(l),un(l))l=await pn(l,o,{projectRoot:process.cwd(),externalizeUserModules:!1,expose:x}),l=Ct(l);l=On(l),l=l.replace(/^export\s+(default\s+)?/gm,""),l=f.transformSync(l),D.push(`// Composable: ${p}
|
|
3
3
|
${l.trim()}`)}catch(l){console.warn(`[stx] Failed to load composable ${o}:`,l)}if(D.length===0||M.size===0)return me(v,k,u,""),null;let Z=[...M].map((o)=>` try { if (!(${JSON.stringify(o)} in __c)) __c[${JSON.stringify(o)}] = ${o}; } catch (e) {}`).join(`
|
|
4
4
|
`),z=JSON.stringify([...M]),j=D.join(`
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$n,B}from"./chunk-60yppcbb.js";import m from"fs";import e from"path";async function Tn(r,o,i){if(r.__stx_runtime_config)return;let n=$n();if(n||i){r.__stx_runtime_config=n??B(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-
|
|
2
|
+
import{$n,B}from"./chunk-60yppcbb.js";import m from"fs";import e from"path";async function Tn(r,o,i){if(r.__stx_runtime_config)return;let n=$n();if(n||i){r.__stx_runtime_config=n??B(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-natvnazg.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=B(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Pi(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
|
|
3
3
|
declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${i(o.public??{})} }
|
|
4
4
|
`),await Bun.write(e.join(r,".stx/runtime-config-server.d.ts"),`import '@stacksjs/stx/runtime-config-server'
|
|
5
5
|
declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${i(o.private??{})} }
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a}from"./chunk-
|
|
2
|
+
import{a}from"./chunk-xr1yrdxy.js";import{_o}from"./chunk-3z1mmar2.js";import p from"path";async function um(t={}){let l=performance.now(),s=t.root||process.cwd(),e=await a(s),o=t.ssr?.routeRules??e.routeRules??{};if(_o(o),!e.ssr&&Object.keys(o).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let u,n;if(r==="ssg"){let{generateStaticSite:i}=await import("./ssg.js");u=await i({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:i}=await import("./chunk-y2ctxchq.js");n=await i({root:s,outputDir:".output",debug:t.debug,...t.ssr})}let d=Math.round(performance.now()-l);return{mode:r,ssg:u,ssr:n,duration:d}}
|
|
3
3
|
export{um};
|