@stacksjs/stx 0.2.780 → 0.2.782
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-02z88h3r.js +2 -0
- package/dist/{chunk-e41tnswv.js → chunk-13zfxwej.js} +2 -2
- package/dist/{chunk-15g4sg16.js → chunk-187s3a84.js} +1 -1
- package/dist/{chunk-xzgbhwty.js → chunk-1dp83080.js} +1 -1
- package/dist/{chunk-v6bsz059.js → chunk-1p8r3w08.js} +1 -1
- package/dist/{chunk-qnmncbs9.js → chunk-209674ms.js} +2 -2
- package/dist/{chunk-9e5jcbhp.js → chunk-267wdqtr.js} +2 -2
- package/dist/{chunk-7qcjeykk.js → chunk-2kztshb4.js} +1 -1
- package/dist/{chunk-y3ebjepx.js → chunk-2skv6cr7.js} +1 -1
- package/dist/{chunk-vfn745ae.js → chunk-311q3pa2.js} +1 -1
- package/dist/{chunk-xz60hh63.js → chunk-3xzzzrhw.js} +1 -1
- package/dist/{chunk-0tjn4hxp.js → chunk-41gq8324.js} +4 -4
- package/dist/{chunk-spfk1hj7.js → chunk-4q4vexpc.js} +1 -1
- package/dist/{chunk-ydjs3bzy.js → chunk-5smaktgt.js} +1 -1
- package/dist/{chunk-x93rbyyd.js → chunk-62xcwhfd.js} +1 -1
- package/dist/{chunk-kv7crjfs.js → chunk-6mdpttxy.js} +1 -1
- package/dist/{chunk-kn991pyq.js → chunk-7086efsc.js} +1 -1
- package/dist/{chunk-j23nska2.js → chunk-7r1tcffk.js} +2 -2
- package/dist/{chunk-2pyfw8k7.js → chunk-a623wybr.js} +4 -4
- package/dist/{chunk-hkh772yj.js → chunk-abzp0cp9.js} +1 -1
- package/dist/{chunk-jp02pcy5.js → chunk-avwsq94a.js} +1 -1
- package/dist/{chunk-02s307f1.js → chunk-axs1wrkr.js} +3 -3
- package/dist/{chunk-xcaq3zyx.js → chunk-ay2by639.js} +1 -1
- package/dist/{chunk-weka7k61.js → chunk-dd12079e.js} +1 -1
- package/dist/{chunk-d4jg4brt.js → chunk-de9dkzwy.js} +1 -1
- package/dist/{chunk-sxwmdxw2.js → chunk-dfn9cp6v.js} +1 -1
- package/dist/{chunk-57s05c7p.js → chunk-djqx359s.js} +1 -1
- package/dist/{chunk-qv2qrjcx.js → chunk-dnk3ahmm.js} +1 -1
- package/dist/{chunk-jfhzqcj9.js → chunk-f9rtfd58.js} +1 -1
- package/dist/{chunk-cdbgjwz8.js → chunk-fj7tedrt.js} +1 -1
- package/dist/{chunk-ty1tq0nw.js → chunk-fkn08jb3.js} +1 -1
- package/dist/chunk-fmzdvgka.js +2 -0
- package/dist/chunk-g9makcfg.js +2 -0
- package/dist/{chunk-w3aw4vw0.js → chunk-gpt1v08p.js} +1 -1
- package/dist/{chunk-gswn2c2y.js → chunk-kkkpgnj3.js} +1 -1
- package/dist/{chunk-b0zc96r4.js → chunk-km0tqwx1.js} +4 -4
- package/dist/{chunk-d3a5ftxf.js → chunk-m60qqnt6.js} +1 -1
- package/dist/chunk-m68scqz0.js +2 -0
- package/dist/{chunk-5t388a0x.js → chunk-mhmphbve.js} +5 -5
- package/dist/chunk-mpny7cmd.js +2 -0
- package/dist/{chunk-t5srthkt.js → chunk-mx0a1ax8.js} +1 -1
- package/dist/{chunk-k66x9s31.js → chunk-p23rgrsc.js} +2 -2
- package/dist/{chunk-7gs16p03.js → chunk-p5qtdqdt.js} +1 -1
- package/dist/{chunk-mnq9g3ra.js → chunk-ppnc68ta.js} +1 -1
- package/dist/chunk-pwetf855.js +2 -0
- package/dist/{chunk-fcf5cv08.js → chunk-q9w8rfve.js} +1 -1
- package/dist/{chunk-a46qpf2y.js → chunk-qgy1w573.js} +1 -1
- package/dist/{chunk-6sz69gvp.js → chunk-r0g70zrf.js} +6 -6
- package/dist/{chunk-566mkn3e.js → chunk-rvvc4twc.js} +1 -1
- package/dist/{chunk-tk8q2r05.js → chunk-ry7w14ax.js} +4 -4
- package/dist/{chunk-w1w8nj6n.js → chunk-smsjcnvm.js} +1 -1
- package/dist/{chunk-b6g1h863.js → chunk-t6z2ty9v.js} +2 -2
- package/dist/{chunk-yq2bpyjd.js → chunk-v1eakek3.js} +1 -1
- package/dist/chunk-vdx4zfq1.js +2 -0
- package/dist/chunk-wbhv5137.js +3 -0
- package/dist/{chunk-gy10h4mh.js → chunk-x2c3mjey.js} +1 -1
- package/dist/{chunk-kygx13s7.js → chunk-xcrrsq09.js} +1 -1
- package/dist/{chunk-w773zjcj.js → chunk-xqa9ze06.js} +1 -1
- package/dist/chunk-y209b8ch.js +2 -0
- package/dist/{chunk-y9vk93nk.js → chunk-y2q9f262.js} +1 -1
- package/dist/{chunk-67e85f7r.js → chunk-z04f6fy2.js} +1 -1
- package/dist/chunk-z5pvmtd7.js +2 -0
- package/dist/chunk-z79s860q.js +2 -0
- package/dist/{chunk-nrr0jfwq.js → chunk-zbeaatev.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/runtime/craft-bridge.js +7 -0
- package/dist/native/runtime/craft.d.ts +23 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-1ckn7fb6.js +0 -2
- package/dist/chunk-1jct3j13.js +0 -2
- package/dist/chunk-1mqymwsd.js +0 -2
- package/dist/chunk-3dx4gb3m.js +0 -2
- package/dist/chunk-7hb0ep9w.js +0 -2
- package/dist/chunk-85e7tay6.js +0 -2
- package/dist/chunk-fc765rv3.js +0 -2
- package/dist/chunk-g3yppmn6.js +0 -2
- package/dist/chunk-p42jm38c.js +0 -2
- package/dist/chunk-w0qzmr1n.js +0 -3
- package/dist/chunk-yfamk0xt.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-
|
|
2
|
+
import{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-r0g70zrf.js";import{yt,Re,tc,ss,Io,Oo,i}from"./chunk-41gq8324.js";import{ae,Er,ke,B,Sn}from"./chunk-bq9xf8nq.js";import{St,pr,Es,Ts,$s,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-yewd8836.js";import{vs,a,P}from"./chunk-13zfxwej.js";import{ft,An,Ce,M,oa,fo,qr,We,ia,qe,Ee}from"./chunk-axs1wrkr.js";import{lr,ur}from"./chunk-q9w8rfve.js";import{$n}from"./chunk-v1eakek3.js";import{e,cn,sr,y}from"./chunk-7r1tcffk.js";import{Je}from"./chunk-km0tqwx1.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-ry7w14ax.js";import{l}from"./chunk-jdj1358b.js";import{K}from"./chunk-bmfk3b29.js";async function Nn(t){try{let n=await Bun.file(t).text(),o=Un(n),d=Wn(n,t),s=Vn(n,o),c=qn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:c}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
|
|
3
3
|
`),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
|
|
4
4
|
`).length,c={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};c.total=c.conditionals+c.loops+c.includes+c.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,b=Math.min(10,Math.ceil(c.total*0.5+h*0.1+x*0.3+(s>10?s*0.05:0)+w));return{lines:n.length,characters:t.length,directives:c,expressions:h,components:x,layouts:v,scriptLines:s,complexity:b}}function Wn(t,n){let o=[],d=Xt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let s=Xt(t,"foreach","endforeach");if(s>0)o.push({type:"error",category:"syntax",message:`Found ${s} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let c=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(c&&c.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
|
|
5
5
|
`).filter((x)=>x.length>120);if(g.length>0)o.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Vn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function qn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Xt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,c=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-c)}async function Ki(t=["**/*.stx"],n){let o=[],d=[];for(let c of t){let u=await Array.fromAsync(new Bun.Glob(c).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let c of d)try{let u=await Nn(c);o.push(u)}catch(u){console.warn(`Failed to analyze ${c}:`,u)}let s=Kn(o);return{results:o,summary:s}}function Kn(t){let n=t.length,o=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,s=t.reduce((h,x)=>h+x.issues.length,0),c={};t.forEach((h)=>{h.issues.forEach((x)=>{c[x.category]=(c[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(s>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(c.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:s,issuesByCategory:c,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function o(d){let s=await Jn(d,{withFileTypes:!0});s.sort((c,u)=>c.name.localeCompare(u.name));for(let c of s){let u=Te.join(d,c.name);if(c.isDirectory()){if(!c.name.startsWith(".")&&c.name!=="node_modules")await o(u)}else if(c.isFile()&&c.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(c.name))n.push(u)}}return await o(t),n}function nr(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(s){throw Error(`${n}: <script component> must contain JSON metadata (${s.message})`)}}function rr(t,n){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let s of d){if(!/\bclient\b/i.test(s[1])||/\bcomponent\b|\bstx:component\b/i.test(s[1]))continue;let c;try{c=new Bun.Transpiler({loader:"ts"}).transformSync(s[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(c)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<c.length&&x>0;T++){let b=c[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";o[g]=`${w}${g}(${f[2]}) {${c.slice(h,T-1)}}`,u.lastIndex=T}}return o}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
@@ -887,7 +887,7 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function Ne(t,n,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-
|
|
890
|
+
`}function Ne(t,n,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-xcrrsq09.js"),k=b(v.join(`
|
|
891
891
|
`),S),_=w.search(/<\/body>/i);if(_!==-1)w=w.slice(0,_)+k+`
|
|
892
892
|
`+w.slice(_);else w+=`
|
|
893
893
|
${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await ur(u,w,f,o),o.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(B.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:o.debug||K()?`<!DOCTYPE html>
|
|
@@ -950,7 +950,7 @@ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await u
|
|
|
950
950
|
<h1>Something went wrong</h1>
|
|
951
951
|
<p>An internal error occurred. Please try again later.</p>
|
|
952
952
|
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let D=n.hmrPort||T+1;c=vt({wsPort:D,verbose:!1}),u=c.start(D)}let w={},b=null,k;try{let{loadStxConfig:D}=await import("./chunk-
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let D=n.hmrPort||T+1;c=vt({wsPort:D,verbose:!1}),u=c.start(D)}let w={},b=null,k;try{let{loadStxConfig:D}=await import("./chunk-vdx4zfq1.js"),I=await D();if(k=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)b=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){w=I.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-x0e0pcn0.js"),xe=I.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:_,isServerApiSource:E}=await import("./chunk-fkn08jb3.js"),R=await _(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Nr({port:T,async fetch(D){return $n(D,await(async()=>{let I=new URL(D.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,I.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(D);if(ne.status!==404)return ne}catch{}if(w[I.pathname])try{return await w[I.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(I.pathname==="/")return(async()=>{let z=await y(h||"");if(s)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let xe=ge.dirname(f),le=ge.join(xe,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Oe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),L="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
|
|
954
954
|
${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
955
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
956
|
${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
|
|
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1437
1437
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1438
1438
|
${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
|
|
1439
1439
|
${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let _=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${_}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-p42jm38c.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-ty1tq0nw.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await oa(f,n.stxOptions?.shell),D){if(C=await fo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-p42jm38c.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-x0e0pcn0.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-p42jm38c.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-7gs16p03.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-p42jm38c.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-kygx13s7.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-67e85f7r.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-mcevnfnx.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...M(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-67e85f7r.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...M(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1440
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-vdx4zfq1.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-fkn08jb3.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await oa(f,n.stxOptions?.shell),D){if(C=await fo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-vdx4zfq1.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-x0e0pcn0.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-vdx4zfq1.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-p5qtdqdt.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-vdx4zfq1.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-xcrrsq09.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-z04f6fy2.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-mcevnfnx.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...M(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-z04f6fy2.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...M(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1441
1441
|
${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1442
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
1443
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),s)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1444
1444
|
${e.yellow}Routes:${e.reset}`);let Dt=[...$s(_,f)];for(let{route:O}of R)Dt.push(`${O.pattern}`);if(Dt.forEach((O,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${O}`)}),console.log(`
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-
|
|
1445
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-p5qtdqdt.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(D&&W){if(te.resolve(U,W)===D||te.basename(D)===W){let G=await fo(D,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-p5qtdqdt.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),s&&c)c.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&c)c.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(c)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],c=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=c.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
|
|
1446
1446
|
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),s.push(h)}if(s.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)s.push({name:v})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Kr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1447
1447
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,o){let d=at.basename(t,".stx"),s=await Vr(t),c=await Kr(t),u="";if(n&&o)u=`<${o}></${o}>`;else{let f=s.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
|
|
1448
1448
|
`);u=`<${d}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Yg}from"./chunk-dnk3ahmm.js";import"./chunk-axs1wrkr.js";import"./chunk-ra8f8sm2.js";import"./chunk-de9dkzwy.js";import"./chunk-x2c3mjey.js";import"./chunk-41gq8324.js";import"./chunk-7r1tcffk.js";import"./chunk-km0tqwx1.js";import"./chunk-2gqhfge6.js";import"./chunk-rvvc4twc.js";import"./chunk-wbhv5137.js";import"./chunk-311q3pa2.js";import"./chunk-he85ksa7.js";import"./chunk-t6z2ty9v.js";import"./chunk-ry7w14ax.js";import"./chunk-wj78td69.js";import"./chunk-q9w8rfve.js";import"./chunk-13zfxwej.js";import"./chunk-qgy1w573.js";import"./chunk-zxfptbac.js";import"./chunk-605b93pe.js";import"./chunk-x8js27hd.js";import"./chunk-yewd8836.js";import"./chunk-r0g70zrf.js";import"./chunk-1dp83080.js";import"./chunk-27rzdq3n.js";import"./chunk-bq9xf8nq.js";import"./chunk-2yxva96k.js";import"./chunk-9f6qx8b9.js";export{Yg as buildForProduction};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{bf,wf,he,vf,Za,en,tn,bh,Qa,nn,Qn,xf,Sf,kf,rs,rn,_f,sn,ec,wh}from"./chunk-
|
|
2
|
+
import{bf,wf,he,vf,Za,en,tn,bh,Qa,nn,Qn,xf,Sf,kf,rs,rn,_f,sn,ec,wh}from"./chunk-f9rtfd58.js";import"./chunk-x2c3mjey.js";import"./chunk-7sh9fa3q.js";import"./chunk-13zfxwej.js";import"./chunk-qgy1w573.js";import"./chunk-zxfptbac.js";import"./chunk-605b93pe.js";import"./chunk-x8js27hd.js";import"./chunk-yewd8836.js";import"./chunk-r0g70zrf.js";import"./chunk-1dp83080.js";import"./chunk-27rzdq3n.js";import"./chunk-bq9xf8nq.js";import"./chunk-2yxva96k.js";import"./chunk-9f6qx8b9.js";export{Qn as MODULE_SPECIFIER_PREFIX,bf as bundleCacheDir,wf as bundleCacheEntryLimit,wh as bundleClientEntriesSplit,sn as bundleClientScript,tn as clearBundleFailures,he as clientBundleDependencies,en as getBundleFailures,nn as hasUserImports,rn as moduleSubstitutionKey,Sf as normalizeRegistrySpecifiers,_f as queueClientBundleBuild,Za as recordBundleFailure,xf as registryIdForPath,Qa as resolveBundlerFallback,kf as rewriteRegistryImports,bh as setBundlerFallbackMode,vf as shouldLogBundlerDiagnostics,ec as tempBuildName,rs as withModuleSubstitutes};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-9f6qx8b9.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-
|
|
2
|
+
import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-9f6qx8b9.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-r0g70zrf.js";import"./chunk-bq9xf8nq.js";import"./chunk-27rzdq3n.js";import"./chunk-1dp83080.js";import{Vt,eo,Ut,Hi,ct,Vi,to,Wt,Wi,qt}from"./chunk-7gdwvnwc.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{Vi("Config file changed, restarting...");try{await e.onChange()}catch(p){ct(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",pt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:pt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:mt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function mt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
const ws = new WebSocket('${t}');
|
|
@@ -556,7 +556,7 @@ window.__stxPerformance = {
|
|
|
556
556
|
|
|
557
557
|
window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
|
|
558
558
|
</script>
|
|
559
|
-
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-
|
|
559
|
+
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-z5pvmtd7.js"),p={},g=h(n);if(g)try{await m(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),u=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:u,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await m(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-z5pvmtd7.js"),c={...r},n=h(e);if(n)try{await m(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
560
560
|
`)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
561
561
|
`)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await Wt(t);ut(t,r);let s=qt(t.config,r);dt(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),g=`http://${o}:${e.port}`,y=Wi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let u=await Wt(t);ut(t,u);let f=qt(t.config,u);if(dt(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=g;try{let{exec:l}=await import("child_process"),u=process.platform;l(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:g,close:async()=>{y(),p.stop()}}}async function xt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],g=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((u)=>u.id===p);if(!l)return new Response("Story not found",{status:404});try{let u=await Y(t,l,g,y);return Response.json({html:u.html,css:u.css,js:u.js,errors:u.errors,duration:u.duration})}catch(u){return Response.json({html:"",css:"",js:"",errors:[u instanceof Error?u.message:String(u)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((g)=>g.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function wt(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
|
|
562
562
|
<html lang="en" class="${r.darkClass||"dark"}">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Nf,Ah,Ph,Ih,Oh,Df,Mf,Nh,Dh,qo,Mh,lr,ur,bs}from"./chunk-
|
|
2
|
+
import{Nf,Ah,Ph,Ih,Oh,Df,Mf,Nh,Dh,qo,Mh,lr,ur,bs}from"./chunk-q9w8rfve.js";import{nt}from"./chunk-5emrarpf.js";import"./chunk-r0g70zrf.js";import"./chunk-1dp83080.js";import"./chunk-27rzdq3n.js";import"./chunk-bq9xf8nq.js";import"./chunk-2yxva96k.js";import"./chunk-9f6qx8b9.js";export{Oh as __setSignalsGeneratorsForTest,nt as cacheEngineFingerprint,ur as cacheTemplate,lr as checkCache,Mh as clearDevCaches,Mf as getCachedRouterScript,Df as getCachedSignalsRuntime,Nh as getServeClientAsset,qo as getServeModuleBundle,bs as hashFilePath,Ph as invalidateFileCache,Ih as invalidateFileCacheByDir,Ah as readFileCached,Dh as registerServeModuleBundle,Nf as templateCache};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{k}from"./chunk-9f6qx8b9.js";import{A,En}from"./chunk-2yxva96k.js";import{Ie,C,Y}from"./chunk-
|
|
2
|
+
import{k}from"./chunk-9f6qx8b9.js";import{A,En}from"./chunk-2yxva96k.js";import{Ie,C,Y}from"./chunk-r0g70zrf.js";import{a}from"./chunk-13zfxwej.js";import{he,nn,rn,sn}from"./chunk-f9rtfd58.js";import{wt}from"./chunk-t6z2ty9v.js";import{mt,zn,Gt,ce}from"./chunk-tsvnhc0c.js";import{E,Cn}from"./chunk-bmfk3b29.js";import M from"fs";import b from"path";import x from"process";function B(s,o){for(let e of s.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(e[1])o.add(e[1]);for(let e of s.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let t of(e[1]??"").split(",")){let r=((t.includes(":")?t.split(":").pop():t)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(r))o.add(r)}for(let e of s.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let t of(e[1]??"").split(",")){let n=t.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(n))o.add(n)}}var h=new Map;async function R(s,o=E()){let e;if(s)e=b.resolve(s);else{let l=await a();e=b.resolve(l.root||x.cwd(),l.storesDir||"stores")}let t=`${e}\x00${rn()}\x00${o?"shared":"inline"}`,n=new Bun.Glob("*.ts"),r=[];try{for await(let l of n.scan({cwd:e,absolute:!0})){let c=b.basename(l,".ts");if(["index","types"].includes(c))continue;if(l.includes(".d.ts"))continue;r.push(l)}}catch{return ce(h,t,"",{chunks:[]}),null}let i=()=>[...new Set([...r,...r.flatMap((l)=>he(l))])],f=mt(i()),u=Gt(h,t,f);if(u!==void 0)return u.chunks.length>0?u:null;if(r.length===0)return ce(h,t,f,{chunks:[]}),null;let m=[];for(let l of r){let c=await Bun.file(l).text();m.push({file:l,hasUseStore:/useStore\s*\(/.test(c)})}m.sort((l,c)=>{if(l.hasUseStore===c.hasUseStore)return 0;return l.hasUseStore?1:-1});let p=m.map((l)=>l.file),g=[],d=Y({loader:"ts",target:"browser",define:C()});for(let l of p)try{let c=await Bun.file(l).text(),_=b.basename(l,".ts"),y=new Set;B(c,y);let v=[...c.matchAll(/\bdefineStore\s*(?:<[^>()]*>)?\(\s*(['"`])([^'"`$\\]+)\1/g)].map((U)=>U[2]),N=c.match(/\bdefineStore\s*(?:<[^>()]*>)?\(/g)?.length??0;if(nn(c))c=await sn(c,l,{projectRoot:x.cwd(),externalizeUserModules:o});c=wt(c),c=A(c),c=En(c),c=c.replace(/^export\s+(default\s+)?/gm,""),c=d.transformSync(c),g.push({name:_,ids:v.length===N?v:[],declared:y,code:`// Store: ${_}
|
|
3
3
|
${c.trim()}`})}catch(c){console.warn(`[stx] Failed to load store ${l}:`,c)}if(g.length===0)return ce(h,t,f,{chunks:[]}),null;f=mt(i());let S={chunks:g};return ce(h,t,f,S),S}function j(s){let o=new Set;for(let r of s)for(let i of r.declared)o.add(i);let e=s.map((r)=>r.code).join(`
|
|
4
4
|
|
|
5
5
|
`),n=`;(function(){
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Nl,sa,Xg,Dl,Ml,Gg,Jg}from"./chunk-6mdpttxy.js";import"./chunk-dd12079e.js";import"./chunk-f9rtfd58.js";import"./chunk-x2c3mjey.js";import"./chunk-7sh9fa3q.js";import"./chunk-t6z2ty9v.js";import"./chunk-ry7w14ax.js";import"./chunk-wj78td69.js";import"./chunk-13zfxwej.js";import"./chunk-qgy1w573.js";import"./chunk-zxfptbac.js";import"./chunk-605b93pe.js";import"./chunk-x8js27hd.js";import"./chunk-yewd8836.js";import{It,Xf}from"./chunk-r0g70zrf.js";import"./chunk-1dp83080.js";import"./chunk-27rzdq3n.js";import"./chunk-bq9xf8nq.js";import"./chunk-2yxva96k.js";import"./chunk-9f6qx8b9.js";export{Nl as buildVirtualSource,It as extractScriptBlocks,Xf as extractTemplateExpressions,Dl as findRuntimeTypeDeclarations,Ml as findStxModuleDeclarations,Jg as formatTypecheckDiagnostics,Xg as sourcePathFor,Gg as typecheckStxFiles,sa as virtualPathFor};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Tc,r,fe}from"./chunk-
|
|
2
|
+
import{Tc,r,fe}from"./chunk-r0g70zrf.js";import{nt}from"./chunk-5emrarpf.js";import{l}from"./chunk-jdj1358b.js";import o from"fs";import u from"path";var Nf=new Map,m=new Map;async function Ah(e){let n;for(let i=0;i<3;i++)try{let g=(await o.promises.stat(e)).mtime.getTime(),a=m.get(e);if(a&&a.mtime===g)return a.content;let h=await Bun.file(e).text(),w=(await o.promises.stat(e)).mtime.getTime();if(w!==g)continue;return m.set(e,{content:h,mtime:w}),h}catch(s){n=s;break}throw m.delete(e),Error(`File not found: ${e}${n?` (${n.message})`:""}`)}function Ph(e){m.delete(e)}function Ih(e){for(let t of m.keys())if(t.startsWith(e))m.delete(t)}var f=null,B=null,x=null;function Oh(e){x=e}async function Df(e=!1){let t=x??await import("./chunk-c91y14ae.js");if(e)return t.generateSignalsRuntimeDev();if(f===null)f=t.generateSignalsRuntime();return f}var S=null;async function Mf(){if(S===null){let{getRouterScript:e}=await import("./chunk-qtcxy3y3.js");S=e()}return S}var y={};async function Nh(e,t=!1){let n=e==="runtime"?await Df(t):await Mf(),i=e==="runtime"&&t?"runtime-debug":e,s=y[i];if(!s||s.content!==n)s={content:n,hash:Bun.hash(n).toString(16).padStart(16,"0").slice(0,16)},y[i]=s;return{content:n,hash:s.hash,url:`/_stx/${e}.${s.hash}.js`}}var E=500,T=33554432,c=new Map,p=0;function C(e){return l(process.cwd(),"module-bundles",`${e}.js`)}function Dh(e){let t=Bun.hash(e).toString(16).padStart(16,"0").slice(0,16),n=c.get(t),i=n!==void 0;if(i)c.delete(t),p-=n.length*2;c.set(t,e),p+=e.length*2;while(c.size>1&&(c.size>E||p>T)){let s=c.keys().next().value;p-=c.get(s).length*2,c.delete(s)}if(!i)try{let s=C(t);if(!o.existsSync(s))o.mkdirSync(u.dirname(s),{recursive:!0}),o.writeFileSync(s,e)}catch{}return`/_stx/modules.${t}.js`}function qo(e){if(!/^[0-9a-f]{16}$/.test(e))return;let t=c.get(e);if(t!==void 0)return t;try{return o.readFileSync(C(e),"utf8")}catch{return}}function Mh(){m.clear(),fe(),Tc(),f=null,B=null,S=null}function v(e){let t={debug:e.debug===!0,middleware:(e.middleware??[]).map((n)=>({name:n.name,timing:n.timing,handler:String(n.handler)})),customDirectives:(e.customDirectives??[]).map((n)=>({name:n.name,hasEndTag:n.hasEndTag===!0,rawParams:n.rawParams===!0,handler:String(n.handler)}))};return new Bun.CryptoHasher("sha1").update(JSON.stringify(t)).digest("hex")}async function lr(e,t){try{if(!t.cachePath)return null;let n=u.resolve(t.cachePath),i=u.join(n,`${bs(e)}.html`),s=u.join(n,`${bs(e)}.meta.json`);if(!await r(i)||!await r(s))return null;let g=await Bun.file(s).text(),a=JSON.parse(g);if(a.cacheVersion!==t.cacheVersion)return null;if(a.engine!==nt())return null;if(a.optionsSignature!==v(t))return null;if((await o.promises.stat(e)).mtime.getTime()>a.mtime)return null;for(let d of a.dependencies)if(await r(d)){if((await o.promises.stat(d)).mtime.getTime()>a.mtime)return null}else return null;return await Bun.file(i).text()}catch(n){return console.warn(`Cache error for ${e}:`,n),null}}async function ur(e,t,n,i){try{if(!i.cachePath)return;let s=u.resolve(i.cachePath);await o.promises.mkdir(s,{recursive:!0});let g=u.join(s,`${bs(e)}.html`),a=u.join(s,`${bs(e)}.meta.json`),h=await o.promises.stat(e);await Bun.write(g,t);let d={sourcePath:e,mtime:h.mtime.getTime(),dependencies:Array.from(n),cacheVersion:i.cacheVersion,engine:nt(),optionsSignature:v(i),generatedAt:Date.now()};await Bun.write(a,JSON.stringify(d,null,2)),Nf.set(e,{output:t,mtime:h.mtime.getTime(),dependencies:n})}catch(s){console.warn(`Failed to cache template ${e}:`,s)}}var _=16;function bs(e){return new Bun.CryptoHasher("sha1").update(e).digest("hex").substring(0,_)}
|
|
3
3
|
export{Nf,Ah,Ph,Ih,Oh,Df,Mf,Nh,Dh,qo,Mh,lr,ur,bs};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R,t,c}from"./chunk-bq9xf8nq.js";import{Z}from"./chunk-
|
|
2
|
+
import{R,t,c}from"./chunk-bq9xf8nq.js";import{Z}from"./chunk-r0g70zrf.js";import{Xo}from"./chunk-zxfptbac.js";import C from"path";var S;async function W(){if(S!==void 0)return S;try{let e=await import("@stacksjs/ts-i18n");S=e.loadLocale??null}catch{S=null}return S}var P={defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},v={},L={},k={};function J(e,s=0){if(s<=0)return!1;return Date.now()-e.loadedAt>s}async function G(e,s){if({...P,...s.i18n}.cache&&v[e]){let r=v[e],o=s.i18n?.cacheMaxAge??0;if(!J(r,o))return r.translations}if(L[e]?.state==="loading")return L[e].promise;k[e]="loading";let n=T(e,s).then((r)=>(k[e]="loaded",delete L[e],r)).catch((r)=>{throw k[e]="error",L[e]={promise:n,state:"error",error:r instanceof Error?r:Error(String(r))},r});return L[e]={promise:n,state:"loading"},n}async function T(e,s){let i={...P,...s.i18n},n=C.isAbsolute(i.translationsDir)?i.translationsDir:C.resolve(s.root||process.cwd(),i.translationsDir);try{let r=await W(),o=r?await r(e,{translationsDir:n,defaultLocale:i.defaultLocale,sources:te(i.format)}):await Y(e,i,n);if(o===void 0){let u=e!==i.defaultLocale?await T(i.defaultLocale,s):{};if(i.cache)v[e]={translations:u,loadedAt:Date.now(),locale:e};return u}let l=o;if(i.cache)v[e]={translations:l,loadedAt:Date.now(),locale:e};return l}catch(r){if(s.debug)console.error(`Error loading translation file for locale "${e}":`,r);if(e!==i.defaultLocale)return T(i.defaultLocale,s);return{}}}async function Y(e,s,i){let n=C.join(i,`${e}${Q(s.format)}`);try{let r=await import(n);return r.default||r}catch(r){try{let o=await Bun.file(n).text();if(s.format==="yaml"||s.format==="yml")return X(o);if(s.format==="json")return JSON.parse(o);throw r}catch{return}}}function Q(e){switch(e){case"yaml":return".yaml";case"yml":return".yml";case"js":return".js";case"ts":return".ts";case"json":default:return".json"}}function X(e){let s={},i=e.split(`
|
|
3
3
|
`),n=[{obj:s,indent:-1}];for(let r of i){let o=r.replace(/#.*$/,"").trimEnd();if(!o.trim())continue;let l=o.search(/\S/);if(l===-1)continue;while(n.length>1&&n[n.length-1].indent>=l)n.pop();let u=n[n.length-1].obj,a=o.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(a){let[,,g,p]=a,f=g.trim(),m=p.trim();if(m==="")u[f]={},n.push({obj:u[f],indent:l});else u[f]=ee(m)}}return s}function ee(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let s=e.toLowerCase();if(s==="true"||s==="yes")return!0;if(s==="false"||s==="no")return!1;if(s==="null"||s==="~")return null;let i=Number(e);if(!Number.isNaN(i)&&e!=="")return i;return e}function te(e){switch(e){case"yaml":case"yml":return["yaml"];case"js":case"ts":return["ts"];case"json":default:return["json"]}}async function re(e,s){return G(e,s)}function ne(e,s){for(let i of e){let n=i.trim(),r=n.match(/^\{(\d+)\}\s*(.*)$/);if(r){let l=Number.parseInt(r[1],10);if(s===l)return r[2];continue}let o=n.match(/^\[(\d+),(\d+|\*)\]\s*(.*)$/);if(o){let l=Number.parseInt(o[1],10),u=o[2]==="*"?Number.POSITIVE_INFINITY:Number.parseInt(o[2],10);if(s>=l&&s<=u)return o[3];continue}}if(e.length===2)return s===1?e[0].trim():e[1].trim();if(s<e.length)return e[s].trim();return e[e.length-1].trim()}function ie(e,s={}){return j(e,s)}function j(e,s){let i="",n=0;while(n<e.length)if(e[n]==="{"){let r=se(e,n);if(r===-1){i+=e[n],n++;continue}let o=e.slice(n+1,r);i+=ae(o,s),n=r+1}else if(e[n]==="'"&&n+1<e.length)if(e[n+1]==="'")i+="'",n+=2;else if(e[n+1]==="{"||e[n+1]==="}")i+=e[n+1],n+=2;else i+=e[n],n++;else i+=e[n],n++;return i}function se(e,s){let i=0;for(let n=s;n<e.length;n++)if(e[n]==="{")i++;else if(e[n]==="}"){if(i--,i===0)return n}return-1}function ae(e,s){let i=oe(e);if(i.length===0)return`{${e}}`;let n=i[0].trim(),r=s[n];if(i.length===1)return r!==void 0?String(r):`{${n}}`;switch(i[1].trim().toLowerCase()){case"plural":return le(r,i.slice(2).join(","),s);case"select":return ue(r,i.slice(2).join(","));case"selectordinal":return de(r,i.slice(2).join(","));case"number":return pe(r,i[2]?.trim());case"date":return fe(r,i[2]?.trim());case"time":return me(r,i[2]?.trim());default:return r!==void 0?String(r):`{${e}}`}}function oe(e){let s=[],i="",n=0;for(let r=0;r<e.length;r++){let o=e[r];if(o==="{")n++,i+=o;else if(o==="}")n--,i+=o;else if(o===","&&n===0)s.push(i),i="";else i+=o}if(i)s.push(i);return s}function le(e,s,i){let n=Number(e)||0,r=I(s),o=`=${n}`;if(r[o])return E(r[o],n,i);let l=ce(n);if(r[l])return E(r[l],n,i);if(r.other)return E(r.other,n,i);return String(n)}function E(e,s,i){let n=e.replace(/#/g,String(s));return j(n,i)}function ce(e){let s=Math.abs(e),i=Math.floor(s),n=String(e).includes(".")?String(e).split(".")[1].length:0;if(i===1&&n===0)return"one";return"other"}function ue(e,s){let i=String(e||""),n=I(s);if(n[i])return n[i];return n.other||String(e)}function de(e,s){let i=Number(e)||0,n=I(s),r=ge(i);if(n[r])return n[r].replace(/#/g,String(i));if(n.other)return n.other.replace(/#/g,String(i));return String(i)}function ge(e){let s=Math.abs(e),i=s%10,n=s%100;if(i===1&&n!==11)return"one";if(i===2&&n!==12)return"two";if(i===3&&n!==13)return"few";return"other"}function I(e){let s={},i=/(\w+|=\d+)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,n=i.exec(e);while(n!==null)s[n[1]]=n[2],n=i.exec(e);return s}function pe(e,s){let i=Number(e);if(Number.isNaN(i))return String(e);switch(s){case"integer":return Math.floor(i).toLocaleString();case"percent":return`${(i*100).toFixed(0)}%`;case"currency":return i.toLocaleString(void 0,{style:"currency",currency:"USD"});default:return i.toLocaleString()}}function fe(e,s){let i=e instanceof Date?e:new Date(String(e));if(Number.isNaN(i.getTime()))return String(e);let n={};switch(s){case"short":n.dateStyle="short";break;case"medium":n.dateStyle="medium";break;case"long":n.dateStyle="long";break;case"full":n.dateStyle="full";break;default:n.dateStyle="medium"}return i.toLocaleDateString(void 0,n)}function me(e,s){let i=e instanceof Date?e:new Date(String(e));if(Number.isNaN(i.getTime()))return String(e);let n={};switch(s){case"short":n.timeStyle="short";break;case"medium":n.timeStyle="medium";break;case"long":n.timeStyle="long";break;case"full":n.timeStyle="full";break;default:n.timeStyle="short"}return i.toLocaleTimeString(void 0,n)}function be(e){return/\{[^}]+,\s*(?:plural|select|selectordinal|number|date|time)\s*,/.test(e)}function O(e,s,i=!0,n={}){let r=e.split("."),o=s;for(let u of r){if(o===void 0||o===null)break;o=o[u]}if(o===void 0||o===null)return i?e:"";let l=String(o);if(be(l))return ie(l,n);if(l.includes("|")&&"count"in n){let u=Number(n.count),a=l.split("|");l=ne(a,u)}for(let[u,a]of Object.entries(n)){let g=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");l=l.replace(new RegExp(`:${g}`,"g"),()=>String(a))}return l}var D=new Set(["ar","arc","ckb","dv","fa","he","khw","ks","nqo","prs","ps","sd","syr","ug","ur","uz-af","yi"]),he=new Set(["adlm","arab","aran","hebr","nkoo","rohg","syrc","thaa","yezi"]);function q(e){if(!e)return"ltr";let s=e.trim().toLowerCase().replace(/_/g,"-").split("-"),i=s[0];if(!i)return"ltr";let n=s[1]?.length===4?s[1]:void 0;if(n)return he.has(n)?"rtl":"ltr";if(s.length>1&&D.has(`${i}-${s[1]}`))return"rtl";return D.has(i)?"rtl":"ltr"}async function fc(e,s,i,n){let r=e,o=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)([\s\S]*?)@endtranslate/g,l={...P,...n.i18n},u=await re(l.locale,n);s.__translations=u,s.__locale=l.locale,s.__i18nConfig=l,r=await F(r,o,async(p,f,m,w,h)=>{try{let b={};if(m)try{let d=[()=>JSON.parse(m),()=>{let x=`{"data":${m}}`,A=JSON.parse(x);return typeof A.data==="object"?A.data:{}},()=>R(m,s)];for(let x of d)try{if(b=x(),Object.keys(b).length>0)break}catch{}}catch(d){if(n.debug)console.error("Error parsing parameters for @translate directive:",d)}let y=O(f,u,l.fallbackToKey,b);return y?Z(r,h,y,!1,p.length):w.trim()}catch(b){if(n.debug)console.error("Error processing @translate directive:",b);return c("Translate",`Error in @translate('${f}'): ${b instanceof Error?b.message:String(b)}`,t.EVALUATION_ERROR)}});let a=/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]+\})\s*)?\)/g;if(n.debug){console.warn(`Processing translations in template. Sections: ${r.includes("<h2>Translation with Parameters</h2>")?"Parameters section found":"Parameters section missing"}`);let p=[...r.matchAll(a)];console.warn(`Found ${p.length} @translate matches`),p.forEach((f,m)=>console.warn(`Match ${m}: ${f[0]}, Key: ${f[1]}, Params: ${f[2]||"none"}`))}return r=await F(r,/@translate\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\})\s*)?\)/g,async(p,f,m,w)=>{try{let h={};if(m)try{let b=[()=>JSON.parse(m),()=>{let y=`{"data":${m}}`,d=JSON.parse(y);return typeof d.data==="object"?d.data:{}},()=>R(m,s)];for(let y of b)try{if(h=y(),Object.keys(h).length>0)break}catch{}}catch(b){if(n.debug)console.error("Error parsing parameters for @translate directive:",b)}return Z(r,w,O(f,u,l.fallbackToKey,h),!1,p.length)}catch(h){if(n.debug)console.error("Error processing @translate directive:",h);return c("Translate",`Error in @translate('${f}'): ${h instanceof Error?h.message:String(h)}`,t.EVALUATION_ERROR)}}),r}async function F(e,s,i){let n=[];return e.replace(s,(o,...l)=>{let u=i(o,...l).then((a)=>({match:o,replacement:a}));return n.push(u),o}),(await Promise.all(n)).reduce((o,{match:l,replacement:u})=>o.replace(l,()=>u),e)}function _(e,s){if(!e||q(e)!=="rtl")return!1;return!s||s.trim().toLowerCase()!=="rtl"}function V(e){if(!e)return!1;return e.trim().split(/\s+/)[0]?.toLowerCase()==="presentation"||e.trim().split(/\s+/)[0]?.toLowerCase()==="none"}function U(e,s){let i=new RegExp(`\\b${s}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`,"i").exec(e);if(!i)return null;return i[2]??i[3]??i[4]??null}function gc(e,s,i,n){let r=e;r=r.replace(/@a11y\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(l,u,a)=>{let p={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[u]||"Make this element accessible";return`<!-- a11y-hint: ${a||p} -->`});let o=/@screenReader\(([^@]*)\)@endScreenReader/g;return r=r.replace(o,(l,u)=>`<span class="sr-only">${u.trim()}</span>`),r=r.replace(/@ariaDescribe\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(l,u,a)=>`<span id="${`desc-${u}`}" class="sr-only">${a}</span>`),r}function ye(){return typeof globalThis.document<"u"&&typeof globalThis.document.createElement==="function"}function xe(e){let s=new Map,i=e.replace(/<(\/?)([A-Z][\w:.-]*)(?=[\s/>])/g,(r,o,l)=>{let u=s.get(l);if(!u)u=`stx-a11y-component-${s.size}`,s.set(l,u);return`<${o}${u}`}),n=new Map([...s.entries()].map(([r,o])=>[o,r]));return{protectedSource:i,restore:(r)=>r.replace(/<(\/?)(stx-a11y-component-\d+)(?=[\s/>])/g,(o,l,u)=>{let a=n.get(u);return a?`<${l}${a}`:o})}}function we(e,s){let i=[],n=/<img\s+([^>]*)>/gi,r;r=n.exec(e);while(r!==null){let d=r[1];if(!/\balt\s*=/i.test(d))i.push({type:"missing-alt",element:r[0].substring(0,100),message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"});r=n.exec(e)}let o=/<button([^>]*)>\s*<\/button>/gi;r=o.exec(e);while(r!==null){let d=r[1];if(!/\baria-label\s*=/i.test(d)&&!/\btitle\s*=/i.test(d))i.push({type:"missing-accessible-name",element:r[0].substring(0,100),message:"Empty button missing accessible name",impact:"critical",help:"Add text content, aria-label, or title",helpUrl:"https://web.dev/learn/accessibility/aria-html/"});r=o.exec(e)}let l=/<a\s+([^>]*)>\s*<\/a>/gi;r=l.exec(e);while(r!==null){let d=r[1];if(!/\baria-label\s*=/i.test(d)&&!/\btitle\s*=/i.test(d))i.push({type:"link-missing-text",element:r[0].substring(0,100),message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"});r=l.exec(e)}let u=/<(input|select|textarea)\s+([^>]*)>/gi;r=u.exec(e);while(r!==null){let d=r[2];if(/\btype\s*=\s*["']hidden["']/i.test(d)){r=u.exec(e);continue}let x=/\baria-label\s*=/i.test(d)||/\baria-labelledby\s*=/i.test(d),A=d.match(/\bid\s*=\s*["']([^"']+)["']/i);if(!x){let B=A&&new RegExp(`<label[^>]*\\bfor\\s*=\\s*["']${A[1]}["']`,"i").test(e),M=r.index,N=e.substring(0,M),Se=e.substring(M),H=(N.match(/<label\b/gi)||[]).length,z=(N.match(/<\/label>/gi)||[]).length,K=H>z;if(!B&&!K)i.push({type:"input-missing-label",element:r[0].substring(0,100),message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})}r=u.exec(e)}let a=/<h([1-6])[^>]*>/gi,g=[];r=a.exec(e);while(r!==null)g.push(Number.parseInt(r[1],10)),r=a.exec(e);let p=0;for(let d of g){if(p>0&&d>p+1)i.push({type:"heading-skip",element:`<h${d}>`,message:`Heading level skipped from h${p} to h${d}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});p=d}if(/<html\b/i.test(e)&&!/<html[^>]*\slang\s*=/i.test(e))i.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"});let f=e.match(/<html\b([^>]*)>/i);if(f&&_(U(f[1],"lang"),U(f[1],"dir")))i.push({type:"missing-dir",element:f[0].substring(0,100),message:'Document language is right-to-left but dir="rtl" is not set',impact:"serious",help:'Add dir="rtl" to the html element so the layout mirrors the text',helpUrl:"https://www.w3.org/International/questions/qa-html-dir"});let m=/<table([^>]*)>([\s\S]*?)<\/table>/gi;r=m.exec(e);while(r!==null){let d=r[2];if(!V(U(r[1],"role"))&&!/<th\b/i.test(d))i.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});r=m.exec(e)}let w=/<(video|audio)[^>]*\sautoplay\s[^>]*>/gi;r=w.exec(e);while(r!==null){if(!/\bmuted\b/i.test(r[0]))i.push({type:"autoplay-audio",element:`<${r[1]}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"});r=w.exec(e)}let h=/\btabindex\s*=\s*["']([1-9]\d*)["']/gi;r=h.exec(e);while(r!==null)i.push({type:"positive-tabindex",element:`tabindex="${r[1]}"`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"}),r=h.exec(e);let b=/<iframe\s+([^>]*)>/gi;r=b.exec(e);while(r!==null){let d=r[1];if(!/\btitle\s*=/i.test(d)&&!/\baria-label\s*=/i.test(d))i.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"});r=b.exec(e)}let y=/<([a-z]+)\s+([^>]*role\s*=\s*["']button["'][^>]*)>/gi;r=y.exec(e);while(r!==null){let d=r[1].toLowerCase(),x=r[2];if(d!=="button"&&!/\btabindex\s*=/i.test(x))i.push({type:"button-not-focusable",element:r[0].substring(0,100),message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"});r=y.exec(e)}return i}async function Ae(e,s){let{protectedSource:i}=xe(e);if(!ye())return we(i,s);let n=[];try{let r=globalThis.document.createElement("div");r.innerHTML=i,r.querySelectorAll("img").forEach((a)=>{if(!a.hasAttribute("alt"))n.push({type:"missing-alt",element:`<${a.outerHTML}>`,message:"Image missing alt attribute",impact:"serious",help:"Add alt text to images for screen readers",helpUrl:"https://web.dev/learn/accessibility/images/"})}),r.querySelectorAll('button, a, [role="button"]').forEach((a)=>{if(!(a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby")||a.textContent&&a.textContent.trim().length>0))n.push({type:"missing-accessible-name",element:`<${a.outerHTML}>`,message:"Interactive element missing accessible name",impact:"critical",help:"Add text content, aria-label, or aria-labelledby",helpUrl:"https://web.dev/learn/accessibility/aria-html/"})}),r.querySelectorAll("input, select, textarea").forEach((a)=>{let g=a.getAttribute("id"),p=g&&r.querySelector(`label[for="${g}"]`),f=a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby"),m=a.closest("label")!==null;if(!p&&!f&&!m)n.push({type:"input-missing-label",element:`<${a.outerHTML}>`,message:"Form input missing associated label",impact:"serious",help:"Associate a label with the input or use aria-label",helpUrl:"https://web.dev/learn/accessibility/forms/"})});let o=Array.from(r.querySelectorAll("h1, h2, h3, h4, h5, h6")),l=0;for(let a of o){let g=Number.parseInt(a.tagName.charAt(1));if(l>0&&g>l+1)n.push({type:"heading-skip",element:`<${a.outerHTML}>`,message:`Heading level skipped from h${l} to h${g}`,impact:"moderate",help:"Maintain proper heading hierarchy without skipping levels",helpUrl:"https://web.dev/learn/accessibility/structure/"});l=g}let u=r.querySelector("html");if(i.includes("<html")&&u&&!u.hasAttribute("lang"))n.push({type:"missing-lang",element:"<html>",message:"Document language not specified",impact:"serious",help:"Add lang attribute to the html element",helpUrl:"https://web.dev/learn/accessibility/more-html/#language"});if(u&&_(u.getAttribute("lang"),u.getAttribute("dir")))n.push({type:"missing-dir",element:"<html>",message:'Document language is right-to-left but dir="rtl" is not set',impact:"serious",help:'Add dir="rtl" to the html element so the layout mirrors the text',helpUrl:"https://www.w3.org/International/questions/qa-html-dir"});if(r.querySelectorAll("a").forEach((a)=>{let g=a.textContent&&a.textContent.trim().length>0,p=a.hasAttribute("aria-label")||a.hasAttribute("aria-labelledby"),f=a.hasAttribute("title"),m=a.querySelector("img[alt]");if(!g&&!p&&!f&&!m)n.push({type:"link-missing-text",element:`<${a.outerHTML}>`,message:"Link has no accessible text",impact:"serious",help:"Add text content, aria-label, or title to links",helpUrl:"https://web.dev/learn/accessibility/more-html/#links"})}),i.includes("<nav")||i.includes("<header")){if(!r.querySelector('a[href="#main"], a[href="#content"], .skip-link, [class*="skip"]')&&r.querySelectorAll("a").length>5)n.push({type:"missing-skip-link",element:"<nav>",message:"Consider adding a skip navigation link",impact:"minor",help:"Add a skip link to allow keyboard users to bypass navigation",helpUrl:"https://web.dev/learn/accessibility/focus/#skip-links"})}if(r.querySelectorAll("table").forEach((a)=>{if(V(a.getAttribute("role")))return;let g=a.querySelector("caption");if(!a.querySelector("th"))n.push({type:"table-missing-headers",element:"<table>",message:"Table missing header cells (th)",impact:"serious",help:"Use th elements for table headers",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"});if(!g&&!a.hasAttribute("aria-label")&&!a.hasAttribute("aria-labelledby"))n.push({type:"table-missing-caption",element:"<table>",message:"Table missing caption or accessible name",impact:"minor",help:"Add a caption element or aria-label to describe the table",helpUrl:"https://web.dev/learn/accessibility/more-html/#tables"})}),r.querySelectorAll('[style*="color"]').forEach((a)=>{let g=a.getAttribute("style")||"";if(g.includes("color:")&&!g.includes("background"))n.push({type:"potential-contrast-issue",element:`<${a.tagName.toLowerCase()}>`,message:"Element has inline color style - verify contrast ratio",impact:"minor",help:"Ensure text has sufficient contrast ratio (4.5:1 for normal text)",helpUrl:"https://web.dev/learn/accessibility/color-contrast/"})}),r.querySelectorAll("video[autoplay], audio[autoplay]").forEach((a)=>{if(!a.hasAttribute("muted"))n.push({type:"autoplay-audio",element:`<${a.tagName.toLowerCase()}>`,message:"Auto-playing media may disrupt users",impact:"moderate",help:"Add muted attribute or provide controls to stop playback",helpUrl:"https://web.dev/learn/accessibility/more-html/#multimedia"})}),r.querySelectorAll("[tabindex]").forEach((a)=>{if(Number.parseInt(a.getAttribute("tabindex")||"0")>0)n.push({type:"positive-tabindex",element:`<${a.tagName.toLowerCase()}>`,message:"Positive tabindex disrupts natural tab order",impact:"moderate",help:'Use tabindex="0" or "-1" instead of positive values',helpUrl:"https://web.dev/learn/accessibility/focus/#tab-index"})}),r.querySelectorAll('[role="button"]').forEach((a)=>{if(!a.hasAttribute("tabindex"))n.push({type:"button-not-focusable",element:`<${a.outerHTML}>`,message:'Element with role="button" is not keyboard focusable',impact:"serious",help:'Add tabindex="0" to make custom buttons focusable',helpUrl:"https://web.dev/learn/accessibility/focus/"})}),i.includes("<body")&&!r.querySelector('main, [role="main"]'))n.push({type:"missing-main-landmark",element:"<body>",message:"Document missing main landmark region",impact:"moderate",help:"Add a main element to identify the primary content",helpUrl:"https://web.dev/learn/accessibility/structure/#landmarks"});r.querySelectorAll("iframe").forEach((a)=>{if(!a.hasAttribute("title")&&!a.hasAttribute("aria-label"))n.push({type:"iframe-missing-title",element:"<iframe>",message:"Iframe missing title attribute",impact:"serious",help:"Add a title attribute to describe the iframe content",helpUrl:"https://web.dev/learn/accessibility/more-html/#frames"})})}catch(r){console.error(`Error checking accessibility in ${s}:`,r)}return n}async function mc(e,s={}){let i={},{recursive:n=!0,ignorePaths:r=[]}=s,o=Array.isArray(e)?e:[e],l=await Xo(o,{recursive:n,ignorePaths:r}),u=[];for(let a of l)try{let g=await Bun.file(a).text();if(a.endsWith("good-a11y.stx"))continue;let p=await Ae(g,a);if(u.push(a),p.length>0)i[a]=p}catch(g){console.error(`Error scanning ${a}:`,g)}return{results:i,scannedFiles:u}}var hc={name:"a11y",handler:(e,s,i,n)=>{if(!s.length)return e;let r=s[0].replace(/['"]/g,""),o=s.length>1?s[1].replace(/['"]/g,""):"",u={"aria-label":"Ensure interactive elements have accessible labels","alt-text":"Provide alternative text for images",focus:"Ensure the element can receive keyboard focus",landmark:"Use appropriate landmark roles","heading-order":"Maintain proper heading hierarchy","color-contrast":"Ensure sufficient color contrast","keyboard-nav":"Make sure element is keyboard navigable","screen-reader":"Optimize for screen reader users"}[r]||"Make this element accessible";return`<!-- a11y-hint: ${o||u} -->${e}`},hasEndTag:!1},yc={name:"screenReader",handler:(e)=>`<span class="sr-only">${e}</span>`,hasEndTag:!0};
|
|
4
4
|
export{fc,gc,mc,hc,yc};
|