@stacksjs/stx 0.2.620 → 0.2.622
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-0r2g00m7.js +2 -0
- package/dist/{chunk-pw2m64jc.js → chunk-18104nfg.js} +1 -1
- package/dist/{chunk-w5qgb5jx.js → chunk-29cbmfrc.js} +2 -2
- package/dist/{chunk-1ach06sw.js → chunk-39qcn4gt.js} +1 -1
- package/dist/{chunk-5bvc0eew.js → chunk-3dd57j7e.js} +1 -1
- package/dist/{chunk-wkadjmmh.js → chunk-3h2rpaps.js} +1 -1
- package/dist/{chunk-fpzbtrp6.js → chunk-3rmby39r.js} +1 -1
- package/dist/{chunk-czv3a49e.js → chunk-3tp481j5.js} +2 -2
- package/dist/{chunk-80ath5b7.js → chunk-40fepd2t.js} +1 -1
- package/dist/{chunk-qst8ztxa.js → chunk-5wa3ydkf.js} +1 -1
- package/dist/{chunk-3wbtbg22.js → chunk-5zzrth32.js} +3 -3
- package/dist/{chunk-s01qe842.js → chunk-6jjrvb9v.js} +1 -1
- package/dist/{chunk-vtpsns2g.js → chunk-81h6xyna.js} +1 -1
- package/dist/{chunk-ttc1fmn4.js → chunk-8xns82s5.js} +1 -1
- package/dist/{chunk-91wzaepm.js → chunk-9eejvpqc.js} +2 -2
- package/dist/{chunk-k6v0kbnr.js → chunk-9pz3jh7w.js} +1 -1
- package/dist/{chunk-vgt56jd0.js → chunk-a39kvc2p.js} +1 -1
- package/dist/{chunk-v66yd92a.js → chunk-e030grrq.js} +195 -195
- package/dist/{chunk-m6v0zebf.js → chunk-erk7afjv.js} +1 -1
- package/dist/{chunk-17fwgkyp.js → chunk-f53x5d7h.js} +1 -1
- package/dist/{chunk-erp0v4mb.js → chunk-fmdezmt4.js} +1 -1
- package/dist/{chunk-kjck941v.js → chunk-fqwyfx6c.js} +1 -1
- package/dist/{chunk-v9qh2bak.js → chunk-fvk33v69.js} +1 -1
- package/dist/{chunk-bqy2wpqx.js → chunk-g6mv9vkp.js} +1 -1
- package/dist/{chunk-wg4gydcs.js → chunk-g8f1dqx1.js} +1 -1
- package/dist/{chunk-fyp6zk1y.js → chunk-hmpzdq4p.js} +1 -1
- package/dist/{chunk-hnagpvee.js → chunk-j8vd52sg.js} +1 -1
- package/dist/chunk-jh2kve7q.js +2 -0
- package/dist/{chunk-m1nb0z16.js → chunk-jwqz8w58.js} +1 -1
- package/dist/{chunk-4qdx2nzq.js → chunk-kaz5smvw.js} +1 -1
- package/dist/{chunk-xfw2cwhz.js → chunk-kep8q407.js} +1 -1
- package/dist/{chunk-w1n3cvay.js → chunk-m0zmexz1.js} +1 -1
- package/dist/{chunk-fz5mzzyj.js → chunk-m64w624a.js} +1 -1
- package/dist/{chunk-j9adyb0v.js → chunk-pwsg9w5g.js} +1 -1
- package/dist/{chunk-a2mmj1e8.js → chunk-qbh3jk5z.js} +1 -1
- package/dist/{chunk-z024wwh6.js → chunk-qk4zkvzh.js} +1 -1
- package/dist/{chunk-4z4c7smx.js → chunk-rg4zqdbj.js} +1 -1
- package/dist/{chunk-6qbkwqc5.js → chunk-rj8fsjx9.js} +1 -1
- package/dist/{chunk-230ssxg1.js → chunk-rmc8cg2n.js} +1 -1
- package/dist/{chunk-mn3kjerc.js → chunk-tc62pvzg.js} +1 -1
- package/dist/{chunk-mstvaxy1.js → chunk-tftnx4vj.js} +1 -1
- package/dist/{chunk-pdw9paq5.js → chunk-vddfv082.js} +1 -1
- package/dist/{chunk-ka7g44tj.js → chunk-w28sn5g5.js} +1 -1
- package/dist/{chunk-gq9m5tmc.js → chunk-wk95x5ym.js} +5 -5
- package/dist/chunk-x5cscz50.js +2 -0
- package/dist/{chunk-nw3kevzk.js → chunk-x7v3m9nk.js} +1 -1
- package/dist/{chunk-ffaw5he6.js → chunk-y3n2cgev.js} +1 -1
- package/dist/{chunk-z4ebap7m.js → chunk-zvg2h3wd.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/dist/utils.js +1 -1
- package/package.json +5 -5
- package/dist/chunk-0ax8sqvn.js +0 -2
- package/dist/chunk-dvhhmk8n.js +0 -2
- package/dist/chunk-e59j52hj.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,b,vn,wn,e,Lt,kn,f,Xe,jt,Je,Ye,se,L,me,Z,u,Te,Oi,Ls,n,r,oe,mr,o,P,he}from"./chunk-
|
|
2
|
+
import{X,b,vn,wn,e,Lt,kn,f,Xe,jt,Je,Ye,se,L,me,Z,u,Te,Oi,Ls,n,r,oe,mr,o,P,he}from"./chunk-e030grrq.js";import{U,Dn,ie,O,Vt}from"./chunk-1gtrs8va.js";import{ut,Fn,Rr,Ar,Pr,dt,pt,ft,gt,mt,ht,Ie}from"./chunk-sxpnpvt5.js";import{Be,$o,ae,T,Ro,Ur,Xn,xe,Ao,ce}from"./chunk-9eejvpqc.js";import{qt}from"./chunk-pwsg9w5g.js";import{pe}from"./chunk-5rtatjwq.js";import{a}from"./chunk-q4a2j4qr.js";import{D}from"./chunk-szjgbjw1.js";async function Gn(t){try{let s=await Bun.file(t).text(),i=Jn(s),d=Yn(s,t),c=Qn(s,i),l=Zn(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Jn(t){let s=t.split(`
|
|
3
3
|
`),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
|
|
4
4
|
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+p+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,R=0;for(let C of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,S=Math.max(S,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function Yn(t,s){let i=[],d=Jt(t,"if","endif");if(d>0)i.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Jt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let y=p.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
|
|
5
5
|
`).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Qn(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.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)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Zn(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:d,recommendations:c}}function Jt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function mo(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await Gn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Ee from"path";function rn(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 on=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ht(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(d){let c=await rr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function dr(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=m.exec(l)){let h=p[1];if(on.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}return i}function pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
|
|
@@ -876,7 +876,7 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Ve(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function lt(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await mr(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await vn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ie(()=>Bun.file(m).text(),"",(x)=>{throw new Dn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new Dn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=X.time("script-extraction",()=>{let x=h,C=se(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",_=[];for(let E of k){let I=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=E.match(/<script\b([^>]*)>/i),K=F?F[1]:"";if(/\bserver\b/i.test(K))B=I;else _.push(E)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:_}}),S={__filename:m,__dirname:Pt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ie(()=>u(g,S,m),void 0,(x)=>{let C=new U(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(O.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await X.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-
|
|
879
|
+
`}function Ve(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function lt(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await mr(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await vn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ie(()=>Bun.file(m).text(),"",(x)=>{throw new Dn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new Dn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=X.time("script-extraction",()=>{let x=h,C=se(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",_=[];for(let E of k){let I=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=E.match(/<script\b([^>]*)>/i),K=F?F[1]:"";if(/\bserver\b/i.test(K))B=I;else _.push(E)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:_}}),S={__filename:m,__dirname:Pt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ie(()=>u(g,S,m),void 0,(x)=>{let C=new U(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(O.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await X.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-rmc8cg2n.js"),C=x(w.join(`
|
|
880
880
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
|
|
881
881
|
`+v.slice(k);else v+=`
|
|
882
882
|
${C}`}if(v=await Z(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await wn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new U(`Plugin processing failed: ${String(p)}`,m);if(O.log(h,{filePath:m,buildConfig:t.config}),Vt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
|
|
@@ -939,7 +939,7 @@ ${C}`}if(v=await Z(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await wn
|
|
|
939
939
|
<h1>Something went wrong</h1>
|
|
940
940
|
<p>An internal error occurred. Please try again later.</p>
|
|
941
941
|
</body>
|
|
942
|
-
</html>`,loader:"html"}}})}};async function Vn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=we.resolve(t);if(!He.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");He.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let I={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ge)=>({path:ge.path,external:!0}))}},F=await Bun.build({entrypoints:[p],outdir:h,plugins:[I,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let K=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await y())return!1;let S=we.dirname(p);await Lt(S);let R=i;try{if(R=await Ge(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||R+1;l=Et({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,C;try{let{loadStxConfig:I}=await import("./chunk-
|
|
942
|
+
</html>`,loader:"html"}}})}};async function Vn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=we.resolve(t);if(!He.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");He.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let I={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ge)=>({path:ge.path,external:!0}))}},F=await Bun.build({entrypoints:[p],outdir:h,plugins:[I,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let K=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await y())return!1;let S=we.dirname(p);await Lt(S);let R=i;try{if(R=await Ge(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||R+1;l=Et({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,C;try{let{loadStxConfig:I}=await import("./chunk-x5cscz50.js"),F=await I();if(C=s.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Q}=await import("./chunk-08jyyegp.js"),$e=F.broadcasting;await K($e);let ge=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ge}/ws${e.reset}`);let Oe=we.join(process.cwd(),"channels.ts");if(He.existsSync(Oe))try{let ne=await Q(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(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-g8f1dqx1.js"),_=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Gr({port:R,async fetch(I){return qt(I,await(async()=>{let F=new URL(I.url);if([h,we.dirname(p),we.join(process.cwd(),"public")].some((ne)=>B(we.join(ne,F.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(I);if(ne.status!==404)return ne}catch{}if(v[F.pathname])try{return await v[F.pathname](I)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await _(I);if(K)return K;if(F.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Ve(W,m);if(s.native)if(W.includes("<head>"))W=W.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(W.includes("<html"))W=W.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 W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.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(W.includes("<html"))W=W.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 W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Q=we.join(h,F.pathname);if(He.existsSync(Q)&&He.statSync(Q).isFile()){let ne=Bun.file(Q),W=we.extname(Q).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let $e=we.dirname(p),ge=we.join($e,F.pathname);if(He.existsSync(ge)&&He.statSync(ge).isFile()){let ne=Bun.file(ge),W=we.extname(ge).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let Oe=we.join(process.cwd(),"public",F.pathname);if(He.existsSync(Oe)&&He.statSync(Oe).isFile()){let ne=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),H="application/octet-stream";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
|
|
943
943
|
${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
945
945
|
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
@@ -1426,12 +1426,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1426
1426
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1427
1427
|
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
1428
1428
|
${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Pe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Pe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",B=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${B}`)}),console.log(`
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),Te.clear(),oe(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Yr}=globalThis.Bun;import be from"fs";import te from"path";async function pn(t){try{return jt(await Bun.file(t).text())}catch{return}}function Nt(t){let s=Bun.file(t),i=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function Wn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-0ax8sqvn.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-wg4gydcs.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!be.existsSync(C)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],_=[];for(let{dir:A,prefix:z}of B)if(be.existsSync(A)){let N=L(te.dirname(A),{pagesDir:te.basename(A)});for(let V of N){let ve=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:ve},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,E=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await Ro(p,s.stxOptions?.shell),I){if(E=await Ur(I,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}dt(),await ft(p);let F=pt();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let K={},Q=null;try{let{loadStxConfig:A}=await import("./chunk-0ax8sqvn.js"),z=await A(p);if(z?.apiRouter)Q=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){K=z.apiRoutes;let N=Object.keys(K).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-08jyyegp.js"),ve=z.broadcasting;await N(ve);let ze=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(be.existsSync(qe))try{let ee=await V(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let $e=a(p,"output");be.mkdirSync($e,{recursive:!0});let ge=new Map,Oe=new Set,ne=async(A)=>{let z=Ar(C,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:ve,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-0ax8sqvn.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:q,templateCache:G}=await import("./chunk-ttc1fmn4.js"),Se=await ze(p),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(p,re)},M={...ve,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Ke(M.partialsDir),M.componentsDir=Ke(M.componentsDir),M.layoutsDir=Ke(M.layoutsDir),M.storesDir=Ke(M.storesDir||"stores"),M.cachePath=Ke(M.cachePath)??a(p,"cache");let ye=!z&&!s.profile,le=M.cache!==!1;if(le&&ye){let re=G.get(A.filePath);if(re)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=re.mtime){let je=!0;for(let Re of re.dependencies){if(!be.existsSync(Re)){je=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>re.mtime){je=!1;break}}if(je){let Re=re.output;if(E)Re=xe(Re,{preserveHead:!0});let ct=W.get(A.filePath);return{route:A,content:Re,status:ct?.status??await pn(A.filePath),headers:ct?.headers}}}}catch{}let _e=await ee(A.filePath,M);if(_e){let Le=_e;if(E)Le=xe(Le,{preserveHead:!0});let je=W.get(A.filePath);return{route:A,content:Le,status:je?.status??await pn(A.filePath),headers:je?.headers}}}let fe=le?await q(A.filePath):await Bun.file(A.filePath).text(),Ce=jt(fe),{classifyAllScripts:J}=await import("./chunk-0ax8sqvn.js"),Me=J(fe),Ne=Me.server.map((re)=>re.content),de=fe;for(let re of Me.server)de=de.replace(re.fullTag,"");let ue={__filename:A.filePath,__dirname:te.dirname(A.filePath),__stx_options:M,params:z??{},__stx_runtime_head:{}};for(let re of Ne)try{await V(re,ue,A.filePath)}catch(_e){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,_e?.message||_e)}let We=new Set,Ae;if(s.profile){let re=performance.now();Ae=await N(de,ue,A.filePath,M,We);let _e=performance.now()-re,Le=te.relative(p,A.filePath)||A.filePath;console.log(`[stx:profile] ${Le} \u2192 ${_e.toFixed(2)}ms`)}else Ae=await N(de,ue,A.filePath,M,We);if(!E)Ae=await qe(Ae,{router:M.router});{let{interpolateScriptExpressions:re}=await import("./chunk-230ssxg1.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(_e,Le,je)=>{if(!/function\s+__stx_setup_/.test(je))return _e;return`<script${Le}>${re(je,ue)}</script>`})}if(E)Ae=xe(Ae,{preserveHead:!0});if(le&&ye)await Y(A.filePath,Ae,We,M);let{extractStreamBoundaries:qn}=await import("./chunk-z024wwh6.js"),nt=qn(ue),at=ue.__streamTemplates;if(at&&typeof at==="object"&&Object.keys(at).length>0){let re=ue.streamBoundaries||{},_e={...M,autoShell:!1},Le=Object.keys(at).map((Re)=>({id:Re,render:async()=>{let ct=typeof re[Re]==="function"?await re[Re]():void 0;return N(at[Re],{...ue,$boundary:ct},A.filePath,_e,new Set)}})),je=new Set(Le.map((Re)=>Re.id));nt=[...(nt||[]).filter((Re)=>!je.has(Re.id)),...Le]}if(nt&&nt.length>0)Oe.add(A.pattern);else nt=void 0;let Kt=Je(ue),Xt=Ye(ue);if(ye)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Ae,status:Kt??Ce,headers:Xt,boundaries:nt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Fe=8,Ue=async()=>{ge.clear(),j.clear();for(let A=0;A<k.length;A+=Fe){let z=k.slice(A,A+Fe),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)ge.set(V.route.pattern,V)}for(let A=0;A<_.length;A+=Fe){let z=_.slice(A,A+Fe),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return ge.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Lt(p);let et=i;try{if(et=await Ge(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||et+1;l=Et({wsPort:A,verbose:!1}),m=l.start(A)}let At=(A,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Yr({port:et,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",V=te.join(p,N,z.pathname),ve=te.join(p,z.pathname),ze=te.join($e,z.pathname);if([V,ve,ze].some((M)=>w(M,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Y]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(ve).catch(()=>null),be.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(V,p,S))return Nt(V);if(ee?.isFile()&&!w(ve,p,S))return Nt(ve);if(Y?.isFile()&&!w(ze,p,S))return Nt(ze);if(z.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(z.pathname.slice(16));if(M)try{let ye=`<${M} />`,le={...buildConfig,autoShell:!1},fe=await processDirectives(ye,{},te.join(p,"components",`${M}.stx`),le,new Set);return new Response(fe,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-wfettff6.js"),ye=await M(A,{publicDir:te.join(p,N),cacheDir:a(p,"cache","img")});if(ye)return ye}if(Q)try{let M=await Q.handleRequest(A);if(M.status!==404)return M}catch{}if(K[z.pathname])try{return await K[z.pathname](A)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await R(A);if(q)return q;let G=Fn(z.pathname,k);if(G){let M=ge.get(G.route.pattern),ye=Oe.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||ye){let le=await H(G.route,G.params);if(le)M=le}if(M){let le=M.status??200,fe=M.headers??{},Ce=(G.route.filePath?Xe(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let Ne=await ne(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=gt(z.pathname,G.params,Ce,z.search),Ne=mt(Me,null,A,{isServer:!0}),de=await ht(Ce.middleware,Ne);if(de.redirect){let ue=de.redirect.path,We=de.redirect.options.redirectCode||302,Ae=new Headers(de.responseHeaders);return Ae.set("Location",ue),new Response(null,{status:We,headers:Ae})}if(de.abort){let{statusCode:ue,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ue}</title></head><body><h1>Error ${ue}</h1><p>${We}</p></body></html>`,{status:ue,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let ue=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${ue}</head>`)}}let J=M.content;if(E&&Ao(A)){let Me=Ie(J),Ne=me(J),de=J.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ue=de?$o(de[1].trim()):"";if(Object.keys(G.params).length>0)J=At(J,G.params);J=await f(J,p);let We=g?.router?.container||"main";return J=ce(J,We),new Response(J,{status:le,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ne?"true":"false",...ue&&{"X-STX-Title":encodeURIComponent(ue)},[Oi]:Ls(),...T(),"Cache-Control":Be}})}if(E)J=Xn(E,J);if(Object.keys(G.params).length>0)J=At(J,G.params);if(J=await f(J,p),c)J=Ve(J,m);if(s.native)if(J.includes("<head>"))J=J.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 J="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+J;if(s.titlebarHidden)if(J.includes("<head>"))J=J.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 J=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${J}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:Ne}=await import("./chunk-z024wwh6.js");return Ne(Me(J,M.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(J,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...fe}})}}if(_.length>0){let M=_.map((le)=>le.route),ye=Fn(z.pathname,M);if(ye){let le=j.get(ye.route.pattern);if(le){let fe=le.content;if(E)fe=Xn(E,fe);if(Object.keys(ye.params).length>0)fe=At(fe,ye.params);if(fe=await f(fe,p),c)fe=Ve(fe,m);return new Response(fe,{status:le.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:le}of B)if(le!=="/"&&z.pathname.startsWith(le)){let fe=j.get(le)||j.get(le+"/");if(fe){let Ce=fe.content;if(E)Ce=Xn(E,Ce);if(Ce=await f(Ce,p),c)Ce=Ve(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(ut(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=ge.get("/");if(Se){let M=Se.content;if(M=await f(M,p),c)M=Ve(M,m);if(s.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ke=await ne(404);if(Ke){let M=Ke;if(M=await f(M,p),c)M=Ve(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await ne(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1429
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),Te.clear(),oe(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Yr}=globalThis.Bun;import be from"fs";import te from"path";async function pn(t){try{return jt(await Bun.file(t).text())}catch{return}}function Nt(t){let s=Bun.file(t),i=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function Wn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-x5cscz50.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-g8f1dqx1.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!be.existsSync(C)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],_=[];for(let{dir:A,prefix:z}of B)if(be.existsSync(A)){let N=L(te.dirname(A),{pagesDir:te.basename(A)});for(let V of N){let ve=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:ve},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,E=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await Ro(p,s.stxOptions?.shell),I){if(E=await Ur(I,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}dt(),await ft(p);let F=pt();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let K={},Q=null;try{let{loadStxConfig:A}=await import("./chunk-x5cscz50.js"),z=await A(p);if(z?.apiRouter)Q=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){K=z.apiRoutes;let N=Object.keys(K).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-08jyyegp.js"),ve=z.broadcasting;await N(ve);let ze=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(be.existsSync(qe))try{let ee=await V(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let $e=a(p,"output");be.mkdirSync($e,{recursive:!0});let ge=new Map,Oe=new Set,ne=async(A)=>{let z=Ar(C,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:ve,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-x5cscz50.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:q,templateCache:G}=await import("./chunk-8xns82s5.js"),Se=await ze(p),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(p,re)},M={...ve,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Ke(M.partialsDir),M.componentsDir=Ke(M.componentsDir),M.layoutsDir=Ke(M.layoutsDir),M.storesDir=Ke(M.storesDir||"stores"),M.cachePath=Ke(M.cachePath)??a(p,"cache");let ye=!z&&!s.profile,le=M.cache!==!1;if(le&&ye){let re=G.get(A.filePath);if(re)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=re.mtime){let je=!0;for(let Re of re.dependencies){if(!be.existsSync(Re)){je=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>re.mtime){je=!1;break}}if(je){let Re=re.output;if(E)Re=xe(Re,{preserveHead:!0});let ct=W.get(A.filePath);return{route:A,content:Re,status:ct?.status??await pn(A.filePath),headers:ct?.headers}}}}catch{}let _e=await ee(A.filePath,M);if(_e){let Le=_e;if(E)Le=xe(Le,{preserveHead:!0});let je=W.get(A.filePath);return{route:A,content:Le,status:je?.status??await pn(A.filePath),headers:je?.headers}}}let fe=le?await q(A.filePath):await Bun.file(A.filePath).text(),Ce=jt(fe),{classifyAllScripts:J}=await import("./chunk-x5cscz50.js"),Me=J(fe),Ne=Me.server.map((re)=>re.content),de=fe;for(let re of Me.server)de=de.replace(re.fullTag,"");let ue={__filename:A.filePath,__dirname:te.dirname(A.filePath),__stx_options:M,params:z??{},__stx_runtime_head:{}};for(let re of Ne)try{await V(re,ue,A.filePath)}catch(_e){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,_e?.message||_e)}let We=new Set,Ae;if(s.profile){let re=performance.now();Ae=await N(de,ue,A.filePath,M,We);let _e=performance.now()-re,Le=te.relative(p,A.filePath)||A.filePath;console.log(`[stx:profile] ${Le} \u2192 ${_e.toFixed(2)}ms`)}else Ae=await N(de,ue,A.filePath,M,We);if(!E)Ae=await qe(Ae,{router:M.router});{let{interpolateScriptExpressions:re}=await import("./chunk-rmc8cg2n.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(_e,Le,je)=>{if(!/function\s+__stx_setup_/.test(je))return _e;return`<script${Le}>${re(je,ue)}</script>`})}if(E)Ae=xe(Ae,{preserveHead:!0});if(le&&ye)await Y(A.filePath,Ae,We,M);let{extractStreamBoundaries:qn}=await import("./chunk-qk4zkvzh.js"),nt=qn(ue),at=ue.__streamTemplates;if(at&&typeof at==="object"&&Object.keys(at).length>0){let re=ue.streamBoundaries||{},_e={...M,autoShell:!1},Le=Object.keys(at).map((Re)=>({id:Re,render:async()=>{let ct=typeof re[Re]==="function"?await re[Re]():void 0;return N(at[Re],{...ue,$boundary:ct},A.filePath,_e,new Set)}})),je=new Set(Le.map((Re)=>Re.id));nt=[...(nt||[]).filter((Re)=>!je.has(Re.id)),...Le]}if(nt&&nt.length>0)Oe.add(A.pattern);else nt=void 0;let Kt=Je(ue),Xt=Ye(ue);if(ye)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Ae,status:Kt??Ce,headers:Xt,boundaries:nt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Fe=8,Ue=async()=>{ge.clear(),j.clear();for(let A=0;A<k.length;A+=Fe){let z=k.slice(A,A+Fe),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)ge.set(V.route.pattern,V)}for(let A=0;A<_.length;A+=Fe){let z=_.slice(A,A+Fe),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return ge.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Lt(p);let et=i;try{if(et=await Ge(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||et+1;l=Et({wsPort:A,verbose:!1}),m=l.start(A)}let At=(A,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Yr({port:et,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",V=te.join(p,N,z.pathname),ve=te.join(p,z.pathname),ze=te.join($e,z.pathname);if([V,ve,ze].some((M)=>w(M,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Y]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(ve).catch(()=>null),be.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(V,p,S))return Nt(V);if(ee?.isFile()&&!w(ve,p,S))return Nt(ve);if(Y?.isFile()&&!w(ze,p,S))return Nt(ze);if(z.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(z.pathname.slice(16));if(M)try{let ye=`<${M} />`,le={...buildConfig,autoShell:!1},fe=await processDirectives(ye,{},te.join(p,"components",`${M}.stx`),le,new Set);return new Response(fe,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-wfettff6.js"),ye=await M(A,{publicDir:te.join(p,N),cacheDir:a(p,"cache","img")});if(ye)return ye}if(Q)try{let M=await Q.handleRequest(A);if(M.status!==404)return M}catch{}if(K[z.pathname])try{return await K[z.pathname](A)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await R(A);if(q)return q;let G=Fn(z.pathname,k);if(G){let M=ge.get(G.route.pattern),ye=Oe.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||ye){let le=await H(G.route,G.params);if(le)M=le}if(M){let le=M.status??200,fe=M.headers??{},Ce=(G.route.filePath?Xe(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let Ne=await ne(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=gt(z.pathname,G.params,Ce,z.search),Ne=mt(Me,null,A,{isServer:!0}),de=await ht(Ce.middleware,Ne);if(de.redirect){let ue=de.redirect.path,We=de.redirect.options.redirectCode||302,Ae=new Headers(de.responseHeaders);return Ae.set("Location",ue),new Response(null,{status:We,headers:Ae})}if(de.abort){let{statusCode:ue,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ue}</title></head><body><h1>Error ${ue}</h1><p>${We}</p></body></html>`,{status:ue,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let ue=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${ue}</head>`)}}let J=M.content;if(E&&Ao(A)){let Me=Ie(J),Ne=me(J),de=J.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ue=de?$o(de[1].trim()):"";if(Object.keys(G.params).length>0)J=At(J,G.params);J=await f(J,p);let We=g?.router?.container||"main";return J=ce(J,We),new Response(J,{status:le,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ne?"true":"false",...ue&&{"X-STX-Title":encodeURIComponent(ue)},[Oi]:Ls(),...T(),"Cache-Control":Be}})}if(E)J=Xn(E,J);if(Object.keys(G.params).length>0)J=At(J,G.params);if(J=await f(J,p),c)J=Ve(J,m);if(s.native)if(J.includes("<head>"))J=J.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 J="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+J;if(s.titlebarHidden)if(J.includes("<head>"))J=J.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 J=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${J}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:Ne}=await import("./chunk-qk4zkvzh.js");return Ne(Me(J,M.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(J,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...fe}})}}if(_.length>0){let M=_.map((le)=>le.route),ye=Fn(z.pathname,M);if(ye){let le=j.get(ye.route.pattern);if(le){let fe=le.content;if(E)fe=Xn(E,fe);if(Object.keys(ye.params).length>0)fe=At(fe,ye.params);if(fe=await f(fe,p),c)fe=Ve(fe,m);return new Response(fe,{status:le.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:le}of B)if(le!=="/"&&z.pathname.startsWith(le)){let fe=j.get(le)||j.get(le+"/");if(fe){let Ce=fe.content;if(E)Ce=Xn(E,Ce);if(Ce=await f(Ce,p),c)Ce=Ve(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(ut(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=ge.get("/");if(Se){let M=Se.content;if(M=await f(M,p),c)M=Ve(M,m);if(s.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ke=await ne(404);if(Ke){let M=Ke;if(M=await f(M,p),c)M=Ve(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await ne(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1430
1430
|
${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1431
1431
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1432
1432
|
${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
1433
1433
|
${e.yellow}Routes:${e.reset}`);let Mt=[...Pr(k,p)];for(let{route:A}of _)Mt.push(`${A.pattern}`);if(Mt.forEach((A,z)=>{let V=z===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),console.log(`
|
|
1434
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.url.toString(),()=>{if(l)lt();Dt.stop()}),s.native){let A,z=te.join(C,"index.stx");if(be.existsSync(z)){let V=await Bun.file(z).text();A=Tt(V)}let N=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),z=(ee)=>{let Y=ee.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},N=new Map,V=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Y)=>Y.root)??[],...g._layerGraph?.configDependencies.map((Y)=>te.dirname(Y))??[]].filter((Y)=>be.existsSync(Y)).map((Y)=>be.realpathSync(Y)));for(let Y of g._layerGraph?.layers??[])for(let q of Object.values(Y.resources)){if(!be.existsSync(q))continue;let G=be.realpathSync(q);if(![...ee].some((Se)=>G===Se||G.startsWith(`${Se}${te.sep}`)))ee.add(G)}for(let[Y,q]of N)if(!ee.has(Y))q.close(),N.delete(Y);for(let Y of ee)if(!N.has(Y)&&be.existsSync(Y))N.set(Y,be.watch(Y,{recursive:!0},(q,G)=>{ze(Y,q,G).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},ve=Promise.resolve(),ze=(ee,Y,q)=>(ve=ve.catch(()=>{}).then(()=>qe(ee,Y,q)),ve),qe=async(ee,Y,q)=>{if(!q||Rt(q))return;if(Ct(q)){if(g._layerGraph){let G=await h(p);Object.assign(g,G),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:G._layerPageDirs?[C,...G._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(z(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.url.toString(),()=>{if(l)lt();Dt.stop()}),s.native){let A,z=te.join(C,"index.stx");if(be.existsSync(z)){let V=await Bun.file(z).text();A=Tt(V)}let N=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),z=(ee)=>{let Y=ee.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},N=new Map,V=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Y)=>Y.root)??[],...g._layerGraph?.configDependencies.map((Y)=>te.dirname(Y))??[]].filter((Y)=>be.existsSync(Y)).map((Y)=>be.realpathSync(Y)));for(let Y of g._layerGraph?.layers??[])for(let q of Object.values(Y.resources)){if(!be.existsSync(q))continue;let G=be.realpathSync(q);if(![...ee].some((Se)=>G===Se||G.startsWith(`${Se}${te.sep}`)))ee.add(G)}for(let[Y,q]of N)if(!ee.has(Y))q.close(),N.delete(Y);for(let Y of ee)if(!N.has(Y)&&be.existsSync(Y))N.set(Y,be.watch(Y,{recursive:!0},(q,G)=>{ze(Y,q,G).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},ve=Promise.resolve(),ze=(ee,Y,q)=>(ve=ve.catch(()=>{}).then(()=>qe(ee,Y,q)),ve),qe=async(ee,Y,q)=>{if(!q||Rt(q))return;if(Ct(q)){if(g._layerGraph){let G=await h(p);Object.assign(g,G),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:G._layerPageDirs?[C,...G._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(z(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-8xns82s5.js");G(te.resolve(ee,q)),Se.delete(te.resolve(ee,q))}catch{}if(I&&q){if(te.resolve(ee,q)===I||te.basename(I)===q){let Se=await Ur(I,s.stxOptions||{});if(Se)E=Se}}if(await Ue(),await kn(p),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-8xns82s5.js");G(te.resolve(ee,q)),Se.delete(te.resolve(ee,q))}catch{}if(await Ue(),c&&l)l.reload(q)}}else if($t(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let ee of N.values())ee.close();if(l)lt();Dt.stop(),process.exit(0)})}return!0}import Ut from"fs";import yt from"path";async function Qr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=p.split(`
|
|
1435
1435
|
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=R.join(" ").trim(),c.push(g)}if(c.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Zr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
|
|
1436
1436
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function eo(t,s=!1,i){let d=yt.basename(t,".stx"),c=await Qr(t),l=await Zr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let p=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
|
|
1437
1437
|
`);m=`<${d}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pa,fa}from"./chunk-wk95x5ym.js";import"./chunk-5wa3ydkf.js";import"./chunk-pwsg9w5g.js";import"./chunk-wsbccxwy.js";import"./chunk-h431swg6.js";import"./chunk-9pz3jh7w.js";import"./chunk-9z9f3d6b.js";import"./chunk-kep8q407.js";import{To}from"./chunk-9eejvpqc.js";import"./chunk-q1983d5e.js";import"./chunk-5wrmcbch.js";import"./chunk-m64w624a.js";import"./chunk-n8595zaf.js";import"./chunk-ebkjpj5m.js";import"./chunk-y3n2cgev.js";import"./chunk-q35z0cyg.js";import"./chunk-0c7ss25y.js";import"./chunk-e6ccfmx9.js";import"./chunk-4hmdcmw1.js";import"./chunk-q7wj2ypd.js";import"./chunk-5m0r0j79.js";import"./chunk-7mehf3h5.js";import"./chunk-a39kvc2p.js";import"./chunk-7zwsgjy4.js";import"./chunk-604hzs2x.js";import"./chunk-q7t2mtn4.js";import"./chunk-a669q9b8.js";import"./chunk-b9kn62k3.js";import"./chunk-hmpzdq4p.js";import"./chunk-19bhnbyn.js";import"./chunk-qbh3jk5z.js";import"./chunk-3tp481j5.js";import"./chunk-jsw5yby0.js";import"./chunk-773vgw1k.js";import"./chunk-fqwyfx6c.js";import"./chunk-erk7afjv.js";import"./chunk-5rtatjwq.js";import{ke,vn,wn,Z,u,n,mr,A,o,he}from"./chunk-e030grrq.js";import"./chunk-n5xbv1a9.js";import"./chunk-10s16tad.js";import"./chunk-z4te6223.js";import"./chunk-j8vd52sg.js";import"./chunk-gc1dzxee.js";import"./chunk-khzyc41k.js";import"./chunk-x6pz1h3x.js";import"./chunk-1gtrs8va.js";import"./chunk-66e4ga0z.js";import"./chunk-dvbgbd06.js";import"./chunk-sxpnpvt5.js";import"./chunk-jp6yn9mj.js";export{mr as buildWebComponents,wn as cacheTemplate,vn as checkCache,To as classifyAllScripts,pa as createMiddleware,fa as createRoute,A as defaultConfig,u as extractVariables,Z as injectRouterScript,o as loadStxConfig,ke as processClientScript,n as processDirectives,he as readMarkdownFile};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$l}from"./chunk-
|
|
2
|
+
import{$l}from"./chunk-kep8q407.js";import"./chunk-9eejvpqc.js";import"./chunk-19bhnbyn.js";import"./chunk-erk7afjv.js";import"./chunk-e030grrq.js";import"./chunk-n5xbv1a9.js";import"./chunk-10s16tad.js";import"./chunk-z4te6223.js";import"./chunk-j8vd52sg.js";import"./chunk-gc1dzxee.js";import"./chunk-khzyc41k.js";import"./chunk-x6pz1h3x.js";import"./chunk-1gtrs8va.js";import"./chunk-66e4ga0z.js";import"./chunk-dvbgbd06.js";import"./chunk-sxpnpvt5.js";import"./chunk-jp6yn9mj.js";export{$l as buildForProduction};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{p,c}from"./chunk-1gtrs8va.js";import{ne,b}from"./chunk-
|
|
2
|
+
import{p,c}from"./chunk-1gtrs8va.js";import{ne,b}from"./chunk-e030grrq.js";function A(t,o){let i=1,r=o,n="<template",e="</template";while(r<t.length&&i>0){let s=t.indexOf("<",r);if(s===-1)break;if(r=s,t.startsWith(n,r)&&(r+n.length>=t.length||/[\s>\/]/.test(t[r+n.length]))){i++,r+=n.length;continue}if(t.startsWith(e,r)){let a=t.indexOf(">",r+e.length);if(a!==-1){if(i--,i===0)return a+1;r=a+1;continue}}r++}return i===0?r:-1}var w=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function x(t,o){let i=null;for(let r=o;r<t.length;r++){let n=t[r];if(i){if(n==="\\"){r++;continue}if(n===i)i=null;continue}if(n==='"'||n==="'"){i=n;continue}if(n===">")return r+1}return-1}function N(t,o,i){let r=o.toLowerCase(),n=1,e=i;while(e<t.length){let s=t.indexOf("<",e);if(s===-1)return-1;if(t.startsWith("<!--",s)){let g=t.indexOf("-->",s+4);e=g===-1?t.length:g+3;continue}let a=x(t,s+1);if(a===-1)return-1;let f=t.slice(s,a),u=f.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(u&&u[2].toLowerCase()===r){if(u[1]==="/"){if(n--,n===0)return a}else if(!/\/\s*>$/.test(f))n++}e=a}return-1}function R(t){let o=[],i=[],r=/\bslot\s*=\s*(?:"([^"]+)"|'([^']+)')/i,n=0;while(n<t.length){let e=t.indexOf("<",n);if(e===-1)break;if(t.startsWith("<!--",e)){let l=t.indexOf("-->",e+4);n=l===-1?t.length:l+3;continue}let s=x(t,e+1);if(s===-1)break;let a=t.slice(e,s),f=a.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(!f){n=s;continue}let u=f[2].toLowerCase();if(f[1]==="/"){let l=i.lastIndexOf(u);if(l!==-1)i.splice(l);n=s;continue}let g=/\/\s*>$/.test(a),m=i.length===0?a.match(r):null;if(m){let l=m[1]||m[2],d=a.replace(r,"").replace(/\s+(?=\/?>$)/,"").replace(/\s{2,}/g," "),h=g||w.has(u)?-1:N(t,u,s);if(h===-1)o.push({start:e,end:s,slotName:l,element:d}),n=s;else o.push({start:e,end:h,slotName:l,element:d+t.slice(s,h)}),n=h;continue}if(!g&&!w.has(u)){if(i.push(u),u==="script"||u==="style"){let l=t.toLowerCase().indexOf(`</${u}>`,s);if(l!==-1){n=l;continue}}}n=s}return o}function O(t){let o=[],i=[],r=/^<template\s+(?:#([a-zA-Z][\w-]*)|v-slot:([a-zA-Z][\w-]*)|slot="([a-zA-Z][\w-]*)")(?:\s*=\s*"([^"]*)")?[^>]*>$/i,n=0;while(n<t.length){let e=t.indexOf("<",n);if(e===-1)break;if(t.startsWith("<!--",e)){let l=t.indexOf("-->",e+4);n=l===-1?t.length:l+3;continue}let s=x(t,e+1);if(s===-1)break;let a=t.slice(e,s),f=a.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(!f){n=s;continue}let u=f[1]==="/",g=f[2].toLowerCase();if(u){let l=i.lastIndexOf(g);if(l!==-1)i.splice(l);n=s;continue}if(g==="template"&&i.length===0){let l=a.match(r);if(l){let d=A(t,s);if(d!==-1){let h=l[1]||l[2]||l[3];o.push({start:e,end:d,slotName:h,content:t.slice(s,d-11).trim(),propsBinding:l[4]||void 0}),n=d;continue}}}if(!/\/\s*>$/.test(a)&&!w.has(g)){if(i.push(g),g==="script"||g==="style"){let l=t.toLowerCase().indexOf(`</${g}>`,s);if(l!==-1){n=l;continue}}}n=s}return o}function Ra(t){let o={default:"",named:new Map},i=t,r=O(t);for(let e of r)o.named.set(e.slotName,{name:e.slotName,content:e.content,propsBinding:e.propsBinding});r.sort((e,s)=>s.start-e.start);for(let e of r)i=i.slice(0,e.start)+i.slice(e.end);let n=R(i);for(let e of n){let s=o.named.get(e.slotName);if(s)s.content+=e.element;else o.named.set(e.slotName,{name:e.slotName,content:e.element})}for(let e=n.length-1;e>=0;e--){let s=n[e];i=i.slice(0,s.start)+i.slice(s.end)}return o.default=i.trim(),o}function Hl(t){let o=t.match(/name\s*=\s*["']([^"']+)["']/),i=o?o[1]:"",r={},n=/:([a-zA-Z][\w-]*)\s*=\s*["']([^"']+)["']/g,e;while((e=n.exec(t))!==null)r[e[1]]=e[2];let s=t.match(/<slot[^>]*>([\s\S]*?)<\/slot>/i),a=s?s[1].trim():"";return{name:i,props:r,defaultContent:a}}async function Aa(t,o,i,r){if(!t)return i;let n=t.content;if(t.propsBinding&&Object.keys(o).length>0){let e=t.propsBinding.trim(),s={...r},a=new Set,f=new Set;if(e.startsWith("{")&&e.endsWith("}")){let u=e.slice(1,-1).split(",").map((g)=>g.trim()).filter(Boolean);for(let g of u){let[m,l]=g.split(":").map((h)=>h.trim()),d=l||m;if(s[d]=o[m],o[m]!==void 0)f.add(d);else a.add(d)}}else if(s[e]=o,Object.values(o).some((u)=>u===void 0))a.add(e);else f.add(e);n=C(n,s,a,f)}return n}function C(t,o,i,r){return t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(n,e)=>{try{let s=e.trim();if(ne(s,i))return n;if(Array.isArray(o.__stx_preserved_client_expressions)&&o.__stx_preserved_client_expressions.includes(s)&&!ne(s,r))return n;let a=k(s,o);if(a===void 0)return n;return b(String(a??""))}catch{return`{{ ${e} }}`}})}function k(t,o){if(/^[a-zA-Z_$][\w$]*(\.[a-zA-Z_$][\w$]*)*$/.test(t)){let r=t.split("."),n=o;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}let i=t.match(/^([a-zA-Z_$][\w$]*)\s*([+\-*/])\s*(\d+)$/);if(i){let[,r,n,e]=i,s=o[r],a=parseInt(e,10);if(typeof s==="number")switch(n){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":return s/a}}try{if(!p(t))return;return c(t,Object.keys(o))(...Object.values(o))}catch{return}}async function Pa(t,o,i){let r=t;r=await M(r,/<slot\s+name\s*=\s*["']([^"']+)["']([^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/gi,async(s,a,f,u)=>{let g=o.named.get(a),m=u?.trim()||"",l=f||"",d={},h=/:([a-zA-Z_$][\w$-]*)\s*=\s*["']([^"']+)["']/g,S;while((S=h.exec(l))!==null){let y=S[1],E=S[2];d[y]=k(E,i)}return await Aa(g,d,m,i)});let e=/<slot\b((?:"[^"]*"|'[^']*'|[^>"'])*?)\s*(?:\/>|>([\s\S]*?)<\/slot>)/gi;return r=r.replace(e,(s,a,f)=>{if(/\bname\s*=/.test(a||""))return s;let u=f?.trim()||"";return o.default||u}),r}async function M(t,o,i){let r=[],n=[];t.replace(o,(a,...f)=>{let u=f[f.length-2];return n.push({match:a,index:u}),r.push(i(a,...f.slice(0,-2))),a});let e=await Promise.all(r),s=t;for(let a=n.length-1;a>=0;a--){let{match:f,index:u}=n[a];s=s.slice(0,u)+e[a]+s.slice(u+f.length)}return s}function Vl(t){let o=Ra(t);return{defaultSlot:o.default,namedSlots:o.named}}async function Ul(t,o,i,r){return await Pa(t,{default:o,named:i},r)}
|
|
3
3
|
export{Ra,Hl,Aa,Pa,Vl,Ul};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{hd,Lc,$s,Rs,_i,Ei,As,Ps,dr,jc,Ti,$i,Bc,et}from"./chunk-
|
|
2
|
+
import{hd,Lc,$s,Rs,_i,Ei,As,Ps,dr,jc,Ti,$i,Bc,et}from"./chunk-e030grrq.js";import"./chunk-n5xbv1a9.js";import"./chunk-10s16tad.js";import"./chunk-z4te6223.js";import"./chunk-j8vd52sg.js";import"./chunk-gc1dzxee.js";import"./chunk-khzyc41k.js";import"./chunk-x6pz1h3x.js";import"./chunk-1gtrs8va.js";import"./chunk-66e4ga0z.js";import"./chunk-dvbgbd06.js";import"./chunk-sxpnpvt5.js";import"./chunk-jp6yn9mj.js";export{hd as clearScriptScanCache,As as convertServerLoopAttributesToDirectives,_i as convertSignalDirectivesToAttributes,Ps as convertSignalLoopsToAttributes,jc as extractExports,$i as findMarkupIndexOutsideScripts,Rs as hasSignalsSyntax,$s as parseLoopExpression,Ei as preEvalLiteralReactiveIfs,dr as processScriptSetup,Ti as processSignals,Bc as rewriteStxImportSpecifiers,Lc as scanScriptTags,et as stripStxRuntimeImports};
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import{X}from"./chunk-
|
|
3
|
+
import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import{X}from"./chunk-e030grrq.js";import"./chunk-x6pz1h3x.js";import"./chunk-khzyc41k.js";import"./chunk-gc1dzxee.js";import"./chunk-j8vd52sg.js";import"./chunk-jp6yn9mj.js";import"./chunk-z4te6223.js";import"./chunk-5m0r0j79.js";import"./chunk-wsbccxwy.js";import"./chunk-jsw5yby0.js";import"./chunk-ebkjpj5m.js";import"./chunk-7mehf3h5.js";import"./chunk-5wrmcbch.js";import"./chunk-h431swg6.js";import"./chunk-9eejvpqc.js";import"./chunk-b9kn62k3.js";import"./chunk-m64w624a.js";import"./chunk-19bhnbyn.js";import"./chunk-q1983d5e.js";import"./chunk-7zwsgjy4.js";import"./chunk-pwsg9w5g.js";import"./chunk-9z9f3d6b.js";import"./chunk-5wa3ydkf.js";import"./chunk-e6ccfmx9.js";import"./chunk-erk7afjv.js";import"./chunk-kep8q407.js";import"./chunk-qbh3jk5z.js";import"./chunk-a669q9b8.js";import"./chunk-604hzs2x.js";import"./chunk-q7t2mtn4.js";import"./chunk-5rtatjwq.js";import{Et,Tt}from"./chunk-fqwyfx6c.js";import"./chunk-a39kvc2p.js";import"./chunk-9pz3jh7w.js";import"./chunk-4hmdcmw1.js";import"./chunk-q7wj2ypd.js";import"./chunk-q35z0cyg.js";import"./chunk-0c7ss25y.js";import"./chunk-n8595zaf.js";import"./chunk-hmpzdq4p.js";import"./chunk-y3n2cgev.js";import{go,mo,ho,yo,Mr,bo,vo,wo,Lr,jr,Vn,Un,Wn}from"./chunk-wk95x5ym.js";import"./chunk-3tp481j5.js";import"./chunk-773vgw1k.js";import{ji}from"./chunk-n5xbv1a9.js";import{d}from"./chunk-yn2d8x8m.js";import{spawn as R}from"child_process";import S from"fs";import f from"path";import s from"process";import{CLI as W}from"@stacksjs/clapp";var j="0.2.622";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new W("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function A(h){try{if(!S.existsSync(h)){let x=f.dirname(h),t=f.basename(h);if(S.existsSync(x)){let o=S.readdirSync(x).filter((n)=>n.toLowerCase().includes(t.toLowerCase().substring(0,3))||n.endsWith(".stx")||n.endsWith(".md")),i=o.length>0?`File not found. Similar files in ${x}: ${o.slice(0,3).join(", ")}`:`File not found. Directory ${x} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${h}`,suggestion:i}}return{isValid:!1,error:`File does not exist: ${h}`,suggestion:"Check the file path and try again"}}if(S.statSync(h).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${h}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var O=(h)=>h.includes("*")||h.includes("?")||h.includes("{")||h.includes("["),V=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);s.exit(p)}function U(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),s.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),s.exit(1);for(let[x,t]of Object.entries(p))if(typeof t!=="string"&&typeof t!=="number"&&typeof t!=="boolean")console.error(`\u274C --info-plist value for "${x}" must be a string, number or boolean`),s.exit(1);return p}async function H(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!1}else t.push(c);if(t.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(x.push(...t),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.resolve("stx-test-report.xml");x.push("--reporter",p.reporter),x.push("--reporter-outfile",c),console.log(`JUnit report: ${c}`)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.watch)x.push("--watch");x.push("--preload",f.join(__dirname,"../../../test-utils/happy-dom.ts"));let e={...s.env,STX_TEST_MODE:"true",STX_TEST_UI:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),n=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{n.on("close",(r)=>{let u=((performance.now()-i)/1000).toFixed(2);if(r===0)c(!0);else c(!1)}),s.on("SIGINT",()=>{console.log(`
|
|
4
4
|
Test run interrupted`),n.kill("SIGINT"),s.exit(1)})})}catch(x){return console.error("Error running tests:",x instanceof Error?x.message:String(x)),!1}}var L=s.argv.length>=3&&(V(s.argv[2])&&S.existsSync(s.argv[2])||O(s.argv[2]));if(L){let h=s.argv[2],p={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let x=3;x<s.argv.length;x++){let t=s.argv[x];if(t==="--port"&&x+1<s.argv.length){let e=B(s.argv[++x]);if(!e.isValid)F(e);p.port=Number.parseInt(s.argv[x],10)}else if(t==="--no-watch")p.watch=!1;else if(t==="--highlight-theme"&&x+1<s.argv.length){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.defaultTheme=s.argv[++x]}else if(t==="--no-highlight"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.enabled=!1}else if(t==="--no-highlight-unknown"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(t==="--no-cache")p.cache=!1;else if(t==="--native")p.native=!0}if(O(h))try{let x=await Array.fromAsync(new Bun.Glob(h).scan({onlyFiles:!0,absolute:!0})),t=h.endsWith(".stx")?x.filter((n)=>n.endsWith(".stx")):h.endsWith(".md")?x.filter((n)=>n.endsWith(".md")):x.filter((n)=>n.endsWith(".stx")||n.endsWith(".md")),e=h.split("*")[0].replace(/\/$/,"")||".",o=f.resolve(e);try{let n=new Bun.Glob("**/*.stx"),r=(await Array.fromAsync(n.scan({cwd:o,onlyFiles:!0,absolute:!0}))).filter((l)=>/\[.+\]/.test(f.basename(l)));for(let l of r)if(!t.includes(l))t.push(l)}catch{}if(t.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${h}`),s.exit(1);if(!await Un(t,p))s.exit(1)}catch(x){console.error("Failed to process files:",x),s.exit(1)}else Vn(h,p).catch((x)=>{console.error("Failed to start dev server:",x),s.exit(1)})}else{let h=function(t,e){let o=[];for(let i=0;i<=e.length;i++)o[i]=[i];for(let i=0;i<=t.length;i++)o[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=t.length;n++)if(e.charAt(i-1)===t.charAt(n-1))o[i][n]=o[i-1][n-1];else o[i][n]=Math.min(o[i-1][n-1]+1,o[i][n-1]+1,o[i-1][n]+1);return o[e.length][t.length]};y.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(t)=>{try{if(await yo(t))console.log("Documentation generated successfully."),s.exit(0);else console.error("Documentation generation failed."),s.exit(1)}catch(e){console.error("Error generating documentation:",e),s.exit(1)}}),y.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(t,e)=>{try{let{fetchCollections:o,generatePackage:i}=await import("./chunk-ktvr45qg.js");if(t==="list"){console.log(`
|
|
5
5
|
\uD83D\uDCDA Fetching available icon collections...
|
|
6
6
|
`);let n=await o(),c=Object.entries(n).sort((r,l)=>l[1].total-r[1].total);console.log(`Available collections:
|
|
7
7
|
`);for(let[r,l]of c){let u=l;console.log(` ${r.padEnd(30)} ${u.name} (${u.total} icons)`)}console.log(`
|
|
8
8
|
Total: ${c.length} collections`)}else if(t.startsWith("generate")){let n=t==="generate"?"":t.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!n)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),s.exit(1);let c=e.output||f.join(s.cwd(),"packages/collections"),r=e.icons?e.icons.split(",").map((l)=>l.trim()):void 0;await i(n,c,r),console.log(`
|
|
9
9
|
\u2713 Package generated successfully!`),console.log(`
|
|
10
|
-
To use the package:`),console.log(` 1. cd packages/collections/iconify-${n}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),s.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),s.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-kp4j8vja.js"),{loadConfig:n}=await import("./chunk-
|
|
10
|
+
To use the package:`),console.log(` 1. cd packages/collections/iconify-${n}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),s.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),s.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-kp4j8vja.js"),{loadConfig:n}=await import("./chunk-6jjrvb9v.js");console.log(`
|
|
11
11
|
\uD83D\uDD0D Running PWA audit...
|
|
12
12
|
`);let c=await n(),r=e.output||"dist",l=o(c,r);if(console.log(i(l)),l.failed>0)s.exit(1)}else console.error(`Unknown pwa command: ${t}`),console.error("Available commands: audit"),s.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),s.exit(1)}}),y.command("dev [file]","Start a development server for an STX app or file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--pages <dir>",'Directory containing page templates (default: pagesDir from stx.config.ts, else "pages")').option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--titlebar-hidden","Hide the native titlebar but keep the traffic-light buttons (web content draws under a transparent full-size titlebar). Implies --native.").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").option("--no-hmr","Disable HMR / live-reload script injection (useful for clean network traces)").option("--profile","Print per-directive timing for every page render via performanceMonitor").option("--debug-directives","Log directive ordering and intermediate template state during rendering").example("stx dev").example("stx dev --port 8080").example("stx dev --pages src/pages").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev template.stx --native").action(async(t,e)=>{try{if(e.port!==void 0){let i=B(e.port);if(!i.isValid)F(i);e.port=Number.parseInt(String(e.port),10)}if(e.timeout!==void 0){let i=z(e.timeout);if(!i.isValid)F(i)}let o={syntaxHighlighting:{enabled:e.highlight!==!1,serverSide:!0,defaultTheme:e.highlightTheme||"github-dark",highlightUnknownLanguages:e.highlightUnknown!==!1}};if(!t){if(!await Wn(".",{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))s.exit(1);return}if(!O(t))try{let i=await import("fs");if(i.existsSync(t)&&i.statSync(t).isDirectory()){if(!await Wn(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))s.exit(1);return}}catch{}if(O(t)){console.log(`Expanding glob pattern: ${t}`);let i=await X.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),n=t.endsWith(".stx")?i.filter((u)=>u.endsWith(".stx")):t.endsWith(".md")?i.filter((u)=>u.endsWith(".md")):i.filter((u)=>u.endsWith(".stx")||u.endsWith(".md"));if(n.length===0)console.error(`No STX or Markdown files found matching pattern: ${t}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),s.exit(1);let c=t.split("*")[0].replace(/\/$/,"")||".",r=f.resolve(c);try{let u=new Bun.Glob("**/*.stx"),m=(await Array.fromAsync(u.scan({cwd:r,onlyFiles:!0,absolute:!0}))).filter((g)=>/\[.+\]/.test(f.basename(g)));for(let g of m)if(!n.includes(g))n.push(g)}catch{}if(console.log(`Found ${n.length} ${n.length===1?"file":"files"} matching ${t}`),!await Un(n,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))s.exit(1)}else{if(!O(t)){let n=A(t);if(!n.isValid)F(n)}if(!await Vn(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))s.exit(1)}}catch(o){console.error("Error starting dev server:",o),s.exit(1)}}),y.command("a11y [target]","Scan .stx files for accessibility issues (directory, file, or glob)").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example('stx a11y "resources/**/*.stx"').example("stx a11y resources/emails/welcome.stx").example("stx a11y --json --output a11y-report.json").action(async(t=".",e)=>{try{console.log(`Scanning ${t} for accessibility issues...`);let o=e.ignore?e.ignore.split(",").map((l)=>l.trim()):[],{results:i,scannedFiles:n}=await ji(t,{recursive:e.recursive!==!1,ignorePaths:o});if(n.length===0)console.log(`
|
|
13
13
|
No .stx files matched ${t}
|
|
@@ -69,7 +69,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
|
|
|
69
69
|
File not found: ${t}`),s.exit(1);if(!t.endsWith(".stx"))console.error(`
|
|
70
70
|
File must have .stx extension: ${t}`),s.exit(1)}let i=f.resolve(e.pages),n=f.resolve(e.out);if(!t&&!S.existsSync(i))console.error(`
|
|
71
71
|
Pages directory not found: ${i}`),console.log(`
|
|
72
|
-
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),s.exit(1);let{buildApp:c}=await import("./chunk-
|
|
72
|
+
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),s.exit(1);let{buildApp:c}=await import("./chunk-m0zmexz1.js");Tt();let r=await c({root:t?f.dirname(t):void 0,debug:e.verbose,ssg:{pagesDir:e.pages,outputDir:e.out,domain:e.domain,baseUrl:e.base,sitemap:e.sitemap,rss:e.rss,minify:e.minify,cache:e.cache!==!1,cleanOutput:e.clean,concurrency:Number.parseInt(e.concurrency,10)||10,publicDir:e.public,trailingSlash:e.trailingSlash,generate404:!0,hooks:e.verbose?{onPageStart:(u)=>console.log(` Generating: ${u}`),onPageEnd:(u,a)=>console.log(` Generated: ${u} (${a.length} bytes)`),onError:(u,a)=>console.error(` Error in ${a}: ${u.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)console.log(`
|
|
73
73
|
Build complete! (SSR)
|
|
74
74
|
`),console.log(` Pages compiled: ${r.ssr.pageCount}`),console.log(` Output: ${r.ssr.outputDir}`),console.log(` Duration: ${l}s
|
|
75
75
|
`);else if(r.ssg){if(console.log(`
|
|
@@ -84,7 +84,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
|
|
|
84
84
|
Build completed with ${r.ssg.failedCount} error(s). Fix the issues above and try again.
|
|
85
85
|
`),s.exit(1);console.log(" To preview locally:"),console.log(` cd ${e.out||"dist"} && npx serve
|
|
86
86
|
`)}}catch(o){console.error(`
|
|
87
|
-
Build failed:`,o instanceof Error?o.message:String(o)),s.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),s.exit(1);let{startProductionServer:o}=await import("./chunk-
|
|
87
|
+
Build failed:`,o instanceof Error?o.message:String(o)),s.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),s.exit(1);let{startProductionServer:o}=await import("./chunk-fmdezmt4.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){console.error(`
|
|
88
88
|
Failed to start production server:`,e instanceof Error?e.message:String(e)),s.exit(1)}}),y.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(t,e)=>{try{let{deploy:o,initNetlify:i,DeployError:n}=await import("./chunk-smpyb21z.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${j}\x1B[0m`),e.init){console.log(`
|
|
89
89
|
\uD83D\uDCDD Initializing Netlify configuration...
|
|
90
90
|
`);let r=await i({directory:t||s.cwd(),siteId:e.siteId});if(console.log(`\u2713 Created ${r.configPath}`),r.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
|
|
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${t}
|
|
|
124
124
|
\uD83D\uDCDD ${f.relative(s.cwd(),a)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${f.basename(a)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(a,b),console.log(`\u2705 Formatted ${f.relative(s.cwd(),a)}`),l++}catch(m){console.error(`\u274C Error formatting ${f.relative(s.cwd(),a)}:`,m),u++}if(e.check&&u>0)console.log(`
|
|
125
125
|
${u} files need formatting. Run 'stx format' to fix.`),s.exit(1);else if(!e.check&&!e.diff)console.log(`\u2728 Formatted ${l} files successfully`)}catch(o){console.error("Error formatting files:",o),s.exit(1)}}),y.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(t,e)=>{try{if(e.clear){X.clear(),console.log("\u2705 Performance statistics cleared");return}let o=X.getStats();if(Object.keys(o).length===0){if(e.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(e.json)console.log(JSON.stringify(o,null,2));else{console.log(`
|
|
126
126
|
\uD83D\uDCCA STX Performance Statistics
|
|
127
|
-
`);for(let[i,n]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${n.count}`),console.log(` Average: ${n.avgTime.toFixed(2)}ms`),console.log(` Total: ${n.totalTime.toFixed(2)}ms`),console.log(` Min: ${n.minTime.toFixed(2)}ms`),console.log(` Max: ${n.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),s.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-
|
|
127
|
+
`);for(let[i,n]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${n.count}`),console.log(` Average: ${n.avgTime.toFixed(2)}ms`),console.log(` Total: ${n.totalTime.toFixed(2)}ms`),console.log(` Min: ${n.minTime.toFixed(2)}ms`),console.log(` Max: ${n.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),s.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-40fepd2t.js"),{resolveStxTargets:n}=await import("./chunk-pz5zh3tg.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await n(r);if(l.length===0){console.log(`
|
|
128
128
|
No .stx files matched ${r.join(", ")}
|
|
129
129
|
`);return}let u=go(s.argv,"--lib"),a=u.length>0?u:e.lib?Array.isArray(e.lib)?e.lib:[e.lib]:[],m=await i(l,{client:e.client!==!1,server:e.server!==!1,templates:e.templates!==!1,extraLibs:a});if(m.failure)console.error(`
|
|
130
130
|
Type-check did not run.
|
|
@@ -160,11 +160,11 @@ Press Ctrl+C to stop watching...
|
|
|
160
160
|
\uD83D\uDCC4 Files with issues:`),u.forEach((a)=>{let m=a.issues.filter((g)=>n[g.type]>=c).length;if(m>0)console.log(` ${f.relative(s.cwd(),a.file)} (${m} issues)`)});if(e.saveReport){let a={summary:l,results:u,generatedAt:new Date().toISOString(),commandOptions:e};await Bun.write(e.saveReport,JSON.stringify(a,null,2)),console.log(`
|
|
161
161
|
\uD83D\uDCCB Analysis report saved to: ${e.saveReport}`)}console.log(`
|
|
162
162
|
\u2728 Analysis complete! Use --detailed for more information.`)}catch(o){console.error("Error analyzing templates:",o),s.exit(1)}}),y.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(t,e)=>{let{captureScreenshots:o}=await import("./chunk-v1ck0wd3.js"),i=t||"dist";try{let n=await o(i,e.out,{width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),waitMs:Number.parseInt(e.wait,10),timeoutMs:Number.parseInt(e.timeout,10),fullPage:Boolean(e.fullPage),waitSelector:e.waitSelector,format:e.format,backend:e.backend});for(let c of n)console.log(`\uD83D\uDCF8 ${c.output} (${(c.bytes/1024).toFixed(0)} KB)`);console.log(`
|
|
163
|
-
\u2728 Captured ${n.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(n){console.error(`Screenshot failed: ${n.message}`),s.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-
|
|
163
|
+
\u2728 Captured ${n.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(n){console.error(`Screenshot failed: ${n.message}`),s.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-81h6xyna.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let n=S.readFileSync(i,"utf-8");o=JSON.parse(n)}catch(n){console.error("Error loading context file:",n),s.exit(1)}else console.error(`Context file not found: ${i}`),s.exit(1)}await e({context:o,cwd:t.cwd?f.resolve(t.cwd):s.cwd(),verbose:t.verbose})}),y.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(t,e)=>{try{let{buildNative:o,getAvailableTargets:i,getAvailableFormats:n}=await import("./chunk-39qcn4gt.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),s.exit(1);let r=i();if(e.target&&!["macos","windows","linux","ios","android"].includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${r.join(", ")}`),s.exit(1);let l=e.target||r[0],u=n(l);if(e.format&&!u.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${u.join(", ")}`),s.exit(1);console.log(`
|
|
164
164
|
\uD83D\uDD28 Building native app...`),console.log(` Input: ${t}`),console.log(` Target: ${l}`),console.log(` Format: ${e.format||"default"}`),console.log(` Output: ${e.output}
|
|
165
165
|
`);let a=await o({input:c,output:f.resolve(e.output),target:l,format:e.format,name:e.name,version:e.version,description:e.description,author:e.author,bundleId:e.bundleId,icon:e.icon?f.resolve(e.icon):void 0,window:{title:e.title,width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),frameless:e.frameless,alwaysOnTop:e.alwaysOnTop},systemTray:e.systemTray,menubarOnly:e.menubarOnly,category:e.category,copyright:e.copyright,minimumSystemVersion:e.minSystemVersion,infoPlist:U(e.infoPlist),devTools:e.devTools,craftPath:e.craftPath,verbose:e.verbose});if(a.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${a.outputPath}`),a.duration)console.log(` Duration: ${(a.duration/1000).toFixed(2)}s`);if(l==="macos"&&a.format==="app")console.log(`
|
|
166
166
|
\uD83D\uDCA1 To run: open "${a.outputPath}"`);else if(l==="linux"&&a.format==="appimage")console.log(`
|
|
167
|
-
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),s.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),s.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-
|
|
167
|
+
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),s.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),s.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-29cbmfrc.js");await e({port:t.port?Number.parseInt(t.port,10):6006,open:t.open,host:t.host})}catch(e){console.error(`\u274C Story error: ${e.message}`),s.exit(1)}}),y.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(t)=>{try{let{buildCommand:e}=await import("./chunk-gd7vq083.js");await e({outDir:t.outDir})}catch(e){console.error(`\u274C Story build error: ${e.message}`),s.exit(1)}}),y.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(t)=>{try{let{createContext:e}=await import("./chunk-z04480ar.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:n}=await import("./chunk-k1k2t4ez.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(n(r)),r.failed>0)s.exit(1)}}catch(e){console.error(`\u274C Story test error: ${e.message}`),s.exit(1)}}),y.command("native <action> [file]","Compile .stx screens into the JavaScriptCore bundle Craft renders natively").option("--format <format>","bundle (the JavaScriptCore bundle) or ir (the template as JSON)",{default:"ir"}).option("--output <path>","Write to this file instead of stdout").option("--minify","Minify the bundle",{default:!1}).option("--config <file>","Screens config (default: native.config.json in the working directory)").example("stx native compile Screen.stx --format bundle --output native-screen.js").example("stx native compile --format bundle --output native-screen.js --minify").example("stx native compile Screen.stx").action(async(t,e,o)=>{if(t!=="compile")console.error(`Unknown native command: ${t}`),console.error("Usage: stx native compile [file.stx] --format bundle|ir [--output <file>] [--minify] [--config <file>]"),s.exit(1);try{let{runNativeCompile:i}=await import("./chunk-5zzrth32.js"),n=await i(e,{format:o.format,output:o.output,minify:Boolean(o.minify),config:o.config});for(let c of n.diagnostics)console.warn(`${c.level}: ${c.message}`);if(n.written)console.log(`Compiled: ${e??"screens"} \u2192 ${f.relative(s.cwd(),n.written)||n.written}`);else console.log(n.output)}catch(i){console.error(i instanceof Error?i.message:String(i)),s.exit(1)}}),y.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(t,e)=>{try{let{compileToNative:o}=await import("./chunk-th9wcse5.js"),i=f.resolve(t);if(!S.existsSync(i))console.error(`\u274C Input file not found: ${t}`),s.exit(1);let n=["macos","windows","linux","ios","android","universal"];if(!n.includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error(`\uD83D\uDCA1 Available targets: ${n.join(", ")}`),s.exit(1);let c=["zig","typescript","json"];if(!c.includes(e.format))console.error(`\u274C Invalid format: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${c.join(", ")}`),s.exit(1);console.log(`
|
|
168
168
|
\uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${t}`),console.log(` Target: ${e.target}`),console.log(` Format: ${e.format}`),console.log(` Output: ${e.output}
|
|
169
169
|
`);let r=S.readFileSync(i,"utf-8"),l=await o(r,{target:e.target,format:e.format,optimize:e.optimize,treeShake:e.treeShake,hotReload:e.hotReload,debug:e.verbose,sourceMaps:e.sourcemaps,bundle:e.bundle,minify:e.minify}),u=f.resolve(e.output);if(!S.existsSync(u))S.mkdirSync(u,{recursive:!0});let a=f.basename(t,f.extname(t)),m=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",g=f.join(u,`${a}.${m}`);S.writeFileSync(g,l.code);let b=f.join(u,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(u,`${a}.${m}.map`);S.writeFileSync(w,l.sourceMaps)}if(e.target==="universal"&&l.platformCode.size>0)for(let[w,k]of l.platformCode){let v=f.join(u,`${a}.${w}.${m}`);S.writeFileSync(v,k)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${g}`),console.log(` Manifest: ${b}`),console.log(`
|
|
170
170
|
\uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${l.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${l.stats.totalComponents}`),console.log(` Native components: ${l.stats.nativeComponents}`),console.log(` Web fallback components: ${l.stats.webComponents}`),console.log(` Bundle size: ${(l.stats.bundleSize/1024).toFixed(2)}KB`),l.stats.warnings.length>0){console.log(`
|
package/dist/craft-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{as,Jo,Yo}from"./chunk-3dth76ce.js";import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import"./chunk-
|
|
2
|
+
import{as,Jo,Yo}from"./chunk-3dth76ce.js";import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import"./chunk-e030grrq.js";import"./chunk-x6pz1h3x.js";import"./chunk-khzyc41k.js";import"./chunk-gc1dzxee.js";import"./chunk-j8vd52sg.js";import"./chunk-jp6yn9mj.js";import"./chunk-z4te6223.js";import"./chunk-jsw5yby0.js";import{zu,Vo,Hu,Vu,Uo,is,Wo,Uu,qo,Wu,qu,Go,Ko,Xo}from"./chunk-3h2rpaps.js";import"./chunk-3tp481j5.js";import"./chunk-n5xbv1a9.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
package/dist/craft.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{as,Jo,Yo}from"./chunk-3dth76ce.js";import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import"./chunk-
|
|
2
|
+
import{as,Jo,Yo}from"./chunk-3dth76ce.js";import"./chunk-1gtrs8va.js";import"./chunk-10s16tad.js";import"./chunk-sxpnpvt5.js";import"./chunk-dvbgbd06.js";import"./chunk-66e4ga0z.js";import"./chunk-e030grrq.js";import"./chunk-x6pz1h3x.js";import"./chunk-khzyc41k.js";import"./chunk-gc1dzxee.js";import"./chunk-j8vd52sg.js";import"./chunk-jp6yn9mj.js";import"./chunk-z4te6223.js";import"./chunk-jsw5yby0.js";import{zu,Vo,Hu,Vu,Uo,is,Wo,Uu,qo,Wu,qu,Go,Ko,Xo}from"./chunk-3h2rpaps.js";import"./chunk-3tp481j5.js";import"./chunk-n5xbv1a9.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
package/dist/pwa.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{nr,Ue,ii,fc}from"./chunk-dayjd2sj.js";import{tr,cs,uc,dc,pc}from"./chunk-9g5sv1p6.js";import{ri,si,oi,cc,lc}from"./chunk-v3anfm9d.js";import{ue,_t,ls}from"./chunk-g8gzxhp8.js";import{ml,hl,yl,bl,Or,jd}from"./chunk-ygkwp4sf.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
|
|
3
|
-
Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-
|
|
3
|
+
Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-3dd57j7e.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|