@stacksjs/stx 0.2.858 → 0.2.861
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/body-close.d.ts +13 -0
- package/dist/body-close.js +8 -0
- package/dist/{chunk-s322kcw7.js → chunk-02css3vk.js} +5 -5
- package/dist/chunk-0hqr6bff.js +2 -0
- package/dist/{chunk-wskdnfh9.js → chunk-121cgm3s.js} +4 -4
- package/dist/{chunk-eazccp6e.js → chunk-15jymk6t.js} +2 -2
- package/dist/{chunk-qvwzaxdd.js → chunk-15rkvc0t.js} +4 -4
- package/dist/chunk-15sgdvyd.js +2 -0
- package/dist/{chunk-7fgfzaah.js → chunk-1jwcp2k0.js} +2 -2
- package/dist/{chunk-jdqmk5sv.js → chunk-261t62q4.js} +63 -63
- package/dist/chunk-2b4a8tbd.js +3 -0
- package/dist/chunk-2fw36w1x.js +2 -0
- package/dist/chunk-2jcxsw75.js +2 -0
- package/dist/{chunk-6d74qdc6.js → chunk-2pbhdaka.js} +1 -1
- package/dist/chunk-2wba5ypm.js +2 -0
- package/dist/chunk-353gnvfe.js +2 -0
- package/dist/{chunk-ff3j7jnf.js → chunk-36vksrry.js} +2 -2
- package/dist/{chunk-m2rm2gxv.js → chunk-37tefp7s.js} +5 -5
- package/dist/{chunk-1z2am28h.js → chunk-38qp2pg2.js} +2 -2
- package/dist/chunk-3cr5y8v1.js +2 -0
- package/dist/{chunk-jwwsxym6.js → chunk-3gfd9t8a.js} +2 -2
- package/dist/{chunk-zn9dp7yn.js → chunk-3wg9kr5z.js} +5 -5
- package/dist/chunk-3y7yp0ka.js +2 -0
- package/dist/chunk-41wwqw0q.js +2 -0
- package/dist/chunk-4a1y51fs.js +2 -0
- package/dist/chunk-4a751brg.js +2 -0
- package/dist/{chunk-cqkr291c.js → chunk-4jgcd4d9.js} +5 -5
- package/dist/{chunk-kedgfk9z.js → chunk-4rrxrxp6.js} +4 -4
- package/dist/chunk-5awhm4na.js +2 -0
- package/dist/chunk-5fhp9hxd.js +2 -0
- package/dist/{chunk-q93jcdgj.js → chunk-5ka3h8dy.js} +12 -12
- package/dist/chunk-5mg443dw.js +2 -0
- package/dist/{chunk-e8we717q.js → chunk-5n7m8vqx.js} +2 -2
- package/dist/{chunk-kq3h2rjq.js → chunk-5neezkj1.js} +4 -4
- package/dist/{chunk-6qbha6fb.js → chunk-5q4tncfw.js} +6 -6
- package/dist/{chunk-sny8rqe8.js → chunk-5rxks14t.js} +2 -2
- package/dist/chunk-5x9ajbq0.js +2 -0
- package/dist/{chunk-az9b4bj4.js → chunk-5xdkmn39.js} +2 -2
- package/dist/{chunk-fw50vydb.js → chunk-65cbfx5x.js} +2 -2
- package/dist/{chunk-tk67pqaf.js → chunk-68w65mhs.js} +3 -3
- package/dist/chunk-6g7tkmty.js +2 -0
- package/dist/{chunk-1347hwt5.js → chunk-6nb49h13.js} +40 -40
- package/dist/{chunk-e7thwrt5.js → chunk-6tp0w6hf.js} +2 -2
- package/dist/chunk-72bj7ea4.js +2 -0
- package/dist/{chunk-jwtp4csj.js → chunk-74g64pzt.js} +4 -4
- package/dist/{chunk-78amng8s.js → chunk-76360zky.js} +6 -6
- package/dist/{chunk-gz0j98dy.js → chunk-7bajrfb1.js} +4 -4
- package/dist/{chunk-rq9pqd4s.js → chunk-7de5y29a.js} +5 -5
- package/dist/{chunk-jafn7f7f.js → chunk-7yhhwv07.js} +2 -2
- package/dist/chunk-811hh6vp.js +2 -0
- package/dist/{chunk-0z2gqttt.js → chunk-830ej8d2.js} +12 -12
- package/dist/chunk-8fkmxrat.js +2 -0
- package/dist/{chunk-gjbnzn7k.js → chunk-8hck9qqm.js} +4 -4
- package/dist/chunk-8p9npc8y.js +2 -0
- package/dist/chunk-9fz3h6sx.js +2 -0
- package/dist/chunk-9jr30fns.js +2 -0
- package/dist/{chunk-e763qsg0.js → chunk-9pyvc0dc.js} +2 -2
- package/dist/{chunk-3b7q7d7j.js → chunk-9syvkm5z.js} +6 -6
- package/dist/{chunk-ym5qgw03.js → chunk-9xr628ew.js} +2 -2
- package/dist/{chunk-k19ba3jz.js → chunk-a6d92kv6.js} +2 -2
- package/dist/chunk-a9m6ajd7.js +2 -0
- package/dist/{chunk-mxazxwc4.js → chunk-aj6vqdf7.js} +3 -3
- package/dist/chunk-asr5v51s.js +2 -0
- package/dist/{chunk-252enthj.js → chunk-avp271q4.js} +1 -1
- package/dist/{chunk-8623gte8.js → chunk-b1tctqn5.js} +6 -6
- package/dist/{chunk-71s4hpkj.js → chunk-b7nmgkwa.js} +3 -3
- package/dist/{chunk-fxk1psd8.js → chunk-bag9q4m0.js} +30 -30
- package/dist/{chunk-0vptj943.js → chunk-bg0ywp5w.js} +2 -2
- package/dist/{chunk-g8d24rfk.js → chunk-bv14vry8.js} +2 -2
- package/dist/chunk-byx82s10.js +2 -0
- package/dist/{chunk-smve11g0.js → chunk-c2w4wc9f.js} +1 -1
- package/dist/chunk-c9y1g61m.js +2 -0
- package/dist/chunk-ck5nzbbv.js +2 -0
- package/dist/{chunk-mh45hcsa.js → chunk-cq2hedwn.js} +6 -6
- package/dist/chunk-cvdm0hgq.js +2 -0
- package/dist/{chunk-27zp4q77.js → chunk-cxpq2zna.js} +1 -1
- package/dist/{chunk-y67r0d0c.js → chunk-d6216bcw.js} +4 -4
- package/dist/{chunk-pa8xkctc.js → chunk-dba4bwkd.js} +6 -6
- package/dist/{chunk-3evwxrpx.js → chunk-dt73ww6m.js} +1 -1
- package/dist/chunk-e0fxgbcc.js +2 -0
- package/dist/{chunk-z703xzhy.js → chunk-e8nzbz66.js} +2 -2
- package/dist/chunk-ed2m6pjf.js +2 -0
- package/dist/chunk-ednwdhv0.js +2 -0
- package/dist/chunk-egtphftq.js +2 -0
- package/dist/{chunk-bhzh7mj1.js → chunk-eye156nv.js} +1 -1
- package/dist/chunk-fahqq7c4.js +2 -0
- package/dist/chunk-fcbpzdyz.js +2 -0
- package/dist/{chunk-4h9kkkh7.js → chunk-fpkp0bqf.js} +1 -1
- package/dist/{chunk-tpw435g0.js → chunk-fyfvqd2s.js} +2 -2
- package/dist/{chunk-xz1csyq9.js → chunk-gc79s0wh.js} +10 -10
- package/dist/{chunk-hjh5wt5f.js → chunk-gggadrs4.js} +3 -3
- package/dist/{chunk-nv5xhfwz.js → chunk-gjnrmz2q.js} +2 -2
- package/dist/{chunk-fbnykfnv.js → chunk-gp1dt8b8.js} +3 -3
- package/dist/{chunk-jgvwzt1t.js → chunk-gx96hctv.js} +2 -2
- package/dist/chunk-h0dsxxz4.js +2 -0
- package/dist/{chunk-wd4z5w4d.js → chunk-h2cvfp9y.js} +1 -1
- package/dist/{chunk-egwtv5hp.js → chunk-h4aqpf2r.js} +3 -3
- package/dist/{chunk-4ezfen91.js → chunk-hyea17hp.js} +69 -69
- package/dist/{chunk-admnvsmx.js → chunk-jh2v1vvb.js} +2 -2
- package/dist/chunk-k3yym9zg.js +2 -0
- package/dist/chunk-k9fsd6t3.js +2 -0
- package/dist/chunk-kepxsjfx.js +2 -0
- package/dist/chunk-kh01rvag.js +2 -0
- package/dist/{chunk-mzg1wq86.js → chunk-kv40xq53.js} +15 -15
- package/dist/{chunk-tjer45j7.js → chunk-m3p4hksq.js} +4 -4
- package/dist/chunk-mad172af.js +2 -0
- package/dist/{chunk-c7eew8qs.js → chunk-mjkdskeg.js} +1 -1
- package/dist/{chunk-qv52et0d.js → chunk-naj146zq.js} +2 -2
- package/dist/chunk-npt0mdzb.js +2 -0
- package/dist/{chunk-snmq7yn4.js → chunk-nwxjh1gv.js} +3 -3
- package/dist/chunk-p95fsnbk.js +2 -0
- package/dist/chunk-ptc3yqn3.js +2 -0
- package/dist/chunk-pybm7c9p.js +2 -0
- package/dist/{chunk-69zj9q02.js → chunk-q6w7a1vc.js} +3 -3
- package/dist/{chunk-w7s3afam.js → chunk-qjm23ma2.js} +1 -1
- package/dist/chunk-qnx71b17.js +2 -0
- package/dist/chunk-qx8cav4w.js +2 -0
- package/dist/chunk-rb7cwck6.js +2 -0
- package/dist/chunk-s1e0t3hv.js +2 -0
- package/dist/chunk-s7vfmasx.js +2 -0
- package/dist/{chunk-bxn4b0wm.js → chunk-scwbttvt.js} +2 -2
- package/dist/{chunk-ksxbfyef.js → chunk-sxtvy0sm.js} +2 -2
- package/dist/chunk-t7z67vf6.js +2 -0
- package/dist/chunk-tarvase5.js +2 -0
- package/dist/{chunk-qa4vs1qg.js → chunk-thdnk1kd.js} +3 -3
- package/dist/{chunk-8cpqcn19.js → chunk-tjz3r7rj.js} +5 -5
- package/dist/{chunk-xhvw0t0f.js → chunk-tm201m9x.js} +3 -3
- package/dist/chunk-tqs9pcga.js +2 -0
- package/dist/chunk-twjfrywv.js +2 -0
- package/dist/{chunk-me16tftr.js → chunk-v0wdgxga.js} +1 -1
- package/dist/{chunk-bef0wr53.js → chunk-vggtxttf.js} +5 -5
- package/dist/chunk-vyna2rsq.js +2 -0
- package/dist/chunk-w4gjx2zs.js +18 -0
- package/dist/{chunk-fd7e162p.js → chunk-wrbhq1y2.js} +3 -3
- package/dist/{chunk-2bks42z4.js → chunk-x69457q9.js} +5 -5
- package/dist/chunk-xhe7pw6e.js +2 -0
- package/dist/{chunk-d6am6en8.js → chunk-xmy6g81m.js} +1 -1
- package/dist/chunk-y86mpnrg.js +2 -0
- package/dist/{chunk-3zjyhhg4.js → chunk-yj9nyt93.js} +2 -2
- package/dist/{chunk-jtag68hg.js → chunk-z99bf0q0.js} +2 -2
- package/dist/chunk-zm0g7ntw.js +2 -0
- package/dist/{chunk-5xy1z71a.js → chunk-zpkgs5d3.js} +4 -4
- package/dist/chunk-zrm2x65c.js +2 -0
- package/dist/{chunk-va1hj69e.js → chunk-zs4s9fcq.js} +4 -4
- package/dist/cli.js +19 -19
- package/dist/config.js +11 -1
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/pwa.js +3 -3
- package/dist/render.js +2 -6
- package/dist/serve.js +2 -6
- package/dist/site-builder/build.js +2 -2
- package/dist/site-builder/router.js +2 -5
- package/dist/site-builder/theme.js +2 -2
- package/dist/ssg.js +4 -4
- package/package.json +5 -5
- package/dist/chunk-0ts3p84y.js +0 -2
- package/dist/chunk-139mxsyc.js +0 -2
- package/dist/chunk-1barsha6.js +0 -2
- package/dist/chunk-1fnx7ze9.js +0 -2
- package/dist/chunk-1g06wfs9.js +0 -2
- package/dist/chunk-1nasq00e.js +0 -2
- package/dist/chunk-2102tvxh.js +0 -2
- package/dist/chunk-39cwa35j.js +0 -2
- package/dist/chunk-3rcegvgg.js +0 -2
- package/dist/chunk-3wvq28hz.js +0 -2
- package/dist/chunk-6m4v1tsq.js +0 -2
- package/dist/chunk-75e4wzzs.js +0 -3
- package/dist/chunk-7ambc4f7.js +0 -2
- package/dist/chunk-8nmc3rh7.js +0 -2
- package/dist/chunk-8pn7ah12.js +0 -2
- package/dist/chunk-8zwwmnpb.js +0 -2
- package/dist/chunk-98bgx3ws.js +0 -2
- package/dist/chunk-a4v8z93r.js +0 -2
- package/dist/chunk-a58w524e.js +0 -2
- package/dist/chunk-a6v6x2pg.js +0 -2
- package/dist/chunk-afrqm7w5.js +0 -18
- package/dist/chunk-b62mr2kz.js +0 -2
- package/dist/chunk-b7vxb2y6.js +0 -2
- package/dist/chunk-bb20hnqd.js +0 -2
- package/dist/chunk-bc3sknxf.js +0 -2
- package/dist/chunk-cbrbrkp1.js +0 -2
- package/dist/chunk-d8djpp7f.js +0 -2
- package/dist/chunk-dk6t4h48.js +0 -2
- package/dist/chunk-dkbm7117.js +0 -2
- package/dist/chunk-e44bse67.js +0 -2
- package/dist/chunk-ewnfgczq.js +0 -2
- package/dist/chunk-f1v5hvbt.js +0 -2
- package/dist/chunk-g6epqcb3.js +0 -2
- package/dist/chunk-gmvypdm8.js +0 -2
- package/dist/chunk-hmgry6dn.js +0 -2
- package/dist/chunk-jbv1srnh.js +0 -2
- package/dist/chunk-jzynkjfc.js +0 -2
- package/dist/chunk-k1qajhpx.js +0 -2
- package/dist/chunk-m28j4ym7.js +0 -2
- package/dist/chunk-mzembfxk.js +0 -2
- package/dist/chunk-ngzjwp2e.js +0 -2
- package/dist/chunk-nj9n0en9.js +0 -2
- package/dist/chunk-nyasqjnt.js +0 -2
- package/dist/chunk-pn0rmd8d.js +0 -2
- package/dist/chunk-pvx1hrqq.js +0 -2
- package/dist/chunk-q78dsejp.js +0 -2
- package/dist/chunk-qw1f97s7.js +0 -2
- package/dist/chunk-rcn0yyh2.js +0 -2
- package/dist/chunk-t9h3e3bp.js +0 -2
- package/dist/chunk-ts9bvjzh.js +0 -2
- package/dist/chunk-tzvgjrp4.js +0 -2
- package/dist/chunk-v8b1wz1b.js +0 -2
- package/dist/chunk-w9aa8xte.js +0 -2
- package/dist/chunk-wegkgjmf.js +0 -2
- package/dist/chunk-wn065q3f.js +0 -2
- package/dist/chunk-y2dtqrrz.js +0 -2
- package/dist/chunk-yss7n9db.js +0 -2
- package/dist/chunk-z6p0yxwd.js +0 -2
- package/dist/chunk-zcpwc47w.js +0 -2
- package/dist/chunk-zsmrq1w3.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{fe,yn,Dt,Lt,g,s,me,p}from"./chunk-
|
|
2
|
+
import{fe,yn,Dt,Lt,g,s,me,p}from"./chunk-261t62q4.js";import{vt,Pe,fc,ls,jo,Bo,i}from"./chunk-kv40xq53.js";import{le,ee,Ar,Ce,z,En}from"./chunk-830ej8d2.js";import{Ct,hr,Ps,Is,Os,Et,Tt,$t,Rt,At,Pt,nt}from"./chunk-3gfd9t8a.js";import{Cs,a,O}from"./chunk-6nb49h13.js";import{ht,Yt,Te,j,ma,wo,Jr,Ke,ha,Ge,$e}from"./chunk-4jgcd4d9.js";import{fr,gr}from"./chunk-z99bf0q0.js";import{e,pn,cr,b}from"./chunk-5q4tncfw.js";import{Ze}from"./chunk-7de5y29a.js";import{Ae}from"./chunk-mzes9ds7.js";import{In}from"./chunk-bv14vry8.js";import{X,ve,xe}from"./chunk-02css3vk.js";import{c}from"./chunk-sxtvy0sm.js";import{G}from"./chunk-9xr628ew.js";async function Nn(t){try{let n=await Bun.file(t).text(),r=Un(n),d=Wn(n,t),o=Vn(n,r),l=qn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
|
|
3
3
|
`),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[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 u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,m=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+m,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:y}}function
|
|
5
|
-
`).filter((x)=>x.length>120);if(m.length>0)r.push({type:"info",category:"maintainability",message:`Found ${m.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}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 u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,m=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+m,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:y}}function Wn(t,n){let r=[],d=Gt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Gt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} 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)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let m=t.split(`
|
|
5
|
+
`).filter((x)=>x.length>120);if(m.length>0)r.push({type:"info",category:"maintainability",message:`Found ${m.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Vn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function qn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Gt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function na(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await Nn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=Kn(r);return{results:r,summary:o}}function Kn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),m=[];if(d>6)m.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)m.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)m.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:m}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Jt,writeFile as Yn}from"fs/promises";import ke from"path";function rn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var on=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function Ht(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function r(d){let o=await Jn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function nr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function rr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(m){throw Error(`${n}: failed to transpile <script client> (${m.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let m=f[1];if(on.has(m))throw Error(`${n}: client ${rn(m)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${m}"`);let w=f[0].includes("async")?"async ":"";r[m]=`${w}${m}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
8
|
-
`)}function
|
|
7
|
+
`)}function sr(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function ir(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 ar(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 lr(t){let n=[],r=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(m)=>{if(d[m]!=="(")return null;let h=0,x="";for(let v=m;v<d.length;v++){let S=d[v];if(x!==""){if(S==="\\")v++;else if(S===x)x="";continue}if(S==="'"||S==='"'||S==="`"){x=S;continue}if(S==="(")h++;else if(S===")"){if(h--,h===0)return{expression:d.slice(m+1,v),end:v+1}}}return null},f=(m)=>{if(m==="")return;let h=0,x=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,v;while(v=x.exec(m)){if(v.index>h)n.push(`out += ${JSON.stringify(m.slice(h,v.index))};`);n.push(v[1]!==void 0?`out += __raw(${v[1]});`:`out += __escape(${v[2]});`),h=v.index+v[0].length}if(h<m.length)n.push(`out += ${JSON.stringify(m.slice(h))};`)};while(l=o.exec(d)){f(d.slice(r,l.index)),r=l.index+l[0].length;let h=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(r):null;if(h)r=h.end,o.lastIndex=h.end;let x=h?.expression;switch(l[1]){case"if":n.push(`if (${x}) {`);break;case"elseif":n.push(`} else if (${x}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let v=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((x||"").trim());if(!v){n.push(`out += ${JSON.stringify(l[0]+(h?`(${x})`:""))};`);break}let[,S,T,w]=v;n.push(T?`for (const [${T}, ${w}] of __entries(${S})) {`:`for (const ${w} of __values(${S})) {`);break}}}return f(d.slice(r)),n.join(`
|
|
8
|
+
`)}function dt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function It(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,m="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(m+=x,x==="\\"){m+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,m+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(m),m="";continue}m+=x}return l.push(m),l.map((h)=>h.trim()).filter(Boolean)}function dr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}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 pr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},m=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(m<t.length&&/\s/.test(t[m]))m++},x;if(t[m]==="{"){let E=dt(t,m,"{","}");if(E===-1)return null;x=t.slice(m,E),m=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(m));if(!E)return null;x=E[0],m+=E[0].length}if(h(),t[m]!=="=")return null;m++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(m)),S=Boolean(v);if(v)m+=v[0].length;let T=/^defineProps\b/.exec(t.slice(m));if(!T)return null;m+=T[0].length;let w="";if(h(),t[m]==="<"){let E=dt(t,m,"<",">");if(E===-1)return null;w=t.slice(m+1,E-1).trim(),m=E}if(h(),t[m]!=="(")return null;let y=dt(t,m,"(",")");if(y===-1)return null;let k=t.slice(m+1,y-1).trim();if(m=y,S){if(h(),t[m]===",")m++,h();if(t[m]==="{"){let E=dt(t,m,"{","}");if(E===-1)return null;for(let[R,A]of jt(t.slice(m,E)))l[R]=A;m=E}if(h(),t[m]===",")m++,h();if(t[m]===")")m++}if(t[m]===";")m++;let M=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of It(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of jt(k)){if(u.push(E),!R.startsWith("{")){let A=Zt(R);if(A)o[E]=A;continue}for(let[A,C]of jt(R))if(A==="default")l[E]=C;else if(A==="type"){let D=Zt(C);if(D)o[E]=D}}else if(k.startsWith("["))for(let E of It(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of It(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=dr(E),A=R===-1?E:E.slice(0,R),C=A.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=A.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,m),propNames:u,propBindings:f,defaults:l,declared:o,typeName:M}}function jt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",m=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(m,d).trim();if(h)r.push([l[1],h]);d++}return r}function ur(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],m={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,y,k,M)=>{let E=ke.resolve(ke.dirname(n),k),R=ke.relative(r,E);return`${y}${R.startsWith(".")?R:`./${R}`}${M}`})),""});let v=pr(l);if(v)f.push(...v.propNames),Object.assign(m,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let y of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[y[1]]=y[2].trim(),w.push(y[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:m,defaults:h,declared:x}}function mr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let m=o.toLowerCase();n.add(m);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${m}="${f}"${h?` data-stx-mod-${m}="${h}"`:""}`}),eventTypes:[...n].sort()}}function yr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function br(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function xr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function en(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function vr(t,n,r){let d=ke.isAbsolute(n.file)?n.file:ke.resolve(t,n.file),o=await Gn(d,"utf8"),l=nr(o,d),u=ke.basename(d,".stx"),f=n.name||l.name||Qn(u),m=`${Ht(r.prefix||"stx")}-${Ht(u)}`,h=n.tag||l.tag||m;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Zn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,A])=>[R,en(R,A)])),S=mr(or(o)),T=yr(S.template),w=ur(o,d,ke.resolve(r.outputDir)),y=lr(T.template);for(let R of w.propNames){if(v[R])continue;let A=w.defaults[R];v[R]=en(R,{type:sr(w.declared[R])??ir(A),...A===void 0?{}:{default:ar(A)}})}let k=l.methods||{},M=n.methods||{},E=rr(o,d);return{file:ke.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Qt(o),shadowMode:er(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...M,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:br(T.template),cssProperties:xr(Qt(o)),scope:w,render:y}}function wr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=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('>', '>')
|
|
@@ -314,7 +314,7 @@ export function defineComponent(Component, definition) {
|
|
|
314
314
|
}
|
|
315
315
|
return Component;
|
|
316
316
|
}
|
|
317
|
-
`}function
|
|
317
|
+
`}function Sr(t){let n=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),r=Object.entries(t.methods).map(([f,m])=>{if(on.has(f))throw Error(`${t.sourcePath}: ${rn(f)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(m.trim()))return` ${m.trim()}`;return` ${f}($event) {
|
|
318
318
|
${m}
|
|
319
319
|
}`}).join(`
|
|
320
320
|
|
|
@@ -339,7 +339,7 @@ ${r}${u}
|
|
|
339
339
|
|
|
340
340
|
defineComponent(${t.name}, ${n});
|
|
341
341
|
export default ${t.name};
|
|
342
|
-
`}function
|
|
342
|
+
`}function Bt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function kr(t){let n=Object.entries(t.properties).map(([o,l])=>` ${o}${l.required?"":"?"}: ${Bt(l)}`).join(`
|
|
343
343
|
`),r=Object.entries(t.events).map(([o,l])=>` ${JSON.stringify(o)}: CustomEvent<${l.detailType||"unknown"}>`).join(`
|
|
344
344
|
`),d=Object.keys(t.methods).map((o)=>` ${o}($event?: Event): unknown`).join(`
|
|
345
345
|
`);return`export interface ${t.name}Props {
|
|
@@ -366,10 +366,10 @@ declare global {
|
|
|
366
366
|
}
|
|
367
367
|
|
|
368
368
|
export default ${t.name}
|
|
369
|
-
`}function
|
|
369
|
+
`}function Tr(t){return`declare global {
|
|
370
370
|
namespace JSX {
|
|
371
371
|
interface IntrinsicElements {
|
|
372
|
-
${t.map((r)=>{let d=Object.entries(r.properties).map(([l,u])=>` ${JSON.stringify(l)}?: ${
|
|
372
|
+
${t.map((r)=>{let d=Object.entries(r.properties).map(([l,u])=>` ${JSON.stringify(l)}?: ${Bt(u)}`).join(`
|
|
373
373
|
`),o=Object.keys(r.events).map((l)=>` ${`on${l.split(/[-:]/).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join("")}`}?: (event: CustomEvent<${r.events[l].detailType||"unknown"}>) => void`).join(`
|
|
374
374
|
`);return` ${JSON.stringify(r.tag)}: {
|
|
375
375
|
${d}
|
|
@@ -385,9 +385,9 @@ ${o}
|
|
|
385
385
|
}
|
|
386
386
|
|
|
387
387
|
export {}
|
|
388
|
-
`}function
|
|
388
|
+
`}function $r(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([r,d])=>({kind:"field",name:r,description:d.description,type:{text:Bt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||Ht(r),reflects:d.reflect})),events:Object.entries(n.events).map(([r,d])=>({name:r,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
|
|
389
389
|
${n}
|
|
390
|
-
}`}function
|
|
390
|
+
}`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Cr(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),l=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
|
|
391
391
|
`);return`const definitions = ${JSON.stringify(o,null,2)};
|
|
392
392
|
const escapeHTML = (value) => String(value ?? '')
|
|
393
393
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -421,21 +421,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
421
421
|
}
|
|
422
422
|
|
|
423
423
|
${l}
|
|
424
|
-
`}async function
|
|
424
|
+
`}async function ra(t){let n=ke.resolve(t.inputDir),r=ke.resolve(t.outputDir);if(!(await Jt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await tr(n)).map((y)=>({file:y}));if(!o.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(o.map((y)=>vr(n,y,t)));l.sort((y,k)=>y.tag.localeCompare(k.tag));let u=l.filter((y,k)=>l.findIndex((M)=>M.tag===y.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((y,k)=>l.findIndex((M)=>M.name===y.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Xn(r,{recursive:!0});let m=[],h=async(y,k)=>{let M=ke.join(r,y);return await Yn(M,k.endsWith(`
|
|
425
425
|
`)?k:`${k}
|
|
426
|
-
`,"utf8"),m.push(M),M};await h("runtime.js",
|
|
427
|
-
`);if(await h("index.js",x),await h("ssr.js"
|
|
428
|
-
`)),await h("custom-elements.d.ts",
|
|
426
|
+
`,"utf8"),m.push(M),M};await h("runtime.js",wr());for(let y of l){if(await h(`${y.tag}.js`,Sr(y)),t.declarations!==!1)await h(`${y.tag}.d.ts`,kr(y));if(t.css!==!1&&y.styles){let k=y.shadowMode?y.styles:tn(y);await h(`${y.tag}.css`,t.minify?nn(k):k)}}let x=l.map((y)=>`export { ${y.name}, default as ${y.name}Element } from './${y.tag}.js';`).join(`
|
|
427
|
+
`);if(await h("index.js",x),await h("ssr.js",Cr(l)),t.declarations!==!1)await h("index.d.ts",l.map((y)=>`export * from './${y.tag}.js'`).join(`
|
|
428
|
+
`)),await h("custom-elements.d.ts",Tr(l)),await h("ssr.d.ts",`${l.map((y)=>`export declare const render${y.name}: (props?: ${y.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
429
429
|
`)}
|
|
430
430
|
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
431
431
|
${l.map((y)=>`import type { ${y.name}Props } from './${y.tag}.js'`).join(`
|
|
432
|
-
`)}`);let v;if(t.manifest!==!1)v=await h("custom-elements.json",JSON.stringify(
|
|
432
|
+
`)}`);let v;if(t.manifest!==!1)v=await h("custom-elements.json",JSON.stringify($r(l),null,2));let S;if(t.css!==!1){let y=l.filter((k)=>!k.shadowMode&&k.styles).map(tn).join(`
|
|
433
433
|
|
|
434
|
-
`);if(y)S=await h("bundle.css",t.minify?
|
|
434
|
+
`);if(y)S=await h("bundle.css",t.minify?nn(y):y)}let T;if(t.bundle!==!1){T=ke.join(r,"bundle.js");let y;try{y=await Bun.build({entrypoints:[ke.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(k){let M=k instanceof AggregateError?k.errors:[k],E=M.map((R)=>String(R).trim()).filter(Boolean).join(`
|
|
435
435
|
`);throw AggregateError(M,`Failed to bundle component library${E?`
|
|
436
436
|
${E}`:""}`)}if(!y.success){let k=y.logs.map((M)=>String(M).trim()).filter(Boolean).join(`
|
|
437
437
|
`);throw AggregateError(y.logs,`Failed to bundle component library${k?`
|
|
438
|
-
${k}`:""}`)}if(m.push(T),t.sourcemap==="external")m.push(`${T}.map`)}let w=await Promise.all(m.map(async(y)=>(await
|
|
438
|
+
${k}`:""}`)}if(m.push(T),t.sourcemap==="external")m.push(`${T}.map`)}let w=await Promise.all(m.map(async(y)=>(await Jt(y)).size));return{components:l.map((y)=>({name:y.name,tag:y.tag,source:y.sourcePath,module:ke.join(r,`${y.tag}.js`)})),files:m,manifest:v,bundle:T,cssBundle:S,totalBytes:w.reduce((y,k)=>y+k,0)}}var{serve:Ir}=globalThis.Bun;import zt from"fs";import et from"path";function pt(){return`
|
|
439
439
|
/* Theme selector for code blocks */
|
|
440
440
|
.theme-selector {
|
|
441
441
|
margin: 1rem 0;
|
|
@@ -485,13 +485,13 @@ ${k}`:""}`)}if(m.push(T),t.sourcemap==="external")m.push(`${T}.map`)}let w=await
|
|
|
485
485
|
|
|
486
486
|
body.dark-mode a {
|
|
487
487
|
color: #58a6ff;
|
|
488
|
-
}`}function
|
|
488
|
+
}`}function ut(t){return`
|
|
489
489
|
<div class="theme-selector">
|
|
490
490
|
Theme:
|
|
491
491
|
<select id="themeSelector" onchange="changeTheme()">
|
|
492
492
|
${t}
|
|
493
493
|
</select>
|
|
494
|
-
</div>`}function
|
|
494
|
+
</div>`}function ft(){return`
|
|
495
495
|
function changeTheme() {
|
|
496
496
|
const theme = document.getElementById('themeSelector').value;
|
|
497
497
|
|
|
@@ -507,7 +507,7 @@ else {
|
|
|
507
507
|
}
|
|
508
508
|
|
|
509
509
|
// Initialize theme on page load
|
|
510
|
-
document.addEventListener('DOMContentLoaded', changeTheme);`}function
|
|
510
|
+
document.addEventListener('DOMContentLoaded', changeTheme);`}function mt(t){if(Object.keys(t).length===0)return"";return`
|
|
511
511
|
<div class="frontmatter">
|
|
512
512
|
<h3>Frontmatter</h3>
|
|
513
513
|
${Object.entries(t).map(([n,r])=>`
|
|
@@ -515,19 +515,19 @@ else {
|
|
|
515
515
|
<span class="frontmatter-label">${n}:</span>
|
|
516
516
|
<span>${Array.isArray(r)?r.join(", "):String(r)}</span>
|
|
517
517
|
</div>`).join("")}
|
|
518
|
-
</div>`}async function
|
|
518
|
+
</div>`}async function Rr(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"0.0.0.0")})}async function Er(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"::")})}async function Pr(t){if(!await Rr(t))return!1;return await Er(t)}async function We(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Pr(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Or={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Dr(){try{let t=await import("./chunk-811hh6vp.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Qe(t,n={}){let r={...Or,...n},d=await Dr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
|
|
519
519
|
${l}
|
|
520
520
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
521
|
-
`,m=Function(u)();if(m)return m}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function
|
|
522
|
-
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
|
|
523
|
-
`)){let l=d.trim().toLowerCase();d="",
|
|
521
|
+
`,m=Function(u)();if(m)return m}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function Ft(){console.log(`
|
|
522
|
+
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 Mr(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`),Ft()}function _r(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ve(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ft();let d="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(d+=o,d.endsWith("\r")||d.endsWith(`
|
|
523
|
+
`)){let l=d.trim().toLowerCase();d="",Lr(l,t,n,r)}})}function Lr(t,n,r,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else _r(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Mr(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Ft();break;default:break}}async function Nt(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=et.resolve(t);if(!zt.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,u=async()=>{try{let{content:v,data:S}=await Pe(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),T=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,w=T?.defaultTheme||"github-dark",y=["github-dark"],k=T?.additionalThemes||[],E=[...new Set([...y,...k])].map((R)=>`<option value="${R}"${R===w?" selected":""}>${R}</option>`).join(`
|
|
524
524
|
`);return l=`
|
|
525
525
|
<!DOCTYPE html>
|
|
526
526
|
<html lang="en">
|
|
527
527
|
<head>
|
|
528
528
|
<meta charset="UTF-8">
|
|
529
529
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
530
|
-
<title>${
|
|
530
|
+
<title>${jr(S.title||et.basename(o))}</title>
|
|
531
531
|
<!-- Syntax highlighting styles -->
|
|
532
532
|
<style id="syntax-theme">
|
|
533
533
|
:root {
|
|
@@ -669,26 +669,26 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
|
|
|
669
669
|
min-width: 100px;
|
|
670
670
|
color: #555;
|
|
671
671
|
}
|
|
672
|
-
${
|
|
672
|
+
${pt()}
|
|
673
673
|
</style>
|
|
674
674
|
</head>
|
|
675
675
|
<body>
|
|
676
|
-
${
|
|
677
|
-
${
|
|
676
|
+
${mt(S)}
|
|
677
|
+
${ut(E)}
|
|
678
678
|
|
|
679
679
|
${v}
|
|
680
680
|
|
|
681
681
|
<script>
|
|
682
|
-
${
|
|
682
|
+
${ft()}
|
|
683
683
|
</script>
|
|
684
684
|
</body>
|
|
685
685
|
</html>
|
|
686
|
-
`,!0}catch(v){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,v),!1}};if(!await u())return!1;let m=r;try{if(m=await We(r),m!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${m} 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:${m}/${e.reset}...`);let h=
|
|
686
|
+
`,!0}catch(v){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,v),!1}};if(!await u())return!1;let m=r;try{if(m=await We(r),m!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${m} 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:${m}/${e.reset}...`);let h=Ir({port:m,fetch(v){if(new URL(v.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","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}
|
|
687
687
|
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
688
688
|
${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(`
|
|
689
689
|
${e.bright}\u2192 ${e.cyan}http://localhost:${m}/${e.reset}`),console.log(`
|
|
690
690
|
${e.yellow}Routes:${e.reset}`);let x=et.relative(process.cwd(),o);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${x}${e.reset}`),console.log(`
|
|
691
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)
|
|
691
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)zt.watch(et.dirname(o),{recursive:!0}).close();h.stop()}),n.native)await Qe(m,{title:et.basename(o,".md")});if(d){let v=et.dirname(o);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=zt.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function jr(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Br}=globalThis.Bun;import Be from"fs";import ge from"path";class sn{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 n=t??this.options.wsPort,r=20;for(let d=0;d<r;d++)try{if(this.server=Bun.serve({port:n,fetch(o,l){if(l.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let m=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${m}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} 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 n=JSON.stringify(t),r=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),r++}catch{this.clients.delete(d)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} 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,n){this.broadcast({type:"css-update",path:t,content:n,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 Hr(t,n={}){let{showOverlay:r=!0,reconnectInterval:d=1000,maxReconnectAttempts:o=10}=n;return`
|
|
692
692
|
<script>
|
|
693
693
|
(function() {
|
|
694
694
|
// stx Hot Reload Client
|
|
@@ -887,7 +887,7 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function Ne(t,n,r={}){let d=
|
|
890
|
+
`}function Ne(t,n,r={}){let d=Hr(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function yt(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var tt=null;function wt(t){if(!tt)tt=new sn(t);return tt}function it(){if(tt)tt.stop(),tt=null}import St from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${St.relative(St.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Cs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await fr(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let m=await Ce(()=>Bun.file(u).text(),"",(y)=>{throw new Ar(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!m)throw new Ar(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=le.time("script-extraction",()=>{let y=m,k=fe(m);if(k)y=k.content.trim();let M=m.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:St.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await Ce(()=>g(h,S,u),void 0,(y)=>{let k=new ee(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await le.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-zrm2x65c.js"),k=y(v.join(`
|
|
891
891
|
`),S),M=w.search(/<\/body>/i);if(M!==-1)w=w.slice(0,M)+k+`
|
|
892
892
|
`+w.slice(M);else w+=`
|
|
893
893
|
${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await gr(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let m=f instanceof Error?f:new ee(`Plugin processing failed: ${String(f)}`,u);if(z.log(m,{filePath:u,buildConfig:t.config}),En.logDetailedError(m,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",m);let h=m,x=h.line||null,v=h.context||null;return{contents:r.debug||G()?`<!DOCTYPE html>
|
|
@@ -931,7 +931,7 @@ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
|
|
|
931
931
|
<li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
|
|
932
932
|
<li>Verify that all variables used in the template are properly defined</li>
|
|
933
933
|
<li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
|
|
934
|
-
<li>Run <code>stx debug ${p(
|
|
934
|
+
<li>Run <code>stx debug ${p(St.basename(u))}</code> for detailed analysis</li>
|
|
935
935
|
<li>Enable debug mode in your stx config for more detailed error messages</li>
|
|
936
936
|
</ul>
|
|
937
937
|
</div>
|
|
@@ -950,12 +950,12 @@ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
|
|
|
950
950
|
<h1>Something went wrong</h1>
|
|
951
951
|
<p>An internal error occurred. Please try again later.</p>
|
|
952
952
|
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function Ur(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Ur(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Nt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let m=c(process.cwd(),"output");Be.mkdirSync(m,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ce)=>({path:ce.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:m,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=ge.dirname(f);await pn(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=wt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-ed2m6pjf.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-npt0mdzb.js"),be=L.broadcasting;await V(be);let ce=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ce}/ws${e.reset}`);let Ee=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Ee))try{let re=await Y(Ee);console.log(`${e.blue}Loaded ${e.bright}${re} broadcast channel${re!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(re){console.warn(`${e.yellow}Failed to load channels.ts: ${re.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-a9m6ajd7.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Br({port:T,async fetch(D){return In(D,await(async()=>{let L=new URL(D.url);if([m,ge.dirname(f),ge.join(process.cwd(),"public")].some((re)=>E(ge.join(re,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let re=await y.handleRequest(D);if(re.status!==404)return re}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(re){return new Response(JSON.stringify({error:re.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(m,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let re=Bun.file(Y),F=ge.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let be=ge.dirname(f),ce=ge.join(be,L.pathname);if(Be.existsSync(ce)&&Be.statSync(ce).isFile()){let re=Bun.file(ce),F=ge.extname(ce).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let Ee=ge.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ee)&&Be.statSync(Ee).isFile()){let re=Bun.file(Ee),F=ge.extname(Ee).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
|
|
954
954
|
${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
955
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
956
|
${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
|
|
957
957
|
${e.yellow}Routes:${e.reset}`);let C=ge.relative(process.cwd(),f);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${C}${e.reset}`),console.log(`
|
|
958
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(ge.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=
|
|
958
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(ge.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=gt(D);await Qe(T,{title:ge.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!L,sidebarConfig:L})}if(d){let D=ge.dirname(f);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let L=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||xt(Y))return;if(bt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me();let be=await x();if(await cr(S),o&&l)if(be)l.reload(Y);else l.error("Build failed - check console for details")}else if(yt(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),o&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(L.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:Fr}=globalThis.Bun;import qe from"fs";import Re from"path";var an=`
|
|
959
959
|
<script data-stx-helpers>
|
|
960
960
|
(function() {
|
|
961
961
|
'use strict'
|
|
@@ -1266,14 +1266,14 @@ else {
|
|
|
1266
1266
|
|
|
1267
1267
|
})()
|
|
1268
1268
|
</script>
|
|
1269
|
-
`;function
|
|
1269
|
+
`;function ln(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split(Re.sep)),r=[];for(let d=0;d<n[0].length;d++){let o=n[0][d];if(n.every((l)=>l[d]===o))r.push(o);else break}return r.join(Re.sep)}async function Wr(t,n={}){let r=n.port||3000,d=n.watch!==!1;for(let w of t){let y=Re.resolve(w);if(!qe.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(!y.endsWith(".stx")&&!y.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1}let o=c(process.cwd(),"output");qe.mkdirSync(o,{recursive:!0});let l=ln(t.map((w)=>Re.dirname(Re.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],m=async()=>{try{for(let w of t){let y=Re.resolve(w);if(y.endsWith(".md"))try{let{content:M,data:E}=await Pe(y,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,A=R?.defaultTheme||"github-dark",C=["github-dark"],D=R?.additionalThemes||[],V=[...new Set([...C,...D])].map((Ee)=>`<option value="${Ee}"${Ee===A?" selected":""}>${Ee}</option>`).join(`
|
|
1270
1270
|
`),Y=`
|
|
1271
1271
|
<!DOCTYPE html>
|
|
1272
1272
|
<html lang="en">
|
|
1273
1273
|
<head>
|
|
1274
1274
|
<meta charset="UTF-8">
|
|
1275
1275
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1276
|
-
<title>${
|
|
1276
|
+
<title>${cn(E.title||Re.basename(y))}</title>
|
|
1277
1277
|
<!-- Syntax highlighting styles -->
|
|
1278
1278
|
<style id="syntax-theme">
|
|
1279
1279
|
:root {
|
|
@@ -1415,40 +1415,40 @@ else {
|
|
|
1415
1415
|
min-width: 100px;
|
|
1416
1416
|
color: #555;
|
|
1417
1417
|
}
|
|
1418
|
-
${
|
|
1418
|
+
${pt()}
|
|
1419
1419
|
</style>
|
|
1420
1420
|
</head>
|
|
1421
1421
|
<body>
|
|
1422
|
-
${
|
|
1423
|
-
${
|
|
1422
|
+
${mt(E)}
|
|
1423
|
+
${ut(V)}
|
|
1424
1424
|
|
|
1425
1425
|
${M}
|
|
1426
1426
|
|
|
1427
1427
|
<script>
|
|
1428
|
-
${
|
|
1428
|
+
${ft()}
|
|
1429
1429
|
</script>
|
|
1430
1430
|
</body>
|
|
1431
1431
|
</html>
|
|
1432
1432
|
`,ce=`/${Re.relative(l,y).replace(/\.md$/,"")}`;if(ce.endsWith("/index"))ce=ce.slice(0,-6)||"/";u[ce||"/"]={filePath:y,content:Y,fileType:"md"}}catch(M){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,M);continue}else{let M={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(D)=>({path:D.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[y],outdir:o,plugins:[M,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,Ae(C.logs,y));continue}let D=C.outputs.find((L)=>L.path.endsWith(".html"));if(!D){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(D.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
|
|
1433
|
-
${Ae(C,y)}`);continue}let A=`/${Re.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=Ps(A,{page:!0});f.push({pattern:C,paramNames:D,filePath:y,routeTemplate:A,fileType:"stx"}),u[A]={filePath:y,content:E,fileType:"stx"}}else u[A||"/"]={filePath:y,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,Ae(w)),!1}};if(!await m())return!1;let x=r;try{if(x=await We(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} 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:${x}/${e.reset}...`);let v=
|
|
1434
|
-
</head>`);else L=V+L;M={...C,content:L}}break}}if(M)return b(M.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${
|
|
1435
|
-
</head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Re.join(o,y.pathname);if(qe.existsSync(E)&&qe.statSync(E).isFile()){let R=Bun.file(E),A=Re.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Te(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${
|
|
1433
|
+
${Ae(C,y)}`);continue}let A=`/${Re.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=Ps(A,{page:!0});f.push({pattern:C,paramNames:D,filePath:y,routeTemplate:A,fileType:"stx"}),u[A]={filePath:y,content:E,fileType:"stx"}}else u[A||"/"]={filePath:y,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,Ae(w)),!1}};if(!await m())return!1;let x=r;try{if(x=await We(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} 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:${x}/${e.reset}...`);let v=Fr({port:x,async fetch(w){let y=new URL(w.url),k=Re.join(process.cwd(),"public",y.pathname);if(qe.existsSync(k)&&qe.statSync(k).isFile()){let R=Bun.file(k),A=Re.extname(k).toLowerCase(),C="application/octet-stream";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let M=u[y.pathname];if(!M&&!y.pathname.endsWith("/"))M=u[`${y.pathname}/`];if(!M)for(let R of f){let A=y.pathname.match(R.pattern);if(A){let C=u[R.routeTemplate];if(C){let D={};for(let Y=0;Y<R.paramNames.length;Y++)D[R.paramNames[Y]]=decodeURIComponent(A[Y+1]);let L=C.content,V=`<script>window.__routeParams = ${JSON.stringify(D)};</script>`;if(L.includes("</head>"))L=L.replace("</head>",`${V}
|
|
1434
|
+
</head>`);else L=V+L;M={...C,content:L}}break}}if(M)return b(M.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${an}
|
|
1435
|
+
</head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Re.join(o,y.pathname);if(qe.existsSync(E)&&qe.statSync(E).isFile()){let R=Bun.file(E),A=Re.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Te(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${cn(L)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...j(),"Cache-Control":ht,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
|
|
1436
1436
|
${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1437
1437
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1438
1438
|
${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
|
|
1439
1439
|
${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:Re.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:Re.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)qe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=qe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me(),await m()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Fr}=globalThis.Bun;import ue from"fs";import ne from"path";async function ln(t){try{return yn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=ne.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function qr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ne.resolve(t),{loadStxConfig:m}=await import("./chunk-w9aa8xte.js"),h=await m(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-tzvgjrp4.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?ne.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=ne.join(w,y);if(!ue.existsSync(k)&&!h._layerPageDirs?.some((P)=>ue.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=X(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(ue.existsSync(P)){let N=X(ne.dirname(P),{pagesDir:ne.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await ga(f,n.stxOptions?.shell),D){if(C=await wo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Et(),await $t(f);let L=Tt();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-w9aa8xte.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-bc3sknxf.js"),q=I.broadcasting;await N(q);let Oe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let we=ne.join(process.cwd(),"channels.ts");if(ue.existsSync(we))try{let U=await Q(we);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");ue.mkdirSync(be,{recursive:!0});let ce=new Map,Ee=new Set,re=async(P)=>{let I=Is(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-w9aa8xte.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-b62mr2kz.js"),K=await Oe(f),Ue=(ie)=>{if(!ie)return ie;if(ne.isAbsolute(ie))return ie;return ne.resolve(f,ie)},ae={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ae.debug=!0;ae.partialsDir=Ue(ae.partialsDir),ae.componentsDir=Ue(ae.componentsDir),ae.layoutsDir=Ue(ae.layoutsDir),ae.storesDir=Ue(ae.storesDir||"stores"),ae.cachePath=Ue(ae.cachePath)??c(f,"cache");let H=!I&&!n.profile,oe=ae.cache!==!1;if(oe&&H){let ie=de.get(P.filePath);if(ie)try{if((await ue.promises.stat(P.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!ue.existsSync(Se)){He=!1;break}if((await ue.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=Ke(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await ln(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ae);if(Ie){let je=Ie;if(C)je=Ke(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=oe?await W(P.filePath):await Bun.file(P.filePath).text(),se=yn(Z),{classifyAllScripts:pe}=await import("./chunk-w9aa8xte.js"),B=pe(Z),Le=B.server.map((ie)=>ie.content),Me=Z;for(let ie of B.server)Me=Me.replace(ie.fullTag,"");let te={__filename:P.filePath,__dirname:ne.dirname(P.filePath),__stx_options:ae,params:I??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,te,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,te,P.filePath,ae,De);let Ie=performance.now()-ie,je=ne.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,te,P.filePath,ae,De);if(!C)he=await we(he,{router:ae.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-rcn0yyh2.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,te)}</script>`})}if(C)he=Ke(he,{preserveHead:!0});if(oe&&H)await J(P.filePath,he,De,ae);let{extractStreamBoundaries:ct}=await import("./chunk-98bgx3ws.js"),Ye=ct(te),ot=te.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=te.streamBoundaries||{},Ie={...ae,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...te,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Ye=[...(Ye||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Ye&&Ye.length>0)Ee.add(P.pattern);else Ye=void 0;let Vt=Dt(te),qt=Lt(te);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??se,headers:qt,boundaries:Ye}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(ce.keys()),I=new Set(A.keys());ce.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Oe=N.slice(q,q+Fe),we=await Promise.all(Oe.map((U)=>_(U)));for(let U of we)if(U)ce.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Oe=Q.slice(q,q+Fe),we=await Promise.all(Oe.map(({route:U})=>_(U)));for(let U of we)if(U)A.set(U.route.pattern,U)}return ce.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await pn(f);let Xe=r;try{if(Xe=await We(r),Xe!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Xe+1;l=xt({wsPort:P,verbose:!1}),u=l.start(P)}let kt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Fr({port:Xe,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===jo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Bo(N,ls()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=ne.join(f,Q,I.pathname),Oe=ne.join(f,I.pathname),we=ne.join(be,I.pathname);if([q,Oe,we].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([ue.promises.stat(q).catch(()=>null),ue.promises.stat(Oe).catch(()=>null),ue.promises.stat(we).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Oe,f,S))return Nt(Oe);if(W?.isFile()&&!v(we,f,S))return Nt(we);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let oe=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(oe,{},ne.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(oe){return new Response(`<div class="stx-async-error">${oe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-ts9bvjzh.js"),oe=await H(P,{publicDir:ne.join(f,Q),cacheDir:c(f,"cache","img")});if(oe)return oe}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=hr(I.pathname,M);if(K){let H=ce.get(K.route.pattern),oe=Ee.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||oe){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!oe)ce.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},pe=(K.route.filePath?vt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(pe.validate){if(!await pe.validate({params:K.params})){let Me=await re(404);if(Me){let te=Me;if(te=await b(te,f),o)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(pe.middleware){let Le=Rt(I.pathname,K.params,pe,I.search),Me=At(Le,null,P,{isServer:!0}),te=await Pt(pe.middleware,Me);if(te.redirect){let De=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:De,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let B=H.content;if(C&&ma(P)&&Ge(B,h?.router?.container||"main")){let Le=nt(B),Me=ve(B),te=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=te?Yt(te[1].trim()):"";if(Object.keys(K.params).length>0)B=kt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=$e(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[dc]:ls(),...j(),"Cache-Control":ht}})}if(C)B=Jr(C,B);if(Object.keys(K.params).length>0)B=kt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-98bgx3ws.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),oe=hr(I.pathname,H);if(oe){let Z=A.get(oe.route.pattern);if(!Z||oe.route.isDynamic){let se=await _(oe.route,oe.params);if(se){if(Z=se,!oe.route.isDynamic)A.set(oe.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Jr(C,se);if(Object.keys(oe.params).length>0)se=kt(se,oe.params);if(se=await b(se,f),o)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let pe=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(pe){let B=await _(pe.route);if(B)se=B,A.set(pe.route.pattern,B)}}if(se){let pe=se.content;if(C)pe=Jr(C,pe);if(pe=await b(pe,f),o)pe=Ne(pe,u);return new Response(pe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ct(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=ce.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ae=await re(404);if(ae){let H=ae;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await re(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1440
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)qe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=qe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me(),await m()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function cn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:zr}=globalThis.Bun;import ue from"fs";import ne from"path";async function dn(t){try{return yn(await Bun.file(t).text())}catch{return}}function Ut(t){let n=Bun.file(t),r=ne.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function qr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ne.resolve(t),{loadStxConfig:m}=await import("./chunk-ed2m6pjf.js"),h=await m(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-a9m6ajd7.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?ne.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=ne.join(w,y);if(!ue.existsSync(k)&&!h._layerPageDirs?.some((P)=>ue.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=X(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(ue.existsSync(P)){let N=X(ne.dirname(P),{pagesDir:ne.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await ma(f,n.stxOptions?.shell),D){if(C=await wo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Et(),await $t(f);let L=Tt();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-ed2m6pjf.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-npt0mdzb.js"),q=I.broadcasting;await N(q);let Oe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let we=ne.join(process.cwd(),"channels.ts");if(ue.existsSync(we))try{let U=await Q(we);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");ue.mkdirSync(be,{recursive:!0});let ce=new Map,Ee=new Set,re=async(P)=>{let I=Is(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-ed2m6pjf.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-qx8cav4w.js"),K=await Oe(f),Ue=(ie)=>{if(!ie)return ie;if(ne.isAbsolute(ie))return ie;return ne.resolve(f,ie)},ae={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ae.debug=!0;ae.partialsDir=Ue(ae.partialsDir),ae.componentsDir=Ue(ae.componentsDir),ae.layoutsDir=Ue(ae.layoutsDir),ae.storesDir=Ue(ae.storesDir||"stores"),ae.cachePath=Ue(ae.cachePath)??c(f,"cache");let H=!I&&!n.profile,oe=ae.cache!==!1;if(oe&&H){let ie=de.get(P.filePath);if(ie)try{if((await ue.promises.stat(P.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!ue.existsSync(Se)){He=!1;break}if((await ue.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=Ke(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await dn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ae);if(Ie){let je=Ie;if(C)je=Ke(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await dn(P.filePath),headers:He?.headers}}}let Z=oe?await W(P.filePath):await Bun.file(P.filePath).text(),se=yn(Z),{classifyAllScripts:pe}=await import("./chunk-ed2m6pjf.js"),B=pe(Z),Le=B.server.map((ie)=>ie.content),Me=Z;for(let ie of B.server)Me=Me.replace(ie.fullTag,"");let te={__filename:P.filePath,__dirname:ne.dirname(P.filePath),__stx_options:ae,params:I??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,te,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,te,P.filePath,ae,De);let Ie=performance.now()-ie,je=ne.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,te,P.filePath,ae,De);if(!C)he=await we(he,{router:ae.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-zrm2x65c.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,te)}</script>`})}if(C)he=Ke(he,{preserveHead:!0});if(oe&&H)await J(P.filePath,he,De,ae);let{extractStreamBoundaries:lt}=await import("./chunk-ck5nzbbv.js"),Ye=lt(te),ot=te.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=te.streamBoundaries||{},Ie={...ae,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...te,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Ye=[...(Ye||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Ye&&Ye.length>0)Ee.add(P.pattern);else Ye=void 0;let qt=Dt(te),Kt=Lt(te);if(H)F.set(P.filePath,{status:qt,headers:Kt});return{route:P,content:he,status:qt??se,headers:Kt,boundaries:Ye}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(ce.keys()),I=new Set(A.keys());ce.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Oe=N.slice(q,q+Fe),we=await Promise.all(Oe.map((U)=>_(U)));for(let U of we)if(U)ce.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Oe=Q.slice(q,q+Fe),we=await Promise.all(Oe.map(({route:U})=>_(U)));for(let U of we)if(U)A.set(U.route.pattern,U)}return ce.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await pn(f);let Xe=r;try{if(Xe=await We(r),Xe!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Xe+1;l=wt({wsPort:P,verbose:!1}),u=l.start(P)}let Ot=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Mt=zr({port:Xe,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===jo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Bo(N,ls()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=ne.join(f,Q,I.pathname),Oe=ne.join(f,I.pathname),we=ne.join(be,I.pathname);if([q,Oe,we].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([ue.promises.stat(q).catch(()=>null),ue.promises.stat(Oe).catch(()=>null),ue.promises.stat(we).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Ut(q);if(J?.isFile()&&!v(Oe,f,S))return Ut(Oe);if(W?.isFile()&&!v(we,f,S))return Ut(we);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let oe=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(oe,{},ne.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(oe){return new Response(`<div class="stx-async-error">${oe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-3cr5y8v1.js"),oe=await H(P,{publicDir:ne.join(f,Q),cacheDir:c(f,"cache","img")});if(oe)return oe}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=hr(I.pathname,M);if(K){let H=ce.get(K.route.pattern),oe=Ee.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||oe){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!oe)ce.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},pe=(K.route.filePath?vt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(pe.validate){if(!await pe.validate({params:K.params})){let Me=await re(404);if(Me){let te=Me;if(te=await b(te,f),o)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(pe.middleware){let Le=Rt(I.pathname,K.params,pe,I.search),Me=At(Le,null,P,{isServer:!0}),te=await Pt(pe.middleware,Me);if(te.redirect){let De=te.redirect.path,he=te.redirect.options.redirectCode||302,lt=new Headers(te.responseHeaders);return lt.set("Location",De),new Response(null,{status:he,headers:lt})}if(te.abort){let{statusCode:De,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let B=H.content;if(C&&ha(P)&&Ge(B,h?.router?.container||"main")){let Le=nt(B),Me=ve(B),te=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=te?Yt(te[1].trim()):"";if(Object.keys(K.params).length>0)B=Ot(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=$e(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[fc]:ls(),...j(),"Cache-Control":ht}})}if(C)B=Jr(C,B);if(Object.keys(K.params).length>0)B=Ot(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-ck5nzbbv.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),oe=hr(I.pathname,H);if(oe){let Z=A.get(oe.route.pattern);if(!Z||oe.route.isDynamic){let se=await _(oe.route,oe.params);if(se){if(Z=se,!oe.route.isDynamic)A.set(oe.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Jr(C,se);if(Object.keys(oe.params).length>0)se=Ot(se,oe.params);if(se=await b(se,f),o)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let pe=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(pe){let B=await _(pe.route);if(B)se=B,A.set(pe.route.pattern,B)}}if(se){let pe=se.content;if(C)pe=Jr(C,pe);if(pe=await b(pe,f),o)pe=Ne(pe,u);return new Response(pe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ct(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=ce.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ae=await re(404);if(ae){let H=ae;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await re(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1441
1441
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1442
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
1443
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1444
|
-
${e.yellow}Routes:${e.reset}`);let
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(
|
|
1446
|
-
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function
|
|
1447
|
-
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function
|
|
1444
|
+
${e.yellow}Routes:${e.reset}`);let _t=[...Os(M,f)];for(let{route:P}of R)_t.push(`${P.pattern}`);if(_t.forEach((P,I)=>{let Q=I===_t.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
|
|
1445
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Mt.url.toString(),()=>{if(l)it();Mt.stop()}),n.native){let P,I=ne.join(k,"index.stx");if(ue.existsSync(I)){let Q=await Bun.file(I).text();P=gt(Q)}let N=h?.app?.window??{};await Qe(Xe,{title:h?.app?.head?.title||ne.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>ne.dirname(J))??[]].filter((J)=>ue.existsSync(J)).map((J)=>ue.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!ue.existsSync(W))continue;let de=ue.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${ne.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&ue.existsSync(J))N.set(J,ue.watch(J,{recursive:!0},(W,de)=>{Oe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Oe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>we(U,J,W)),q),we=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let de=await m(f);Object.assign(h,de),M.splice(0,M.length,...X(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ze.clear(),me();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-qx8cav4w.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(D&&W){if(ne.resolve(U,W)===D||ne.basename(D)===W){let K=await wo(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await cr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ze.clear(),me();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-qx8cav4w.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(yt(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();Mt.stop(),process.exit(0)})}return!0}import Wt from"fs";import at from"path";async function Nr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],m=u[2]||u[3]||u[4];if(!m)continue;let h={name:m},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
|
|
1446
|
+
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Vr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
|
|
1447
|
+
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,n=!1,r){let d=at.basename(t,".stx"),o=await Nr(t),l=await Vr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((m)=>{if(m.type==="boolean")return`:${m.name}="true"`;return`${m.name}="value"`}).join(`
|
|
1448
1448
|
`);u=`<${d}
|
|
1449
1449
|
${f}
|
|
1450
|
-
/>`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function
|
|
1451
|
-
`).map((y)=>y.trim().replace(/^\*\s*/,"")).join(" ").trim():"",h=/@component\(\s*['"]([^'"]+)['"]/g,x=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,v=new Set,S;while((S=h.exec(l))!==null)v.add(S[1]);while((S=x.exec(l))!==null)if(S[1]&&S[1]!=="slot")v.add(S[1]);let T=/@([a-z]+)(?:\s*\(|\s+|$)/g,w=new Set;while((S=T.exec(l))!==null)w.add(S[1]);r.push({name:u,path:o,description:m,components:[...v],directives:[...w]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function
|
|
1450
|
+
/>`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function un(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Wt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){let o=at.join(t,d.name);if(d.isDirectory()){let l=await un(o);r.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Xr(t,n){try{if(!await s(t))return[];let r=await un(t),d=[],o=new Map;if(n?.components?.length)for(let l of n.components)o.set(l.file,l);for(let l of r){let u=o.get(l),f=!!u,m=u?.tag,h=await Kr(l,f,m);d.push(h)}return d}catch(r){return console.error("Error generating component docs:",r),[]}}async function Gr(t){try{if(!await s(t))return[];let n=await Wt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let o=at.join(t,d.name),l=await Bun.file(o).text(),u=at.basename(o,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),m=f?f[1].split(`
|
|
1451
|
+
`).map((y)=>y.trim().replace(/^\*\s*/,"")).join(" ").trim():"",h=/@component\(\s*['"]([^'"]+)['"]/g,x=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,v=new Set,S;while((S=h.exec(l))!==null)v.add(S[1]);while((S=x.exec(l))!==null)if(S[1]&&S[1]!=="slot")v.add(S[1]);let T=/@([a-z]+)(?:\s*\(|\s+|$)/g,w=new Set;while((S=T.exec(l))!==null)w.add(S[1]);r.push({name:u,path:o,description:m,components:[...v],directives:[...w]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function Yr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1452
1452
|
<p>Welcome, {{ user.name }}!</p>
|
|
1453
1453
|
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
1454
1454
|
<p>Welcome back!</p>
|
|
@@ -1468,7 +1468,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1468
1468
|
<p>Page {{ page }}</p>
|
|
1469
1469
|
@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
|
|
1470
1470
|
{{ This will be displayed as-is }}
|
|
1471
|
-
@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 r of t)n.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function
|
|
1471
|
+
@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 r of t)n.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function Qr(t=[],n=[],r=[],d){let o=`# stx Documentation
|
|
1472
1472
|
|
|
1473
1473
|
`;if(d)o+=`${d}
|
|
1474
1474
|
|
|
@@ -1510,7 +1510,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1510
1510
|
|
|
1511
1511
|
`,o+=`#### Example
|
|
1512
1512
|
|
|
1513
|
-
`,o+="```html\n",o+=l.example,o+="\n```\n\n"}return o}function
|
|
1513
|
+
`,o+="```html\n",o+=l.example,o+="\n```\n\n"}return o}function Zr(t=[],n=[],r=[],d){let o=`<!DOCTYPE html>
|
|
1514
1514
|
<html lang="en">
|
|
1515
1515
|
<head>
|
|
1516
1516
|
<meta charset="UTF-8">
|
|
@@ -1581,12 +1581,12 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1581
1581
|
<td>@${l.name}</td>
|
|
1582
1582
|
<td>${l.description||"-"}</td>
|
|
1583
1583
|
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1584
|
-
</tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return o+="</body></html>",o}function
|
|
1585
|
-
`;let d=t;if(r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=
|
|
1584
|
+
</tr>`;o+="</tbody></table>";for(let l of r)if(l.example)o+=`<h3>@${l.name}</h3>`,o+=`<p>${l.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return o+="</body></html>",o}function eo(t=[],n=[],r=[],d){return JSON.stringify({components:t,templates:n,directives:r,extraContent:d||""},null,2)}async function to(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:d,customDirectives:o,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Wt.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Xr(n,d),console.log(`Found ${f.length} components`);let m=[];if(l.templates!==!1&&r)console.log("Generating template documentation..."),m=await Gr(r),console.log(`Found ${m.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Yr(o),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Qr(f,m,h,v),T="md";break;case"html":S=Zr(f,m,h,v),T="html";break;case"json":S=eo(f,m,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function sa(t){let n={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},r=t.componentsDir||O.componentsDir,d=t.templatesDir||".";return to({componentsDir:r,templatesDir:d,webComponentsConfig:O.webComponents,customDirectives:O.customDirectives,config:n})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function uo(t,n={}){let r={...mn,...n};if(t.trim()==="")return`
|
|
1585
|
+
`;let d=t;if(r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=oo(d,r),d=co(d,r),d=so(d,r),r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
|
|
1586
1586
|
`).replace(/\r/g,`
|
|
1587
1587
|
`),!d.endsWith(`
|
|
1588
1588
|
`))d+=`
|
|
1589
|
-
`;return d}function
|
|
1589
|
+
`;return d}function oa(t,n={}){let r={...mn,...n};if(t.trim()==="")return`
|
|
1590
1590
|
`;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(o,l,u,f,m)=>{let h=f.split(`
|
|
1591
1591
|
`),x=h.filter((y)=>y.trim().length>0);if(x.length===0)return o;let v=Math.min(...x.map((y)=>{let k=y.match(/^( *)/);return k?k[1].length:0})),S=h.map((y)=>{if(y.trim().length===0)return"";return y.substring(v)}).join(`
|
|
1592
1592
|
`),w=uo(S,r).trimEnd().split(`
|
|
@@ -1597,7 +1597,7 @@ ${l}\`\`\``}),r.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replac
|
|
|
1597
1597
|
`).replace(/\r/g,`
|
|
1598
1598
|
`),!d.endsWith(`
|
|
1599
1599
|
`))d+=`
|
|
1600
|
-
`;return d}function
|
|
1600
|
+
`;return d}function ro(t){let n=t,r=[],d="__PROTECTED_BLOCK_";return n=n.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(o)=>{let l=r.length;return r.push(o),`${d}${l}__`}),n=n.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1601
1601
|
$1
|
|
1602
1602
|
`),n=n.replace(/(@end\w+)/g,`
|
|
1603
1603
|
$1
|
|
@@ -1611,10 +1611,10 @@ ${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,l,u,f)=>{let m=f.substring(Math.max
|
|
|
1611
1611
|
`}),n=n.replace(new RegExp(`${d}(\\d+)__`,"g"),(o,l)=>r[Number.parseInt(l,10)]),n=n.replace(/\n{2,}/g,`
|
|
1612
1612
|
`),n=n.split(`
|
|
1613
1613
|
`).map((o)=>o.trim()).join(`
|
|
1614
|
-
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function
|
|
1615
|
-
`),o=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let m=0;m<d.length;m++){let h=d[m],x=h.trim();if(x===""){o.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){o.push(h);continue}let T=x===">";if(
|
|
1616
|
-
`)}function
|
|
1617
|
-
`)||o.includes("@"))return r;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(o))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let m=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${m?` ${m}`:""}>`})}import
|
|
1614
|
+
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function oo(t,n){let d=ro(t).split(`
|
|
1615
|
+
`),o=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let m=0;m<d.length;m++){let h=d[m],x=h.trim();if(x===""){o.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){o.push(h);continue}let T=x===">";if(fn(x)&&!x.startsWith("<")&&!x.startsWith("@")){o.push(f.repeat(l)+x);continue}let w=x.startsWith("@end"),y=x.startsWith("@else")||x.startsWith("@elseif"),k=x.startsWith("@")&&ao(x),M=x.startsWith("<!DOCTYPE")||x.startsWith("<!doctype"),E=x.startsWith("<!--"),R=x.startsWith("</"),A=x.startsWith("<")&&!R&&!E&&!M,C=x.includes("/>")||io(x),D=fn(x);if(R||w)l=Math.max(0,l-1);let L=y?Math.max(0,l-1):l;if(T)o.push(h);else o.push(f.repeat(L)+x);if(A&&!C&&!D&&!T||k)l++;if(v)u=!0;if(S)u=!1}return o.join(`
|
|
1616
|
+
`)}function so(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,d,o)=>{let l=o.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,d,o)=>{if(o.trim()==="")return`@${d}`;return`@${d}(${o.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,d)=>`{!! ${d.trim()} !!}`);return t}function io(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let r=t.match(/<(\w+)/);if(r){let d=r[1];return n.includes(d.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ao(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of n)if(t.startsWith(`@${r}`))return!t.includes(`@end${r}`);return!1}function co(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(r,d,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
|
|
1617
|
+
`)||o.includes("@"))return r;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(o))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let m=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${m?` ${m}`:""}>`})}import gn from"fs";import Vt from"path";async function ia(t="index.stx",n={}){try{let r=n.force||!1,d=Vt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Vt.dirname(d);if(!gn.existsSync(o))gn.mkdirSync(o,{recursive:!0});let l;if(n.template){let u=Vt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)l=hn(n.preset),console.warn(`Using '${n.preset}' preset template`);else l=hn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function hn(t){switch(t){case"basic":return bn();case"component":return lo();case"layout":return mo();case"blog":return go();case"api":return ho();case"app":return yo();default:return bn()}}function bn(){return`<script>
|
|
1618
1618
|
const title = "My stx Page"
|
|
1619
1619
|
const description = "A page built with stx"
|
|
1620
1620
|
const features = [
|
|
@@ -1639,7 +1639,7 @@ const features = [
|
|
|
1639
1639
|
</div>
|
|
1640
1640
|
@endforeach
|
|
1641
1641
|
</main>
|
|
1642
|
-
@endsection`}function
|
|
1642
|
+
@endsection`}function lo(){return`{{-- Component: Card --}}
|
|
1643
1643
|
{{-- Props: title, variant, collapsible --}}
|
|
1644
1644
|
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1645
1645
|
<script>
|
|
@@ -1684,7 +1684,7 @@ const features = [
|
|
|
1684
1684
|
.card.collapsed .card__toggle { transform: rotate(-90deg); }
|
|
1685
1685
|
.card__body { padding: 1rem; }
|
|
1686
1686
|
.card.collapsed .card__body { display: none; }
|
|
1687
|
-
</style>`}function
|
|
1687
|
+
</style>`}function mo(){return`<!DOCTYPE html>
|
|
1688
1688
|
<html lang="en">
|
|
1689
1689
|
<head>
|
|
1690
1690
|
<meta charset="UTF-8">
|
|
@@ -1735,7 +1735,7 @@ const features = [
|
|
|
1735
1735
|
|
|
1736
1736
|
@yield('scripts')
|
|
1737
1737
|
</body>
|
|
1738
|
-
</html>`}function
|
|
1738
|
+
</html>`}function go(){return`<script>
|
|
1739
1739
|
// Article metadata
|
|
1740
1740
|
const title = "My Blog Post"
|
|
1741
1741
|
const author = "Your Name"
|
|
@@ -1780,7 +1780,7 @@ const features = [
|
|
|
1780
1780
|
<p>Wrap up your thoughts here.</p>
|
|
1781
1781
|
</div>
|
|
1782
1782
|
</article>
|
|
1783
|
-
@endsection`}function
|
|
1783
|
+
@endsection`}function ho(){return`<script>
|
|
1784
1784
|
// API endpoint configuration
|
|
1785
1785
|
const endpoint = "/api/data"
|
|
1786
1786
|
const method = "GET"
|
|
@@ -1815,7 +1815,7 @@ const features = [
|
|
|
1815
1815
|
}
|
|
1816
1816
|
@else
|
|
1817
1817
|
{{ JSON.stringify(data, null, 2) }}
|
|
1818
|
-
@endif`}function
|
|
1818
|
+
@endif`}function yo(){return`<!DOCTYPE html>
|
|
1819
1819
|
<html lang="en">
|
|
1820
1820
|
<head>
|
|
1821
1821
|
<meta charset="UTF-8">
|
|
@@ -2040,5 +2040,5 @@ const features = [
|
|
|
2040
2040
|
})();
|
|
2041
2041
|
</script>
|
|
2042
2042
|
</body>
|
|
2043
|
-
</html>`}var
|
|
2044
|
-
`)}export{
|
|
2043
|
+
</html>`}var aa="f9c3713";function Ll(t){return t}function jl(t){return t}function ta(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function Cn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function kt(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $i(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function Rn(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Ci(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ri(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,m){if(m>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Pn){let S=ye.join(f,v),T=Ci(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:m>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let y of w){let k=ye.join(S,y.name,"node_modules");if(_e.existsSync(k))l(k,m+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,m+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ei(t){let n=[];for(let r of Pn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function po(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??$i,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.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 u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let m of Ei(Ri(n)))o.push(m);let f=Rn(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let m=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=Cn(m),v=h?Cn(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.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 ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${kt(v,d)}) is OLDER than src/signals.ts (${kt(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${kt(x,d)}, dist ${kt(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let y=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===y?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.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(o.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 h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(m){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${m.message}`})}return{checks:o,ok:!o.some((m)=>m.status==="error")}}function fo(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
|
|
2044
|
+
`)}export{ta,na,ra,sa,uo,oa,ia,aa,Ll,jl,po,fo,Ur,Wr,qr};
|