@stacksjs/stx 0.2.570 → 0.2.571
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-01mxer9s.js +2 -0
- package/dist/chunk-09gtbb1w.js +2 -0
- package/dist/{chunk-v9gy8rda.js → chunk-0bt0fbs1.js} +59 -59
- package/dist/{chunk-k0shfsfx.js → chunk-0dz1b6a1.js} +3 -3
- package/dist/{chunk-3m01ym55.js → chunk-0g2ybnht.js} +2 -2
- package/dist/{chunk-jvm6agq7.js → chunk-0q6n3by0.js} +3 -3
- package/dist/chunk-15erabm6.js +2 -0
- package/dist/chunk-194qgkc9.js +2 -0
- package/dist/{chunk-fas9k7sw.js → chunk-1dg5qxg9.js} +5 -5
- package/dist/{chunk-tdv9np5t.js → chunk-1edvsndv.js} +2 -2
- package/dist/{chunk-brkq2s62.js → chunk-1n64749x.js} +3 -3
- package/dist/chunk-1z6c6dyk.js +2 -0
- package/dist/{chunk-36aj0yzt.js → chunk-232jswfm.js} +1 -1
- package/dist/chunk-279jv0yf.js +2 -0
- package/dist/chunk-2a1q5y6r.js +2 -0
- package/dist/{chunk-xfpfs9zq.js → chunk-2ads8rw5.js} +2 -2
- package/dist/chunk-2cqbyb8w.js +2 -0
- package/dist/{chunk-wjazf68a.js → chunk-2crxkm7j.js} +3 -3
- package/dist/{chunk-he2et28k.js → chunk-2jjff8kv.js} +5 -5
- package/dist/chunk-2jsnrfc8.js +2 -0
- package/dist/{chunk-ffxwsa94.js → chunk-2z0trbbm.js} +2 -2
- package/dist/{chunk-ywah1c30.js → chunk-36agnyhe.js} +7 -7
- package/dist/chunk-3gft8zng.js +2 -0
- package/dist/chunk-49gwmcrn.js +2 -0
- package/dist/{chunk-r17t24jr.js → chunk-4bgfpkwx.js} +3 -3
- package/dist/{chunk-dgr561sc.js → chunk-4easd8da.js} +11 -11
- package/dist/chunk-4ssg5xpq.js +64 -0
- package/dist/chunk-4wfr074d.js +2 -0
- package/dist/{chunk-cbyh8fhn.js → chunk-58tz7tmf.js} +3 -3
- package/dist/chunk-5afw7z6v.js +2 -0
- package/dist/{chunk-9d6dr0dr.js → chunk-5dmkkvs7.js} +2 -2
- package/dist/chunk-5fv4g4et.js +2 -0
- package/dist/{chunk-d8jdr1k4.js → chunk-5t1whxxt.js} +6 -6
- package/dist/{chunk-dkyqkkpj.js → chunk-5vw8493b.js} +3 -3
- package/dist/chunk-604rs9sq.js +2 -0
- package/dist/chunk-636sfxyj.js +2 -0
- package/dist/chunk-6aq3sm83.js +2 -0
- package/dist/chunk-6f4qrd0s.js +2 -0
- package/dist/chunk-6va5pe2m.js +2 -0
- package/dist/{chunk-r8h9b3f8.js → chunk-6wc2t6cd.js} +6 -6
- package/dist/{chunk-2t3bhp2j.js → chunk-707n4pbz.js} +5 -5
- package/dist/{chunk-5s555c1r.js → chunk-74xwzxwz.js} +3 -3
- package/dist/{chunk-nmy7mcbd.js → chunk-79vdkvhf.js} +5 -5
- package/dist/{chunk-mbj9dbrh.js → chunk-7bwkeake.js} +6 -6
- package/dist/chunk-7kh4p06d.js +2 -0
- package/dist/{chunk-8cs45k3f.js → chunk-7t3ykgsm.js} +2 -2
- package/dist/chunk-7xrrzqh7.js +2 -0
- package/dist/{chunk-724zsgbk.js → chunk-83fdt4yj.js} +6 -6
- package/dist/chunk-8jaw6exk.js +2 -0
- package/dist/chunk-8k61b4ae.js +2 -0
- package/dist/{chunk-chythmea.js → chunk-9k7bq97t.js} +1 -1
- package/dist/chunk-9yar9rfq.js +2 -0
- package/dist/{chunk-knpzph55.js → chunk-a6jq7hex.js} +3 -3
- package/dist/{chunk-mw2dravv.js → chunk-anjm087t.js} +5 -5
- package/dist/chunk-asbq9cgs.js +2 -0
- package/dist/{chunk-0zq4btre.js → chunk-b2q8bk8p.js} +2 -2
- package/dist/chunk-b7t8jejd.js +2 -0
- package/dist/chunk-b894fxfc.js +2 -0
- package/dist/{chunk-y3mmeywt.js → chunk-b9r88ysg.js} +2 -2
- package/dist/{chunk-0pzbg1bt.js → chunk-beqkrwt1.js} +2 -2
- package/dist/chunk-bm2q1srp.js +2 -0
- package/dist/{chunk-xjr67xvb.js → chunk-bpdsdbvg.js} +2 -2
- package/dist/{chunk-8zmahjqg.js → chunk-c4zpzxex.js} +6 -6
- package/dist/chunk-cgwyd9aq.js +2 -0
- package/dist/chunk-cvswrbzw.js +2 -0
- package/dist/{chunk-hvzznc50.js → chunk-cyg9w31a.js} +2 -2
- package/dist/chunk-d8206zbp.js +2 -0
- package/dist/chunk-dcpf6kas.js +15 -0
- package/dist/chunk-ensp20xk.js +2 -0
- package/dist/chunk-f10299sf.js +2 -0
- package/dist/chunk-f1apaqfk.js +2 -0
- package/dist/chunk-f4jh9vrj.js +2834 -0
- package/dist/{chunk-rrce2fyv.js → chunk-g66m3g2r.js} +1 -1
- package/dist/chunk-g6zeqvvb.js +2 -0
- package/dist/chunk-ghy82tsc.js +2 -0
- package/dist/{chunk-35kmebz9.js → chunk-gzgc8zk5.js} +4 -4
- package/dist/{chunk-qw4fjtt1.js → chunk-h4k3hyny.js} +2 -2
- package/dist/chunk-jqefcghh.js +31 -0
- package/dist/chunk-jw33eys8.js +2 -0
- package/dist/chunk-jwvzvapp.js +11 -0
- package/dist/{chunk-b76jbdtk.js → chunk-jze68d0z.js} +2 -2
- package/dist/chunk-k6wgh598.js +2 -0
- package/dist/{chunk-c1ys37c9.js → chunk-k7ht6tqe.js} +2 -2
- package/dist/{chunk-q94wdmdp.js → chunk-kgj852hx.js} +4 -4
- package/dist/{chunk-nebtks7j.js → chunk-kzjrgh0b.js} +10 -10
- package/dist/chunk-m2a1fxpb.js +2 -0
- package/dist/chunk-m6mxqepz.js +2 -0
- package/dist/chunk-mbmbaj0m.js +2 -0
- package/dist/{chunk-3tzkqf6e.js → chunk-mr9c2ej6.js} +2 -2
- package/dist/chunk-mzqyv7s5.js +33 -0
- package/dist/chunk-n61v7e3s.js +2 -0
- package/dist/chunk-n6qp05t9.js +2 -0
- package/dist/chunk-nn174xjh.js +2 -0
- package/dist/chunk-ntgy4e1q.js +2 -0
- package/dist/chunk-nw4axkpx.js +2 -0
- package/dist/chunk-p5chk3s9.js +2 -0
- package/dist/{chunk-w8vg3te3.js → chunk-phzs239m.js} +4 -4
- package/dist/{chunk-gwabvrc3.js → chunk-pnag11c4.js} +3 -3
- package/dist/{chunk-tc5zk2ka.js → chunk-pqcvh9pp.js} +1 -1
- package/dist/{chunk-a849hqna.js → chunk-pveafhzg.js} +2 -2
- package/dist/chunk-pw9verqx.js +2 -0
- package/dist/{chunk-rh606w0q.js → chunk-q79kmad5.js} +1 -1
- package/dist/chunk-q83w8edy.js +3 -0
- package/dist/{chunk-je0jxvmj.js → chunk-qcymqscj.js} +5 -5
- package/dist/{chunk-rtc17gy5.js → chunk-qt3x1sh3.js} +3 -3
- package/dist/chunk-qx6tr8mr.js +2 -0
- package/dist/{chunk-q8nw82pz.js → chunk-qzbzn1yf.js} +23 -23
- package/dist/{chunk-kaaxb9c5.js → chunk-r4w1cye7.js} +2 -2
- package/dist/{chunk-ebg20d8s.js → chunk-rfnr4xz6.js} +2 -2
- package/dist/{chunk-dajh1369.js → chunk-rrj5m9xv.js} +2 -2
- package/dist/{chunk-d4ybwtqt.js → chunk-s12b57m9.js} +2 -2
- package/dist/chunk-s6sf70ty.js +2 -0
- package/dist/{chunk-wemq37qe.js → chunk-sfwprq8q.js} +8 -8
- package/dist/chunk-ta8bhz27.js +2 -0
- package/dist/chunk-tc5r2vmw.js +2 -0
- package/dist/chunk-ts80ktq7.js +2 -0
- package/dist/{chunk-9k6r7f3c.js → chunk-tv784gv0.js} +4 -4
- package/dist/{chunk-3wcwtqx1.js → chunk-vp31ff54.js} +2 -2
- package/dist/{chunk-nz0krznq.js → chunk-vr36s2en.js} +2 -2
- package/dist/chunk-vyg8bvkt.js +2 -0
- package/dist/{chunk-9zf49tqg.js → chunk-wwhxgvr8.js} +4 -4
- package/dist/{chunk-ncq5n15k.js → chunk-xckzvbvn.js} +1 -1
- package/dist/chunk-xq2ck69k.js +2 -0
- package/dist/chunk-y4ajd836.js +2 -0
- package/dist/{chunk-j3vwyzvb.js → chunk-ydx3mfpp.js} +7 -7
- package/dist/{chunk-z3smaz4z.js → chunk-yk3wh2xv.js} +3 -3
- package/dist/{chunk-5hxsdkvp.js → chunk-ymawe0y5.js} +2 -2
- package/dist/{chunk-zckbg2vb.js → chunk-zd01r00t.js} +1 -1
- package/dist/chunk-zddzjd60.js +2 -0
- package/dist/chunk-zgxj1q7w.js +2 -0
- package/dist/chunk-zs7qhh40.js +2 -0
- package/dist/{chunk-qh0es7mk.js → chunk-zyk12484.js} +2 -2
- package/dist/cli.js +20 -20
- package/dist/client-script-bundler.js +1 -1
- package/dist/composable-loader.js +3 -2
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/env.d.ts +16 -0
- package/dist/env.js +12 -0
- package/dist/native/compiler/bundle.d.ts +2 -0
- package/dist/native/compiler/bundle.js +40 -11
- package/dist/process.js +3 -3
- package/dist/pwa.js +3 -3
- package/dist/ssg.js +8 -8
- package/dist/store-loader.js +4 -3
- package/package.json +5 -5
- package/dist/chunk-0mw3d5fc.js +0 -2
- package/dist/chunk-1sh80b1c.js +0 -2
- package/dist/chunk-1xyhdpbn.js +0 -2
- package/dist/chunk-20nrvpps.js +0 -2
- package/dist/chunk-2j7tr8wj.js +0 -2
- package/dist/chunk-2mxhp1yy.js +0 -2
- package/dist/chunk-32yj7sbw.js +0 -2
- package/dist/chunk-3ss3vfad.js +0 -2
- package/dist/chunk-4zp2zzch.js +0 -2
- package/dist/chunk-503w9dn3.js +0 -2
- package/dist/chunk-6m406xsn.js +0 -63
- package/dist/chunk-6yja1c8e.js +0 -2
- package/dist/chunk-74va4kza.js +0 -2
- package/dist/chunk-74w81h3v.js +0 -2
- package/dist/chunk-85j8cxfd.js +0 -2
- package/dist/chunk-8bwp2m95.js +0 -2
- package/dist/chunk-8rj08x1d.js +0 -2
- package/dist/chunk-8yn9wxzt.js +0 -31
- package/dist/chunk-98xp5rfe.js +0 -2
- package/dist/chunk-9ah35e2w.js +0 -2
- package/dist/chunk-9d1bs55s.js +0 -2
- package/dist/chunk-9rts16ta.js +0 -2
- package/dist/chunk-a2mztbta.js +0 -33
- package/dist/chunk-ajezxt0s.js +0 -2
- package/dist/chunk-bf572npc.js +0 -2
- package/dist/chunk-cqeccn7x.js +0 -2
- package/dist/chunk-dkyjw3hc.js +0 -3
- package/dist/chunk-dsdxa5x1.js +0 -2
- package/dist/chunk-ectcp21m.js +0 -2
- package/dist/chunk-ewcnyvcd.js +0 -2
- package/dist/chunk-ez7r18ef.js +0 -2
- package/dist/chunk-ffgsaf9e.js +0 -2
- package/dist/chunk-fnnhekdc.js +0 -2
- package/dist/chunk-g8b74qvn.js +0 -2
- package/dist/chunk-ge87hcgb.js +0 -2
- package/dist/chunk-gra2v7xz.js +0 -2
- package/dist/chunk-jg9fydw8.js +0 -2
- package/dist/chunk-k50k9zbw.js +0 -2
- package/dist/chunk-kz131809.js +0 -2834
- package/dist/chunk-mg8yjzkr.js +0 -2
- package/dist/chunk-mjkw1esn.js +0 -2
- package/dist/chunk-n0ra4mv3.js +0 -2
- package/dist/chunk-nspfk500.js +0 -2
- package/dist/chunk-nwyp2xaf.js +0 -2
- package/dist/chunk-pdk87hhe.js +0 -2
- package/dist/chunk-pxcmv1xz.js +0 -2
- package/dist/chunk-re030f77.js +0 -2
- package/dist/chunk-rn80ctkd.js +0 -2
- package/dist/chunk-s7dzs6yg.js +0 -2
- package/dist/chunk-t1tqn3xx.js +0 -2
- package/dist/chunk-tgwdk0gt.js +0 -15
- package/dist/chunk-tma2vac1.js +0 -2
- package/dist/chunk-v0chatw1.js +0 -2
- package/dist/chunk-v9mkambt.js +0 -2
- package/dist/chunk-vwjqbn5y.js +0 -2
- package/dist/chunk-wrvksj26.js +0 -2
- package/dist/chunk-wvjpvs89.js +0 -11
- package/dist/chunk-xkxwg6d4.js +0 -2
- package/dist/chunk-xspkz804.js +0 -2
- package/dist/chunk-xwqyw7zt.js +0 -2
- package/dist/chunk-y3kp87w1.js +0 -2
- package/dist/chunk-ya39wk58.js +0 -2
- package/dist/chunk-ygbdfzqn.js +0 -2
- package/dist/chunk-ypswj8sv.js +0 -2
- package/dist/chunk-yqzhev40.js +0 -2
- package/dist/chunk-z1tnn2pm.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{G,b,on,an,e,Et,cn,f,He,Tt,Ue,Ve,te,L,ue,J,d,ve,vi,ks,n,r,re,er,o,P,pe}from"./chunk-f4jh9vrj.js";import{Y,vn,se,I,It}from"./chunk-ydx3mfpp.js";import{nt,_n,gr,mr,hr,rt,st,ot,it,at,ct,_e}from"./chunk-phzs239m.js";import{Ie,go,oe,T,mo,Rr,Dn,ye,ho,ie}from"./chunk-jqefcghh.js";import{Mt}from"./chunk-vr36s2en.js";import{de}from"./chunk-2z0trbbm.js";import{a}from"./chunk-0g2ybnht.js";import{M}from"./chunk-q83w8edy.js";async function Xn(t){try{let s=await Bun.file(t).text(),i=Gn(s),p=Jn(s,t),c=Yn(s,i),l=Qn(s,i);return{file:t,metrics:i,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Gn(t){let s=t.split(`
|
|
3
3
|
`),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
|
|
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,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,
|
|
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 Yn(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 p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.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
|
|
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,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+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 Jn(t,s){let i=[],p=Jt(t,"if","endif");if(p>0)i.push({type:"error",category:"syntax",message:`Found ${p} 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 u=t.match(/<img[^>]*>/g);if(u){let y=u.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
|
+
`).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 Yn(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 p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.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 Qn(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 p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="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:p,recommendations:c}}function Jt(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function eo(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await Xn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=Zn(i);return{results:i,summary:c}}function Zn(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),p=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,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),h=[];if(p>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(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,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 sn=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 Ft(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(p){let c=await rr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,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 p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function dr(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){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,u;while(u=m.exec(l)){let h=u[1];if(sn.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=u[0].includes("async")?"async ":"";i[h]=`${v}${h}(${u[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(`
|
|
6
6
|
|
|
7
|
-
`)}function ur(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function
|
|
8
|
-
`)}function bt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Ht(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function
|
|
7
|
+
`)}function ur(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function fr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function yr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function br(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(p[h]!=="(")return null;let g=0,y="";for(let w=h;w<p.length;w++){let S=p[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,R,v]=w;s.push(R?`for (const [${R}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
|
|
8
|
+
`)}function bt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Ht(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function vr(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Zt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function wr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let R="";if(h(),t[u]==="<"){let k=bt(t,u,"<",">");if(k===-1)return null;R=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=bt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;for(let[B,D]of Bt(t.slice(u,k)))l[B]=D;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of Ht(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of Bt(x)){if(m.push(k),!B.startsWith("{")){let D=Zt(B);if(D)c[k]=D;continue}for(let[D,j]of Bt(B))if(D==="default")l[k]=j;else if(D==="type"){let E=Zt(j);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of Ht(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of Ht(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=vr(k),j=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),B!==-1)l[j]=k.slice(B+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:C}}function Bt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",h=p;while(p<s.length){let y=s[p];if(u){if(y==="\\")p++;else if(y===u)u=""}else if(y==="'"||y==='"'||y==="`")u=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;p++}let g=s.slice(h,p).trim();if(g)i.push([l[1],g]);p++}return i}function Tr(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Ee.resolve(Ee.dirname(s),x),B=Ee.relative(i,k);return`${v}${B.startsWith(".")?B:`./${B}`}${C}`})),""});let y=wr(l);if(y)u.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let R=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:h,declared:g}}function $r(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Cr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Er(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Pr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function Or(t,s,i){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await nr(p,"utf8"),l=lr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||sr(m),h=`${Ft(i.prefix||"stx")}-${Ft(m)}`,g=s.tag||l.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!ir(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([D,j])=>[D,en(D,j)])),S=$r(pr(c)),R=Cr(S.template),v=Tr(c,p,Ee.resolve(i.outputDir)),x=br(R.template);for(let D of v.propNames){if(w[D])continue;let j=v.defaults[D];w[D]=en(D,{type:ur(v.declared[D])??fr(j),...j===void 0?{}:{default:yr(j)}})}let C=l.methods||{},k=s.methods||{},B=dr(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:R.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...B},eventTypes:S.eventTypes,bindings:R.bindings,slots:Er(R.template),cssProperties:Pr(Qt(c)),scope:v,render:x}}function Ar(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
9
9
|
|
|
10
10
|
const escapeHTML = (value) => String(value ?? '')
|
|
11
11
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -410,21 +410,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
410
410
|
}
|
|
411
411
|
|
|
412
412
|
${l}
|
|
413
|
-
`}async function
|
|
414
|
-
`)?
|
|
415
|
-
`,"utf8"),h.push(k),k};await g("runtime.js",Ar());for(let x of l){if(await g(`${x.tag}.js`,Dr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Mr(x));if(t.css!==!1&&x.styles){let
|
|
413
|
+
`}async function to(t){let s=Ee.resolve(t.inputDir),i=Ee.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Or(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Ee.join(i,x);return await or(k,C.endsWith(`
|
|
414
|
+
`)?C:`${C}
|
|
415
|
+
`,"utf8"),h.push(k),k};await g("runtime.js",Ar());for(let x of l){if(await g(`${x.tag}.js`,Dr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Mr(x));if(t.css!==!1&&x.styles){let C=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(C):C)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
|
|
416
416
|
`);if(await g("index.js",y),await g("ssr.js",Ir(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
|
|
417
417
|
`)),await g("custom-elements.d.ts",_r(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
418
418
|
`)}
|
|
419
419
|
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
420
420
|
${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
|
|
421
|
-
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Lr(l),null,2));let S;if(t.css!==!1){let x=l.filter((
|
|
421
|
+
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Lr(l),null,2));let S;if(t.css!==!1){let x=l.filter((C)=>!C.shadowMode&&C.styles).map(tn).join(`
|
|
422
422
|
|
|
423
|
-
`);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let
|
|
424
|
-
`);throw AggregateError(k,`Failed to bundle component library${
|
|
425
|
-
${
|
|
426
|
-
`);throw AggregateError(x.logs,`Failed to bundle component library${
|
|
427
|
-
${
|
|
423
|
+
`);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Ee.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],B=k.map((D)=>String(D).trim()).filter(Boolean).join(`
|
|
424
|
+
`);throw AggregateError(k,`Failed to bundle component library${B?`
|
|
425
|
+
${B}`:""}`)}if(!x.success){let C=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
|
|
426
|
+
`);throw AggregateError(x.logs,`Failed to bundle component library${C?`
|
|
427
|
+
${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}var{serve:Vr}=globalThis.Bun;import Nt from"fs";import pt from"path";function vt(){return`
|
|
428
428
|
/* Theme selector for code blocks */
|
|
429
429
|
.theme-selector {
|
|
430
430
|
margin: 1rem 0;
|
|
@@ -509,7 +509,7 @@ else {
|
|
|
509
509
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
510
510
|
`,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function zt(){console.log(`
|
|
511
511
|
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Nr(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),zt()}function Ur(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
|
|
512
|
-
`)){let l=p.trim().toLowerCase();p="",Wr(l,t,s,i)}})}function Wr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ur(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Nr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Nt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await
|
|
512
|
+
`)){let l=p.trim().toLowerCase();p="",Wr(l,t,s,i)}})}function Wr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ur(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Nr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Nt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await pe(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],B=[...new Set([...x,...C])].map((D)=>`<option value="${D}"${D===v?" selected":""}>${D}</option>`).join(`
|
|
513
513
|
`);return l=`
|
|
514
514
|
<!DOCTYPE html>
|
|
515
515
|
<html lang="en">
|
|
@@ -663,7 +663,7 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
|
|
|
663
663
|
</head>
|
|
664
664
|
<body>
|
|
665
665
|
${kt(S)}
|
|
666
|
-
${wt(
|
|
666
|
+
${wt(B)}
|
|
667
667
|
|
|
668
668
|
${w}
|
|
669
669
|
|
|
@@ -677,7 +677,7 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
677
677
|
${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(`
|
|
678
678
|
${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
|
|
679
679
|
${e.yellow}Routes:${e.reset}`);let y=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
|
|
680
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(p)Nt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Nt.watch(w,{recursive:!0},async(
|
|
680
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(p)Nt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Nt.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function qr(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Xr}=globalThis.Bun;import Fe from"fs";import Se from"path";class dn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let h=u.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${y}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),i++}catch{this.clients.delete(p)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Kr(t,s={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
|
|
681
681
|
<script>
|
|
682
682
|
(function() {
|
|
683
683
|
// stx Hot Reload Client
|
|
@@ -876,10 +876,10 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Xe(t,s,i={}){let p=Kr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Pt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Ot(t){if(!ut)ut=new dn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import At from"path";var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${At.relative(At.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await
|
|
880
|
-
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+
|
|
879
|
+
`}function Xe(t,s,i={}){let p=Kr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Pt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Ot(t){if(!ut)ut=new dn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import At from"path";var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${At.relative(At.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await er(i,p);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 u=new Set;if(i.cache&&i.cachePath){let x=await on(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await se(()=>Bun.file(m).text(),"",(x)=>{throw new vn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new vn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=G.time("script-extraction",()=>{let x=h,C=te(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",D=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=E.match(/<script\b([^>]*)>/i),q=F?F[1]:"";if(/\bserver\b/i.test(q))B=_;else D.push(E)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:D}}),S={__filename:m,__dirname:At.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await se(()=>d(g,S,m),void 0,(x)=>{let C=new Y(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(I.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await G.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-cgwyd9aq.js"),C=x(w.join(`
|
|
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 J(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await an(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new Y(`Plugin processing failed: ${String(u)}`,m);if(I.log(h,{filePath:m,buildConfig:t.config}),It.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||M()?`<!DOCTYPE html>
|
|
883
883
|
<html lang="en">
|
|
884
884
|
<head>
|
|
885
885
|
<meta charset="UTF-8">
|
|
@@ -939,12 +939,12 @@ ${T}`}if(v=await X(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await an
|
|
|
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
|
|
943
|
-
${
|
|
942
|
+
</html>`,loader:"html"}}})}};async function $n(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Fe.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ut(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Fe.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let _={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},F=await Bun.build({entrypoints:[u],outdir:h,plugins:[_,ft],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 q=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(q.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await y())return!1;let S=Se.dirname(u);await Et(S);let R=i;try{if(R=await Ye(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 _=s.hmrPort||R+1;l=Ot({wsPort:_,verbose:!1}),m=l.start(_)}let v={},x=null,C;try{let{loadStxConfig:_}=await import("./chunk-6va5pe2m.js"),F=await _();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 q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:Z}=await import("./chunk-ensp20xk.js"),$e=F.broadcasting;await q($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=Se.join(process.cwd(),"channels.ts");if(Fe.existsSync(Oe))try{let ae=await Z(Oe);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-cvswrbzw.js"),D=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=Xr({port:R,async fetch(_){return Mt(_,await(async()=>{let F=new URL(_.url);if([h,Se.dirname(u),Se.join(process.cwd(),"public")].some((ae)=>B(Se.join(ae,F.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(_);if(ae.status!==404)return ae}catch{}if(v[F.pathname])try{return await v[F.pathname](_)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await D(_);if(q)return q;if(F.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Z=Se.join(h,F.pathname);if(Fe.existsSync(Z)&&Fe.statSync(Z).isFile()){let ae=Bun.file(Z),U=Se.extname(Z).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){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(ae,{headers:{"Content-Type":H}})}let $e=Se.dirname(u),he=Se.join($e,F.pathname);if(Fe.existsSync(he)&&Fe.statSync(he).isFile()){let ae=Bun.file(he),U=Se.extname(he).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){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(ae,{headers:{"Content-Type":H}})}let Oe=Se.join(process.cwd(),"public",F.pathname);if(Fe.existsSync(Oe)&&Fe.statSync(Oe).isFile()){let ae=Bun.file(Oe),U=Se.extname(Oe).toLowerCase(),H="application/octet-stream";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){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(ae,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
943
|
+
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
945
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${
|
|
946
|
-
${e.yellow}Routes:${e.reset}`);let
|
|
947
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(
|
|
945
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
946
|
+
${e.yellow}Routes:${e.reset}`);let E=Se.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
|
|
947
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(j.url.toString(),()=>{if(p)Fe.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let _=await Bun.file(u).text(),F=$t(_);await dt(R,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(p){let _=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let F=Fe.watch(_,{recursive:!0},async(q,Z)=>{if(!Z||Pt(Z))return;if(Rt(Z)){console.log(`${e.yellow}File ${e.bright}${Z}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),re();let $e=await y();if(await cn(S),c&&l)if($e)l.reload(Z);else l.error("Build failed - check console for details")}else if(Ct(Z)){if(console.log(`${e.cyan}CSS ${e.bright}${Z}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Z)}});process.on("SIGINT",()=>{if(F.close(),l)ht();j.stop(),process.exit(0)})}return!0}var{serve:Gr}=globalThis.Bun;import Ze from"fs";import Pe from"path";var pn=`
|
|
948
948
|
<script data-stx-helpers>
|
|
949
949
|
(function() {
|
|
950
950
|
'use strict'
|
|
@@ -1255,14 +1255,14 @@ else {
|
|
|
1255
1255
|
|
|
1256
1256
|
})()
|
|
1257
1257
|
</script>
|
|
1258
|
-
`;function fn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Pe.sep)}async function
|
|
1258
|
+
`;function fn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Pe.sep)}async function Rn(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Pe.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=fn(t.map((v)=>Pe.dirname(Pe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],h=async()=>{try{for(let v of t){let x=Pe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await pe(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),D=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,j=D?.defaultTheme||"github-dark",E=["github-dark"],_=D?.additionalThemes||[],q=[...new Set([...E,..._])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
|
|
1259
1259
|
`),Z=`
|
|
1260
1260
|
<!DOCTYPE html>
|
|
1261
1261
|
<html lang="en">
|
|
1262
1262
|
<head>
|
|
1263
1263
|
<meta charset="UTF-8">
|
|
1264
1264
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1265
|
-
<title>${un(
|
|
1265
|
+
<title>${un(B.title||Pe.basename(x))}</title>
|
|
1266
1266
|
<!-- Syntax highlighting styles -->
|
|
1267
1267
|
<style id="syntax-theme">
|
|
1268
1268
|
:root {
|
|
@@ -1408,8 +1408,8 @@ else {
|
|
|
1408
1408
|
</style>
|
|
1409
1409
|
</head>
|
|
1410
1410
|
<body>
|
|
1411
|
-
${kt(
|
|
1412
|
-
${wt(
|
|
1411
|
+
${kt(B)}
|
|
1412
|
+
${wt(q)}
|
|
1413
1413
|
|
|
1414
1414
|
${k}
|
|
1415
1415
|
|
|
@@ -1418,26 +1418,26 @@ else {
|
|
|
1418
1418
|
</script>
|
|
1419
1419
|
</body>
|
|
1420
1420
|
</html>
|
|
1421
|
-
`,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(
|
|
1422
|
-
${
|
|
1423
|
-
</head>`);else
|
|
1424
|
-
</head>`);return new Response(
|
|
1421
|
+
`,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(_)=>({path:_.path,external:!0}))}},B;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,de(E.logs,x));continue}let _=E.outputs.find((F)=>F.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
|
|
1422
|
+
${de(E,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:E,params:_}=gr(j,{page:!0});u.push({pattern:E,paramNames:_,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:B,fileType:"stx"}}else m[j||"/"]={filePath:x,content:B,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,de(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=Gr({port:y,async fetch(v){let x=new URL(v.url),C=Pe.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(C)&&Ze.statSync(C).isFile()){let D=Bun.file(C),j=Pe.extname(C).toLowerCase(),E="application/octet-stream";if(j===".ts"||j===".tsx"){let _=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await D.text(),q=_.transformSync(F);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let D of u){let j=x.pathname.match(D.pattern);if(j){let E=m[D.routeTemplate];if(E){let _={};for(let Z=0;Z<D.paramNames.length;Z++)_[D.paramNames[Z]]=decodeURIComponent(j[Z+1]);let F=E.content,q=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${q}
|
|
1423
|
+
</head>`);else F=q+F;k={...E,content:F}}break}}if(k)return f(k.content).then((D)=>{if(D.includes("</head>"))D=D.replace("</head>",`${pn}
|
|
1424
|
+
</head>`);return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let B=Pe.join(c,x.pathname);if(Ze.existsSync(B)&&Ze.statSync(B).isFile()){let D=Bun.file(B),j=Pe.extname(B).toLowerCase(),E="text/plain";if(j===".ts"||j===".tsx"){let _=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await D.text(),q=_.transformSync(F);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(D,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let D=oe(v);return f(m["/"].content).then((j)=>{if(D){let E=j.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=j.match(/<title[^>]*>([\s\S]*?)<\/title>/i),F=_?_[1]:"",q=`<!DOCTYPE html><html><head><title>${un(F)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(q,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":Ie,Pragma:"no-cache",Expires:"0"}})}}return new Response(j,{headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
|
|
1425
1425
|
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
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
|
-
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),ne(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Jr}=globalThis.Bun;import xe from"fs";import ie from"path";async function mn(t){try{return Tt(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function Rn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-s7dzs6yg.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-1sh80b1c.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!xe.existsSync(T)&&!g._layerPageDirs?.some((O)=>xe.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],_=[];for(let{dir:O,prefix:F}of H)if(xe.existsSync(O)){let z=N(ie.dirname(O),{pagesDir:ie.basename(O)});for(let W of z){let we=F==="/"?W.pattern:`${F}${W.pattern==="/"?"":W.pattern}`;_.push({route:{...W,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await fo(u,s.stxOptions?.shell),L){if(R=await $r(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}rt(),await ot(u);let B=st();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let K={},Z=null;try{let{loadStxConfig:O}=await import("./chunk-s7dzs6yg.js"),F=await O(u);if(F?.apiRouter)Z=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){K=F.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:W}=await import("./chunk-ffgsaf9e.js"),we=F.broadcasting;await z(we);let Ne=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ne}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let te=await W(Ge);console.log(`${e.blue}Loaded ${e.bright}${te} broadcast channel${te!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(te){console.warn(`${e.yellow}Failed to load channels.ts: ${te.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,ae=async(O)=>{let F=gr(T,O);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let W=z.outputs.find((we)=>we.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,j=async(O,F)=>{try{let{processDirectives:z,extractVariables:W,defaultConfig:we,loadStxConfig:Ne,injectRouterScript:Ge}=await import("./chunk-s7dzs6yg.js"),{checkCache:te,cacheTemplate:Q,readFileCached:V,templateCache:G}=await import("./chunk-ge87hcgb.js"),ke=await Ne(u),Je=(ce)=>{if(!ce)return ce;if(ie.isAbsolute(ce))return ce;return ie.resolve(u,ce)},M={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,pe=M.cache!==!1;if(pe&&be){let ce=G.get(O.filePath);if(ce)try{if((await xe.promises.stat(O.filePath)).mtime.getTime()<=ce.mtime){let Be=!0;for(let Re of ce.dependencies){if(!xe.existsSync(Re)){Be=!1;break}if((await xe.promises.stat(Re)).mtime.getTime()>ce.mtime){Be=!1;break}}if(Be){let Re=ce.output;if(R)Re=ye(Re,{preserveHead:!0});let gt=U.get(O.filePath);return{route:O,content:Re,status:gt?.status??await mn(O.filePath),headers:gt?.headers}}}}catch{}let Le=await te(O.filePath,M);if(Le){let je=Le;if(R)je=ye(je,{preserveHead:!0});let Be=U.get(O.filePath);return{route:O,content:je,status:Be?.status??await mn(O.filePath),headers:Be?.headers}}}let ge=pe?await V(O.filePath):await Bun.file(O.filePath).text(),Ce=Tt(ge),{classifyAllScripts:Y}=await import("./chunk-s7dzs6yg.js"),Me=Y(ge),We=Me.server.map((ce)=>ce.content),fe=ge;for(let ce of Me.server)fe=fe.replace(ce.fullTag,"");let me={__filename:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let ce of We)try{await W(ce,me,O.filePath)}catch(Le){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Le?.message||Le)}let Ke=new Set,Ae;if(s.profile){let ce=performance.now();Ae=await z(fe,me,O.filePath,M,Ke);let Le=performance.now()-ce,je=ie.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Le.toFixed(2)}ms`)}else Ae=await z(fe,me,O.filePath,M,Ke);if(!R)Ae=await Ge(Ae,{router:M.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-3ss3vfad.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Le,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Le;return`<script${je}>${ce(Be,me)}</script>`})}if(R)Ae=ye(Ae,{preserveHead:!0});if(pe&&be)await Q(O.filePath,Ae,Ke,M);let{extractStreamBoundaries:Kn}=await import("./chunk-1xyhdpbn.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=me.streamBoundaries||{},Le={...M,autoShell:!1},je=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof ce[Re]==="function"?await ce[Re]():void 0;return z(mt[Re],{...me,$boundary:gt},O.filePath,Le,new Set)}})),Be=new Set(je.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!Be.has(Re.id)),...je]}if(lt&<.length>0)Oe.add(O.pattern);else lt=void 0;let Kt=Ue(me),Xt=Ve(me);if(be)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,z),null}},ze=8,qe=async()=>{he.clear(),I.clear();for(let O=0;O<k.length;O+=ze){let F=k.slice(O,O+ze),z=await Promise.all(F.map((W)=>j(W)));for(let W of z)if(W)he.set(W.route.pattern,W)}for(let O=0;O<_.length;O+=ze){let F=_.slice(O,O+ze),z=await Promise.all(F.map(({route:W})=>j(W)));for(let W of z)if(W)I.set(W.route.pattern,W)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Et(u);let et=i;try{if(et=await Ye(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 O=s.hmrPort||et+1;l=Ot({wsPort:O,verbose:!1}),m=l.start(O)}let _t=(O,F)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${W}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+O};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Jr({port:et,async fetch(O){let F=new URL(O.url),z=g?.publicDir||"public",W=ie.join(u,z,F.pathname),we=ie.join(u,F.pathname),Ne=ie.join($e,F.pathname);if([W,we,Ne].some((M)=>w(M,u,S)))return new Response("Not Found",{status:404});let[Ge,te,Q]=await Promise.all([xe.promises.stat(W).catch(()=>null),xe.promises.stat(we).catch(()=>null),xe.promises.stat(Ne).catch(()=>null)]);if(Ge?.isFile()&&!w(W,u,S))return Wt(W);if(te?.isFile()&&!w(we,u,S))return Wt(we);if(Q?.isFile()&&!w(Ne,u,S))return Wt(Ne);if(F.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,pe={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${M}.stx`),pe,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-ez7r18ef.js"),be=await M(O,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(Z)try{let M=await Z.handleRequest(O);if(M.status!==404)return M}catch{}if(K[F.pathname])try{return await K[F.pathname](O)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await C(O);if(V)return V;let G=Cn(F.pathname,k);if(G){let M=he.get(G.route.pattern),be=Oe.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||be){let pe=await j(G.route,G.params);if(pe)M=pe}if(M){let pe=M.status??200,ge=M.headers??{},Ce=(G.route.filePath?He(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let We=await ae(404);if(We){let fe=We;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=it(F.pathname,G.params,Ce,F.search),We=at(Me,null,O,{isServer:!0}),fe=await ct(Ce.middleware,We);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Ae=new Headers(fe.responseHeaders);return Ae.set("Location",me),new Response(null,{status:Ke,headers:Ae})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${me}</head>`)}}let Y=M.content;if(R&&go(O)){let Me=_e(Y),We=de(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?po(fe[1].trim()):"";if(Object.keys(G.params).length>0)Y=_t(Y,G.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=oe(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":We?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[bi]:Ss(),...E(),"Cache-Control":Ie}})}if(R)Y=On(R,Y);if(Object.keys(G.params).length>0)Y=_t(Y,G.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.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 Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.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 Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:We}=await import("./chunk-1xyhdpbn.js");return We(Me(Y,M.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",...E(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(_.length>0){let M=_.map((pe)=>pe.route),be=Cn(F.pathname,M);if(be){let pe=I.get(be.route.pattern);if(pe){let ge=pe.content;if(R)ge=On(R,ge);if(Object.keys(be.params).length>0)ge=_t(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of H)if(pe!=="/"&&F.pathname.startsWith(pe)){let ge=I.get(pe)||I.get(pe+"/");if(ge){let Ce=ge.content;if(R)Ce=On(R,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(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(nt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let M=ke.content;if(M=await f(M,u),c)M=Xe(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 Je=await ae(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1428
|
+
${e.yellow}Routes:${e.reset}`);let S=new Set(u.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 u){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(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){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}`),ve.clear(),re(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Jr}=globalThis.Bun;import xe from"fs";import ne from"path";async function mn(t){try{return Tt(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),i=ne.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function An(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ne.resolve(t),{loadStxConfig:h}=await import("./chunk-6va5pe2m.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-cvswrbzw.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(u,S),v=g.root&&g.root!=="."?ne.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",C=ne.join(v,x);if(!xe.existsSync(C)&&!g._layerPageDirs?.some((O)=>xe.existsSync(O)))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||[],D=[];for(let{dir:O,prefix:z}of B)if(xe.existsSync(O)){let N=L(ne.dirname(O),{pagesDir:ne.basename(O)});for(let W of N){let we=z==="/"?W.pattern:`${z}${W.pattern==="/"?"":W.pattern}`;D.push({route:{...W,pattern:we},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,_=null;if(s.stxOptions?.shell!==!1){if(_=await mo(u,s.stxOptions?.shell),_){if(E=await Rr(_,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}rt(),await ot(u);let F=st();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let q={},Z=null;try{let{loadStxConfig:O}=await import("./chunk-6va5pe2m.js"),z=await O(u);if(z?.apiRouter)Z=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){q=z.apiRoutes;let N=Object.keys(q).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:W}=await import("./chunk-ensp20xk.js"),we=z.broadcasting;await N(we);let Ne=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ne}/ws${e.reset}`);let Ge=ne.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let ee=await W(Ge);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(u,"output");xe.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,ae=async(O)=>{let z=mr(C,O);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let W=N.outputs.find((we)=>we.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,H=async(O,z)=>{try{let{processDirectives:N,extractVariables:W,defaultConfig:we,loadStxConfig:Ne,injectRouterScript:Ge}=await import("./chunk-6va5pe2m.js"),{checkCache:ee,cacheTemplate:Q,readFileCached:V,templateCache:K}=await import("./chunk-2cqbyb8w.js"),ke=await Ne(u),Je=(ce)=>{if(!ce)return ce;if(ne.isAbsolute(ce))return ce;return ne.resolve(u,ce)},A={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)A.debug=!0;A.partialsDir=Je(A.partialsDir),A.componentsDir=Je(A.componentsDir),A.layoutsDir=Je(A.layoutsDir),A.storesDir=Je(A.storesDir||"stores"),A.cachePath=Je(A.cachePath)??a(u,"cache");let be=!z&&!s.profile,le=A.cache!==!1;if(le&&be){let ce=K.get(O.filePath);if(ce)try{if((await xe.promises.stat(O.filePath)).mtime.getTime()<=ce.mtime){let Be=!0;for(let Re of ce.dependencies){if(!xe.existsSync(Re)){Be=!1;break}if((await xe.promises.stat(Re)).mtime.getTime()>ce.mtime){Be=!1;break}}if(Be){let Re=ce.output;if(E)Re=ye(Re,{preserveHead:!0});let gt=U.get(O.filePath);return{route:O,content:Re,status:gt?.status??await mn(O.filePath),headers:gt?.headers}}}}catch{}let Le=await ee(O.filePath,A);if(Le){let je=Le;if(E)je=ye(je,{preserveHead:!0});let Be=U.get(O.filePath);return{route:O,content:je,status:Be?.status??await mn(O.filePath),headers:Be?.headers}}}let ge=le?await V(O.filePath):await Bun.file(O.filePath).text(),Ce=Tt(ge),{classifyAllScripts:X}=await import("./chunk-6va5pe2m.js"),Me=X(ge),We=Me.server.map((ce)=>ce.content),fe=ge;for(let ce of Me.server)fe=fe.replace(ce.fullTag,"");let me={__filename:O.filePath,__dirname:ne.dirname(O.filePath),__stx_options:A,params:z??{},__stx_runtime_head:{}};for(let ce of We)try{await W(ce,me,O.filePath)}catch(Le){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Le?.message||Le)}let Ke=new Set,Ae;if(s.profile){let ce=performance.now();Ae=await N(fe,me,O.filePath,A,Ke);let Le=performance.now()-ce,je=ne.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Le.toFixed(2)}ms`)}else Ae=await N(fe,me,O.filePath,A,Ke);if(!E)Ae=await Ge(Ae,{router:A.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-cgwyd9aq.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Le,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Le;return`<script${je}>${ce(Be,me)}</script>`})}if(E)Ae=ye(Ae,{preserveHead:!0});if(le&&be)await Q(O.filePath,Ae,Ke,A);let{extractStreamBoundaries:Kn}=await import("./chunk-pw9verqx.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=me.streamBoundaries||{},Le={...A,autoShell:!1},je=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof ce[Re]==="function"?await ce[Re]():void 0;return N(mt[Re],{...me,$boundary:gt},O.filePath,Le,new Set)}})),Be=new Set(je.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!Be.has(Re.id)),...je]}if(lt&<.length>0)Oe.add(O.pattern);else lt=void 0;let Kt=Ue(me),Xt=Ve(me);if(be)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},ze=8,qe=async()=>{he.clear(),j.clear();for(let O=0;O<k.length;O+=ze){let z=k.slice(O,O+ze),N=await Promise.all(z.map((W)=>H(W)));for(let W of N)if(W)he.set(W.route.pattern,W)}for(let O=0;O<D.length;O+=ze){let z=D.slice(O,O+ze),N=await Promise.all(z.map(({route:W})=>H(W)));for(let W of N)if(W)j.set(W.route.pattern,W)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Et(u);let et=i;try{if(et=await Ye(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 O=s.hmrPort||et+1;l=Ot({wsPort:O,verbose:!1}),m=l.start(O)}let _t=(O,z)=>{let W=`<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(O.includes("</head>"))return O.replace("</head>",`${W}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+O};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Jr({port:et,async fetch(O){let z=new URL(O.url),N=g?.publicDir||"public",W=ne.join(u,N,z.pathname),we=ne.join(u,z.pathname),Ne=ne.join($e,z.pathname);if([W,we,Ne].some((A)=>w(A,u,S)))return new Response("Not Found",{status:404});let[Ge,ee,Q]=await Promise.all([xe.promises.stat(W).catch(()=>null),xe.promises.stat(we).catch(()=>null),xe.promises.stat(Ne).catch(()=>null)]);if(Ge?.isFile()&&!w(W,u,S))return Wt(W);if(ee?.isFile()&&!w(we,u,S))return Wt(we);if(Q?.isFile()&&!w(Ne,u,S))return Wt(Ne);if(z.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(z.pathname.slice(16));if(A)try{let be=`<${A} />`,le={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ne.join(u,"components",`${A}.stx`),le,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-1z6c6dyk.js"),be=await A(O,{publicDir:ne.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(Z)try{let A=await Z.handleRequest(O);if(A.status!==404)return A}catch{}if(q[z.pathname])try{return await q[z.pathname](O)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(O);if(V)return V;let K=_n(z.pathname,k);if(K){let A=he.get(K.route.pattern),be=Oe.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||be){let le=await H(K.route,K.params);if(le)A=le}if(A){let le=A.status??200,ge=A.headers??{},Ce=(K.route.filePath?He(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:K.params})){let We=await ae(404);if(We){let fe=We;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=it(z.pathname,K.params,Ce,z.search),We=at(Me,null,O,{isServer:!0}),fe=await ct(Ce.middleware,We);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Ae=new Headers(fe.responseHeaders);return Ae.set("Location",me),new Response(null,{status:Ke,headers:Ae})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${me}</head>`)}}let X=A.content;if(E&&ho(O)){let Me=_e(X),We=ue(X),fe=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?go(fe[1].trim()):"";if(Object.keys(K.params).length>0)X=_t(X,K.params);X=await f(X,u);let Ke=g?.router?.container||"main";return X=ie(X,Ke),new Response(X,{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":We?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[vi]:ks(),...T(),"Cache-Control":Ie}})}if(E)X=Dn(E,X);if(Object.keys(K.params).length>0)X=_t(X,K.params);if(X=await f(X,u),c)X=Xe(X,m);if(s.native)if(X.includes("<head>"))X=X.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 X="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+X;if(s.titlebarHidden)if(X.includes("<head>"))X=X.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 X=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${X}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:We}=await import("./chunk-pw9verqx.js");return We(Me(X,A.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(D.length>0){let A=D.map((le)=>le.route),be=_n(z.pathname,A);if(be){let le=j.get(be.route.pattern);if(le){let ge=le.content;if(E)ge=Dn(E,ge);if(Object.keys(be.params).length>0)ge=_t(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{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 ge=j.get(le)||j.get(le+"/");if(ge){let Ce=ge.content;if(E)Ce=Dn(E,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(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(nt(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let A=ke.content;if(A=await f(A,u),c)A=Xe(A,m);if(s.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let A=Je;if(A=await f(A,u),c)A=Xe(A,m);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let z=await ae(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1430
1430
|
${O.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
|
-
${e.yellow}Routes:${e.reset}`);let jt=[...
|
|
1434
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let O,
|
|
1435
|
-
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=
|
|
1433
|
+
${e.yellow}Routes:${e.reset}`);let jt=[...hr(k,u)];for(let{route:O}of D)jt.push(`${O.pattern}`);if(jt.forEach((O,z)=>{let W=z===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${W}${e.reset}${O}`)}),console.log(`
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let O,z=ne.join(C,"index.stx");if(xe.existsSync(z)){let W=await Bun.file(z).text();O=$t(W)}let N=g?.app?.window??{};await dt(et,{title:g?.app?.head?.title||ne.basename(u)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),z=(ee)=>{let Q=ee.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,W=()=>{let ee=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ne.dirname(Q))??[]].filter((Q)=>xe.existsSync(Q)).map((Q)=>xe.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let V of Object.values(Q.resources)){if(!xe.existsSync(V))continue;let K=xe.realpathSync(V);if(![...ee].some((ke)=>K===ke||K.startsWith(`${ke}${ne.sep}`)))ee.add(K)}for(let[Q,V]of N)if(!ee.has(Q))V.close(),N.delete(Q);for(let Q of ee)if(!N.has(Q)&&xe.existsSync(Q))N.set(Q,xe.watch(Q,{recursive:!0},(V,K)=>{Ne(Q,V,K).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),Ne=(ee,Q,V)=>(we=we.catch(()=>{}).then(()=>Ge(ee,Q,V)),we),Ge=async(ee,Q,V)=>{if(!V||Pt(V))return;if(Rt(V)){if(g._layerGraph){let K=await h(u);Object.assign(g,K),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[C,...K._layerPageDirs.slice(1)]:void 0})),W()}if(O(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),c&&l)l.reload(V)}else if(z(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ve.clear(),re();try{let{invalidateFileCache:K,templateCache:ke}=await import("./chunk-2cqbyb8w.js");K(ne.resolve(ee,V)),ke.delete(ne.resolve(ee,V))}catch{}if(_&&V){if(ne.resolve(ee,V)===_||ne.basename(_)===V){let ke=await Rr(_,s.stxOptions||{});if(ke)E=ke}}if(await qe(),await cn(u),c&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ve.clear(),re();try{let{invalidateFileCache:K,templateCache:ke}=await import("./chunk-2cqbyb8w.js");K(ne.resolve(ee,V)),ke.delete(ne.resolve(ee,V))}catch{}if(await qe(),c&&l)l.reload(V)}}else if(Ct(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),c&&l)l.updateCss(V)}};W(),process.on("SIGINT",()=>{for(let ee of N.values())ee.close();if(l)ht();Lt.stop(),process.exit(0)})}return!0}import Vt from"fs";import yt from"path";async function Yr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let p=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(p))!==null){let u=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=u.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=u.split(`
|
|
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 u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[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 Qr(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((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Zr(t,s=!1,i){let p=yt.basename(t,".stx"),c=await Yr(t),l=await Qr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let u=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
|
|
1437
1437
|
`);m=`<${p}
|
|
1438
1438
|
${u}
|
|
1439
|
-
/>`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function gn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await gn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function
|
|
1440
|
-
`).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let
|
|
1439
|
+
/>`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function gn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await gn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function io(t,s){try{if(!await r(t))return[];let i=await gn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),u=!!m,h=m?.tag,g=await Zr(l,u,h);p.push(g)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function ao(t){try{if(!await r(t))return[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=u?u[1].split(`
|
|
1440
|
+
`).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=R.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function co(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1441
1441
|
<p>Welcome, {{ user.name }}!</p>
|
|
1442
1442
|
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
1443
1443
|
<p>Welcome back!</p>
|
|
@@ -1457,7 +1457,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.
|
|
|
1457
1457
|
<p>Page {{ page }}</p>
|
|
1458
1458
|
@endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
|
|
1459
1459
|
{{ This will be displayed as-is }}
|
|
1460
|
-
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function
|
|
1460
|
+
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function lo(t=[],s=[],i=[],p){let c=`# stx Documentation
|
|
1461
1461
|
|
|
1462
1462
|
`;if(p)c+=`${p}
|
|
1463
1463
|
|
|
@@ -1499,7 +1499,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.
|
|
|
1499
1499
|
|
|
1500
1500
|
`,c+=`#### Example
|
|
1501
1501
|
|
|
1502
|
-
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function
|
|
1502
|
+
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function po(t=[],s=[],i=[],p){let c=`<!DOCTYPE html>
|
|
1503
1503
|
<html lang="en">
|
|
1504
1504
|
<head>
|
|
1505
1505
|
<meta charset="UTF-8">
|
|
@@ -1570,15 +1570,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.
|
|
|
1570
1570
|
<td>@${l.name}</td>
|
|
1571
1571
|
<td>${l.description||"-"}</td>
|
|
1572
1572
|
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1573
|
-
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function
|
|
1574
|
-
`;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=
|
|
1573
|
+
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function uo(t=[],s=[],i=[],p){return JSON.stringify({components:t,templates:s,directives:i,extraContent:p||""},null,2)}async function fo(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Vt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await io(s,p),console.log(`Found ${u.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await ao(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await co(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=lo(u,h,g,w),R="md";break;case"html":S=po(u,h,g,w),R="html";break;case"json":S=uo(u,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function no(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||P.componentsDir,p=t.templatesDir||".";return fo({componentsDir:i,templatesDir:p,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var yn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function xr(t,s={}){let i={...yn,...s};if(t.trim()==="")return`
|
|
1574
|
+
`;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=xo(p,i),p=ko(p,i),p=vo(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
|
|
1575
1575
|
`).replace(/\r/g,`
|
|
1576
1576
|
`),!p.endsWith(`
|
|
1577
1577
|
`))p+=`
|
|
1578
|
-
`;return p}function
|
|
1578
|
+
`;return p}function ro(t,s={}){let i={...yn,...s};if(t.trim()==="")return`
|
|
1579
1579
|
`;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,h)=>{let g=u.split(`
|
|
1580
|
-
`),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let
|
|
1581
|
-
`),v=
|
|
1580
|
+
`),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let C=x.match(/^( *)/);return C?C[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
|
|
1581
|
+
`),v=xr(S,i).trimEnd().split(`
|
|
1582
1582
|
`).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
|
|
1583
1583
|
`);return`${l}\`\`\`${m}
|
|
1584
1584
|
${v}
|
|
@@ -1586,7 +1586,7 @@ ${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replac
|
|
|
1586
1586
|
`).replace(/\r/g,`
|
|
1587
1587
|
`),!p.endsWith(`
|
|
1588
1588
|
`))p+=`
|
|
1589
|
-
`;return p}function
|
|
1589
|
+
`;return p}function bo(t){let s=t,i=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1590
1590
|
$1
|
|
1591
1591
|
`),s=s.replace(/(@end\w+)/g,`
|
|
1592
1592
|
$1
|
|
@@ -1600,10 +1600,10 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let h=u.substring(Math.max
|
|
|
1600
1600
|
`}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
|
|
1601
1601
|
`),s=s.split(`
|
|
1602
1602
|
`).map((c)=>c.trim()).join(`
|
|
1603
|
-
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function
|
|
1604
|
-
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let
|
|
1605
|
-
`)}function
|
|
1606
|
-
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import bn from"fs";import qt from"path";async function
|
|
1603
|
+
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function xo(t,s){let p=bo(t).split(`
|
|
1604
|
+
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let R=y===">";if(hn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&So(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),B=y.startsWith("<!--"),D=y.startsWith("</"),j=y.startsWith("<")&&!D&&!B&&!k,E=y.includes("/>")||wo(y),_=hn(y);if(D||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(u.repeat(F)+y);if(j&&!E&&!_&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
1605
|
+
`)}function vo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function wo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function hn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function So(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function ko(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
|
|
1606
|
+
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import bn from"fs";import qt from"path";async function so(t="index.stx",s={}){try{let i=s.force||!1,p=qt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(p);if(!bn.existsSync(c))bn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=qt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=xn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=xn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function xn(t){switch(t){case"basic":return wn();case"component":return To();case"layout":return $o();case"blog":return Co();case"api":return Ro();case"app":return Eo();default:return wn()}}function wn(){return`<script>
|
|
1607
1607
|
const title = "My stx Page"
|
|
1608
1608
|
const description = "A page built with stx"
|
|
1609
1609
|
const features = [
|
|
@@ -1628,7 +1628,7 @@ const features = [
|
|
|
1628
1628
|
</div>
|
|
1629
1629
|
@endforeach
|
|
1630
1630
|
</main>
|
|
1631
|
-
@endsection`}function
|
|
1631
|
+
@endsection`}function To(){return`{{-- Component: Card --}}
|
|
1632
1632
|
{{-- Props: title, variant, collapsible --}}
|
|
1633
1633
|
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1634
1634
|
<script>
|
|
@@ -1673,7 +1673,7 @@ const features = [
|
|
|
1673
1673
|
.card.collapsed .card__toggle { transform: rotate(-90deg); }
|
|
1674
1674
|
.card__body { padding: 1rem; }
|
|
1675
1675
|
.card.collapsed .card__body { display: none; }
|
|
1676
|
-
</style>`}function
|
|
1676
|
+
</style>`}function $o(){return`<!DOCTYPE html>
|
|
1677
1677
|
<html lang="en">
|
|
1678
1678
|
<head>
|
|
1679
1679
|
<meta charset="UTF-8">
|
|
@@ -1724,7 +1724,7 @@ const features = [
|
|
|
1724
1724
|
|
|
1725
1725
|
@yield('scripts')
|
|
1726
1726
|
</body>
|
|
1727
|
-
</html>`}function
|
|
1727
|
+
</html>`}function Co(){return`<script>
|
|
1728
1728
|
// Article metadata
|
|
1729
1729
|
const title = "My Blog Post"
|
|
1730
1730
|
const author = "Your Name"
|
|
@@ -1769,7 +1769,7 @@ const features = [
|
|
|
1769
1769
|
<p>Wrap up your thoughts here.</p>
|
|
1770
1770
|
</div>
|
|
1771
1771
|
</article>
|
|
1772
|
-
@endsection`}function
|
|
1772
|
+
@endsection`}function Ro(){return`<script>
|
|
1773
1773
|
// API endpoint configuration
|
|
1774
1774
|
const endpoint = "/api/data"
|
|
1775
1775
|
const method = "GET"
|
|
@@ -1804,7 +1804,7 @@ const features = [
|
|
|
1804
1804
|
}
|
|
1805
1805
|
@else
|
|
1806
1806
|
{{ JSON.stringify(data, null, 2) }}
|
|
1807
|
-
@endif`}function
|
|
1807
|
+
@endif`}function Eo(){return`<!DOCTYPE html>
|
|
1808
1808
|
<html lang="en">
|
|
1809
1809
|
<head>
|
|
1810
1810
|
<meta charset="UTF-8">
|
|
@@ -2029,5 +2029,5 @@ const features = [
|
|
|
2029
2029
|
})();
|
|
2030
2030
|
</script>
|
|
2031
2031
|
</body>
|
|
2032
|
-
</html>`}var
|
|
2033
|
-
`)}export{
|
|
2032
|
+
</html>`}var oo="f9c3713";function Qi(t){return t}function ea(t){return t}function Qs(t,s){let i=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}import De from"fs";import Te from"path";function Mn(t){try{return De.statSync(t).mtimeMs}catch{return null}}function Dt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ai(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Ln(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(De.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var In=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=De.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Mi(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=De.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of In){let S=Te.join(u,w),R=Di(S);if(R!==null)p.push({name:w,version:R,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=De.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=De.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=Te.join(S,x.name,"node_modules");if(De.existsSync(C))l(C,h+1)}continue}let R=Te.join(S,"node_modules");if(De.existsSync(R))l(R,h+1)}}let m=Te.join(i,"node_modules");if(De.existsSync(m))l(m,0);return p}function _i(t){let s=[];for(let i of In){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function Sr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ai,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of _i(Mi(s)))c.push(h);let u=Ln(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>De.existsSync(v))||null,y=Mn(h),w=g?Mn(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Dt(w,p)}) is OLDER than src/signals.ts (${Dt(y,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Dt(y,p)}, dist ${Dt(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=De.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=De.realpathSync(S)}catch{}let x=(()=>{try{return De.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function kr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
|
|
2033
|
+
`)}export{Qs,eo,to,no,xr,ro,so,oo,Qi,ea,Sr,kr,$n,Rn,An};
|