@stacksjs/stx 0.2.563 → 0.2.565
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/app-shell.d.ts +3 -0
- package/dist/app-shell.js +27 -3
- package/dist/{chunk-2tm3vzm7.js → chunk-01s01ten.js} +5 -5
- package/dist/chunk-04qvjcsr.js +2 -0
- package/dist/chunk-125rc958.js +3 -0
- package/dist/chunk-15g5sc0p.js +3 -0
- package/dist/{chunk-171xv81z.js → chunk-18270qgd.js} +2 -2
- package/dist/{chunk-g6cwhsb4.js → chunk-1hrj0t0j.js} +11 -11
- package/dist/chunk-1zfg1kd5.js +2 -0
- package/dist/chunk-203rr1c8.js +3 -0
- package/dist/{chunk-xb739v4r.js → chunk-2ernwctg.js} +6 -6
- package/dist/chunk-2xbrrc5a.js +2 -0
- package/dist/chunk-2yypassp.js +2 -0
- package/dist/{chunk-fgmv8f14.js → chunk-325p135t.js} +12 -12
- package/dist/{chunk-v1m9nrn9.js → chunk-36aj0yzt.js} +1 -1
- package/dist/chunk-375skn32.js +2 -0
- package/dist/{chunk-qmza4327.js → chunk-39tkfkp7.js} +3 -3
- package/dist/{chunk-jjwg83xv.js → chunk-3hkv4e7t.js} +1 -1
- package/dist/chunk-3wyxe996.js +2 -0
- package/dist/chunk-4mmdpb46.js +2 -0
- package/dist/chunk-4q5d5r7s.js +2 -0
- package/dist/{chunk-mtdx75j5.js → chunk-4zb2ga7p.js} +2 -2
- package/dist/{chunk-vb1w9wy4.js → chunk-55hfvmvv.js} +13 -13
- package/dist/{chunk-7t05bpf7.js → chunk-5grx48s2.js} +2 -2
- package/dist/{chunk-7wfh2hqy.js → chunk-5s555c1r.js} +4 -4
- package/dist/chunk-5ytg0wbc.js +2 -0
- package/dist/{chunk-8227vfw0.js → chunk-68b64sj4.js} +1 -1
- package/dist/chunk-6qyters0.js +2 -0
- package/dist/{chunk-6bxy1b9q.js → chunk-6sf4v894.js} +5 -5
- package/dist/{chunk-yp00nht2.js → chunk-6vnnx536.js} +2 -2
- package/dist/chunk-6yn90mq9.js +2 -0
- package/dist/chunk-7d2vyre0.js +2 -0
- package/dist/{chunk-r4199q6x.js → chunk-7m0r2qs2.js} +2 -2
- package/dist/chunk-7pewegtw.js +2 -0
- package/dist/chunk-7w0qa3n0.js +2 -0
- package/dist/{chunk-5fx8m234.js → chunk-7wyyjdks.js} +2 -2
- package/dist/{chunk-nd8v4xgb.js → chunk-7ze47qgv.js} +5 -5
- package/dist/{chunk-x8rx0s3h.js → chunk-8afnq4qx.js} +3 -3
- package/dist/{chunk-gxtk4fbm.js → chunk-8cpqy9ea.js} +1726 -1726
- package/dist/{chunk-97vj2cqz.js → chunk-8cs45k3f.js} +3 -3
- package/dist/chunk-8d788kvt.js +2 -0
- package/dist/{chunk-s040j1bv.js → chunk-8nr1kras.js} +6 -6
- package/dist/{chunk-912cj8pq.js → chunk-8txqk9nq.js} +2 -2
- package/dist/chunk-90qywh24.js +31 -0
- package/dist/{chunk-nda4xq79.js → chunk-9tcvkbb5.js} +2 -2
- package/dist/{chunk-vpmb8gcc.js → chunk-9ya4tdpz.js} +4 -4
- package/dist/{chunk-n1cqg89v.js → chunk-b76jbdtk.js} +2 -2
- package/dist/chunk-bdhtq3vs.js +2 -0
- package/dist/chunk-brnapchc.js +2 -0
- package/dist/chunk-c765y72x.js +18 -0
- package/dist/chunk-c78327kx.js +2 -0
- package/dist/chunk-cbyh8fhn.js +4 -0
- package/dist/chunk-d19w3e4x.js +2 -0
- package/dist/{chunk-jen9yg68.js → chunk-d1mqedk0.js} +7 -7
- package/dist/{chunk-6v1gwdbv.js → chunk-d4ybwtqt.js} +2 -2
- package/dist/chunk-da649d3k.js +2 -0
- package/dist/chunk-da9avgd9.js +2 -0
- package/dist/chunk-dkyjw3hc.js +3 -0
- package/dist/{chunk-ff61d2wr.js → chunk-dmf1jmge.js} +3 -3
- package/dist/chunk-e3njkecx.js +2 -0
- package/dist/chunk-efzc1nw8.js +2 -0
- package/dist/{chunk-h23bjqn1.js → chunk-ev3qnr9q.js} +31 -31
- package/dist/{chunk-y0pbnxjg.js → chunk-f46a7pvn.js} +2 -2
- package/dist/{chunk-azb58ven.js → chunk-ffxwsa94.js} +2 -2
- package/dist/chunk-fm4w1r9e.js +2 -0
- package/dist/{chunk-8jc86h7n.js → chunk-fpa1nq88.js} +2 -2
- package/dist/{chunk-tc2z8t2q.js → chunk-g1epk002.js} +5 -5
- package/dist/{chunk-8a4g0mex.js → chunk-g8tx0yf8.js} +7 -7
- package/dist/chunk-gan95hj0.js +2 -0
- package/dist/{chunk-e124cgb6.js → chunk-ghnkphy4.js} +2 -2
- package/dist/{chunk-m5fw8jq1.js → chunk-gjx5256r.js} +5 -5
- package/dist/chunk-hg7amzgz.js +2 -0
- package/dist/chunk-hmk7z0z6.js +2 -0
- package/dist/chunk-hn105xy3.js +2 -0
- package/dist/{chunk-8nwzd6eg.js → chunk-jbmhdyzz.js} +3 -3
- package/dist/chunk-jq079mrx.js +2 -0
- package/dist/chunk-jr149mmp.js +2 -0
- package/dist/{chunk-v79qs0qh.js → chunk-jra9r8fq.js} +1 -1
- package/dist/{chunk-zmq9hwta.js → chunk-k2dgwy05.js} +2 -2
- package/dist/chunk-k50k9zbw.js +2 -0
- package/dist/{chunk-xab6b4mt.js → chunk-kch9a9v1.js} +2 -2
- package/dist/chunk-kwxy0e3r.js +2 -0
- package/dist/chunk-kza3nxr0.js +2 -0
- package/dist/{chunk-g12j8ahm.js → chunk-m6m19hwd.js} +4 -4
- package/dist/{chunk-a5kaw8sc.js → chunk-m8qgr307.js} +8 -8
- package/dist/chunk-m9cmc6np.js +2 -0
- package/dist/chunk-m9r4x7e6.js +2 -0
- package/dist/chunk-mahv855w.js +2 -0
- package/dist/{chunk-27t55gtk.js → chunk-mb59b499.js} +6 -6
- package/dist/chunk-mbwdn96z.js +2 -0
- package/dist/chunk-mdxg95mq.js +2 -0
- package/dist/{chunk-2m91qmby.js → chunk-mm1vvk49.js} +5 -5
- package/dist/chunk-mqje968d.js +2 -0
- package/dist/{chunk-pp9jgyb6.js → chunk-mt8sew7a.js} +10 -10
- package/dist/{chunk-7gdvp6py.js → chunk-n1xcmhjw.js} +3 -3
- package/dist/chunk-n2g9mj2h.js +2 -0
- package/dist/chunk-n2nha538.js +2 -0
- package/dist/{chunk-f92hq39b.js → chunk-n6va14bt.js} +2 -2
- package/dist/chunk-nebw444s.js +2 -0
- package/dist/{chunk-gbx3gx8a.js → chunk-nm0y4qjg.js} +4 -4
- package/dist/chunk-nmt7kw0e.js +2 -0
- package/dist/chunk-pq8mz4ma.js +2 -0
- package/dist/chunk-pxcmv1xz.js +2 -0
- package/dist/chunk-pxes1ft6.js +2 -0
- package/dist/{chunk-v09hk0j6.js → chunk-pzasxhwz.js} +1 -1
- package/dist/{chunk-v2b8pa86.js → chunk-q94wdmdp.js} +3 -3
- package/dist/chunk-qajc13zq.js +2 -0
- package/dist/{chunk-1c4t7ncb.js → chunk-qj4j547f.js} +2 -2
- package/dist/chunk-qtnqmw1n.js +2 -0
- package/dist/chunk-r3zdgeah.js +2 -0
- package/dist/{chunk-4r7s3862.js → chunk-r47cs92n.js} +2 -2
- package/dist/chunk-r5htacg5.js +2 -0
- package/dist/chunk-rf2rwddd.js +2 -0
- package/dist/{chunk-1xgs9gd5.js → chunk-rgage0vm.js} +2 -2
- package/dist/{chunk-1zeqghsw.js → chunk-s1xxkzc9.js} +9 -9
- package/dist/chunk-s833fbvf.js +2 -0
- package/dist/{chunk-tqnh98j7.js → chunk-saf7kypg.js} +3 -3
- package/dist/chunk-sgvszh9s.js +2 -0
- package/dist/{chunk-emta09j6.js → chunk-ss78553t.js} +1 -1
- package/dist/chunk-t5r3s1wj.js +2 -0
- package/dist/{chunk-bqdsc6rm.js → chunk-tc01jkfc.js} +1 -1
- package/dist/{chunk-p2mxsjv1.js → chunk-tfeenp4h.js} +10 -10
- package/dist/chunk-tjprg6kq.js +2 -0
- package/dist/{chunk-hj67a88k.js → chunk-tsmbstj6.js} +7 -7
- package/dist/chunk-v0dzrwg8.js +2 -0
- package/dist/chunk-vtz9empe.js +2 -0
- package/dist/chunk-wa6nzq5b.js +2 -0
- package/dist/{chunk-3nc2fr4q.js → chunk-wm11csdm.js} +2 -2
- package/dist/{chunk-xj45mw7v.js → chunk-wsdn5fxe.js} +3 -3
- package/dist/{chunk-ah7h9q0x.js → chunk-wwn9dh6p.js} +2 -2
- package/dist/{chunk-yn3kp3qy.js → chunk-wy4hfmjs.js} +5 -5
- package/dist/{chunk-qfc912e5.js → chunk-xfpfs9zq.js} +2 -2
- package/dist/chunk-xw8kzm6b.js +2834 -0
- package/dist/chunk-xyhg70x9.js +63 -0
- package/dist/{chunk-w8q1xp9e.js → chunk-ymdy7b8z.js} +2 -2
- package/dist/chunk-ytdzgctp.js +2 -0
- package/dist/{chunk-wk85dz07.js → chunk-z06npyzn.js} +3 -3
- package/dist/chunk-z2n1rtj5.js +2 -0
- package/dist/cli.js +22 -22
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/database.js +2 -2
- package/dist/native/components/primitives.d.ts +20 -4
- package/dist/native/index.d.ts +3 -0
- package/dist/native/primitives/Map.stx +2 -1
- package/dist/native/prop-names.js +3 -0
- package/dist/native/runtime/craft-bridge.js +24 -11
- package/dist/native/runtime/craft.d.ts +6 -5
- package/dist/pwa.js +3 -3
- package/dist/ssg.js +11 -11
- package/dist/stx.d.ts +1 -1028
- package/dist/variable-extractor.js +2 -2
- package/package.json +5 -5
- package/stx.d.ts +2 -0
- package/dist/chunk-00dp53cx.js +0 -2
- package/dist/chunk-0pvn63x7.js +0 -2
- package/dist/chunk-0vpmdhfm.js +0 -2
- package/dist/chunk-10jwyvm0.js +0 -2
- package/dist/chunk-1ena03xn.js +0 -2
- package/dist/chunk-2bpj2dsh.js +0 -2
- package/dist/chunk-31ez1sq0.js +0 -2
- package/dist/chunk-3m2h76cz.js +0 -2
- package/dist/chunk-3n26hf93.js +0 -2
- package/dist/chunk-3nk8cnrm.js +0 -3
- package/dist/chunk-3tccqahy.js +0 -2
- package/dist/chunk-40fqmb3q.js +0 -2
- package/dist/chunk-45tq56qf.js +0 -2
- package/dist/chunk-46wykvrs.js +0 -2
- package/dist/chunk-4cmqjmqr.js +0 -3
- package/dist/chunk-56mkcxvb.js +0 -2
- package/dist/chunk-56wcmck6.js +0 -2
- package/dist/chunk-5eyf2zeg.js +0 -2
- package/dist/chunk-68ph8r20.js +0 -2
- package/dist/chunk-6bcvd3pg.js +0 -2
- package/dist/chunk-6n8jzdnm.js +0 -18
- package/dist/chunk-6va8wt88.js +0 -2
- package/dist/chunk-7acxdp9r.js +0 -2
- package/dist/chunk-7h324n17.js +0 -2
- package/dist/chunk-8fpz04kx.js +0 -2
- package/dist/chunk-8fwczr4s.js +0 -63
- package/dist/chunk-9skdekv5.js +0 -2
- package/dist/chunk-c3v5zmnq.js +0 -2
- package/dist/chunk-ce7zwt4v.js +0 -2
- package/dist/chunk-cp4dr9ch.js +0 -2
- package/dist/chunk-d7mfkc61.js +0 -2
- package/dist/chunk-d8fhthyf.js +0 -2
- package/dist/chunk-dekpf1ry.js +0 -2
- package/dist/chunk-dyavx9a1.js +0 -2
- package/dist/chunk-dz7v901d.js +0 -2
- package/dist/chunk-e099d50m.js +0 -2
- package/dist/chunk-e473tm1d.js +0 -2
- package/dist/chunk-eeadhr78.js +0 -2
- package/dist/chunk-evwj0k99.js +0 -2834
- package/dist/chunk-f11sx09b.js +0 -3
- package/dist/chunk-fdkyvr7y.js +0 -2
- package/dist/chunk-fqge0zn8.js +0 -2
- package/dist/chunk-fz7dxc1q.js +0 -2
- package/dist/chunk-hp8g2q2n.js +0 -2
- package/dist/chunk-hpeg9erh.js +0 -3
- package/dist/chunk-hv2kxb94.js +0 -2
- package/dist/chunk-j9c0yam7.js +0 -2
- package/dist/chunk-k9nd7z8j.js +0 -2
- package/dist/chunk-m7jmpech.js +0 -2
- package/dist/chunk-m7ktr4xn.js +0 -2
- package/dist/chunk-mjdyyekx.js +0 -4
- package/dist/chunk-njrakvz7.js +0 -2
- package/dist/chunk-nr5jf1hp.js +0 -2
- package/dist/chunk-qd7bqhm3.js +0 -2
- package/dist/chunk-qprkb5qe.js +0 -2
- package/dist/chunk-schxd5k5.js +0 -2
- package/dist/chunk-sn5c0x7q.js +0 -2
- package/dist/chunk-sx4wmprc.js +0 -2
- package/dist/chunk-t94z65ry.js +0 -2
- package/dist/chunk-vakryadj.js +0 -2
- package/dist/chunk-vgge9rf4.js +0 -2
- package/dist/chunk-w36w5jgs.js +0 -30
- package/dist/chunk-wzymzex7.js +0 -2
- package/dist/chunk-x07x8hzs.js +0 -2
- package/dist/chunk-z9q5p39g.js +0 -2
- package/dist/chunk-zfypzka2.js +0 -2
- package/dist/chunk-zh0jbzvk.js +0 -2
- package/dist/chunk-zpf9he2x.js +0 -2
- package/dist/chunk-zpftj8s8.js +0 -2
|
@@ -1,1480 +1,950 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
import{q,b,on,an,e,_t,cn,f,He,Tt,Ue,Ve,ee,N,de,X,d,ve,yi,Ss,n,r,ne,Qn,o,A,ue}from"./chunk-xw8kzm6b.js";import{J,vn,re,P,It}from"./chunk-m8qgr307.js";import{nt,Cn,fr,gr,mr,rt,st,ot,it,at,ct,Ee}from"./chunk-ev3qnr9q.js";import{Ie,uo,se,_,po,$r,On,ye,fo,oe}from"./chunk-90qywh24.js";import{Mt}from"./chunk-125rc958.js";import{le}from"./chunk-ffxwsa94.js";import{a}from"./chunk-203rr1c8.js";import{D}from"./chunk-dkyjw3hc.js";async function Xn(t){try{let s=await Bun.file(t).text(),i=Gn(s),p=Jn(s,t),c=Yn(s,i),l=Zn(s,i);return{file:t,metrics:i,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Gn(t){let s=t.split(`
|
|
3
|
+
`),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
|
|
4
|
+
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function Jn(t,s){let i=[],p=Jt(t,"if","endif");if(p>0)i.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Jt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let y=u.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
|
|
5
|
+
`).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Yn(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Zn(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Jt(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Ys(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await Xn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),p=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),h=[];if(p>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Pe from"path";function rn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var sn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ft(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(p){let c=await rr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Pe.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function dr(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let h=u[1];if(sn.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,C=g;for(;C<l.length&&y>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=u[0].includes("async")?"async ":"";i[h]=`${v}${h}(${u[2]}) {${l.slice(g,C-1)}}`,m.lastIndex=C}}return i}function pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
|
|
6
|
+
|
|
7
|
+
`)}function ur(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function hr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function yr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function br(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(p[h]!=="(")return null;let g=0,y="";for(let w=h;w<p.length;w++){let S=p[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,C,v]=w;s.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
|
|
8
|
+
`)}function bt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Ht(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function wr(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Zt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function kr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(h(),t[u]==="<"){let k=bt(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=bt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;for(let[H,M]of Bt(t.slice(u,k)))l[H]=M;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of Ht(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Bt(x)){if(m.push(k),!H.startsWith("{")){let M=Zt(H);if(M)c[k]=M;continue}for(let[M,I]of Bt(H))if(M==="default")l[k]=I;else if(M==="type"){let R=Zt(I);if(R)c[k]=R}}else if(x.startsWith("["))for(let k of Ht(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of Ht(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=wr(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:T}}function Bt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",h=p;while(p<s.length){let y=s[p];if(u){if(y==="\\")p++;else if(y===u)u=""}else if(y==="'"||y==='"'||y==="`")u=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;p++}let g=s.slice(h,p).trim();if(g)i.push([l[1],g]);p++}return i}function Tr(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Pe.resolve(Pe.dirname(s),x),H=Pe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${T}`})),""});let y=kr(l);if(y)u.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:h,declared:g}}function Cr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Rr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Er(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Pr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function Or(t,s,i){let p=Pe.isAbsolute(s.file)?s.file:Pe.resolve(t,s.file),c=await nr(p,"utf8"),l=lr(c,p),m=Pe.basename(p,".stx"),u=s.name||l.name||sr(m),h=`${Ft(i.prefix||"stx")}-${Ft(m)}`,g=s.tag||l.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!ir(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([M,I])=>[M,en(M,I)])),S=Cr(pr(c)),C=Rr(S.template),v=Tr(c,p,Pe.resolve(i.outputDir)),x=br(C.template);for(let M of v.propNames){if(w[M])continue;let I=v.defaults[M];w[M]=en(M,{type:ur(v.declared[M])??hr(I),...I===void 0?{}:{default:yr(I)}})}let T=l.methods||{},k=s.methods||{},H=dr(c,p);return{file:Pe.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:C.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...T,...k,...H},eventTypes:S.eventTypes,bindings:C.bindings,slots:Er(C.template),cssProperties:Pr(Qt(c)),scope:v,render:x}}function Ar(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
9
|
+
|
|
10
|
+
const escapeHTML = (value) => String(value ?? '')
|
|
11
|
+
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
12
|
+
.replaceAll('"', '"').replaceAll("'", ''');
|
|
13
|
+
|
|
14
|
+
const valueAt = (host, path) => {
|
|
15
|
+
const parts = path.trim().split('.');
|
|
16
|
+
let value = host;
|
|
17
|
+
for (const part of parts) value = value?.[part];
|
|
18
|
+
return typeof value === 'function' ? value.call(host) : value;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const deserialize = (value, type, fallback) => {
|
|
22
|
+
if (value === null) return type === 'boolean' ? false : fallback;
|
|
23
|
+
if (type === 'boolean') return value !== 'false' && value !== '0';
|
|
24
|
+
if (type === 'number') return Number(value);
|
|
25
|
+
if (type === 'object' || type === 'array') {
|
|
26
|
+
try { return JSON.parse(value); }
|
|
27
|
+
catch { return fallback; }
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const serialize = (value, type) => {
|
|
33
|
+
if (value == null || value === false) return null;
|
|
34
|
+
if (type === 'boolean') return '';
|
|
35
|
+
if (type === 'object' || type === 'array') return JSON.stringify(value);
|
|
36
|
+
return String(value);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const cloneDefault = (value, type) => {
|
|
40
|
+
if (value == null || (type !== 'object' && type !== 'array')) return value;
|
|
41
|
+
if (typeof structuredClone === 'function') return structuredClone(value);
|
|
42
|
+
return JSON.parse(JSON.stringify(value));
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const defaultFor = property => cloneDefault(
|
|
46
|
+
property.default ?? ({ string: '', number: 0, boolean: false, object: {}, array: [] })[property.type],
|
|
47
|
+
property.type,
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
export class StxElement extends HTMLElementBase {
|
|
51
|
+
static definition = {};
|
|
52
|
+
static get observedAttributes() { return this.definition.observedAttributes || []; }
|
|
53
|
+
|
|
54
|
+
constructor() {
|
|
55
|
+
super();
|
|
56
|
+
this._values = Object.create(null);
|
|
57
|
+
this._reflecting = false;
|
|
58
|
+
this._connected = false;
|
|
59
|
+
this._hasConnected = false;
|
|
60
|
+
this._initializing = false;
|
|
61
|
+
this._updatePending = false;
|
|
62
|
+
this._listeners = new Map();
|
|
63
|
+
const definition = this.constructor.definition;
|
|
64
|
+
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
65
|
+
this._values[name] = defaultFor(property);
|
|
10
66
|
}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
border-radius: 3px;
|
|
14
|
-
border: 1px solid #ddd;
|
|
67
|
+
if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
|
|
68
|
+
this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
|
|
15
69
|
}
|
|
70
|
+
}
|
|
16
71
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
background-color: #121212;
|
|
20
|
-
color: #e1e4e8;
|
|
21
|
-
}
|
|
72
|
+
get updateComplete() { return this._updateComplete || Promise.resolve(); }
|
|
73
|
+
get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
|
|
22
74
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
75
|
+
connectedCallback() {
|
|
76
|
+
if (this._connected) return;
|
|
77
|
+
this._connected = true;
|
|
78
|
+
this._initializing = true;
|
|
79
|
+
const definition = this.constructor.definition;
|
|
80
|
+
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
81
|
+
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
82
|
+
if (attribute && this.hasAttribute?.(attribute)) this._values[name] = deserialize(this.getAttribute(attribute), property.type, defaultFor(property));
|
|
28
83
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
84
|
+
// Properties assigned before customElements.define() become own properties.
|
|
85
|
+
// Upgrade them after attributes so imperative state wins, matching the
|
|
86
|
+
// platform's property-first custom-element initialization convention.
|
|
87
|
+
for (const name of Object.keys(definition.properties || {})) this._upgradeProperty(name);
|
|
88
|
+
this._initializing = false;
|
|
89
|
+
const root = this.renderRoot;
|
|
90
|
+
const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
|
|
91
|
+
const firstConnection = !this._hasConnected;
|
|
92
|
+
if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
|
|
93
|
+
else this._upgradeDeclarativeEvents();
|
|
94
|
+
this._bindEvents();
|
|
95
|
+
if (firstConnection) {
|
|
96
|
+
this._hasConnected = true;
|
|
97
|
+
this.setAttribute?.('hydrated', '');
|
|
98
|
+
this.dispatchEvent?.(new CustomEvent('stx:hydrated', { bubbles: true, composed: true }));
|
|
33
99
|
}
|
|
100
|
+
// Called last, so a component that acquires something sees its own rendered
|
|
101
|
+
// markup and its events already bound. Reported rather than rethrown: a
|
|
102
|
+
// component that fails to set up must not take the element down with it.
|
|
103
|
+
try { this.onConnect?.(); }
|
|
104
|
+
catch (error) { console.error('[stx] onConnect failed', error); }
|
|
105
|
+
}
|
|
34
106
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
107
|
+
disconnectedCallback() {
|
|
108
|
+
this._connected = false;
|
|
109
|
+
// Called before the framework releases anything, so the element is still
|
|
110
|
+
// intact for a component that needs to read it on the way out, and inside
|
|
111
|
+
// try/finally so a throwing hook cannot leak the framework's own listeners.
|
|
112
|
+
try { this.onDisconnect?.(); }
|
|
113
|
+
catch (error) { console.error('[stx] onDisconnect failed', error); }
|
|
114
|
+
finally {
|
|
115
|
+
for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
|
|
116
|
+
this._listeners.clear();
|
|
39
117
|
}
|
|
118
|
+
}
|
|
40
119
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
120
|
+
attributeChangedCallback(attribute, oldValue, newValue) {
|
|
121
|
+
if (oldValue === newValue || this._reflecting) return;
|
|
122
|
+
const definition = this.constructor.definition;
|
|
123
|
+
const name = definition.attributeToProperty?.[attribute];
|
|
124
|
+
if (!name) return;
|
|
125
|
+
const property = definition.properties[name];
|
|
126
|
+
const value = deserialize(newValue, property.type, defaultFor(property));
|
|
127
|
+
if (!Object.is(this._values[name], value)) {
|
|
128
|
+
this._values[name] = value;
|
|
129
|
+
this.requestUpdate();
|
|
44
130
|
}
|
|
131
|
+
}
|
|
45
132
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
133
|
+
/**
|
|
134
|
+
* The props a compiled render reads.
|
|
135
|
+
*
|
|
136
|
+
* Its own method rather than _values directly, so a component that sets a
|
|
137
|
+
* property before upgrade still sees it, and so the generated code has one
|
|
138
|
+
* name to depend on rather than a private field's shape.
|
|
139
|
+
*/
|
|
140
|
+
_props() {
|
|
141
|
+
return this._values;
|
|
142
|
+
}
|
|
49
143
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
144
|
+
requestUpdate() {
|
|
145
|
+
if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
|
|
146
|
+
this._updatePending = true;
|
|
147
|
+
this._updateComplete = new Promise((resolve) => {
|
|
148
|
+
queueMicrotask(() => {
|
|
149
|
+
this._updatePending = false;
|
|
150
|
+
if (this._connected) this._render();
|
|
151
|
+
resolve();
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
return this._updateComplete;
|
|
155
|
+
}
|
|
61
156
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
157
|
+
emit(name, detail, options = {}) {
|
|
158
|
+
return this.dispatchEvent(new CustomEvent(name, {
|
|
159
|
+
detail, bubbles: true, composed: true, ...options,
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
_upgradeProperty(name) {
|
|
164
|
+
if (!Object.prototype.hasOwnProperty.call(this, name)) return;
|
|
165
|
+
const value = this[name];
|
|
166
|
+
delete this[name];
|
|
167
|
+
this[name] = value;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
_upgradeDeclarativeEvents() {
|
|
171
|
+
for (const element of this.renderRoot.querySelectorAll?.('*') || []) {
|
|
172
|
+
const names = element.getAttributeNames?.() || [...(element.attributes || [])].filter(Boolean).map(attribute => attribute.name);
|
|
173
|
+
for (const attributeName of names) {
|
|
174
|
+
if (!attributeName?.startsWith('@')) continue;
|
|
175
|
+
const [event, ...modifiers] = attributeName.slice(1).split('.');
|
|
176
|
+
element.setAttribute('data-stx-on-' + event, element.getAttribute(attributeName));
|
|
177
|
+
if (modifiers.length) element.setAttribute('data-stx-mod-' + event, modifiers.join(' '));
|
|
178
|
+
element.removeAttribute(attributeName);
|
|
70
179
|
}
|
|
71
180
|
}
|
|
181
|
+
}
|
|
72
182
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
`);return l=`
|
|
89
|
-
<!DOCTYPE html>
|
|
90
|
-
<html lang="en">
|
|
91
|
-
<head>
|
|
92
|
-
<meta charset="UTF-8">
|
|
93
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
94
|
-
<title>${or(S.title||pt.basename(c))}</title>
|
|
95
|
-
<!-- Syntax highlighting styles -->
|
|
96
|
-
<style id="syntax-theme">
|
|
97
|
-
:root {
|
|
98
|
-
--shiki-color-text: #24292e;
|
|
99
|
-
--shiki-color-background: #ffffff;
|
|
100
|
-
--shiki-token-constant: #005cc5;
|
|
101
|
-
--shiki-token-string: #032f62;
|
|
102
|
-
--shiki-token-comment: #6a737d;
|
|
103
|
-
--shiki-token-keyword: #d73a49;
|
|
104
|
-
--shiki-token-parameter: #24292e;
|
|
105
|
-
--shiki-token-function: #6f42c1;
|
|
106
|
-
--shiki-token-string-expression: #032f62;
|
|
107
|
-
--shiki-token-punctuation: #24292e;
|
|
108
|
-
--shiki-token-link: #032f62;
|
|
109
|
-
}
|
|
110
|
-
pre {
|
|
111
|
-
background-color: var(--shiki-color-background);
|
|
112
|
-
padding: 1rem;
|
|
113
|
-
border-radius: 4px;
|
|
114
|
-
}
|
|
115
|
-
code {
|
|
116
|
-
color: var(--shiki-color-text);
|
|
117
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
118
|
-
}
|
|
119
|
-
.dark-mode {
|
|
120
|
-
--shiki-color-text: #e1e4e8;
|
|
121
|
-
--shiki-color-background: #24292e;
|
|
122
|
-
--shiki-token-constant: #79b8ff;
|
|
123
|
-
--shiki-token-string: #9ecbff;
|
|
124
|
-
--shiki-token-comment: #6a737d;
|
|
125
|
-
--shiki-token-keyword: #f97583;
|
|
126
|
-
--shiki-token-parameter: #e1e4e8;
|
|
127
|
-
--shiki-token-function: #b392f0;
|
|
128
|
-
--shiki-token-string-expression: #9ecbff;
|
|
129
|
-
--shiki-token-punctuation: #e1e4e8;
|
|
130
|
-
--shiki-token-link: #9ecbff;
|
|
131
|
-
}
|
|
132
|
-
</style>
|
|
133
|
-
<style>
|
|
134
|
-
body {
|
|
135
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
136
|
-
line-height: 1.6;
|
|
137
|
-
color: #333;
|
|
138
|
-
max-width: 800px;
|
|
139
|
-
margin: 0 auto;
|
|
140
|
-
padding: 2rem;
|
|
141
|
-
}
|
|
142
|
-
pre, code {
|
|
143
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
144
|
-
}
|
|
145
|
-
pre {
|
|
146
|
-
border-radius: 4px;
|
|
147
|
-
padding: 0;
|
|
148
|
-
margin: 1.5rem 0;
|
|
149
|
-
overflow-x: auto;
|
|
150
|
-
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
151
|
-
}
|
|
152
|
-
pre code {
|
|
153
|
-
display: block;
|
|
154
|
-
padding: 1rem;
|
|
155
|
-
overflow-x: auto;
|
|
156
|
-
}
|
|
157
|
-
/* Apply background color to code blocks based on theme */
|
|
158
|
-
pre.syntax-highlighter {
|
|
159
|
-
background-color: var(--shiki-color-background) !important;
|
|
160
|
-
}
|
|
161
|
-
.dark-mode pre.syntax-highlighter {
|
|
162
|
-
background-color: var(--shiki-color-background) !important;
|
|
163
|
-
}
|
|
164
|
-
code {
|
|
165
|
-
padding: 0.2rem 0.4rem;
|
|
166
|
-
border-radius: 3px;
|
|
167
|
-
}
|
|
168
|
-
h1, h2, h3, h4 {
|
|
169
|
-
margin-top: 2rem;
|
|
170
|
-
margin-bottom: 1rem;
|
|
171
|
-
}
|
|
172
|
-
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
173
|
-
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
174
|
-
h3 { color: #444; }
|
|
175
|
-
img {
|
|
176
|
-
max-width: 100%;
|
|
177
|
-
border-radius: 4px;
|
|
178
|
-
margin: 1rem 0;
|
|
179
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
180
|
-
}
|
|
181
|
-
blockquote {
|
|
182
|
-
border-left: 4px solid #ddd;
|
|
183
|
-
padding-left: 1rem;
|
|
184
|
-
margin-left: 0;
|
|
185
|
-
color: #555;
|
|
186
|
-
background: #f9f9f9;
|
|
187
|
-
padding: 0.5rem 1rem;
|
|
188
|
-
margin: 1.5rem 0;
|
|
189
|
-
}
|
|
190
|
-
table {
|
|
191
|
-
border-collapse: collapse;
|
|
192
|
-
width: 100%;
|
|
193
|
-
margin: 1.5rem 0;
|
|
194
|
-
}
|
|
195
|
-
th, td {
|
|
196
|
-
border: 1px solid #ddd;
|
|
197
|
-
padding: 0.5rem;
|
|
198
|
-
}
|
|
199
|
-
th {
|
|
200
|
-
background: #f0f0f0;
|
|
201
|
-
text-align: left;
|
|
202
|
-
}
|
|
203
|
-
tr:nth-child(even) {
|
|
204
|
-
background-color: #f8f8f8;
|
|
205
|
-
}
|
|
206
|
-
a {
|
|
207
|
-
color: #0066cc;
|
|
208
|
-
text-decoration: none;
|
|
209
|
-
}
|
|
210
|
-
a:hover {
|
|
211
|
-
text-decoration: underline;
|
|
212
|
-
}
|
|
213
|
-
hr {
|
|
214
|
-
border: 0;
|
|
215
|
-
border-top: 1px solid #eee;
|
|
216
|
-
margin: 2rem 0;
|
|
217
|
-
}
|
|
218
|
-
.frontmatter {
|
|
219
|
-
background: #f8f8f8;
|
|
220
|
-
border-radius: 4px;
|
|
221
|
-
padding: 1.5rem;
|
|
222
|
-
margin-bottom: 2rem;
|
|
223
|
-
font-size: 0.9rem;
|
|
224
|
-
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
225
|
-
border-left: 4px solid #ddd;
|
|
226
|
-
}
|
|
227
|
-
.frontmatter-item {
|
|
228
|
-
margin-bottom: 0.5rem;
|
|
229
|
-
display: flex;
|
|
230
|
-
}
|
|
231
|
-
.frontmatter-label {
|
|
232
|
-
font-weight: bold;
|
|
233
|
-
min-width: 100px;
|
|
234
|
-
color: #555;
|
|
183
|
+
_bindEvents() {
|
|
184
|
+
for (const event of this.constructor.definition.eventTypes || []) {
|
|
185
|
+
if (this._listeners.has(event)) continue;
|
|
186
|
+
const listener = ($event) => {
|
|
187
|
+
const selector = '[data-stx-on-' + event + ']';
|
|
188
|
+
const target = $event.target?.closest?.(selector);
|
|
189
|
+
if (!target || !this.renderRoot.contains(target)) return;
|
|
190
|
+
const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
|
|
191
|
+
if (modifiers.includes('prevent')) $event.preventDefault();
|
|
192
|
+
if (modifiers.includes('stop')) $event.stopPropagation();
|
|
193
|
+
const method = target.getAttribute('data-stx-on-' + event);
|
|
194
|
+
if (typeof this[method] === 'function') this[method]($event);
|
|
195
|
+
};
|
|
196
|
+
this.renderRoot.addEventListener(event, listener);
|
|
197
|
+
this._listeners.set(event, listener);
|
|
235
198
|
}
|
|
236
|
-
${bt()}
|
|
237
|
-
</style>
|
|
238
|
-
</head>
|
|
239
|
-
<body>
|
|
240
|
-
${wt(S)}
|
|
241
|
-
${xt(H)}
|
|
242
|
-
|
|
243
|
-
${w}
|
|
244
|
-
|
|
245
|
-
<script>
|
|
246
|
-
${vt()}
|
|
247
|
-
</script>
|
|
248
|
-
</body>
|
|
249
|
-
</html>
|
|
250
|
-
`,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let h=i;try{if(h=await Ye(i),h!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${h} 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:${h}/${e.reset}...`);let g=rr({port:h,fetch(w){if(new URL(w.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(w){return new Response(`<pre>${w}
|
|
251
|
-
${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
252
|
-
${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(`
|
|
253
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
|
|
254
|
-
${e.yellow}Routes:${e.reset}`);let y=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
|
|
255
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(p)Bt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(C,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function or(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Fi}=globalThis.Bun;import Fe from"fs";import Se from"path";class Jt{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let h=u.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${y}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),i++}catch{this.clients.delete(p)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function sr(t,s={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
|
|
256
|
-
<script>
|
|
257
|
-
(function() {
|
|
258
|
-
// stx Hot Reload Client
|
|
259
|
-
var wsUrl = 'ws://' + window.location.hostname + ':${t}';
|
|
260
|
-
var reconnectAttempts = 0;
|
|
261
|
-
var maxAttempts = ${c};
|
|
262
|
-
var reconnectInterval = ${p};
|
|
263
|
-
var socket = null;
|
|
264
|
-
var overlay = null;
|
|
265
|
-
var wasConnected = false; // Track if we ever connected successfully
|
|
266
|
-
|
|
267
|
-
${i?`
|
|
268
|
-
// Create connection status overlay
|
|
269
|
-
function createOverlay() {
|
|
270
|
-
overlay = document.createElement('div');
|
|
271
|
-
overlay.id = 'stx-hmr-overlay';
|
|
272
|
-
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;padding:8px 16px;background:#f59e0b;color:#000;font-family:system-ui,sans-serif;font-size:14px;text-align:center;z-index:999999;display:none;';
|
|
273
|
-
document.body.appendChild(overlay);
|
|
274
199
|
}
|
|
275
200
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
201
|
+
_render() {
|
|
202
|
+
const definition = this.constructor.definition;
|
|
203
|
+
const root = this.renderRoot;
|
|
204
|
+
const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
|
|
205
|
+
const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
|
|
206
|
+
const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
|
|
207
|
+
// A compiled component renders itself: the control flow and the derived
|
|
208
|
+
// values were turned into JavaScript at build time, so there is nothing to
|
|
209
|
+
// interpret here and nothing that needs an eval the page's CSP forbids.
|
|
210
|
+
// The string template remains for components that carry no logic.
|
|
211
|
+
let html = typeof this.render === 'function'
|
|
212
|
+
? this.render(RENDER_HELPERS)
|
|
213
|
+
: definition.template
|
|
214
|
+
.replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
|
|
215
|
+
.replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
|
|
216
|
+
if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
|
|
217
|
+
root.innerHTML = html;
|
|
218
|
+
this._applyBindings();
|
|
219
|
+
this._bindEvents();
|
|
220
|
+
if (focusKey) {
|
|
221
|
+
const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
|
|
222
|
+
const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
|
|
223
|
+
next?.focus?.();
|
|
224
|
+
if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
|
|
225
|
+
}
|
|
226
|
+
this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
|
|
288
227
|
}
|
|
289
|
-
`:`
|
|
290
|
-
function showOverlay() {}
|
|
291
|
-
function hideOverlay() {}
|
|
292
|
-
`}
|
|
293
228
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
if (
|
|
301
|
-
|
|
229
|
+
_applyBindings() {
|
|
230
|
+
for (const binding of this.constructor.definition.bindings || []) {
|
|
231
|
+
const element = this.renderRoot.querySelector('[data-stx-bind-' + binding.id + ']');
|
|
232
|
+
if (!element) continue;
|
|
233
|
+
const value = valueAt(this, binding.expression);
|
|
234
|
+
if (binding.name === 'class') element.className = value || '';
|
|
235
|
+
else if (binding.name === 'style' && typeof value === 'object') {
|
|
236
|
+
Object.assign(element.style, value);
|
|
302
237
|
}
|
|
303
|
-
|
|
238
|
+
else if (typeof value === 'boolean') {
|
|
239
|
+
element.toggleAttribute(binding.name, value);
|
|
240
|
+
if (binding.name in element) element[binding.name] = value;
|
|
241
|
+
}
|
|
242
|
+
else if (value == null || value === false) element.removeAttribute(binding.name);
|
|
243
|
+
else element.setAttribute(binding.name, String(value));
|
|
304
244
|
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
305
247
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
248
|
+
/**
|
|
249
|
+
* What a compiled render is handed.
|
|
250
|
+
*
|
|
251
|
+
* Passed in rather than closed over so the generated code names no globals, and
|
|
252
|
+
* a component module stays readable on its own: __escape is visibly a
|
|
253
|
+
* parameter, not something the bundler happened to leave in scope.
|
|
254
|
+
*/
|
|
255
|
+
const RENDER_HELPERS = {
|
|
256
|
+
escape: escapeHTML,
|
|
257
|
+
// The raw form is the author declaring the value is markup. Null becomes an
|
|
258
|
+
// empty string rather than the word "null", which is the only sensible
|
|
259
|
+
// reading of a missing fragment.
|
|
260
|
+
raw: (value) => String(value ?? ''),
|
|
261
|
+
// A loop over something absent runs zero times. Throwing here would fail a
|
|
262
|
+
// whole page over one empty list, which is never what the author meant.
|
|
263
|
+
values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
|
|
264
|
+
entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
|
|
265
|
+
};
|
|
316
266
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
// keeps the address bar untouched (this is a reload, not a
|
|
327
|
-
// navigation) and force=true bypasses the early return.
|
|
328
|
-
if (window.stxRouter && typeof window.stxRouter.navigate === 'function') {
|
|
329
|
-
window.stxRouter.navigate(window.location.pathname + window.location.search, false, true);
|
|
330
|
-
} else {
|
|
331
|
-
window.location.reload();
|
|
332
|
-
}
|
|
333
|
-
break;
|
|
334
|
-
|
|
335
|
-
case 'css-update':
|
|
336
|
-
console.log('[stx] CSS update:', msg.path);
|
|
337
|
-
updateCss(msg.path, msg.content);
|
|
338
|
-
break;
|
|
339
|
-
|
|
340
|
-
case 'error':
|
|
341
|
-
console.error('[stx] Error:', msg.content);
|
|
342
|
-
showOverlay('Build Error: ' + msg.content, true);
|
|
343
|
-
break;
|
|
344
|
-
|
|
345
|
-
case 'connected':
|
|
346
|
-
break;
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
catch (e) {
|
|
350
|
-
console.error('[stx] Invalid message:', e);
|
|
351
|
-
}
|
|
352
|
-
};
|
|
353
|
-
|
|
354
|
-
socket.onclose = function() {
|
|
355
|
-
socket = null;
|
|
356
|
-
// Only log and show overlay if we were previously connected
|
|
357
|
-
if (wasConnected) {
|
|
358
|
-
console.log('[stx] Connection closed, reconnecting...');
|
|
359
|
-
scheduleReconnect();
|
|
360
|
-
}
|
|
361
|
-
else {
|
|
362
|
-
// Silently retry initial connection
|
|
363
|
-
setTimeout(connect, reconnectInterval);
|
|
364
|
-
}
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
socket.onerror = function() {
|
|
368
|
-
// Errors are handled in onclose
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
function scheduleReconnect() {
|
|
373
|
-
if (reconnectAttempts < maxAttempts) {
|
|
374
|
-
reconnectAttempts++;
|
|
375
|
-
showOverlay('Reconnecting... (' + reconnectAttempts + '/' + maxAttempts + ')');
|
|
376
|
-
setTimeout(connect, reconnectInterval);
|
|
377
|
-
}
|
|
378
|
-
else {
|
|
379
|
-
showOverlay('Connection lost. Refresh to reconnect.', true);
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
// CSS hot update without full reload
|
|
384
|
-
function updateCss(path, content) {
|
|
385
|
-
// Try to find and update existing stylesheet
|
|
386
|
-
var links = document.querySelectorAll('link[rel="stylesheet"]');
|
|
387
|
-
for (var i = 0; i < links.length; i++) {
|
|
388
|
-
var href = links[i].getAttribute('href');
|
|
389
|
-
if (href && href.indexOf(path) !== -1) {
|
|
390
|
-
// Add cache-busting query param
|
|
391
|
-
var newHref = href.split('?')[0] + '?t=' + Date.now();
|
|
392
|
-
links[i].setAttribute('href', newHref);
|
|
393
|
-
return;
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// If content provided, inject as style tag
|
|
398
|
-
if (content) {
|
|
399
|
-
var style = document.createElement('style');
|
|
400
|
-
style.setAttribute('data-stx-hmr', path);
|
|
401
|
-
style.textContent = content;
|
|
402
|
-
|
|
403
|
-
// Remove old injected style
|
|
404
|
-
var old = document.querySelector('style[data-stx-hmr="' + path + '"]');
|
|
405
|
-
if (old) old.remove();
|
|
406
|
-
|
|
407
|
-
document.head.appendChild(style);
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// Start connection when DOM is ready
|
|
412
|
-
if (document.readyState === 'loading') {
|
|
413
|
-
document.addEventListener('DOMContentLoaded', connect);
|
|
414
|
-
}
|
|
415
|
-
else {
|
|
416
|
-
connect();
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
// Forward browser console to the dev server terminal
|
|
420
|
-
var _origLog = console.log;
|
|
421
|
-
var _origError = console.error;
|
|
422
|
-
var _origWarn = console.warn;
|
|
423
|
-
var _origInfo = console.info;
|
|
424
|
-
|
|
425
|
-
function _fwd(level, args) {
|
|
426
|
-
if (socket && socket.readyState === 1) {
|
|
427
|
-
try {
|
|
428
|
-
socket.send(JSON.stringify({
|
|
429
|
-
type: 'console',
|
|
430
|
-
level: level,
|
|
431
|
-
args: Array.prototype.slice.call(args).map(function(a) {
|
|
432
|
-
if (a === null) return 'null';
|
|
433
|
-
if (a === undefined) return 'undefined';
|
|
434
|
-
if (typeof a === 'object') { try { return JSON.stringify(a); } catch(e) { return String(a); } }
|
|
435
|
-
return String(a);
|
|
436
|
-
})
|
|
437
|
-
}));
|
|
438
|
-
} catch(e) {}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
console.log = function() { _origLog.apply(console, arguments); _fwd('log', arguments); };
|
|
443
|
-
console.error = function() { _origError.apply(console, arguments); _fwd('error', arguments); };
|
|
444
|
-
console.warn = function() { _origWarn.apply(console, arguments); _fwd('warn', arguments); };
|
|
445
|
-
console.info = function() { _origInfo.apply(console, arguments); _fwd('info', arguments); };
|
|
446
|
-
|
|
447
|
-
// Expose for debugging
|
|
448
|
-
window.__stxHmr = {
|
|
449
|
-
reconnect: connect,
|
|
450
|
-
status: function() { return socket ? socket.readyState : -1; }
|
|
451
|
-
};
|
|
452
|
-
})();
|
|
453
|
-
</script>
|
|
454
|
-
`}function Xe(t,s,i={}){let p=sr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function kt(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Tt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function $t(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Ct(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Mt from"path";async function ir(t){try{let s=await Bun.file(t).text(),i=ar(s),p=cr(s,t),c=lr(s,i),l=dr(s,i);return{file:t,metrics:i,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function ar(t){let s=t.split(`
|
|
455
|
-
`),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
|
|
456
|
-
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function cr(t,s){let i=[],p=Qt(t,"if","endif");if(p>0)i.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Qt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let y=u.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
|
|
457
|
-
`).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function lr(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function dr(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Qt(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Js(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await ir(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=ur(i);return{results:i,summary:c}}function ur(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),p=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),h=[];if(p>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:h}}import{mkdir as mr,readFile as hr,readdir as yr,stat as Zt,writeFile as br}from"fs/promises";import Oe from"path";function ln(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 dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function kr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let s=[];async function i(p){let c=await yr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Oe.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function Rr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let h=u[1];if(dn.has(h))throw Error(`${s}: client ${ln(h)}`);let g=m.lastIndex,y=1,w="",S=!1,C=g;for(;C<l.length&&y>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=u[0].includes("async")?"async ":"";i[h]=`${v}${h}(${u[2]}) {${l.slice(g,C-1)}}`,m.lastIndex=C}}return i}function Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function en(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
|
|
458
|
-
|
|
459
|
-
`)}function Or(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function Ar(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 Dr(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 Mr(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(p[h]!=="(")return null;let g=0,y="";for(let w=h;w<p.length;w++){let S=p[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,C,v]=w;s.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
|
|
460
|
-
`)}function Rt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function tn(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 Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(h(),t[u]==="<"){let k=Rt(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=Rt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;for(let[H,_]of Nt(t.slice(u,k)))l[H]=_;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of zt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Nt(x)){if(m.push(k),!H.startsWith("{")){let _=tn(H);if(_)c[k]=_;continue}for(let[_,I]of Nt(H))if(_==="default")l[k]=I;else if(_==="type"){let R=tn(I);if(R)c[k]=R}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=_r(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:T}}function Nt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",h=p;while(p<s.length){let y=s[p];if(u){if(y==="\\")p++;else if(y===u)u=""}else if(y==="'"||y==='"'||y==="`")u=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;p++}let g=s.slice(h,p).trim();if(g)i.push([l[1],g]);p++}return i}function Ir(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Oe.resolve(Oe.dirname(s),x),H=Oe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${T}`})),""});let y=Lr(l);if(y)u.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:h,declared:g}}function jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Br(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function nn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,i){let p=Oe.isAbsolute(s.file)?s.file:Oe.resolve(t,s.file),c=await hr(p,"utf8"),l=Rr(c,p),m=Oe.basename(p,".stx"),u=s.name||l.name||Sr(m),h=`${Ut(i.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!kr(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([_,I])=>[_,nn(_,I)])),S=jr(Pr(c)),C=Hr(S.template),v=Ir(c,p,Oe.resolve(i.outputDir)),x=Mr(C.template);for(let _ of v.propNames){if(w[_])continue;let I=v.defaults[_];w[_]=nn(_,{type:Or(v.declared[_])??Ar(I),...I===void 0?{}:{default:Dr(I)}})}let T=l.methods||{},k=s.methods||{},H=Er(c,p);return{file:Oe.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:C.template,styles:en(c),shadowMode:$r(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...T,...k,...H},eventTypes:S.eventTypes,bindings:C.bindings,slots:Br(C.template),cssProperties:Fr(en(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
461
|
-
|
|
462
|
-
const escapeHTML = (value) => String(value ?? '')
|
|
463
|
-
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
464
|
-
.replaceAll('"', '"').replaceAll("'", ''');
|
|
465
|
-
|
|
466
|
-
const valueAt = (host, path) => {
|
|
467
|
-
const parts = path.trim().split('.');
|
|
468
|
-
let value = host;
|
|
469
|
-
for (const part of parts) value = value?.[part];
|
|
470
|
-
return typeof value === 'function' ? value.call(host) : value;
|
|
471
|
-
};
|
|
472
|
-
|
|
473
|
-
const deserialize = (value, type, fallback) => {
|
|
474
|
-
if (value === null) return type === 'boolean' ? false : fallback;
|
|
475
|
-
if (type === 'boolean') return value !== 'false' && value !== '0';
|
|
476
|
-
if (type === 'number') return Number(value);
|
|
477
|
-
if (type === 'object' || type === 'array') {
|
|
478
|
-
try { return JSON.parse(value); }
|
|
479
|
-
catch { return fallback; }
|
|
480
|
-
}
|
|
481
|
-
return value;
|
|
482
|
-
};
|
|
483
|
-
|
|
484
|
-
const serialize = (value, type) => {
|
|
485
|
-
if (value == null || value === false) return null;
|
|
486
|
-
if (type === 'boolean') return '';
|
|
487
|
-
if (type === 'object' || type === 'array') return JSON.stringify(value);
|
|
488
|
-
return String(value);
|
|
489
|
-
};
|
|
490
|
-
|
|
491
|
-
const cloneDefault = (value, type) => {
|
|
492
|
-
if (value == null || (type !== 'object' && type !== 'array')) return value;
|
|
493
|
-
if (typeof structuredClone === 'function') return structuredClone(value);
|
|
494
|
-
return JSON.parse(JSON.stringify(value));
|
|
495
|
-
};
|
|
496
|
-
|
|
497
|
-
const defaultFor = property => cloneDefault(
|
|
498
|
-
property.default ?? ({ string: '', number: 0, boolean: false, object: {}, array: [] })[property.type],
|
|
499
|
-
property.type,
|
|
500
|
-
);
|
|
501
|
-
|
|
502
|
-
export class StxElement extends HTMLElementBase {
|
|
503
|
-
static definition = {};
|
|
504
|
-
static get observedAttributes() { return this.definition.observedAttributes || []; }
|
|
505
|
-
|
|
506
|
-
constructor() {
|
|
507
|
-
super();
|
|
508
|
-
this._values = Object.create(null);
|
|
509
|
-
this._reflecting = false;
|
|
510
|
-
this._connected = false;
|
|
511
|
-
this._hasConnected = false;
|
|
512
|
-
this._initializing = false;
|
|
513
|
-
this._updatePending = false;
|
|
514
|
-
this._listeners = new Map();
|
|
515
|
-
const definition = this.constructor.definition;
|
|
516
|
-
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
517
|
-
this._values[name] = defaultFor(property);
|
|
518
|
-
}
|
|
519
|
-
if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
|
|
520
|
-
this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
get updateComplete() { return this._updateComplete || Promise.resolve(); }
|
|
525
|
-
get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
|
|
526
|
-
|
|
527
|
-
connectedCallback() {
|
|
528
|
-
if (this._connected) return;
|
|
529
|
-
this._connected = true;
|
|
530
|
-
this._initializing = true;
|
|
531
|
-
const definition = this.constructor.definition;
|
|
532
|
-
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
533
|
-
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
534
|
-
if (attribute && this.hasAttribute?.(attribute)) this._values[name] = deserialize(this.getAttribute(attribute), property.type, defaultFor(property));
|
|
535
|
-
}
|
|
536
|
-
// Properties assigned before customElements.define() become own properties.
|
|
537
|
-
// Upgrade them after attributes so imperative state wins, matching the
|
|
538
|
-
// platform's property-first custom-element initialization convention.
|
|
539
|
-
for (const name of Object.keys(definition.properties || {})) this._upgradeProperty(name);
|
|
540
|
-
this._initializing = false;
|
|
541
|
-
const root = this.renderRoot;
|
|
542
|
-
const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
|
|
543
|
-
const firstConnection = !this._hasConnected;
|
|
544
|
-
if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
|
|
545
|
-
else this._upgradeDeclarativeEvents();
|
|
546
|
-
this._bindEvents();
|
|
547
|
-
if (firstConnection) {
|
|
548
|
-
this._hasConnected = true;
|
|
549
|
-
this.setAttribute?.('hydrated', '');
|
|
550
|
-
this.dispatchEvent?.(new CustomEvent('stx:hydrated', { bubbles: true, composed: true }));
|
|
551
|
-
}
|
|
552
|
-
// Called last, so a component that acquires something sees its own rendered
|
|
553
|
-
// markup and its events already bound. Reported rather than rethrown: a
|
|
554
|
-
// component that fails to set up must not take the element down with it.
|
|
555
|
-
try { this.onConnect?.(); }
|
|
556
|
-
catch (error) { console.error('[stx] onConnect failed', error); }
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
disconnectedCallback() {
|
|
560
|
-
this._connected = false;
|
|
561
|
-
// Called before the framework releases anything, so the element is still
|
|
562
|
-
// intact for a component that needs to read it on the way out, and inside
|
|
563
|
-
// try/finally so a throwing hook cannot leak the framework's own listeners.
|
|
564
|
-
try { this.onDisconnect?.(); }
|
|
565
|
-
catch (error) { console.error('[stx] onDisconnect failed', error); }
|
|
566
|
-
finally {
|
|
567
|
-
for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
|
|
568
|
-
this._listeners.clear();
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
attributeChangedCallback(attribute, oldValue, newValue) {
|
|
573
|
-
if (oldValue === newValue || this._reflecting) return;
|
|
574
|
-
const definition = this.constructor.definition;
|
|
575
|
-
const name = definition.attributeToProperty?.[attribute];
|
|
576
|
-
if (!name) return;
|
|
577
|
-
const property = definition.properties[name];
|
|
578
|
-
const value = deserialize(newValue, property.type, defaultFor(property));
|
|
579
|
-
if (!Object.is(this._values[name], value)) {
|
|
580
|
-
this._values[name] = value;
|
|
581
|
-
this.requestUpdate();
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
/**
|
|
586
|
-
* The props a compiled render reads.
|
|
587
|
-
*
|
|
588
|
-
* Its own method rather than _values directly, so a component that sets a
|
|
589
|
-
* property before upgrade still sees it, and so the generated code has one
|
|
590
|
-
* name to depend on rather than a private field's shape.
|
|
591
|
-
*/
|
|
592
|
-
_props() {
|
|
593
|
-
return this._values;
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
requestUpdate() {
|
|
597
|
-
if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
|
|
598
|
-
this._updatePending = true;
|
|
599
|
-
this._updateComplete = new Promise((resolve) => {
|
|
600
|
-
queueMicrotask(() => {
|
|
601
|
-
this._updatePending = false;
|
|
602
|
-
if (this._connected) this._render();
|
|
603
|
-
resolve();
|
|
604
|
-
});
|
|
605
|
-
});
|
|
606
|
-
return this._updateComplete;
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
emit(name, detail, options = {}) {
|
|
610
|
-
return this.dispatchEvent(new CustomEvent(name, {
|
|
611
|
-
detail, bubbles: true, composed: true, ...options,
|
|
612
|
-
}));
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
_upgradeProperty(name) {
|
|
616
|
-
if (!Object.prototype.hasOwnProperty.call(this, name)) return;
|
|
617
|
-
const value = this[name];
|
|
618
|
-
delete this[name];
|
|
619
|
-
this[name] = value;
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
_upgradeDeclarativeEvents() {
|
|
623
|
-
for (const element of this.renderRoot.querySelectorAll?.('*') || []) {
|
|
624
|
-
const names = element.getAttributeNames?.() || [...(element.attributes || [])].filter(Boolean).map(attribute => attribute.name);
|
|
625
|
-
for (const attributeName of names) {
|
|
626
|
-
if (!attributeName?.startsWith('@')) continue;
|
|
627
|
-
const [event, ...modifiers] = attributeName.slice(1).split('.');
|
|
628
|
-
element.setAttribute('data-stx-on-' + event, element.getAttribute(attributeName));
|
|
629
|
-
if (modifiers.length) element.setAttribute('data-stx-mod-' + event, modifiers.join(' '));
|
|
630
|
-
element.removeAttribute(attributeName);
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
_bindEvents() {
|
|
636
|
-
for (const event of this.constructor.definition.eventTypes || []) {
|
|
637
|
-
if (this._listeners.has(event)) continue;
|
|
638
|
-
const listener = ($event) => {
|
|
639
|
-
const selector = '[data-stx-on-' + event + ']';
|
|
640
|
-
const target = $event.target?.closest?.(selector);
|
|
641
|
-
if (!target || !this.renderRoot.contains(target)) return;
|
|
642
|
-
const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
|
|
643
|
-
if (modifiers.includes('prevent')) $event.preventDefault();
|
|
644
|
-
if (modifiers.includes('stop')) $event.stopPropagation();
|
|
645
|
-
const method = target.getAttribute('data-stx-on-' + event);
|
|
646
|
-
if (typeof this[method] === 'function') this[method]($event);
|
|
647
|
-
};
|
|
648
|
-
this.renderRoot.addEventListener(event, listener);
|
|
649
|
-
this._listeners.set(event, listener);
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
_render() {
|
|
654
|
-
const definition = this.constructor.definition;
|
|
655
|
-
const root = this.renderRoot;
|
|
656
|
-
const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
|
|
657
|
-
const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
|
|
658
|
-
const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
|
|
659
|
-
// A compiled component renders itself: the control flow and the derived
|
|
660
|
-
// values were turned into JavaScript at build time, so there is nothing to
|
|
661
|
-
// interpret here and nothing that needs an eval the page's CSP forbids.
|
|
662
|
-
// The string template remains for components that carry no logic.
|
|
663
|
-
let html = typeof this.render === 'function'
|
|
664
|
-
? this.render(RENDER_HELPERS)
|
|
665
|
-
: definition.template
|
|
666
|
-
.replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
|
|
667
|
-
.replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
|
|
668
|
-
if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
|
|
669
|
-
root.innerHTML = html;
|
|
670
|
-
this._applyBindings();
|
|
671
|
-
this._bindEvents();
|
|
672
|
-
if (focusKey) {
|
|
673
|
-
const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
|
|
674
|
-
const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
|
|
675
|
-
next?.focus?.();
|
|
676
|
-
if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
|
|
677
|
-
}
|
|
678
|
-
this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
_applyBindings() {
|
|
682
|
-
for (const binding of this.constructor.definition.bindings || []) {
|
|
683
|
-
const element = this.renderRoot.querySelector('[data-stx-bind-' + binding.id + ']');
|
|
684
|
-
if (!element) continue;
|
|
685
|
-
const value = valueAt(this, binding.expression);
|
|
686
|
-
if (binding.name === 'class') element.className = value || '';
|
|
687
|
-
else if (binding.name === 'style' && typeof value === 'object') {
|
|
688
|
-
Object.assign(element.style, value);
|
|
689
|
-
}
|
|
690
|
-
else if (typeof value === 'boolean') {
|
|
691
|
-
element.toggleAttribute(binding.name, value);
|
|
692
|
-
if (binding.name in element) element[binding.name] = value;
|
|
693
|
-
}
|
|
694
|
-
else if (value == null || value === false) element.removeAttribute(binding.name);
|
|
695
|
-
else element.setAttribute(binding.name, String(value));
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
/**
|
|
701
|
-
* What a compiled render is handed.
|
|
702
|
-
*
|
|
703
|
-
* Passed in rather than closed over so the generated code names no globals, and
|
|
704
|
-
* a component module stays readable on its own: __escape is visibly a
|
|
705
|
-
* parameter, not something the bundler happened to leave in scope.
|
|
706
|
-
*/
|
|
707
|
-
const RENDER_HELPERS = {
|
|
708
|
-
escape: escapeHTML,
|
|
709
|
-
// The raw form is the author declaring the value is markup. Null becomes an
|
|
710
|
-
// empty string rather than the word "null", which is the only sensible
|
|
711
|
-
// reading of a missing fragment.
|
|
712
|
-
raw: (value) => String(value ?? ''),
|
|
713
|
-
// A loop over something absent runs zero times. Throwing here would fail a
|
|
714
|
-
// whole page over one empty list, which is never what the author meant.
|
|
715
|
-
values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
|
|
716
|
-
entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
|
|
717
|
-
};
|
|
718
|
-
|
|
719
|
-
export function defineComponent(Component, definition) {
|
|
720
|
-
const properties = definition.properties || {};
|
|
721
|
-
const attributeToProperty = {};
|
|
722
|
-
const observedAttributes = [];
|
|
723
|
-
for (const [name, property] of Object.entries(properties)) {
|
|
724
|
-
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
725
|
-
if (attribute) {
|
|
726
|
-
attributeToProperty[attribute] = name;
|
|
727
|
-
observedAttributes.push(attribute);
|
|
728
|
-
}
|
|
729
|
-
Object.defineProperty(Component.prototype, name, {
|
|
730
|
-
configurable: true,
|
|
731
|
-
enumerable: true,
|
|
732
|
-
get() { return this._values[name]; },
|
|
733
|
-
set(value) {
|
|
734
|
-
const oldValue = this._values[name];
|
|
735
|
-
if (Object.is(oldValue, value)) return;
|
|
736
|
-
this._values[name] = value;
|
|
737
|
-
if (property.reflect && attribute && !this._reflecting) {
|
|
738
|
-
const serialized = serialize(value, property.type);
|
|
739
|
-
this._reflecting = true;
|
|
740
|
-
if (serialized === null) this.removeAttribute(attribute);
|
|
741
|
-
else this.setAttribute(attribute, serialized);
|
|
742
|
-
this._reflecting = false;
|
|
743
|
-
}
|
|
744
|
-
this.requestUpdate();
|
|
745
|
-
this.dispatchEvent?.(new CustomEvent(name + '-changed', {
|
|
746
|
-
detail: { value, oldValue }, bubbles: true, composed: true,
|
|
747
|
-
}));
|
|
748
|
-
},
|
|
749
|
-
});
|
|
750
|
-
}
|
|
751
|
-
Component.definition = { ...definition, attributeToProperty, observedAttributes };
|
|
752
|
-
const registry = globalThis.customElements || globalThis.window?.customElements;
|
|
753
|
-
if (registry && !registry.get(definition.tag)) {
|
|
754
|
-
registry.define(definition.tag, Component);
|
|
755
|
-
}
|
|
756
|
-
return Component;
|
|
757
|
-
}
|
|
758
|
-
`}function Ur(t){let s=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),i=Object.entries(t.methods).map(([u,h])=>{if(dn.has(u))throw Error(`${t.sourcePath}: ${ln(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${u}($event) {
|
|
759
|
-
${h}
|
|
760
|
-
}`}).join(`
|
|
761
|
-
|
|
762
|
-
`),p=t.scope,c=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
|
|
763
|
-
`).map((h)=>h.trim()===""?h:` ${h}`).join(`
|
|
764
|
-
`),m="";if(t.render.trim()!==""||p.body!==""||c!==""){let u=[c?`const { ${c} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
|
|
765
|
-
`),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
|
|
766
|
-
${u}
|
|
767
|
-
}`),y=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(y+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
|
|
768
|
-
render(__helpers) {
|
|
769
|
-
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
770
|
-
${l(h.trim())}
|
|
771
|
-
}
|
|
772
|
-
`}return`import { StxElement, defineComponent } from './runtime.js';
|
|
773
|
-
${p.imports.length?`${p.imports.join(`
|
|
774
|
-
`)}
|
|
775
|
-
`:""}
|
|
776
|
-
/** ${t.description||`${t.name} web component generated from ${t.file}.`} */
|
|
777
|
-
export class ${t.name} extends StxElement {
|
|
778
|
-
${i}${m}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
defineComponent(${t.name}, ${s});
|
|
782
|
-
export default ${t.name};
|
|
783
|
-
`}function Ot(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 Wr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${Ot(m)}`).join(`
|
|
784
|
-
`),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${Ot(m)}`).join(`
|
|
785
|
-
`),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
|
|
786
|
-
`),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
|
|
787
|
-
`);return`export interface ${t.name}Props {
|
|
788
|
-
${s}
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
export interface ${t.name}EventMap {
|
|
792
|
-
${p}
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
export declare class ${t.name} extends HTMLElement {
|
|
796
|
-
${i}
|
|
797
|
-
${c}
|
|
798
|
-
readonly updateComplete: Promise<void>
|
|
799
|
-
requestUpdate(): Promise<void>
|
|
800
|
-
emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
declare global {
|
|
804
|
-
interface HTMLElementTagNameMap {
|
|
805
|
-
${JSON.stringify(t.tag)}: ${t.name}
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
export default ${t.name}
|
|
810
|
-
`}function Vr(t){return`declare global {
|
|
811
|
-
namespace JSX {
|
|
812
|
-
interface IntrinsicElements {
|
|
813
|
-
${t.map((i)=>{let p=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${Ot(m)}`).join(`
|
|
814
|
-
`),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
|
|
815
|
-
`);return` ${JSON.stringify(i.tag)}: {
|
|
816
|
-
${p}
|
|
817
|
-
${c}
|
|
818
|
-
children?: unknown
|
|
819
|
-
slot?: string
|
|
820
|
-
class?: string
|
|
821
|
-
className?: string
|
|
822
|
-
}`}).join(`
|
|
823
|
-
`)}
|
|
267
|
+
export function defineComponent(Component, definition) {
|
|
268
|
+
const properties = definition.properties || {};
|
|
269
|
+
const attributeToProperty = {};
|
|
270
|
+
const observedAttributes = [];
|
|
271
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
272
|
+
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
273
|
+
if (attribute) {
|
|
274
|
+
attributeToProperty[attribute] = name;
|
|
275
|
+
observedAttributes.push(attribute);
|
|
824
276
|
}
|
|
277
|
+
Object.defineProperty(Component.prototype, name, {
|
|
278
|
+
configurable: true,
|
|
279
|
+
enumerable: true,
|
|
280
|
+
get() { return this._values[name]; },
|
|
281
|
+
set(value) {
|
|
282
|
+
const oldValue = this._values[name];
|
|
283
|
+
if (Object.is(oldValue, value)) return;
|
|
284
|
+
this._values[name] = value;
|
|
285
|
+
if (property.reflect && attribute && !this._reflecting) {
|
|
286
|
+
const serialized = serialize(value, property.type);
|
|
287
|
+
this._reflecting = true;
|
|
288
|
+
if (serialized === null) this.removeAttribute(attribute);
|
|
289
|
+
else this.setAttribute(attribute, serialized);
|
|
290
|
+
this._reflecting = false;
|
|
291
|
+
}
|
|
292
|
+
this.requestUpdate();
|
|
293
|
+
this.dispatchEvent?.(new CustomEvent(name + '-changed', {
|
|
294
|
+
detail: { value, oldValue }, bubbles: true, composed: true,
|
|
295
|
+
}));
|
|
296
|
+
},
|
|
297
|
+
});
|
|
825
298
|
}
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
${s}
|
|
831
|
-
}`}function cn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
|
|
832
|
-
`);return`const definitions = ${JSON.stringify(c,null,2)};
|
|
833
|
-
const escapeHTML = (value) => String(value ?? '')
|
|
834
|
-
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
835
|
-
.replaceAll('"', '"').replaceAll("'", ''');
|
|
836
|
-
const valueAt = (values, path) => path.trim().split('.').reduce((value, part) => value?.[part], values);
|
|
837
|
-
|
|
838
|
-
export function renderComponent(tag, props = {}, slots = {}) {
|
|
839
|
-
const definition = definitions[tag];
|
|
840
|
-
if (!definition) throw new Error('Unknown STX component: ' + tag);
|
|
841
|
-
const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
|
|
842
|
-
Object.assign(values, props);
|
|
843
|
-
let template = definition.template
|
|
844
|
-
.replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
|
|
845
|
-
.replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
|
|
846
|
-
.replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
|
|
847
|
-
const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
|
|
848
|
-
if (property.attribute === false || !(name in props)) return [];
|
|
849
|
-
const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
850
|
-
const value = props[name];
|
|
851
|
-
if (value == null || value === false) return [];
|
|
852
|
-
if (value === true) return [attribute];
|
|
853
|
-
const serialized = typeof value === 'object' ? JSON.stringify(value) : value;
|
|
854
|
-
return [attribute + '=\\"' + escapeHTML(serialized) + '\\"'];
|
|
855
|
-
}).join(' ');
|
|
856
|
-
if (definition.shadowMode) {
|
|
857
|
-
template = '<template shadowrootmode="' + definition.shadowMode + '">' +
|
|
858
|
-
(definition.styles ? '<style>' + definition.styles + '</style>' : '') + template + '</template>' +
|
|
859
|
-
String(slots.default ?? '');
|
|
299
|
+
Component.definition = { ...definition, attributeToProperty, observedAttributes };
|
|
300
|
+
const registry = globalThis.customElements || globalThis.window?.customElements;
|
|
301
|
+
if (registry && !registry.get(definition.tag)) {
|
|
302
|
+
registry.define(definition.tag, Component);
|
|
860
303
|
}
|
|
861
|
-
return
|
|
304
|
+
return Component;
|
|
862
305
|
}
|
|
306
|
+
`}function Dr(t){let s=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),i=Object.entries(t.methods).map(([u,h])=>{if(sn.has(u))throw Error(`${t.sourcePath}: ${rn(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${u}($event) {
|
|
307
|
+
${h}
|
|
308
|
+
}`}).join(`
|
|
863
309
|
|
|
864
|
-
${l
|
|
865
|
-
`
|
|
866
|
-
`)
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
`)
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
${l.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
`)
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
${
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
`);m=`<${p}
|
|
883
|
-
${u}
|
|
884
|
-
/>`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function pn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await pn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let i=await pn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),u=!!m,h=m?.tag,g=await Jr(l,u,h);p.push(g)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=u?u[1].split(`
|
|
885
|
-
`).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let C=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=C.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function Zr(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
886
|
-
<p>Welcome, {{ user.name }}!</p>
|
|
887
|
-
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
888
|
-
<p>Welcome back!</p>
|
|
889
|
-
@else
|
|
890
|
-
<p>Please log in</p>
|
|
891
|
-
@endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
|
|
892
|
-
<p>A</p>
|
|
893
|
-
@elseif(score > 80)
|
|
894
|
-
<p>B</p>
|
|
895
|
-
@elseif(score > 70)
|
|
896
|
-
<p>C</p>
|
|
897
|
-
@endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
|
|
898
|
-
<p>Please log in</p>
|
|
899
|
-
@endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
|
|
900
|
-
<li>{{ item.name }}</li>
|
|
901
|
-
@endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
|
|
902
|
-
<p>Page {{ page }}</p>
|
|
903
|
-
@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
|
|
904
|
-
{{ This will be displayed as-is }}
|
|
905
|
-
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function no(t=[],s=[],i=[],p){let c=`# stx Documentation
|
|
906
|
-
|
|
907
|
-
`;if(p)c+=`${p}
|
|
908
|
-
|
|
909
|
-
`;if(t.length>0){c+=`## Components
|
|
910
|
-
|
|
911
|
-
`;for(let l of t){if(c+=`### ${l.name}
|
|
912
|
-
|
|
913
|
-
`,l.description)c+=`${l.description}
|
|
914
|
-
|
|
915
|
-
`;if(l.isWebComponent)c+=`**Web Component Tag:** \`${l.tag}\`
|
|
916
|
-
|
|
917
|
-
`;if(l.props.length>0){c+=`#### Properties
|
|
918
|
-
|
|
919
|
-
`,c+=`| Name | Type | Required | Default | Description |
|
|
920
|
-
`,c+=`| ---- | ---- | -------- | ------- | ----------- |
|
|
921
|
-
`;for(let m of l.props)c+=`| ${m.name} | ${m.type||"any"} | ${m.required?"Yes":"No"} | ${m.default||"-"} | ${m.description||"-"} |
|
|
922
|
-
`;c+=`
|
|
923
|
-
`}if(l.example)c+=`#### Example
|
|
924
|
-
|
|
925
|
-
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
|
|
926
|
-
|
|
927
|
-
`;for(let l of s){if(c+=`### ${l.name}
|
|
928
|
-
|
|
929
|
-
`,l.description)c+=`${l.description}
|
|
930
|
-
|
|
931
|
-
`;if(l.components&&l.components.length>0)c+=`**Components Used:** ${l.components.join(", ")}
|
|
932
|
-
|
|
933
|
-
`;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
|
|
934
|
-
|
|
935
|
-
`}}if(i.length>0){c+=`## Directives
|
|
936
|
-
|
|
937
|
-
`,c+=`| Directive | Description | Has End Tag |
|
|
938
|
-
`,c+=`| --------- | ----------- | ----------- |
|
|
939
|
-
`;for(let l of i)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
|
|
940
|
-
`;c+=`
|
|
941
|
-
`;for(let l of i)if(l.example)c+=`### @${l.name}
|
|
942
|
-
|
|
943
|
-
`,c+=`${l.description||""}
|
|
944
|
-
|
|
945
|
-
`,c+=`#### Example
|
|
946
|
-
|
|
947
|
-
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ro(t=[],s=[],i=[],p){let c=`<!DOCTYPE html>
|
|
948
|
-
<html lang="en">
|
|
949
|
-
<head>
|
|
950
|
-
<meta charset="UTF-8">
|
|
951
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
952
|
-
<title>stx Documentation</title>
|
|
953
|
-
<style>
|
|
954
|
-
body {
|
|
955
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
|
956
|
-
line-height: 1.6;
|
|
957
|
-
color: #333;
|
|
958
|
-
max-width: 1200px;
|
|
959
|
-
margin: 0 auto;
|
|
960
|
-
padding: 2rem;
|
|
961
|
-
}
|
|
962
|
-
h1, h2, h3, h4 { margin-top: 2rem; }
|
|
963
|
-
table {
|
|
964
|
-
border-collapse: collapse;
|
|
965
|
-
width: 100%;
|
|
966
|
-
margin: 1rem 0;
|
|
967
|
-
}
|
|
968
|
-
th, td {
|
|
969
|
-
text-align: left;
|
|
970
|
-
padding: 0.5rem;
|
|
971
|
-
border-bottom: 1px solid #ddd;
|
|
972
|
-
}
|
|
973
|
-
th { border-bottom: 2px solid #ddd; }
|
|
974
|
-
pre {
|
|
975
|
-
background: #f5f5f5;
|
|
976
|
-
padding: 1rem;
|
|
977
|
-
border-radius: 4px;
|
|
978
|
-
overflow-x: auto;
|
|
979
|
-
}
|
|
980
|
-
code {
|
|
981
|
-
background: #f5f5f5;
|
|
982
|
-
padding: 0.2rem 0.4rem;
|
|
983
|
-
border-radius: 4px;
|
|
984
|
-
font-size: 0.9em;
|
|
985
|
-
}
|
|
986
|
-
</style>
|
|
987
|
-
</head>
|
|
988
|
-
<body>
|
|
989
|
-
<h1>stx Documentation</h1>
|
|
990
|
-
`;if(p)c+=`<div>${p}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
|
|
991
|
-
<thead>
|
|
992
|
-
<tr>
|
|
993
|
-
<th>Name</th>
|
|
994
|
-
<th>Type</th>
|
|
995
|
-
<th>Required</th>
|
|
996
|
-
<th>Default</th>
|
|
997
|
-
<th>Description</th>
|
|
998
|
-
</tr>
|
|
999
|
-
</thead>
|
|
1000
|
-
<tbody>`;for(let m of l.props)c+=`<tr>
|
|
1001
|
-
<td>${m.name}</td>
|
|
1002
|
-
<td>${m.type||"any"}</td>
|
|
1003
|
-
<td>${m.required?"Yes":"No"}</td>
|
|
1004
|
-
<td>${m.default||"-"}</td>
|
|
1005
|
-
<td>${m.description||"-"}</td>
|
|
1006
|
-
</tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(i.length>0){c+="<h2>Directives</h2>",c+=`<table>
|
|
1007
|
-
<thead>
|
|
1008
|
-
<tr>
|
|
1009
|
-
<th>Directive</th>
|
|
1010
|
-
<th>Description</th>
|
|
1011
|
-
<th>Has End Tag</th>
|
|
1012
|
-
</tr>
|
|
1013
|
-
</thead>
|
|
1014
|
-
<tbody>`;for(let l of i)c+=`<tr>
|
|
1015
|
-
<td>@${l.name}</td>
|
|
1016
|
-
<td>${l.description||"-"}</td>
|
|
1017
|
-
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1018
|
-
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function oo(t=[],s=[],i=[],p){return JSON.stringify({components:t,templates:s,directives:i,extraContent:p||""},null,2)}async function so(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await Yr(s,p),console.log(`Found ${u.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await Qr(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",C="";switch(y){case"markdown":S=no(u,h,g,w),C="md";break;case"html":S=ro(u,h,g,w),C="html";break;case"json":S=oo(u,h,g,w),C="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Zs(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||A.componentsDir,p=t.templatesDir||".";return so({componentsDir:i,templatesDir:p,webComponentsConfig:A.webComponents,customDirectives:A.customDirectives,config:s})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function wr(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
|
|
1019
|
-
`;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=co(p,i),p=ho(p,i),p=fo(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
|
|
1020
|
-
`).replace(/\r/g,`
|
|
1021
|
-
`),!p.endsWith(`
|
|
1022
|
-
`))p+=`
|
|
1023
|
-
`;return p}function Qs(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
|
|
1024
|
-
`;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,h)=>{let g=u.split(`
|
|
1025
|
-
`),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
|
|
1026
|
-
`),v=wr(S,i).trimEnd().split(`
|
|
1027
|
-
`).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
|
|
1028
|
-
`);return`${l}\`\`\`${m}
|
|
1029
|
-
${v}
|
|
1030
|
-
${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
|
|
1031
|
-
`).replace(/\r/g,`
|
|
1032
|
-
`),!p.endsWith(`
|
|
1033
|
-
`))p+=`
|
|
1034
|
-
`;return p}function ao(t){let s=t,i=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1035
|
-
$1
|
|
1036
|
-
`),s=s.replace(/(@end\w+)/g,`
|
|
1037
|
-
$1
|
|
1038
|
-
`),s=s.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1039
|
-
$1
|
|
1040
|
-
`),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
|
|
1041
|
-
$1
|
|
1042
|
-
`),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let h=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
|
|
1043
|
-
${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,h)=>{let g=h.substring(Math.max(0,u-50),u),w=h.substring(u+c.length,Math.min(h.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
|
|
1044
|
-
${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let h=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
|
|
1045
|
-
`}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
|
|
1046
|
-
`),s=s.split(`
|
|
1047
|
-
`).map((c)=>c.trim()).join(`
|
|
1048
|
-
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function co(t,s){let p=ao(t).split(`
|
|
1049
|
-
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let C=y===">";if(un(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),T=y.startsWith("@")&&go(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),_=y.startsWith("</"),I=y.startsWith("<")&&!_&&!H&&!k,R=y.includes("/>")||mo(y),L=un(y);if(_||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(C)c.push(g);else c.push(u.repeat(B)+y);if(I&&!R&&!L&&!C||T)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
1050
|
-
`)}function fo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function mo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function go(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function ho(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
|
|
1051
|
-
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import mn from"fs";import Vt from"path";async function eo(t="index.stx",s={}){try{let i=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!mn.existsSync(c))mn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=gn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=gn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return yo();case"layout":return bo();case"blog":return xo();case"api":return vo();case"app":return wo();default:return hn()}}function hn(){return`<script>
|
|
1052
|
-
const title = "My stx Page"
|
|
1053
|
-
const description = "A page built with stx"
|
|
1054
|
-
const features = [
|
|
1055
|
-
{ name: "Single File Components", desc: "Script, style, and template in one .stx file" },
|
|
1056
|
-
{ name: "Component System", desc: "Import components with @component('name', {})" },
|
|
1057
|
-
{ name: "Blade Directives", desc: "@if, @foreach, @switch, @layout and more" }
|
|
1058
|
-
]
|
|
1059
|
-
</script>
|
|
310
|
+
`),p=t.scope,c=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
|
|
311
|
+
`).map((h)=>h.trim()===""?h:` ${h}`).join(`
|
|
312
|
+
`),m="";if(t.render.trim()!==""||p.body!==""||c!==""){let u=[c?`const { ${c} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
|
|
313
|
+
`),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
|
|
314
|
+
${u}
|
|
315
|
+
}`),y=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(y+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
|
|
316
|
+
render(__helpers) {
|
|
317
|
+
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
318
|
+
${l(h.trim())}
|
|
319
|
+
}
|
|
320
|
+
`}return`import { StxElement, defineComponent } from './runtime.js';
|
|
321
|
+
${p.imports.length?`${p.imports.join(`
|
|
322
|
+
`)}
|
|
323
|
+
`:""}
|
|
324
|
+
/** ${t.description||`${t.name} web component generated from ${t.file}.`} */
|
|
325
|
+
export class ${t.name} extends StxElement {
|
|
326
|
+
${i}${m}
|
|
327
|
+
}
|
|
1060
328
|
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
329
|
+
defineComponent(${t.name}, ${s});
|
|
330
|
+
export default ${t.name};
|
|
331
|
+
`}function xt(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 Mr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${xt(m)}`).join(`
|
|
332
|
+
`),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${xt(m)}`).join(`
|
|
333
|
+
`),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
|
|
334
|
+
`),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
|
|
335
|
+
`);return`export interface ${t.name}Props {
|
|
336
|
+
${s}
|
|
337
|
+
}
|
|
1066
338
|
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
<div class="card">
|
|
1071
|
-
<h3>{{ feature.name }}</h3>
|
|
1072
|
-
<p>{{ feature.desc }}</p>
|
|
1073
|
-
</div>
|
|
1074
|
-
@endforeach
|
|
1075
|
-
</main>
|
|
1076
|
-
@endsection`}function yo(){return`{{-- Component: Card --}}
|
|
1077
|
-
{{-- Props: title, variant, collapsible --}}
|
|
1078
|
-
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1079
|
-
<script>
|
|
1080
|
-
// Props with defaults
|
|
1081
|
-
const title = props.title || 'Card Title'
|
|
1082
|
-
const variant = props.variant || 'default'
|
|
1083
|
-
const collapsible = props.collapsible || false
|
|
1084
|
-
</script>
|
|
339
|
+
export interface ${t.name}EventMap {
|
|
340
|
+
${p}
|
|
341
|
+
}
|
|
1085
342
|
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
<div class="card__body">
|
|
1094
|
-
{{ slot }}
|
|
1095
|
-
</div>
|
|
1096
|
-
</div>
|
|
343
|
+
export declare class ${t.name} extends HTMLElement {
|
|
344
|
+
${i}
|
|
345
|
+
${c}
|
|
346
|
+
readonly updateComplete: Promise<void>
|
|
347
|
+
requestUpdate(): Promise<void>
|
|
348
|
+
emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
|
|
349
|
+
}
|
|
1097
350
|
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
background: #fff;
|
|
1102
|
-
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
1103
|
-
overflow: hidden;
|
|
1104
|
-
}
|
|
1105
|
-
.card--primary { border-top: 3px solid #3498db; }
|
|
1106
|
-
.card--success { border-top: 3px solid #2ecc71; }
|
|
1107
|
-
.card--warning { border-top: 3px solid #f39c12; }
|
|
1108
|
-
.card--danger { border-top: 3px solid #e74c3c; }
|
|
1109
|
-
.card__header {
|
|
1110
|
-
padding: 1rem;
|
|
1111
|
-
background: #f8f9fa;
|
|
1112
|
-
display: flex;
|
|
1113
|
-
justify-content: space-between;
|
|
1114
|
-
align-items: center;
|
|
351
|
+
declare global {
|
|
352
|
+
interface HTMLElementTagNameMap {
|
|
353
|
+
${JSON.stringify(t.tag)}: ${t.name}
|
|
1115
354
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
display: flex;
|
|
1134
|
-
flex-direction: column;
|
|
1135
|
-
}
|
|
1136
|
-
header, footer {
|
|
1137
|
-
background: #2c3e50;
|
|
1138
|
-
color: white;
|
|
1139
|
-
padding: 1rem 2rem;
|
|
1140
|
-
}
|
|
1141
|
-
main {
|
|
1142
|
-
flex: 1;
|
|
1143
|
-
padding: 2rem;
|
|
1144
|
-
max-width: 1200px;
|
|
1145
|
-
margin: 0 auto;
|
|
1146
|
-
width: 100%;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export default ${t.name}
|
|
358
|
+
`}function _r(t){return`declare global {
|
|
359
|
+
namespace JSX {
|
|
360
|
+
interface IntrinsicElements {
|
|
361
|
+
${t.map((i)=>{let p=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${xt(m)}`).join(`
|
|
362
|
+
`),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
|
|
363
|
+
`);return` ${JSON.stringify(i.tag)}: {
|
|
364
|
+
${p}
|
|
365
|
+
${c}
|
|
366
|
+
children?: unknown
|
|
367
|
+
slot?: string
|
|
368
|
+
class?: string
|
|
369
|
+
className?: string
|
|
370
|
+
}`}).join(`
|
|
371
|
+
`)}
|
|
1147
372
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
</style>
|
|
1151
|
-
@yield('styles')
|
|
1152
|
-
</head>
|
|
1153
|
-
<body>
|
|
1154
|
-
<header>
|
|
1155
|
-
<nav>
|
|
1156
|
-
<a href="/">Home</a>
|
|
1157
|
-
<a href="/about">About</a>
|
|
1158
|
-
<a href="/contact">Contact</a>
|
|
1159
|
-
</nav>
|
|
1160
|
-
</header>
|
|
373
|
+
}
|
|
374
|
+
}
|
|
1161
375
|
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
376
|
+
export {}
|
|
377
|
+
`}function Lr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,p])=>({kind:"field",name:i,description:p.description,type:{text:xt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ft(i),reflects:p.reflect})),events:Object.entries(s.events).map(([i,p])=>({name:i,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
|
|
378
|
+
${s}
|
|
379
|
+
}`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Ir(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
|
|
380
|
+
`);return`const definitions = ${JSON.stringify(c,null,2)};
|
|
381
|
+
const escapeHTML = (value) => String(value ?? '')
|
|
382
|
+
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
383
|
+
.replaceAll('"', '"').replaceAll("'", ''');
|
|
384
|
+
const valueAt = (values, path) => path.trim().split('.').reduce((value, part) => value?.[part], values);
|
|
1165
385
|
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
386
|
+
export function renderComponent(tag, props = {}, slots = {}) {
|
|
387
|
+
const definition = definitions[tag];
|
|
388
|
+
if (!definition) throw new Error('Unknown STX component: ' + tag);
|
|
389
|
+
const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
|
|
390
|
+
Object.assign(values, props);
|
|
391
|
+
let template = definition.template
|
|
392
|
+
.replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
|
|
393
|
+
.replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
|
|
394
|
+
.replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
|
|
395
|
+
const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
|
|
396
|
+
if (property.attribute === false || !(name in props)) return [];
|
|
397
|
+
const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
398
|
+
const value = props[name];
|
|
399
|
+
if (value == null || value === false) return [];
|
|
400
|
+
if (value === true) return [attribute];
|
|
401
|
+
const serialized = typeof value === 'object' ? JSON.stringify(value) : value;
|
|
402
|
+
return [attribute + '=\\"' + escapeHTML(serialized) + '\\"'];
|
|
403
|
+
}).join(' ');
|
|
404
|
+
if (definition.shadowMode) {
|
|
405
|
+
template = '<template shadowrootmode="' + definition.shadowMode + '">' +
|
|
406
|
+
(definition.styles ? '<style>' + definition.styles + '</style>' : '') + template + '</template>' +
|
|
407
|
+
String(slots.default ?? '');
|
|
408
|
+
}
|
|
409
|
+
return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
|
|
410
|
+
}
|
|
1169
411
|
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
})
|
|
1181
|
-
const tags = ["stx", "tutorial", "web development"]
|
|
1182
|
-
const readingTime = "5 min read"
|
|
1183
|
-
</script>
|
|
412
|
+
${l}
|
|
413
|
+
`}async function Zs(t){let s=Pe.resolve(t.inputDir),i=Pe.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Or(s,x,t)));l.sort((x,T)=>x.tag.localeCompare(T.tag));let m=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,T)=>{let k=Pe.join(i,x);return await or(k,T.endsWith(`
|
|
414
|
+
`)?T:`${T}
|
|
415
|
+
`,"utf8"),h.push(k),k};await g("runtime.js",Ar());for(let x of l){if(await g(`${x.tag}.js`,Dr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Mr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(T):T)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
|
|
416
|
+
`);if(await g("index.js",y),await g("ssr.js",Ir(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
|
|
417
|
+
`)),await g("custom-elements.d.ts",_r(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
418
|
+
`)}
|
|
419
|
+
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
420
|
+
${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
|
|
421
|
+
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Lr(l),null,2));let S;if(t.css!==!1){let x=l.filter((T)=>!T.shadowMode&&T.styles).map(tn).join(`
|
|
1184
422
|
|
|
1185
|
-
|
|
423
|
+
`);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let C;if(t.bundle!==!1){C=Pe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Pe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],H=k.map((M)=>String(M).trim()).filter(Boolean).join(`
|
|
424
|
+
`);throw AggregateError(k,`Failed to bundle component library${H?`
|
|
425
|
+
${H}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
|
|
426
|
+
`);throw AggregateError(x.logs,`Failed to bundle component library${T?`
|
|
427
|
+
${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Pe.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}var{serve:Vr}=globalThis.Bun;import Nt from"fs";import pt from"path";function vt(){return`
|
|
428
|
+
/* Theme selector for code blocks */
|
|
429
|
+
.theme-selector {
|
|
430
|
+
margin: 1rem 0;
|
|
431
|
+
padding: 0.5rem;
|
|
432
|
+
background: #f8f8f8;
|
|
433
|
+
border-radius: 4px;
|
|
434
|
+
text-align: right;
|
|
435
|
+
}
|
|
436
|
+
select {
|
|
437
|
+
padding: 0.25rem 0.5rem;
|
|
438
|
+
border-radius: 3px;
|
|
439
|
+
border: 1px solid #ddd;
|
|
440
|
+
}
|
|
1186
441
|
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
442
|
+
/* Dark mode body styles */
|
|
443
|
+
body.dark-mode {
|
|
444
|
+
background-color: #121212;
|
|
445
|
+
color: #e1e4e8;
|
|
446
|
+
}
|
|
1190
447
|
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
<span class="date">{{ date }}</span>
|
|
1198
|
-
<span class="reading-time">{{ readingTime }}</span>
|
|
1199
|
-
</div>
|
|
1200
|
-
<div class="blog-post__tags">
|
|
1201
|
-
@foreach(tags as tag)
|
|
1202
|
-
<span class="tag">#{{ tag }}</span>
|
|
1203
|
-
@endforeach
|
|
1204
|
-
</div>
|
|
1205
|
-
</header>
|
|
448
|
+
body.dark-mode h1,
|
|
449
|
+
body.dark-mode h2,
|
|
450
|
+
body.dark-mode h3 {
|
|
451
|
+
color: #e1e4e8;
|
|
452
|
+
border-color: #2f363d;
|
|
453
|
+
}
|
|
1206
454
|
|
|
1207
|
-
|
|
1208
|
-
|
|
455
|
+
body.dark-mode .theme-selector {
|
|
456
|
+
background: #2f363d;
|
|
457
|
+
color: #e1e4e8;
|
|
458
|
+
}
|
|
1209
459
|
|
|
1210
|
-
|
|
1211
|
-
|
|
460
|
+
body.dark-mode select {
|
|
461
|
+
background: #24292e;
|
|
462
|
+
color: #e1e4e8;
|
|
463
|
+
border-color: #444;
|
|
464
|
+
}
|
|
1212
465
|
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
@endsection`}function vo(){return`<script>
|
|
1218
|
-
// API endpoint configuration
|
|
1219
|
-
const endpoint = "/api/data"
|
|
1220
|
-
const method = "GET"
|
|
466
|
+
body.dark-mode blockquote {
|
|
467
|
+
background: #24292e;
|
|
468
|
+
color: #e1e4e8;
|
|
469
|
+
}
|
|
1221
470
|
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
success: true,
|
|
1225
|
-
message: "Data retrieved successfully",
|
|
1226
|
-
items: [
|
|
1227
|
-
{ id: 1, name: "Item 1" },
|
|
1228
|
-
{ id: 2, name: "Item 2" },
|
|
1229
|
-
{ id: 3, name: "Item 3" }
|
|
1230
|
-
],
|
|
1231
|
-
meta: {
|
|
1232
|
-
total: 3,
|
|
1233
|
-
page: 1,
|
|
1234
|
-
perPage: 10
|
|
471
|
+
body.dark-mode .frontmatter {
|
|
472
|
+
background: #24292e;
|
|
1235
473
|
}
|
|
1236
|
-
}
|
|
1237
474
|
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
475
|
+
body.dark-mode a {
|
|
476
|
+
color: #58a6ff;
|
|
477
|
+
}`}function wt(t){return`
|
|
478
|
+
<div class="theme-selector">
|
|
479
|
+
Theme:
|
|
480
|
+
<select id="themeSelector" onchange="changeTheme()">
|
|
481
|
+
${t}
|
|
482
|
+
</select>
|
|
483
|
+
</div>`}function St(){return`
|
|
484
|
+
function changeTheme() {
|
|
485
|
+
const theme = document.getElementById('themeSelector').value;
|
|
1241
486
|
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
487
|
+
// Toggle dark mode class based on theme
|
|
488
|
+
// Dark themes typically include these keywords in their names
|
|
489
|
+
if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
|
|
490
|
+
theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
|
|
491
|
+
document.body.classList.add('dark-mode');
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
document.body.classList.remove('dark-mode');
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// Initialize theme on page load
|
|
499
|
+
document.addEventListener('DOMContentLoaded', changeTheme);`}function kt(t){if(Object.keys(t).length===0)return"";return`
|
|
500
|
+
<div class="frontmatter">
|
|
501
|
+
<h3>Frontmatter</h3>
|
|
502
|
+
${Object.entries(t).map(([s,i])=>`
|
|
503
|
+
<div class="frontmatter-item">
|
|
504
|
+
<span class="frontmatter-label">${s}:</span>
|
|
505
|
+
<span>${Array.isArray(i)?i.join(", "):String(i)}</span>
|
|
506
|
+
</div>`).join("")}
|
|
507
|
+
</div>`}import ln from"net";async function jr(t){return new Promise((s)=>{let i=ln.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let i=ln.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let p=t+i;if(await Br(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Fr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function zr(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let i={...Fr,...s},p=await zr();if(!p)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 c=await p.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function $t(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
|
|
508
|
+
${l}
|
|
509
|
+
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
510
|
+
`,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function zt(){console.log(`
|
|
511
|
+
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Nr(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),zt()}function Ur(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
|
|
512
|
+
`)){let l=p.trim().toLowerCase();p="",Wr(l,t,s,i)}})}function Wr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ur(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Nr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Nt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await ue(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],H=[...new Set([...x,...T])].map((M)=>`<option value="${M}"${M===v?" selected":""}>${M}</option>`).join(`
|
|
513
|
+
`);return l=`
|
|
514
|
+
<!DOCTYPE html>
|
|
1253
515
|
<html lang="en">
|
|
1254
516
|
<head>
|
|
1255
517
|
<meta charset="UTF-8">
|
|
1256
518
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1257
|
-
<title
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
</script>
|
|
1261
|
-
<style>
|
|
519
|
+
<title>${qr(S.title||pt.basename(c))}</title>
|
|
520
|
+
<!-- Syntax highlighting styles -->
|
|
521
|
+
<style id="syntax-theme">
|
|
1262
522
|
:root {
|
|
1263
|
-
--
|
|
1264
|
-
--
|
|
1265
|
-
--
|
|
1266
|
-
--
|
|
1267
|
-
--
|
|
1268
|
-
--
|
|
1269
|
-
--
|
|
523
|
+
--shiki-color-text: #24292e;
|
|
524
|
+
--shiki-color-background: #ffffff;
|
|
525
|
+
--shiki-token-constant: #005cc5;
|
|
526
|
+
--shiki-token-string: #032f62;
|
|
527
|
+
--shiki-token-comment: #6a737d;
|
|
528
|
+
--shiki-token-keyword: #d73a49;
|
|
529
|
+
--shiki-token-parameter: #24292e;
|
|
530
|
+
--shiki-token-function: #6f42c1;
|
|
531
|
+
--shiki-token-string-expression: #032f62;
|
|
532
|
+
--shiki-token-punctuation: #24292e;
|
|
533
|
+
--shiki-token-link: #032f62;
|
|
1270
534
|
}
|
|
1271
|
-
|
|
535
|
+
pre {
|
|
536
|
+
background-color: var(--shiki-color-background);
|
|
537
|
+
padding: 1rem;
|
|
538
|
+
border-radius: 4px;
|
|
539
|
+
}
|
|
540
|
+
code {
|
|
541
|
+
color: var(--shiki-color-text);
|
|
542
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
543
|
+
}
|
|
544
|
+
.dark-mode {
|
|
545
|
+
--shiki-color-text: #e1e4e8;
|
|
546
|
+
--shiki-color-background: #24292e;
|
|
547
|
+
--shiki-token-constant: #79b8ff;
|
|
548
|
+
--shiki-token-string: #9ecbff;
|
|
549
|
+
--shiki-token-comment: #6a737d;
|
|
550
|
+
--shiki-token-keyword: #f97583;
|
|
551
|
+
--shiki-token-parameter: #e1e4e8;
|
|
552
|
+
--shiki-token-function: #b392f0;
|
|
553
|
+
--shiki-token-string-expression: #9ecbff;
|
|
554
|
+
--shiki-token-punctuation: #e1e4e8;
|
|
555
|
+
--shiki-token-link: #9ecbff;
|
|
556
|
+
}
|
|
557
|
+
</style>
|
|
558
|
+
<style>
|
|
1272
559
|
body {
|
|
1273
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
1274
|
-
|
|
1275
|
-
color:
|
|
1276
|
-
|
|
560
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
561
|
+
line-height: 1.6;
|
|
562
|
+
color: #333;
|
|
563
|
+
max-width: 800px;
|
|
564
|
+
margin: 0 auto;
|
|
565
|
+
padding: 2rem;
|
|
1277
566
|
}
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
567
|
+
pre, code {
|
|
568
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
569
|
+
}
|
|
570
|
+
pre {
|
|
571
|
+
border-radius: 4px;
|
|
572
|
+
padding: 0;
|
|
573
|
+
margin: 1.5rem 0;
|
|
574
|
+
overflow-x: auto;
|
|
575
|
+
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
576
|
+
}
|
|
577
|
+
pre code {
|
|
578
|
+
display: block;
|
|
579
|
+
padding: 1rem;
|
|
580
|
+
overflow-x: auto;
|
|
581
|
+
}
|
|
582
|
+
/* Apply background color to code blocks based on theme */
|
|
583
|
+
pre.syntax-highlighter {
|
|
584
|
+
background-color: var(--shiki-color-background) !important;
|
|
585
|
+
}
|
|
586
|
+
.dark-mode pre.syntax-highlighter {
|
|
587
|
+
background-color: var(--shiki-color-background) !important;
|
|
588
|
+
}
|
|
589
|
+
code {
|
|
590
|
+
padding: 0.2rem 0.4rem;
|
|
591
|
+
border-radius: 3px;
|
|
592
|
+
}
|
|
593
|
+
h1, h2, h3, h4 {
|
|
594
|
+
margin-top: 2rem;
|
|
1286
595
|
margin-bottom: 1rem;
|
|
1287
596
|
}
|
|
1288
|
-
.
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
border-radius:
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
transition: opacity 0.2s;
|
|
597
|
+
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
598
|
+
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
599
|
+
h3 { color: #444; }
|
|
600
|
+
img {
|
|
601
|
+
max-width: 100%;
|
|
602
|
+
border-radius: 4px;
|
|
603
|
+
margin: 1rem 0;
|
|
604
|
+
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
1297
605
|
}
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
606
|
+
blockquote {
|
|
607
|
+
border-left: 4px solid #ddd;
|
|
608
|
+
padding-left: 1rem;
|
|
609
|
+
margin-left: 0;
|
|
610
|
+
color: #555;
|
|
611
|
+
background: #f9f9f9;
|
|
612
|
+
padding: 0.5rem 1rem;
|
|
613
|
+
margin: 1.5rem 0;
|
|
614
|
+
}
|
|
615
|
+
table {
|
|
616
|
+
border-collapse: collapse;
|
|
1303
617
|
width: 100%;
|
|
1304
|
-
|
|
1305
|
-
border: 1px solid var(--border);
|
|
1306
|
-
color: var(--fg);
|
|
1307
|
-
padding: 0.75rem 1rem;
|
|
1308
|
-
border-radius: 8px;
|
|
1309
|
-
font-size: 1rem;
|
|
1310
|
-
margin-bottom: 1rem;
|
|
618
|
+
margin: 1.5rem 0;
|
|
1311
619
|
}
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
620
|
+
th, td {
|
|
621
|
+
border: 1px solid #ddd;
|
|
622
|
+
padding: 0.5rem;
|
|
623
|
+
}
|
|
624
|
+
th {
|
|
625
|
+
background: #f0f0f0;
|
|
626
|
+
text-align: left;
|
|
627
|
+
}
|
|
628
|
+
tr:nth-child(even) {
|
|
629
|
+
background-color: #f8f8f8;
|
|
630
|
+
}
|
|
631
|
+
a {
|
|
632
|
+
color: #0066cc;
|
|
633
|
+
text-decoration: none;
|
|
634
|
+
}
|
|
635
|
+
a:hover {
|
|
636
|
+
text-decoration: underline;
|
|
637
|
+
}
|
|
638
|
+
hr {
|
|
639
|
+
border: 0;
|
|
640
|
+
border-top: 1px solid #eee;
|
|
641
|
+
margin: 2rem 0;
|
|
642
|
+
}
|
|
643
|
+
.frontmatter {
|
|
644
|
+
background: #f8f8f8;
|
|
645
|
+
border-radius: 4px;
|
|
646
|
+
padding: 1.5rem;
|
|
647
|
+
margin-bottom: 2rem;
|
|
648
|
+
font-size: 0.9rem;
|
|
649
|
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
650
|
+
border-left: 4px solid #ddd;
|
|
651
|
+
}
|
|
652
|
+
.frontmatter-item {
|
|
653
|
+
margin-bottom: 0.5rem;
|
|
654
|
+
display: flex;
|
|
655
|
+
}
|
|
656
|
+
.frontmatter-label {
|
|
657
|
+
font-weight: bold;
|
|
658
|
+
min-width: 100px;
|
|
659
|
+
color: #555;
|
|
660
|
+
}
|
|
661
|
+
${vt()}
|
|
1319
662
|
</style>
|
|
1320
663
|
</head>
|
|
1321
664
|
<body>
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
<h1>{{ title }}</h1>
|
|
1325
|
-
<p class="text-muted">Built with stx</p>
|
|
1326
|
-
</header>
|
|
665
|
+
${kt(S)}
|
|
666
|
+
${wt(H)}
|
|
1327
667
|
|
|
1328
|
-
|
|
1329
|
-
<div class="card">
|
|
1330
|
-
<h2 class="mb-1">Counter Example</h2>
|
|
1331
|
-
<div class="flex flex-between">
|
|
1332
|
-
<span id="counterDisplay">Count: 0</span>
|
|
1333
|
-
<div class="flex">
|
|
1334
|
-
<button class="btn btn--secondary" onclick="window.app?.decrement()">-</button>
|
|
1335
|
-
<button class="btn" onclick="window.app?.increment()">+</button>
|
|
1336
|
-
<button class="btn btn--success" onclick="window.app?.reset()">Reset</button>
|
|
1337
|
-
</div>
|
|
1338
|
-
</div>
|
|
1339
|
-
</div>
|
|
668
|
+
${w}
|
|
1340
669
|
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
670
|
+
<script>
|
|
671
|
+
${St()}
|
|
672
|
+
</script>
|
|
673
|
+
</body>
|
|
674
|
+
</html>
|
|
675
|
+
`,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let h=i;try{if(h=await Ye(i),h!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${h} 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:${h}/${e.reset}...`);let g=Vr({port:h,fetch(w){if(new URL(w.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(w){return new Response(`<pre>${w}
|
|
676
|
+
${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
677
|
+
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
678
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
|
|
679
|
+
${e.yellow}Routes:${e.reset}`);let y=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
|
|
680
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(p)Nt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Nt.watch(w,{recursive:!0},async(C,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function qr(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Xr}=globalThis.Bun;import Fe from"fs";import Se from"path";class dn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let h=u.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${y}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),i++}catch{this.clients.delete(p)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Kr(t,s={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
|
|
681
|
+
<script>
|
|
682
|
+
(function() {
|
|
683
|
+
// stx Hot Reload Client
|
|
684
|
+
var wsUrl = 'ws://' + window.location.hostname + ':${t}';
|
|
685
|
+
var reconnectAttempts = 0;
|
|
686
|
+
var maxAttempts = ${c};
|
|
687
|
+
var reconnectInterval = ${p};
|
|
688
|
+
var socket = null;
|
|
689
|
+
var overlay = null;
|
|
690
|
+
var wasConnected = false; // Track if we ever connected successfully
|
|
1358
691
|
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
<div id="toggleContent" class="mt-1" style="margin-top:1rem;display:none">
|
|
1368
|
-
<p class="text-success">This content is visible when active!</p>
|
|
1369
|
-
</div>
|
|
1370
|
-
</div>
|
|
1371
|
-
</div>
|
|
692
|
+
${i?`
|
|
693
|
+
// Create connection status overlay
|
|
694
|
+
function createOverlay() {
|
|
695
|
+
overlay = document.createElement('div');
|
|
696
|
+
overlay.id = 'stx-hmr-overlay';
|
|
697
|
+
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;padding:8px 16px;background:#f59e0b;color:#000;font-family:system-ui,sans-serif;font-size:14px;text-align:center;z-index:999999;display:none;';
|
|
698
|
+
document.body.appendChild(overlay);
|
|
699
|
+
}
|
|
1372
700
|
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
(
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
701
|
+
function showOverlay(message, isError) {
|
|
702
|
+
// Only show overlay if we were previously connected (don't show during initial connection)
|
|
703
|
+
if (!wasConnected && !isError) return;
|
|
704
|
+
if (!overlay) createOverlay();
|
|
705
|
+
overlay.textContent = message;
|
|
706
|
+
overlay.style.background = isError ? '#ef4444' : '#f59e0b';
|
|
707
|
+
overlay.style.color = isError ? '#fff' : '#000';
|
|
708
|
+
overlay.style.display = 'block';
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function hideOverlay() {
|
|
712
|
+
if (overlay) overlay.style.display = 'none';
|
|
713
|
+
}
|
|
714
|
+
`:`
|
|
715
|
+
function showOverlay() {}
|
|
716
|
+
function hideOverlay() {}
|
|
717
|
+
`}
|
|
718
|
+
|
|
719
|
+
function connect() {
|
|
720
|
+
try {
|
|
721
|
+
socket = new WebSocket(wsUrl);
|
|
722
|
+
}
|
|
723
|
+
catch (e) {
|
|
724
|
+
// Silent fail for initial connection attempts
|
|
725
|
+
if (wasConnected) {
|
|
726
|
+
scheduleReconnect();
|
|
1392
727
|
}
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
1393
730
|
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
731
|
+
socket.onopen = function() {
|
|
732
|
+
// connected silently
|
|
733
|
+
wasConnected = true;
|
|
734
|
+
reconnectAttempts = 0;
|
|
735
|
+
hideOverlay();
|
|
736
|
+
};
|
|
1400
737
|
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
738
|
+
socket.onmessage = function(event) {
|
|
739
|
+
try {
|
|
740
|
+
var msg = JSON.parse(event.data);
|
|
741
|
+
|
|
742
|
+
switch (msg.type) {
|
|
743
|
+
case 'reload':
|
|
744
|
+
console.log('[stx] Reloading...', msg.path || '');
|
|
745
|
+
// Use SPA router for progressive update instead of full page reload.
|
|
746
|
+
// Falls back to hard reload only when the router isn't available.
|
|
747
|
+
// Call the ROUTER directly, not window.navigate: the runtime helper
|
|
748
|
+
// takes (url, options) and silently dropped the third argument, so
|
|
749
|
+
// force never arrived and the same-URL early return made this a
|
|
750
|
+
// no-op on every page that had the router (#1807). pushState=false
|
|
751
|
+
// keeps the address bar untouched (this is a reload, not a
|
|
752
|
+
// navigation) and force=true bypasses the early return.
|
|
753
|
+
if (window.stxRouter && typeof window.stxRouter.navigate === 'function') {
|
|
754
|
+
window.stxRouter.navigate(window.location.pathname + window.location.search, false, true);
|
|
755
|
+
} else {
|
|
756
|
+
window.location.reload();
|
|
757
|
+
}
|
|
758
|
+
break;
|
|
759
|
+
|
|
760
|
+
case 'css-update':
|
|
761
|
+
console.log('[stx] CSS update:', msg.path);
|
|
762
|
+
updateCss(msg.path, msg.content);
|
|
763
|
+
break;
|
|
764
|
+
|
|
765
|
+
case 'error':
|
|
766
|
+
console.error('[stx] Error:', msg.content);
|
|
767
|
+
showOverlay('Build Error: ' + msg.content, true);
|
|
768
|
+
break;
|
|
769
|
+
|
|
770
|
+
case 'connected':
|
|
771
|
+
break;
|
|
1435
772
|
}
|
|
1436
|
-
}
|
|
773
|
+
}
|
|
774
|
+
catch (e) {
|
|
775
|
+
console.error('[stx] Invalid message:', e);
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
socket.onclose = function() {
|
|
780
|
+
socket = null;
|
|
781
|
+
// Only log and show overlay if we were previously connected
|
|
782
|
+
if (wasConnected) {
|
|
783
|
+
console.log('[stx] Connection closed, reconnecting...');
|
|
784
|
+
scheduleReconnect();
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
// Silently retry initial connection
|
|
788
|
+
setTimeout(connect, reconnectInterval);
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
socket.onerror = function() {
|
|
793
|
+
// Errors are handled in onclose
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function scheduleReconnect() {
|
|
798
|
+
if (reconnectAttempts < maxAttempts) {
|
|
799
|
+
reconnectAttempts++;
|
|
800
|
+
showOverlay('Reconnecting... (' + reconnectAttempts + '/' + maxAttempts + ')');
|
|
801
|
+
setTimeout(connect, reconnectInterval);
|
|
802
|
+
}
|
|
803
|
+
else {
|
|
804
|
+
showOverlay('Connection lost. Refresh to reconnect.', true);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// CSS hot update without full reload
|
|
809
|
+
function updateCss(path, content) {
|
|
810
|
+
// Try to find and update existing stylesheet
|
|
811
|
+
var links = document.querySelectorAll('link[rel="stylesheet"]');
|
|
812
|
+
for (var i = 0; i < links.length; i++) {
|
|
813
|
+
var href = links[i].getAttribute('href');
|
|
814
|
+
if (href && href.indexOf(path) !== -1) {
|
|
815
|
+
// Add cache-busting query param
|
|
816
|
+
var newHref = href.split('?')[0] + '?t=' + Date.now();
|
|
817
|
+
links[i].setAttribute('href', newHref);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// If content provided, inject as style tag
|
|
823
|
+
if (content) {
|
|
824
|
+
var style = document.createElement('style');
|
|
825
|
+
style.setAttribute('data-stx-hmr', path);
|
|
826
|
+
style.textContent = content;
|
|
1437
827
|
|
|
1438
|
-
//
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
const counterDisplay = document.getElementById('counterDisplay');
|
|
1442
|
-
if (counterDisplay) counterDisplay.textContent = 'Count: ' + state.count;
|
|
828
|
+
// Remove old injected style
|
|
829
|
+
var old = document.querySelector('style[data-stx-hmr="' + path + '"]');
|
|
830
|
+
if (old) old.remove();
|
|
1443
831
|
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
832
|
+
document.head.appendChild(style);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
1447
835
|
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
836
|
+
// Start connection when DOM is ready
|
|
837
|
+
if (document.readyState === 'loading') {
|
|
838
|
+
document.addEventListener('DOMContentLoaded', connect);
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
connect();
|
|
842
|
+
}
|
|
1454
843
|
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
844
|
+
// Forward browser console to the dev server terminal
|
|
845
|
+
var _origLog = console.log;
|
|
846
|
+
var _origError = console.error;
|
|
847
|
+
var _origWarn = console.warn;
|
|
848
|
+
var _origInfo = console.info;
|
|
1458
849
|
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
850
|
+
function _fwd(level, args) {
|
|
851
|
+
if (socket && socket.readyState === 1) {
|
|
852
|
+
try {
|
|
853
|
+
socket.send(JSON.stringify({
|
|
854
|
+
type: 'console',
|
|
855
|
+
level: level,
|
|
856
|
+
args: Array.prototype.slice.call(args).map(function(a) {
|
|
857
|
+
if (a === null) return 'null';
|
|
858
|
+
if (a === undefined) return 'undefined';
|
|
859
|
+
if (typeof a === 'object') { try { return JSON.stringify(a); } catch(e) { return String(a); } }
|
|
860
|
+
return String(a);
|
|
861
|
+
})
|
|
862
|
+
}));
|
|
863
|
+
} catch(e) {}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
1471
866
|
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
867
|
+
console.log = function() { _origLog.apply(console, arguments); _fwd('log', arguments); };
|
|
868
|
+
console.error = function() { _origError.apply(console, arguments); _fwd('error', arguments); };
|
|
869
|
+
console.warn = function() { _origWarn.apply(console, arguments); _fwd('warn', arguments); };
|
|
870
|
+
console.info = function() { _origInfo.apply(console, arguments); _fwd('info', arguments); };
|
|
871
|
+
|
|
872
|
+
// Expose for debugging
|
|
873
|
+
window.__stxHmr = {
|
|
874
|
+
reconnect: connect,
|
|
875
|
+
status: function() { return socket ? socket.readyState : -1; }
|
|
876
|
+
};
|
|
877
|
+
})();
|
|
878
|
+
</script>
|
|
879
|
+
`}function Xe(t,s,i={}){let p=Kr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Et(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Pt(t){if(!ut)ut=new dn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Ot from"path";var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${Ot.relative(Ot.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Qn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await on(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await re(()=>Bun.file(m).text(),"",(x)=>{throw new vn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new vn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=q.time("script-extraction",()=>{let x=h,T=ee(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),K=B?B[1]:"";if(/\bserver\b/i.test(K))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Ot.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await re(()=>d(g,S,m),void 0,(x)=>{let T=new J(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await q.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-s833fbvf.js"),T=x(w.join(`
|
|
880
|
+
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
881
|
+
`+v.slice(k);else v+=`
|
|
882
|
+
${T}`}if(v=await X(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await an(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new J(`Plugin processing failed: ${String(u)}`,m);if(P.log(h,{filePath:m,buildConfig:t.config}),It.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
|
|
883
|
+
<html lang="en">
|
|
884
|
+
<head>
|
|
885
|
+
<meta charset="UTF-8">
|
|
886
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
887
|
+
<title>stx Rendering Error</title>
|
|
888
|
+
<style>
|
|
889
|
+
body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; }
|
|
890
|
+
.error-header { color: #dc3545; border-left: 4px solid #dc3545; padding-left: 16px; margin-bottom: 24px; }
|
|
891
|
+
.error-details { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 16px; margin: 16px 0; }
|
|
892
|
+
.error-code { background: #2d3748; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: 'Monaco', 'Menlo', monospace; font-size: 14px; }
|
|
893
|
+
.help-section { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 16px; margin-top: 24px; }
|
|
894
|
+
.file-path { font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px; }
|
|
895
|
+
</style>
|
|
896
|
+
</head>
|
|
897
|
+
<body>
|
|
898
|
+
<div class="error-header">
|
|
899
|
+
<h1>stx Template Error</h1>
|
|
900
|
+
<p>An error occurred while processing your stx template.</p>
|
|
901
|
+
</div>
|
|
902
|
+
|
|
903
|
+
<div class="error-details">
|
|
904
|
+
<h3>Error Details</h3>
|
|
905
|
+
<p><strong>File:</strong> <span class="file-path">${b(m)}</span></p>
|
|
906
|
+
<p><strong>Error:</strong> ${b(h.message)}</p>
|
|
907
|
+
${y?`<p><strong>Line:</strong> ${b(String(y))}</p>`:""}
|
|
908
|
+
${w?`<p><strong>Context:</strong> ${b(String(w))}</p>`:""}
|
|
909
|
+
</div>
|
|
910
|
+
|
|
911
|
+
${h.stack?`
|
|
912
|
+
<div class="error-details">
|
|
913
|
+
<h3>Stack Trace</h3>
|
|
914
|
+
<pre class="error-code">${b(h.stack)}</pre>
|
|
915
|
+
</div>`:""}
|
|
916
|
+
|
|
917
|
+
<div class="help-section">
|
|
918
|
+
<h3>Troubleshooting Tips</h3>
|
|
919
|
+
<ul>
|
|
920
|
+
<li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
|
|
921
|
+
<li>Verify that all variables used in the template are properly defined</li>
|
|
922
|
+
<li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
|
|
923
|
+
<li>Run <code>stx debug ${b(Ot.basename(m))}</code> for detailed analysis</li>
|
|
924
|
+
<li>Enable debug mode in your stx config for more detailed error messages</li>
|
|
925
|
+
</ul>
|
|
926
|
+
</div>
|
|
1476
927
|
</body>
|
|
1477
|
-
</html
|
|
928
|
+
</html>`:`<!DOCTYPE html>
|
|
929
|
+
<html lang="en">
|
|
930
|
+
<head>
|
|
931
|
+
<meta charset="UTF-8">
|
|
932
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
933
|
+
<title>Error</title>
|
|
934
|
+
<style>
|
|
935
|
+
body { font-family: system-ui, -apple-system, sans-serif; max-width: 600px; margin: 80px auto; padding: 20px; text-align: center; color: #333; }
|
|
936
|
+
</style>
|
|
937
|
+
</head>
|
|
938
|
+
<body>
|
|
939
|
+
<h1>Something went wrong</h1>
|
|
940
|
+
<p>An internal error occurred. Please try again later.</p>
|
|
941
|
+
</body>
|
|
942
|
+
</html>`,loader:"html"}}})}};async function Tn(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Fe.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ut(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Fe.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},B=await Bun.build({entrypoints:[u],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let K=B.outputs.find(($e)=>$e.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(u);await _t(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Pt({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-8d788kvt.js"),B=await L();if(T=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Z}=await import("./chunk-mdxg95mq.js"),$e=B.broadcasting;await K($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Ae=Se.join(process.cwd(),"channels.ts");if(Fe.existsSync(Ae))try{let ae=await Z(Ae);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-bdhtq3vs.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Xr({port:C,async fetch(L){return Mt(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(u),Se.join(process.cwd(),"public")].some((ae)=>H(Se.join(ae,B.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(L);if(ae.status!==404)return ae}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await M(L);if(K)return K;if(B.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Z=Se.join(h,B.pathname);if(Fe.existsSync(Z)&&Fe.statSync(Z).isFile()){let ae=Bun.file(Z),U=Se.extname(Z).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let $e=Se.dirname(u),he=Se.join($e,B.pathname);if(Fe.existsSync(he)&&Fe.statSync(he).isFile()){let ae=Bun.file(he),U=Se.extname(he).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let Ae=Se.join(process.cwd(),"public",B.pathname);if(Fe.existsSync(Ae)&&Fe.statSync(Ae).isFile()){let ae=Bun.file(Ae),U=Se.extname(Ae).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),tt=ze.transformSync(qe);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
|
|
943
|
+
${L.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
|
+
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
945
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
|
|
946
|
+
${e.yellow}Routes:${e.reset}`);let R=Se.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${R}${e.reset}`),console.log(`
|
|
947
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.url.toString(),()=>{if(p)Fe.watch(Se.dirname(u),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(u).text(),B=$t(L);await dt(C,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(p){let L=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let B=Fe.watch(L,{recursive:!0},async(K,Z)=>{if(!Z||Et(Z))return;if(Rt(Z)){console.log(`${e.yellow}File ${e.bright}${Z}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),ne();let $e=await y();if(await cn(S),c&&l)if($e)l.reload(Z);else l.error("Build failed - check console for details")}else if(Ct(Z)){if(console.log(`${e.cyan}CSS ${e.bright}${Z}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Z)}});process.on("SIGINT",()=>{if(B.close(),l)ht();I.stop(),process.exit(0)})}return!0}var{serve:Gr}=globalThis.Bun;import Ze from"fs";import Oe from"path";var pn=`
|
|
1478
948
|
<script data-stx-helpers>
|
|
1479
949
|
(function() {
|
|
1480
950
|
'use strict'
|
|
@@ -1641,393 +1111,923 @@ else {
|
|
|
1641
1111
|
return \`<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:0.75rem;padding:0 1.5rem 1rem">\${cards}</div>\`
|
|
1642
1112
|
},
|
|
1643
1113
|
|
|
1644
|
-
timeline: function(items) {
|
|
1645
|
-
var entries = items.map(function(item, i) {
|
|
1646
|
-
var color = item.color || 'var(--text-accent)'
|
|
1647
|
-
var isLast = i === items.length - 1
|
|
1114
|
+
timeline: function(items) {
|
|
1115
|
+
var entries = items.map(function(item, i) {
|
|
1116
|
+
var color = item.color || 'var(--text-accent)'
|
|
1117
|
+
var isLast = i === items.length - 1
|
|
1118
|
+
|
|
1119
|
+
return \`
|
|
1120
|
+
<div style="display:flex;gap:0.75rem">
|
|
1121
|
+
<div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0">
|
|
1122
|
+
<div style="width:10px;height:10px;border-radius:50%;background:\${color};flex-shrink:0"></div>
|
|
1123
|
+
\${!isLast ? '<div style="width:2px;flex:1;background:var(--bar-track);min-height:24px"></div>' : ''}
|
|
1124
|
+
</div>
|
|
1125
|
+
<div style="padding-bottom:\${isLast ? '0' : '1rem'};flex:1">
|
|
1126
|
+
<div style="font-size:0.8125rem;font-weight:500;color:var(--text-primary)">\${item.title}</div>
|
|
1127
|
+
\${item.description ? \`<div style="font-size:0.75rem;color:var(--text-muted);margin-top:0.125rem">\${item.description}</div>\` : ''}
|
|
1128
|
+
\${item.meta ? \`<div style="font-size:0.6875rem;color:var(--text-tertiary);margin-top:0.25rem">\${item.meta}</div>\` : ''}
|
|
1129
|
+
</div>
|
|
1130
|
+
</div>\`
|
|
1131
|
+
}).join('')
|
|
1132
|
+
|
|
1133
|
+
return \`<div style="padding:0 1.5rem 1rem">\${entries}</div>\`
|
|
1134
|
+
},
|
|
1135
|
+
|
|
1136
|
+
open: function(html) {
|
|
1137
|
+
if (typeof openSlideOver === 'function') openSlideOver(html)
|
|
1138
|
+
},
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// ===== DATA TABLE HELPERS =====
|
|
1142
|
+
|
|
1143
|
+
stx.table = {
|
|
1144
|
+
filter: function(opts) {
|
|
1145
|
+
var searchEl = document.getElementById(opts.searchId)
|
|
1146
|
+
var search = searchEl ? searchEl.value.toLowerCase() : ''
|
|
1147
|
+
var rows = document.querySelectorAll(opts.rowSelector || 'tbody tr')
|
|
1148
|
+
var filters = opts.filters || []
|
|
1149
|
+
var matched = []
|
|
1150
|
+
|
|
1151
|
+
rows.forEach(function(row) {
|
|
1152
|
+
var text = row.textContent.toLowerCase()
|
|
1153
|
+
var matchSearch = !search || text.indexOf(search) !== -1
|
|
1154
|
+
var matchFilters = filters.every(function(f) {
|
|
1155
|
+
var el = document.getElementById(f.id)
|
|
1156
|
+
if (!el) return true
|
|
1157
|
+
var val = el.value
|
|
1158
|
+
if (!val || val === f.allValue) return true
|
|
1159
|
+
return row.getAttribute(\`data-\${f.attr}\`) === val
|
|
1160
|
+
})
|
|
1161
|
+
|
|
1162
|
+
if (matchSearch && matchFilters) matched.push(row)
|
|
1163
|
+
else row.style.display = 'none'
|
|
1164
|
+
})
|
|
1165
|
+
|
|
1166
|
+
return matched
|
|
1167
|
+
},
|
|
1168
|
+
|
|
1169
|
+
sort: function(rows, sortBy, direction) {
|
|
1170
|
+
direction = direction || 'asc'
|
|
1171
|
+
return rows.slice().sort(function(a, b) {
|
|
1172
|
+
var aVal = a.getAttribute(\`data-\${sortBy}\`) || a.textContent
|
|
1173
|
+
var bVal = b.getAttribute(\`data-\${sortBy}\`) || b.textContent
|
|
1174
|
+
var aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''))
|
|
1175
|
+
var bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''))
|
|
1176
|
+
if (!isNaN(aNum) && !isNaN(bNum)) return direction === 'asc' ? aNum - bNum : bNum - aNum
|
|
1177
|
+
return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
|
|
1178
|
+
})
|
|
1179
|
+
},
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// ===== PAGINATION =====
|
|
1183
|
+
|
|
1184
|
+
stx.pagination = function(opts) {
|
|
1185
|
+
var page = opts.page || 1
|
|
1186
|
+
var perPage = opts.perPage || 10
|
|
1187
|
+
var items = opts.items || []
|
|
1188
|
+
var total = items.length
|
|
1189
|
+
var totalPages = Math.max(1, Math.ceil(total / perPage))
|
|
1190
|
+
if (page > totalPages) page = totalPages
|
|
1191
|
+
|
|
1192
|
+
var start = (page - 1) * perPage
|
|
1193
|
+
var end = Math.min(start + perPage, total)
|
|
1194
|
+
|
|
1195
|
+
items.forEach(function(el, i) { el.style.display = (i >= start && i < end) ? '' : 'none' })
|
|
1196
|
+
|
|
1197
|
+
var ids = { count: opts.countId, total: opts.totalId, empty: opts.emptyId, bar: opts.barId }
|
|
1198
|
+
if (ids.count) { var el = document.getElementById(ids.count); if (el) el.textContent = total === 0 ? '0' : \`\${start + 1}\\u2013\${end}\` }
|
|
1199
|
+
if (ids.total) { var el = document.getElementById(ids.total); if (el) el.textContent = total }
|
|
1200
|
+
if (ids.empty) { var el = document.getElementById(ids.empty); if (el) el.style.display = total === 0 ? 'block' : 'none' }
|
|
1201
|
+
if (ids.bar) { var el = document.getElementById(ids.bar); if (el) el.style.display = total === 0 ? 'none' : '' }
|
|
1202
|
+
|
|
1203
|
+
if (opts.buttonsId) {
|
|
1204
|
+
var wrap = document.getElementById(opts.buttonsId)
|
|
1205
|
+
if (wrap) {
|
|
1206
|
+
var go = opts.goToPage
|
|
1207
|
+
var pages = stx.pagination.getPages(page, totalPages)
|
|
1208
|
+
|
|
1209
|
+
var btn = function(label, target, disabled) {
|
|
1210
|
+
return \`<button onclick="\${go}(\${target})" \${disabled ? 'disabled' : ''}
|
|
1211
|
+
class="px-3 py-1.5 rounded-lg text-sm cursor-pointer"
|
|
1212
|
+
style="background:var(--bg-subtle);border:1px solid var(--border-input);color:\${disabled ? 'var(--text-muted)' : 'var(--text-primary)'};opacity:\${disabled ? '0.5' : '1'}">\${label}</button>\`
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
var h = btn('Previous', page - 1, page === 1)
|
|
1216
|
+
pages.forEach(function(p) {
|
|
1217
|
+
if (p === '...') {
|
|
1218
|
+
h += '<span class="px-2 text-sm" style="color:var(--text-muted)">\\u2026</span>'
|
|
1219
|
+
}
|
|
1220
|
+
else if (p === page) {
|
|
1221
|
+
h += \`<button class="w-9 h-9 rounded-lg text-sm font-medium" style="background:var(--btn-primary-bg, var(--text-accent));color:#fff">\${p}</button>\`
|
|
1222
|
+
}
|
|
1223
|
+
else {
|
|
1224
|
+
h += btn(p, p, false)
|
|
1225
|
+
}
|
|
1226
|
+
})
|
|
1227
|
+
h += btn('Next', page + 1, page === totalPages)
|
|
1228
|
+
wrap.innerHTML = h
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
return { page: page, totalPages: totalPages, total: total, start: start, end: end }
|
|
1233
|
+
}
|
|
1648
1234
|
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
\${item.meta ? \`<div style="font-size:0.6875rem;color:var(--text-tertiary);margin-top:0.25rem">\${item.meta}</div>\` : ''}
|
|
1659
|
-
</div>
|
|
1660
|
-
</div>\`
|
|
1661
|
-
}).join('')
|
|
1235
|
+
stx.pagination.getPages = function(current, total) {
|
|
1236
|
+
if (total <= 7) return Array.from({ length: total }, function(_, i) { return i + 1 })
|
|
1237
|
+
var pages = [1]
|
|
1238
|
+
if (current > 3) pages.push('...')
|
|
1239
|
+
for (var i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) pages.push(i)
|
|
1240
|
+
if (current < total - 2) pages.push('...')
|
|
1241
|
+
pages.push(total)
|
|
1242
|
+
return pages
|
|
1243
|
+
}
|
|
1662
1244
|
|
|
1663
|
-
|
|
1664
|
-
},
|
|
1245
|
+
// ===== UTILITIES =====
|
|
1665
1246
|
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1247
|
+
stx.debounce = function(fn, delay) {
|
|
1248
|
+
var timer
|
|
1249
|
+
return function() {
|
|
1250
|
+
var args = arguments, ctx = this
|
|
1251
|
+
clearTimeout(timer)
|
|
1252
|
+
timer = setTimeout(function() { fn.apply(ctx, args) }, delay || 250)
|
|
1253
|
+
}
|
|
1669
1254
|
}
|
|
1670
1255
|
|
|
1671
|
-
|
|
1256
|
+
})()
|
|
1257
|
+
</script>
|
|
1258
|
+
`;function fn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Oe.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Oe.sep)}async function $n(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Oe.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=fn(t.map((v)=>Oe.dirname(Oe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],h=async()=>{try{for(let v of t){let x=Oe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await ue(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),M=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,I=M?.defaultTheme||"github-dark",R=["github-dark"],L=M?.additionalThemes||[],K=[...new Set([...R,...L])].map((Ae)=>`<option value="${Ae}"${Ae===I?" selected":""}>${Ae}</option>`).join(`
|
|
1259
|
+
`),Z=`
|
|
1260
|
+
<!DOCTYPE html>
|
|
1261
|
+
<html lang="en">
|
|
1262
|
+
<head>
|
|
1263
|
+
<meta charset="UTF-8">
|
|
1264
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1265
|
+
<title>${un(H.title||Oe.basename(x))}</title>
|
|
1266
|
+
<!-- Syntax highlighting styles -->
|
|
1267
|
+
<style id="syntax-theme">
|
|
1268
|
+
:root {
|
|
1269
|
+
--shiki-color-text: #24292e;
|
|
1270
|
+
--shiki-color-background: #ffffff;
|
|
1271
|
+
--shiki-token-constant: #005cc5;
|
|
1272
|
+
--shiki-token-string: #032f62;
|
|
1273
|
+
--shiki-token-comment: #6a737d;
|
|
1274
|
+
--shiki-token-keyword: #d73a49;
|
|
1275
|
+
--shiki-token-parameter: #24292e;
|
|
1276
|
+
--shiki-token-function: #6f42c1;
|
|
1277
|
+
--shiki-token-string-expression: #032f62;
|
|
1278
|
+
--shiki-token-punctuation: #24292e;
|
|
1279
|
+
--shiki-token-link: #032f62;
|
|
1280
|
+
}
|
|
1281
|
+
pre {
|
|
1282
|
+
background-color: var(--shiki-color-background);
|
|
1283
|
+
padding: 1rem;
|
|
1284
|
+
border-radius: 4px;
|
|
1285
|
+
}
|
|
1286
|
+
code {
|
|
1287
|
+
color: var(--shiki-color-text);
|
|
1288
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1289
|
+
}
|
|
1290
|
+
.dark-mode {
|
|
1291
|
+
--shiki-color-text: #e1e4e8;
|
|
1292
|
+
--shiki-color-background: #24292e;
|
|
1293
|
+
--shiki-token-constant: #79b8ff;
|
|
1294
|
+
--shiki-token-string: #9ecbff;
|
|
1295
|
+
--shiki-token-comment: #6a737d;
|
|
1296
|
+
--shiki-token-keyword: #f97583;
|
|
1297
|
+
--shiki-token-parameter: #e1e4e8;
|
|
1298
|
+
--shiki-token-function: #b392f0;
|
|
1299
|
+
--shiki-token-string-expression: #9ecbff;
|
|
1300
|
+
--shiki-token-punctuation: #e1e4e8;
|
|
1301
|
+
--shiki-token-link: #9ecbff;
|
|
1302
|
+
}
|
|
1303
|
+
</style>
|
|
1304
|
+
<style>
|
|
1305
|
+
body {
|
|
1306
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
1307
|
+
line-height: 1.6;
|
|
1308
|
+
color: #333;
|
|
1309
|
+
max-width: 800px;
|
|
1310
|
+
margin: 0 auto;
|
|
1311
|
+
padding: 2rem;
|
|
1312
|
+
}
|
|
1313
|
+
pre, code {
|
|
1314
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1315
|
+
}
|
|
1316
|
+
pre {
|
|
1317
|
+
border-radius: 4px;
|
|
1318
|
+
padding: 0;
|
|
1319
|
+
margin: 1.5rem 0;
|
|
1320
|
+
overflow-x: auto;
|
|
1321
|
+
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
1322
|
+
}
|
|
1323
|
+
pre code {
|
|
1324
|
+
display: block;
|
|
1325
|
+
padding: 1rem;
|
|
1326
|
+
overflow-x: auto;
|
|
1327
|
+
}
|
|
1328
|
+
/* Apply background color to code blocks based on theme */
|
|
1329
|
+
pre.syntax-highlighter {
|
|
1330
|
+
background-color: var(--shiki-color-background) !important;
|
|
1331
|
+
}
|
|
1332
|
+
.dark-mode pre.syntax-highlighter {
|
|
1333
|
+
background-color: var(--shiki-color-background) !important;
|
|
1334
|
+
}
|
|
1335
|
+
code {
|
|
1336
|
+
padding: 0.2rem 0.4rem;
|
|
1337
|
+
border-radius: 3px;
|
|
1338
|
+
}
|
|
1339
|
+
h1, h2, h3, h4 {
|
|
1340
|
+
margin-top: 2rem;
|
|
1341
|
+
margin-bottom: 1rem;
|
|
1342
|
+
}
|
|
1343
|
+
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
1344
|
+
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
1345
|
+
h3 { color: #444; }
|
|
1346
|
+
img {
|
|
1347
|
+
max-width: 100%;
|
|
1348
|
+
border-radius: 4px;
|
|
1349
|
+
margin: 1rem 0;
|
|
1350
|
+
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
1351
|
+
}
|
|
1352
|
+
blockquote {
|
|
1353
|
+
border-left: 4px solid #ddd;
|
|
1354
|
+
padding-left: 1rem;
|
|
1355
|
+
margin-left: 0;
|
|
1356
|
+
color: #555;
|
|
1357
|
+
background: #f9f9f9;
|
|
1358
|
+
padding: 0.5rem 1rem;
|
|
1359
|
+
margin: 1.5rem 0;
|
|
1360
|
+
}
|
|
1361
|
+
table {
|
|
1362
|
+
border-collapse: collapse;
|
|
1363
|
+
width: 100%;
|
|
1364
|
+
margin: 1.5rem 0;
|
|
1365
|
+
}
|
|
1366
|
+
th, td {
|
|
1367
|
+
border: 1px solid #ddd;
|
|
1368
|
+
padding: 0.5rem;
|
|
1369
|
+
}
|
|
1370
|
+
th {
|
|
1371
|
+
background: #f0f0f0;
|
|
1372
|
+
text-align: left;
|
|
1373
|
+
}
|
|
1374
|
+
tr:nth-child(even) {
|
|
1375
|
+
background-color: #f8f8f8;
|
|
1376
|
+
}
|
|
1377
|
+
a {
|
|
1378
|
+
color: #0066cc;
|
|
1379
|
+
text-decoration: none;
|
|
1380
|
+
}
|
|
1381
|
+
a:hover {
|
|
1382
|
+
text-decoration: underline;
|
|
1383
|
+
}
|
|
1384
|
+
hr {
|
|
1385
|
+
border: 0;
|
|
1386
|
+
border-top: 1px solid #eee;
|
|
1387
|
+
margin: 2rem 0;
|
|
1388
|
+
}
|
|
1389
|
+
.frontmatter {
|
|
1390
|
+
background: #f8f8f8;
|
|
1391
|
+
border-radius: 4px;
|
|
1392
|
+
padding: 1.5rem;
|
|
1393
|
+
margin-bottom: 2rem;
|
|
1394
|
+
font-size: 0.9rem;
|
|
1395
|
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
1396
|
+
border-left: 4px solid #ddd;
|
|
1397
|
+
}
|
|
1398
|
+
.frontmatter-item {
|
|
1399
|
+
margin-bottom: 0.5rem;
|
|
1400
|
+
display: flex;
|
|
1401
|
+
}
|
|
1402
|
+
.frontmatter-label {
|
|
1403
|
+
font-weight: bold;
|
|
1404
|
+
min-width: 100px;
|
|
1405
|
+
color: #555;
|
|
1406
|
+
}
|
|
1407
|
+
${vt()}
|
|
1408
|
+
</style>
|
|
1409
|
+
</head>
|
|
1410
|
+
<body>
|
|
1411
|
+
${kt(H)}
|
|
1412
|
+
${wt(K)}
|
|
1672
1413
|
|
|
1673
|
-
|
|
1674
|
-
filter: function(opts) {
|
|
1675
|
-
var searchEl = document.getElementById(opts.searchId)
|
|
1676
|
-
var search = searchEl ? searchEl.value.toLowerCase() : ''
|
|
1677
|
-
var rows = document.querySelectorAll(opts.rowSelector || 'tbody tr')
|
|
1678
|
-
var filters = opts.filters || []
|
|
1679
|
-
var matched = []
|
|
1414
|
+
${k}
|
|
1680
1415
|
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1416
|
+
<script>
|
|
1417
|
+
${St()}
|
|
1418
|
+
</script>
|
|
1419
|
+
</body>
|
|
1420
|
+
</html>
|
|
1421
|
+
`,he=`/${Oe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(R){R.onResolve({filter:/^\/(images|fonts|assets|public)\//},(L)=>({path:L.path,external:!0}))}},H;try{let R=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!R.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,le(R.logs,x));continue}let L=R.outputs.find((B)=>B.path.endsWith(".html"));if(!L){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(L.path).text()}catch(R){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
|
|
1422
|
+
${le(R,x)}`);continue}let I=`/${Oe.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:R,params:L}=fr(I,{page:!0});u.push({pattern:R,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,le(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=Gr({port:y,async fetch(v){let x=new URL(v.url),T=Oe.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(T)&&Ze.statSync(T).isFile()){let M=Bun.file(T),I=Oe.extname(T).toLowerCase(),R="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),K=L.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(M,{headers:{"Content-Type":R}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let M of u){let I=x.pathname.match(M.pattern);if(I){let R=m[M.routeTemplate];if(R){let L={};for(let Z=0;Z<M.paramNames.length;Z++)L[M.paramNames[Z]]=decodeURIComponent(I[Z+1]);let B=R.content,K=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${K}
|
|
1423
|
+
</head>`);else B=K+B;k={...R,content:B}}break}}if(k)return f(k.content).then((M)=>{if(M.includes("</head>"))M=M.replace("</head>",`${pn}
|
|
1424
|
+
</head>`);return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Oe.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let M=Bun.file(H),I=Oe.extname(H).toLowerCase(),R="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),K=L.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(M,{headers:{"Content-Type":R}})}if(x.pathname!=="/"&&m["/"]){let M=se(v);return f(m["/"].content).then((I)=>{if(M){let R=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(R){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=L?L[1]:"",K=`<!DOCTYPE html><html><head><title>${un(B)}</title></head><body><main>${R[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",..._(),"Cache-Control":Ie,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{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}
|
|
1425
|
+
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1426
|
+
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1427
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
1428
|
+
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Oe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Oe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
|
|
1429
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),ne(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Jr}=globalThis.Bun;import xe from"fs";import ie from"path";async function mn(t){try{return Tt(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function Rn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-8d788kvt.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-bdhtq3vs.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!xe.existsSync(T)&&!g._layerPageDirs?.some((E)=>xe.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(xe.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let W of z){let we=F==="/"?W.pattern:`${F}${W.pattern==="/"?"":W.pattern}`;M.push({route:{...W,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await po(u,s.stxOptions?.shell),L){if(R=await $r(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}rt(),await ot(u);let B=st();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let K={},Z=null;try{let{loadStxConfig:E}=await import("./chunk-8d788kvt.js"),F=await E(u);if(F?.apiRouter)Z=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){K=F.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:W}=await import("./chunk-mdxg95mq.js"),we=F.broadcasting;await z(we);let Ne=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ne}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let te=await W(Ge);console.log(`${e.blue}Loaded ${e.bright}${te} broadcast channel${te!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(te){console.warn(`${e.yellow}Failed to load channels.ts: ${te.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let he=new Map,Ae=new Set,ae=async(E)=>{let F=gr(T,E);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let W=z.outputs.find((we)=>we.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:W,defaultConfig:we,loadStxConfig:Ne,injectRouterScript:Ge}=await import("./chunk-8d788kvt.js"),{checkCache:te,cacheTemplate:Q,readFileCached:V,templateCache:G}=await import("./chunk-kwxy0e3r.js"),ke=await Ne(u),Je=(ce)=>{if(!ce)return ce;if(ie.isAbsolute(ce))return ce;return ie.resolve(u,ce)},O={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(u,"cache");let be=!F&&!s.profile,pe=O.cache!==!1;if(pe&&be){let ce=G.get(E.filePath);if(ce)try{if((await xe.promises.stat(E.filePath)).mtime.getTime()<=ce.mtime){let Be=!0;for(let Re of ce.dependencies){if(!xe.existsSync(Re)){Be=!1;break}if((await xe.promises.stat(Re)).mtime.getTime()>ce.mtime){Be=!1;break}}if(Be){let Re=ce.output;if(R)Re=ye(Re,{preserveHead:!0});let gt=U.get(E.filePath);return{route:E,content:Re,status:gt?.status??await mn(E.filePath),headers:gt?.headers}}}}catch{}let Le=await te(E.filePath,O);if(Le){let je=Le;if(R)je=ye(je,{preserveHead:!0});let Be=U.get(E.filePath);return{route:E,content:je,status:Be?.status??await mn(E.filePath),headers:Be?.headers}}}let ge=pe?await V(E.filePath):await Bun.file(E.filePath).text(),Ce=Tt(ge),{classifyAllScripts:Y}=await import("./chunk-8d788kvt.js"),_e=Y(ge),We=_e.server.map((ce)=>ce.content),fe=ge;for(let ce of _e.server)fe=fe.replace(ce.fullTag,"");let me={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let ce of We)try{await W(ce,me,E.filePath)}catch(Le){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Le?.message||Le)}let Ke=new Set,De;if(s.profile){let ce=performance.now();De=await z(fe,me,E.filePath,O,Ke);let Le=performance.now()-ce,je=ie.relative(u,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Le.toFixed(2)}ms`)}else De=await z(fe,me,E.filePath,O,Ke);if(!R)De=await Ge(De,{router:O.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-s833fbvf.js");De=De.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Le,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Le;return`<script${je}>${ce(Be,me)}</script>`})}if(R)De=ye(De,{preserveHead:!0});if(pe&&be)await Q(E.filePath,De,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-04qvjcsr.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=me.streamBoundaries||{},Le={...O,autoShell:!1},je=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof ce[Re]==="function"?await ce[Re]():void 0;return z(mt[Re],{...me,$boundary:gt},E.filePath,Le,new Set)}})),Be=new Set(je.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!Be.has(Re.id)),...je]}if(lt&<.length>0)Ae.add(E.pattern);else lt=void 0;let Kt=Ue(me),Xt=Ve(me);if(be)U.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:De,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},ze=8,qe=async()=>{he.clear(),I.clear();for(let E=0;E<k.length;E+=ze){let F=k.slice(E,E+ze),z=await Promise.all(F.map((W)=>j(W)));for(let W of z)if(W)he.set(W.route.pattern,W)}for(let E=0;E<M.length;E+=ze){let F=M.slice(E,E+ze),z=await Promise.all(F.map(({route:W})=>j(W)));for(let W of z)if(W)I.set(W.route.pattern,W)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await _t(u);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||et+1;l=Pt({wsPort:E,verbose:!1}),m=l.start(E)}let Dt=(E,F)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(E.includes("</head>"))return E.replace("</head>",`${W}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+E};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Jr({port:et,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",W=ie.join(u,z,F.pathname),we=ie.join(u,F.pathname),Ne=ie.join($e,F.pathname);if([W,we,Ne].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,te,Q]=await Promise.all([xe.promises.stat(W).catch(()=>null),xe.promises.stat(we).catch(()=>null),xe.promises.stat(Ne).catch(()=>null)]);if(Ge?.isFile()&&!w(W,u,S))return Wt(W);if(te?.isFile()&&!w(we,u,S))return Wt(we);if(Q?.isFile()&&!w(Ne,u,S))return Wt(Ne);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let be=`<${O} />`,pe={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),pe,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:O}=await import("./chunk-375skn32.js"),be=await O(E,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(Z)try{let O=await Z.handleRequest(E);if(O.status!==404)return O}catch{}if(K[F.pathname])try{return await K[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await C(E);if(V)return V;let G=Cn(F.pathname,k);if(G){let O=he.get(G.route.pattern),be=Ae.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||be){let pe=await j(G.route,G.params);if(pe)O=pe}if(O){let pe=O.status??200,ge=O.headers??{},Ce=(G.route.filePath?He(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let We=await ae(404);if(We){let fe=We;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let _e=it(F.pathname,G.params,Ce,F.search),We=at(_e,null,E,{isServer:!0}),fe=await ct(Ce.middleware,We);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,De=new Headers(fe.responseHeaders);return De.set("Location",me),new Response(null,{status:Ke,headers:De})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${me}</head>`)}}let Y=O.content;if(R&&fo(E)){let _e=Ee(Y),We=de(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?uo(fe[1].trim()):"";if(Object.keys(G.params).length>0)Y=Dt(Y,G.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=oe(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":_e.layout,"X-STX-Layout-Group":_e.group,"X-STX-Runtime":We?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[yi]:Ss(),..._(),"Cache-Control":Ie}})}if(R)Y=On(R,Y);if(Object.keys(G.params).length>0)Y=Dt(Y,G.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:_e,streamToResponse:We}=await import("./chunk-04qvjcsr.js");return We(_e(Y,O.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(M.length>0){let O=M.map((pe)=>pe.route),be=Cn(F.pathname,O);if(be){let pe=I.get(be.route.pattern);if(pe){let ge=pe.content;if(R)ge=On(R,ge);if(Object.keys(be.params).length>0)ge=Dt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of H)if(pe!=="/"&&F.pathname.startsWith(pe)){let ge=I.get(pe)||I.get(pe+"/");if(ge){let Ce=ge.content;if(R)Ce=On(R,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(nt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let O=ke.content;if(O=await f(O,u),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.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 O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let O=Je;if(O=await f(O,u),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
|
|
1430
|
+
${E.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1431
|
+
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1432
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
1433
|
+
${e.yellow}Routes:${e.reset}`);let jt=[...mr(k,u)];for(let{route:E}of M)jt.push(`${E.pattern}`);if(jt.forEach((E,F)=>{let W=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${W}${e.reset}${E}`)}),console.log(`
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(xe.existsSync(F)){let W=await Bun.file(F).text();E=$t(W)}let z=g?.app?.window??{};await dt(et,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!E,sidebarConfig:E})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(te)=>te.startsWith("public/")||te.startsWith("public\\"),F=(te)=>{let Q=te.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,W=()=>{let te=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>xe.existsSync(Q)).map((Q)=>xe.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let V of Object.values(Q.resources)){if(!xe.existsSync(V))continue;let G=xe.realpathSync(V);if(![...te].some((ke)=>G===ke||G.startsWith(`${ke}${ie.sep}`)))te.add(G)}for(let[Q,V]of z)if(!te.has(Q))V.close(),z.delete(Q);for(let Q of te)if(!z.has(Q)&&xe.existsSync(Q))z.set(Q,xe.watch(Q,{recursive:!0},(V,G)=>{Ne(Q,V,G).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),Ne=(te,Q,V)=>(we=we.catch(()=>{}).then(()=>Ge(te,Q,V)),we),Ge=async(te,Q,V)=>{if(!V||Et(V))return;if(Rt(V)){if(g._layerGraph){let G=await h(u);Object.assign(g,G),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:G._layerPageDirs?[T,...G._layerPageDirs.slice(1)]:void 0})),W()}if(E(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),c&&l)l.reload(V)}else if(F(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ve.clear(),ne();try{let{invalidateFileCache:G,templateCache:ke}=await import("./chunk-kwxy0e3r.js");G(ie.resolve(te,V)),ke.delete(ie.resolve(te,V))}catch{}if(L&&V){if(ie.resolve(te,V)===L||ie.basename(L)===V){let ke=await $r(L,s.stxOptions||{});if(ke)R=ke}}if(await qe(),await cn(u),c&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),ve.clear(),ne();try{let{invalidateFileCache:G,templateCache:ke}=await import("./chunk-kwxy0e3r.js");G(ie.resolve(te,V)),ke.delete(ie.resolve(te,V))}catch{}if(await qe(),c&&l)l.reload(V)}}else if(Ct(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),c&&l)l.updateCss(V)}};W(),process.on("SIGINT",()=>{for(let te of z.values())te.close();if(l)ht();Lt.stop(),process.exit(0)})}return!0}import Vt from"fs";import yt from"path";async function Yr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let p=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=u.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let C=u.split(`
|
|
1435
|
+
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=C.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Qr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
|
|
1436
|
+
`).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Zr(t,s=!1,i){let p=yt.basename(t,".stx"),c=await Yr(t),l=await Qr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let u=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
|
|
1437
|
+
`);m=`<${p}
|
|
1438
|
+
${u}
|
|
1439
|
+
/>`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function gn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await gn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function ro(t,s){try{if(!await r(t))return[];let i=await gn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),u=!!m,h=m?.tag,g=await Zr(l,u,h);p.push(g)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function oo(t){try{if(!await r(t))return[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=u?u[1].split(`
|
|
1440
|
+
`).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let C=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=C.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function so(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1441
|
+
<p>Welcome, {{ user.name }}!</p>
|
|
1442
|
+
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
1443
|
+
<p>Welcome back!</p>
|
|
1444
|
+
@else
|
|
1445
|
+
<p>Please log in</p>
|
|
1446
|
+
@endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
|
|
1447
|
+
<p>A</p>
|
|
1448
|
+
@elseif(score > 80)
|
|
1449
|
+
<p>B</p>
|
|
1450
|
+
@elseif(score > 70)
|
|
1451
|
+
<p>C</p>
|
|
1452
|
+
@endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
|
|
1453
|
+
<p>Please log in</p>
|
|
1454
|
+
@endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
|
|
1455
|
+
<li>{{ item.name }}</li>
|
|
1456
|
+
@endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
|
|
1457
|
+
<p>Page {{ page }}</p>
|
|
1458
|
+
@endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
|
|
1459
|
+
{{ This will be displayed as-is }}
|
|
1460
|
+
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function io(t=[],s=[],i=[],p){let c=`# stx Documentation
|
|
1691
1461
|
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1462
|
+
`;if(p)c+=`${p}
|
|
1463
|
+
|
|
1464
|
+
`;if(t.length>0){c+=`## Components
|
|
1695
1465
|
|
|
1696
|
-
|
|
1697
|
-
},
|
|
1466
|
+
`;for(let l of t){if(c+=`### ${l.name}
|
|
1698
1467
|
|
|
1699
|
-
|
|
1700
|
-
direction = direction || 'asc'
|
|
1701
|
-
return rows.slice().sort(function(a, b) {
|
|
1702
|
-
var aVal = a.getAttribute(\`data-\${sortBy}\`) || a.textContent
|
|
1703
|
-
var bVal = b.getAttribute(\`data-\${sortBy}\`) || b.textContent
|
|
1704
|
-
var aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''))
|
|
1705
|
-
var bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''))
|
|
1706
|
-
if (!isNaN(aNum) && !isNaN(bNum)) return direction === 'asc' ? aNum - bNum : bNum - aNum
|
|
1707
|
-
return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
|
|
1708
|
-
})
|
|
1709
|
-
},
|
|
1710
|
-
}
|
|
1468
|
+
`,l.description)c+=`${l.description}
|
|
1711
1469
|
|
|
1712
|
-
|
|
1470
|
+
`;if(l.isWebComponent)c+=`**Web Component Tag:** \`${l.tag}\`
|
|
1713
1471
|
|
|
1714
|
-
|
|
1715
|
-
var page = opts.page || 1
|
|
1716
|
-
var perPage = opts.perPage || 10
|
|
1717
|
-
var items = opts.items || []
|
|
1718
|
-
var total = items.length
|
|
1719
|
-
var totalPages = Math.max(1, Math.ceil(total / perPage))
|
|
1720
|
-
if (page > totalPages) page = totalPages
|
|
1472
|
+
`;if(l.props.length>0){c+=`#### Properties
|
|
1721
1473
|
|
|
1722
|
-
|
|
1723
|
-
|
|
1474
|
+
`,c+=`| Name | Type | Required | Default | Description |
|
|
1475
|
+
`,c+=`| ---- | ---- | -------- | ------- | ----------- |
|
|
1476
|
+
`;for(let m of l.props)c+=`| ${m.name} | ${m.type||"any"} | ${m.required?"Yes":"No"} | ${m.default||"-"} | ${m.description||"-"} |
|
|
1477
|
+
`;c+=`
|
|
1478
|
+
`}if(l.example)c+=`#### Example
|
|
1724
1479
|
|
|
1725
|
-
|
|
1480
|
+
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
|
|
1726
1481
|
|
|
1727
|
-
|
|
1728
|
-
if (ids.count) { var el = document.getElementById(ids.count); if (el) el.textContent = total === 0 ? '0' : \`\${start + 1}\\u2013\${end}\` }
|
|
1729
|
-
if (ids.total) { var el = document.getElementById(ids.total); if (el) el.textContent = total }
|
|
1730
|
-
if (ids.empty) { var el = document.getElementById(ids.empty); if (el) el.style.display = total === 0 ? 'block' : 'none' }
|
|
1731
|
-
if (ids.bar) { var el = document.getElementById(ids.bar); if (el) el.style.display = total === 0 ? 'none' : '' }
|
|
1482
|
+
`;for(let l of s){if(c+=`### ${l.name}
|
|
1732
1483
|
|
|
1733
|
-
|
|
1734
|
-
var wrap = document.getElementById(opts.buttonsId)
|
|
1735
|
-
if (wrap) {
|
|
1736
|
-
var go = opts.goToPage
|
|
1737
|
-
var pages = stx.pagination.getPages(page, totalPages)
|
|
1484
|
+
`,l.description)c+=`${l.description}
|
|
1738
1485
|
|
|
1739
|
-
|
|
1740
|
-
return \`<button onclick="\${go}(\${target})" \${disabled ? 'disabled' : ''}
|
|
1741
|
-
class="px-3 py-1.5 rounded-lg text-sm cursor-pointer"
|
|
1742
|
-
style="background:var(--bg-subtle);border:1px solid var(--border-input);color:\${disabled ? 'var(--text-muted)' : 'var(--text-primary)'};opacity:\${disabled ? '0.5' : '1'}">\${label}</button>\`
|
|
1743
|
-
}
|
|
1486
|
+
`;if(l.components&&l.components.length>0)c+=`**Components Used:** ${l.components.join(", ")}
|
|
1744
1487
|
|
|
1745
|
-
|
|
1746
|
-
pages.forEach(function(p) {
|
|
1747
|
-
if (p === '...') {
|
|
1748
|
-
h += '<span class="px-2 text-sm" style="color:var(--text-muted)">\\u2026</span>'
|
|
1749
|
-
}
|
|
1750
|
-
else if (p === page) {
|
|
1751
|
-
h += \`<button class="w-9 h-9 rounded-lg text-sm font-medium" style="background:var(--btn-primary-bg, var(--text-accent));color:#fff">\${p}</button>\`
|
|
1752
|
-
}
|
|
1753
|
-
else {
|
|
1754
|
-
h += btn(p, p, false)
|
|
1755
|
-
}
|
|
1756
|
-
})
|
|
1757
|
-
h += btn('Next', page + 1, page === totalPages)
|
|
1758
|
-
wrap.innerHTML = h
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1488
|
+
`;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
|
|
1761
1489
|
|
|
1762
|
-
|
|
1763
|
-
}
|
|
1490
|
+
`}}if(i.length>0){c+=`## Directives
|
|
1764
1491
|
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
if (current < total - 2) pages.push('...')
|
|
1771
|
-
pages.push(total)
|
|
1772
|
-
return pages
|
|
1773
|
-
}
|
|
1492
|
+
`,c+=`| Directive | Description | Has End Tag |
|
|
1493
|
+
`,c+=`| --------- | ----------- | ----------- |
|
|
1494
|
+
`;for(let l of i)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
|
|
1495
|
+
`;c+=`
|
|
1496
|
+
`;for(let l of i)if(l.example)c+=`### @${l.name}
|
|
1774
1497
|
|
|
1775
|
-
|
|
1498
|
+
`,c+=`${l.description||""}
|
|
1776
1499
|
|
|
1777
|
-
|
|
1778
|
-
var timer
|
|
1779
|
-
return function() {
|
|
1780
|
-
var args = arguments, ctx = this
|
|
1781
|
-
clearTimeout(timer)
|
|
1782
|
-
timer = setTimeout(function() { fn.apply(ctx, args) }, delay || 250)
|
|
1783
|
-
}
|
|
1784
|
-
}
|
|
1500
|
+
`,c+=`#### Example
|
|
1785
1501
|
|
|
1786
|
-
}
|
|
1787
|
-
</script>
|
|
1788
|
-
`;import _e from"fs";import Te from"path";function On(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function At(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function An(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var Dn=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=_e.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Oi(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Dn){let S=Te.join(u,w),C=Pi(S);if(C!==null)p.push({name:w,version:C,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=_e.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=Te.join(S,x.name,"node_modules");if(_e.existsSync(T))l(T,h+1)}continue}let C=Te.join(S,"node_modules");if(_e.existsSync(C))l(C,h+1)}}let m=Te.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return p}function Ai(t){let s=[];for(let i of Dn){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function vr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Ai(Oi(s)))c.push(h);let u=An(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,y=On(h),w=g?On(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${At(w,p)}) is OLDER than src/signals.ts (${At(y,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${At(y,p)}, dist ${At(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),C=null;try{C=_e.lstatSync(S)}catch{C=null}if(!C)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function xr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
|
|
1789
|
-
`)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Zn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await sn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ne(()=>Bun.file(m).text(),"",(x)=>{throw new wn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new wn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=W.time("script-extraction",()=>{let x=h,T=Q(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",_=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else _.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:_}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ne(()=>d(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await W.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-sn5c0x7q.js"),T=x(w.join(`
|
|
1790
|
-
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
1791
|
-
`+v.slice(k);else v+=`
|
|
1792
|
-
${T}`}if(v=await K(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await on(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new X(`Plugin processing failed: ${String(u)}`,m);if(P.log(h,{filePath:m,buildConfig:t.config}),Pt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
|
|
1502
|
+
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ao(t=[],s=[],i=[],p){let c=`<!DOCTYPE html>
|
|
1793
1503
|
<html lang="en">
|
|
1794
1504
|
<head>
|
|
1795
1505
|
<meta charset="UTF-8">
|
|
1796
1506
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1797
|
-
<title>stx
|
|
1507
|
+
<title>stx Documentation</title>
|
|
1798
1508
|
<style>
|
|
1799
|
-
body {
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1509
|
+
body {
|
|
1510
|
+
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
|
1511
|
+
line-height: 1.6;
|
|
1512
|
+
color: #333;
|
|
1513
|
+
max-width: 1200px;
|
|
1514
|
+
margin: 0 auto;
|
|
1515
|
+
padding: 2rem;
|
|
1516
|
+
}
|
|
1517
|
+
h1, h2, h3, h4 { margin-top: 2rem; }
|
|
1518
|
+
table {
|
|
1519
|
+
border-collapse: collapse;
|
|
1520
|
+
width: 100%;
|
|
1521
|
+
margin: 1rem 0;
|
|
1522
|
+
}
|
|
1523
|
+
th, td {
|
|
1524
|
+
text-align: left;
|
|
1525
|
+
padding: 0.5rem;
|
|
1526
|
+
border-bottom: 1px solid #ddd;
|
|
1527
|
+
}
|
|
1528
|
+
th { border-bottom: 2px solid #ddd; }
|
|
1529
|
+
pre {
|
|
1530
|
+
background: #f5f5f5;
|
|
1531
|
+
padding: 1rem;
|
|
1532
|
+
border-radius: 4px;
|
|
1533
|
+
overflow-x: auto;
|
|
1534
|
+
}
|
|
1535
|
+
code {
|
|
1536
|
+
background: #f5f5f5;
|
|
1537
|
+
padding: 0.2rem 0.4rem;
|
|
1538
|
+
border-radius: 4px;
|
|
1539
|
+
font-size: 0.9em;
|
|
1540
|
+
}
|
|
1805
1541
|
</style>
|
|
1806
1542
|
</head>
|
|
1807
1543
|
<body>
|
|
1808
|
-
<
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1544
|
+
<h1>stx Documentation</h1>
|
|
1545
|
+
`;if(p)c+=`<div>${p}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
|
|
1546
|
+
<thead>
|
|
1547
|
+
<tr>
|
|
1548
|
+
<th>Name</th>
|
|
1549
|
+
<th>Type</th>
|
|
1550
|
+
<th>Required</th>
|
|
1551
|
+
<th>Default</th>
|
|
1552
|
+
<th>Description</th>
|
|
1553
|
+
</tr>
|
|
1554
|
+
</thead>
|
|
1555
|
+
<tbody>`;for(let m of l.props)c+=`<tr>
|
|
1556
|
+
<td>${m.name}</td>
|
|
1557
|
+
<td>${m.type||"any"}</td>
|
|
1558
|
+
<td>${m.required?"Yes":"No"}</td>
|
|
1559
|
+
<td>${m.default||"-"}</td>
|
|
1560
|
+
<td>${m.description||"-"}</td>
|
|
1561
|
+
</tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(i.length>0){c+="<h2>Directives</h2>",c+=`<table>
|
|
1562
|
+
<thead>
|
|
1563
|
+
<tr>
|
|
1564
|
+
<th>Directive</th>
|
|
1565
|
+
<th>Description</th>
|
|
1566
|
+
<th>Has End Tag</th>
|
|
1567
|
+
</tr>
|
|
1568
|
+
</thead>
|
|
1569
|
+
<tbody>`;for(let l of i)c+=`<tr>
|
|
1570
|
+
<td>@${l.name}</td>
|
|
1571
|
+
<td>${l.description||"-"}</td>
|
|
1572
|
+
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1573
|
+
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function co(t=[],s=[],i=[],p){return JSON.stringify({components:t,templates:s,directives:i,extraContent:p||""},null,2)}async function lo(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Vt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await ro(s,p),console.log(`Found ${u.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await oo(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await so(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",C="";switch(y){case"markdown":S=io(u,h,g,w),C="md";break;case"html":S=ao(u,h,g,w),C="html";break;case"json":S=co(u,h,g,w),C="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Qs(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||A.componentsDir,p=t.templatesDir||".";return lo({componentsDir:i,templatesDir:p,webComponentsConfig:A.webComponents,customDirectives:A.customDirectives,config:s})}var yn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function vr(t,s={}){let i={...yn,...s};if(t.trim()==="")return`
|
|
1574
|
+
`;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=ho(p,i),p=vo(p,i),p=yo(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
|
|
1575
|
+
`).replace(/\r/g,`
|
|
1576
|
+
`),!p.endsWith(`
|
|
1577
|
+
`))p+=`
|
|
1578
|
+
`;return p}function eo(t,s={}){let i={...yn,...s};if(t.trim()==="")return`
|
|
1579
|
+
`;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,h)=>{let g=u.split(`
|
|
1580
|
+
`),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
|
|
1581
|
+
`),v=vr(S,i).trimEnd().split(`
|
|
1582
|
+
`).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
|
|
1583
|
+
`);return`${l}\`\`\`${m}
|
|
1584
|
+
${v}
|
|
1585
|
+
${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
|
|
1586
|
+
`).replace(/\r/g,`
|
|
1587
|
+
`),!p.endsWith(`
|
|
1588
|
+
`))p+=`
|
|
1589
|
+
`;return p}function go(t){let s=t,i=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1590
|
+
$1
|
|
1591
|
+
`),s=s.replace(/(@end\w+)/g,`
|
|
1592
|
+
$1
|
|
1593
|
+
`),s=s.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1594
|
+
$1
|
|
1595
|
+
`),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
|
|
1596
|
+
$1
|
|
1597
|
+
`),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let h=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
|
|
1598
|
+
${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,h)=>{let g=h.substring(Math.max(0,u-50),u),w=h.substring(u+c.length,Math.min(h.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
|
|
1599
|
+
${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let h=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
|
|
1600
|
+
`}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
|
|
1601
|
+
`),s=s.split(`
|
|
1602
|
+
`).map((c)=>c.trim()).join(`
|
|
1603
|
+
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function ho(t,s){let p=go(t).split(`
|
|
1604
|
+
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let C=y===">";if(hn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),T=y.startsWith("@")&&xo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),M=y.startsWith("</"),I=y.startsWith("<")&&!M&&!H&&!k,R=y.includes("/>")||bo(y),L=hn(y);if(M||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(C)c.push(g);else c.push(u.repeat(B)+y);if(I&&!R&&!L&&!C||T)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
1605
|
+
`)}function yo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function bo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function hn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function xo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function vo(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
|
|
1606
|
+
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import bn from"fs";import qt from"path";async function to(t="index.stx",s={}){try{let i=s.force||!1,p=qt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(p);if(!bn.existsSync(c))bn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=qt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=xn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=xn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function xn(t){switch(t){case"basic":return wn();case"component":return wo();case"layout":return So();case"blog":return ko();case"api":return To();case"app":return $o();default:return wn()}}function wn(){return`<script>
|
|
1607
|
+
const title = "My stx Page"
|
|
1608
|
+
const description = "A page built with stx"
|
|
1609
|
+
const features = [
|
|
1610
|
+
{ name: "Single File Components", desc: "Script, style, and template in one .stx file" },
|
|
1611
|
+
{ name: "Component System", desc: "Import components with @component('name', {})" },
|
|
1612
|
+
{ name: "Blade Directives", desc: "@if, @foreach, @switch, @layout and more" }
|
|
1613
|
+
]
|
|
1614
|
+
</script>
|
|
1812
1615
|
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
${w?`<p><strong>Context:</strong> ${b(String(w))}</p>`:""}
|
|
1819
|
-
</div>
|
|
1616
|
+
@section('content')
|
|
1617
|
+
<header>
|
|
1618
|
+
<h1>{{ title }}</h1>
|
|
1619
|
+
<p>{{ description }}</p>
|
|
1620
|
+
</header>
|
|
1820
1621
|
|
|
1821
|
-
|
|
1822
|
-
<
|
|
1823
|
-
|
|
1824
|
-
<
|
|
1825
|
-
|
|
1622
|
+
<main>
|
|
1623
|
+
<h2>Features</h2>
|
|
1624
|
+
@foreach(features as feature)
|
|
1625
|
+
<div class="card">
|
|
1626
|
+
<h3>{{ feature.name }}</h3>
|
|
1627
|
+
<p>{{ feature.desc }}</p>
|
|
1628
|
+
</div>
|
|
1629
|
+
@endforeach
|
|
1630
|
+
</main>
|
|
1631
|
+
@endsection`}function wo(){return`{{-- Component: Card --}}
|
|
1632
|
+
{{-- Props: title, variant, collapsible --}}
|
|
1633
|
+
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1634
|
+
<script>
|
|
1635
|
+
// Props with defaults
|
|
1636
|
+
const title = props.title || 'Card Title'
|
|
1637
|
+
const variant = props.variant || 'default'
|
|
1638
|
+
const collapsible = props.collapsible || false
|
|
1639
|
+
</script>
|
|
1826
1640
|
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
<
|
|
1830
|
-
|
|
1831
|
-
<
|
|
1832
|
-
|
|
1833
|
-
<li>Run <code>stx debug ${b(Mt.basename(m))}</code> for detailed analysis</li>
|
|
1834
|
-
<li>Enable debug mode in your stx config for more detailed error messages</li>
|
|
1835
|
-
</ul>
|
|
1641
|
+
<div class="card card--{{ variant }}">
|
|
1642
|
+
<div class="card__header" onclick="this.parentElement.classList.toggle('collapsed')">
|
|
1643
|
+
<h3 class="card__title">{{ title }}</h3>
|
|
1644
|
+
@if(collapsible)
|
|
1645
|
+
<span class="card__toggle">\u25BC</span>
|
|
1646
|
+
@endif
|
|
1836
1647
|
</div>
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1648
|
+
<div class="card__body">
|
|
1649
|
+
{{ slot }}
|
|
1650
|
+
</div>
|
|
1651
|
+
</div>
|
|
1652
|
+
|
|
1653
|
+
<style scoped>
|
|
1654
|
+
.card {
|
|
1655
|
+
border-radius: 8px;
|
|
1656
|
+
background: #fff;
|
|
1657
|
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
1658
|
+
overflow: hidden;
|
|
1659
|
+
}
|
|
1660
|
+
.card--primary { border-top: 3px solid #3498db; }
|
|
1661
|
+
.card--success { border-top: 3px solid #2ecc71; }
|
|
1662
|
+
.card--warning { border-top: 3px solid #f39c12; }
|
|
1663
|
+
.card--danger { border-top: 3px solid #e74c3c; }
|
|
1664
|
+
.card__header {
|
|
1665
|
+
padding: 1rem;
|
|
1666
|
+
background: #f8f9fa;
|
|
1667
|
+
display: flex;
|
|
1668
|
+
justify-content: space-between;
|
|
1669
|
+
align-items: center;
|
|
1670
|
+
}
|
|
1671
|
+
.card__title { margin: 0; font-size: 1.1rem; }
|
|
1672
|
+
.card__toggle { transition: transform 0.2s; }
|
|
1673
|
+
.card.collapsed .card__toggle { transform: rotate(-90deg); }
|
|
1674
|
+
.card__body { padding: 1rem; }
|
|
1675
|
+
.card.collapsed .card__body { display: none; }
|
|
1676
|
+
</style>`}function So(){return`<!DOCTYPE html>
|
|
1860
1677
|
<html lang="en">
|
|
1861
1678
|
<head>
|
|
1862
1679
|
<meta charset="UTF-8">
|
|
1863
1680
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1864
|
-
<title
|
|
1865
|
-
|
|
1866
|
-
<style id="syntax-theme">
|
|
1867
|
-
:root {
|
|
1868
|
-
--shiki-color-text: #24292e;
|
|
1869
|
-
--shiki-color-background: #ffffff;
|
|
1870
|
-
--shiki-token-constant: #005cc5;
|
|
1871
|
-
--shiki-token-string: #032f62;
|
|
1872
|
-
--shiki-token-comment: #6a737d;
|
|
1873
|
-
--shiki-token-keyword: #d73a49;
|
|
1874
|
-
--shiki-token-parameter: #24292e;
|
|
1875
|
-
--shiki-token-function: #6f42c1;
|
|
1876
|
-
--shiki-token-string-expression: #032f62;
|
|
1877
|
-
--shiki-token-punctuation: #24292e;
|
|
1878
|
-
--shiki-token-link: #032f62;
|
|
1879
|
-
}
|
|
1880
|
-
pre {
|
|
1881
|
-
background-color: var(--shiki-color-background);
|
|
1882
|
-
padding: 1rem;
|
|
1883
|
-
border-radius: 4px;
|
|
1884
|
-
}
|
|
1885
|
-
code {
|
|
1886
|
-
color: var(--shiki-color-text);
|
|
1887
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1888
|
-
}
|
|
1889
|
-
.dark-mode {
|
|
1890
|
-
--shiki-color-text: #e1e4e8;
|
|
1891
|
-
--shiki-color-background: #24292e;
|
|
1892
|
-
--shiki-token-constant: #79b8ff;
|
|
1893
|
-
--shiki-token-string: #9ecbff;
|
|
1894
|
-
--shiki-token-comment: #6a737d;
|
|
1895
|
-
--shiki-token-keyword: #f97583;
|
|
1896
|
-
--shiki-token-parameter: #e1e4e8;
|
|
1897
|
-
--shiki-token-function: #b392f0;
|
|
1898
|
-
--shiki-token-string-expression: #9ecbff;
|
|
1899
|
-
--shiki-token-punctuation: #e1e4e8;
|
|
1900
|
-
--shiki-token-link: #9ecbff;
|
|
1901
|
-
}
|
|
1902
|
-
</style>
|
|
1681
|
+
<title>@yield('title', 'My App')</title>
|
|
1682
|
+
@yield('head')
|
|
1903
1683
|
<style>
|
|
1684
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1904
1685
|
body {
|
|
1905
|
-
font-family: system-ui,
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
margin: 0 auto;
|
|
1910
|
-
padding: 2rem;
|
|
1911
|
-
}
|
|
1912
|
-
pre, code {
|
|
1913
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1914
|
-
}
|
|
1915
|
-
pre {
|
|
1916
|
-
border-radius: 4px;
|
|
1917
|
-
padding: 0;
|
|
1918
|
-
margin: 1.5rem 0;
|
|
1919
|
-
overflow-x: auto;
|
|
1920
|
-
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
1921
|
-
}
|
|
1922
|
-
pre code {
|
|
1923
|
-
display: block;
|
|
1924
|
-
padding: 1rem;
|
|
1925
|
-
overflow-x: auto;
|
|
1926
|
-
}
|
|
1927
|
-
/* Apply background color to code blocks based on theme */
|
|
1928
|
-
pre.syntax-highlighter {
|
|
1929
|
-
background-color: var(--shiki-color-background) !important;
|
|
1930
|
-
}
|
|
1931
|
-
.dark-mode pre.syntax-highlighter {
|
|
1932
|
-
background-color: var(--shiki-color-background) !important;
|
|
1933
|
-
}
|
|
1934
|
-
code {
|
|
1935
|
-
padding: 0.2rem 0.4rem;
|
|
1936
|
-
border-radius: 3px;
|
|
1937
|
-
}
|
|
1938
|
-
h1, h2, h3, h4 {
|
|
1939
|
-
margin-top: 2rem;
|
|
1940
|
-
margin-bottom: 1rem;
|
|
1941
|
-
}
|
|
1942
|
-
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
1943
|
-
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
1944
|
-
h3 { color: #444; }
|
|
1945
|
-
img {
|
|
1946
|
-
max-width: 100%;
|
|
1947
|
-
border-radius: 4px;
|
|
1948
|
-
margin: 1rem 0;
|
|
1949
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
1686
|
+
font-family: system-ui, sans-serif;
|
|
1687
|
+
min-height: 100vh;
|
|
1688
|
+
display: flex;
|
|
1689
|
+
flex-direction: column;
|
|
1950
1690
|
}
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
color: #555;
|
|
1956
|
-
background: #f9f9f9;
|
|
1957
|
-
padding: 0.5rem 1rem;
|
|
1958
|
-
margin: 1.5rem 0;
|
|
1691
|
+
header, footer {
|
|
1692
|
+
background: #2c3e50;
|
|
1693
|
+
color: white;
|
|
1694
|
+
padding: 1rem 2rem;
|
|
1959
1695
|
}
|
|
1960
|
-
|
|
1961
|
-
|
|
1696
|
+
main {
|
|
1697
|
+
flex: 1;
|
|
1698
|
+
padding: 2rem;
|
|
1699
|
+
max-width: 1200px;
|
|
1700
|
+
margin: 0 auto;
|
|
1962
1701
|
width: 100%;
|
|
1963
|
-
margin: 1.5rem 0;
|
|
1964
|
-
}
|
|
1965
|
-
th, td {
|
|
1966
|
-
border: 1px solid #ddd;
|
|
1967
|
-
padding: 0.5rem;
|
|
1968
|
-
}
|
|
1969
|
-
th {
|
|
1970
|
-
background: #f0f0f0;
|
|
1971
|
-
text-align: left;
|
|
1972
|
-
}
|
|
1973
|
-
tr:nth-child(even) {
|
|
1974
|
-
background-color: #f8f8f8;
|
|
1975
1702
|
}
|
|
1976
|
-
a {
|
|
1977
|
-
|
|
1978
|
-
|
|
1703
|
+
nav a { color: white; margin-right: 1rem; text-decoration: none; }
|
|
1704
|
+
nav a:hover { text-decoration: underline; }
|
|
1705
|
+
</style>
|
|
1706
|
+
@yield('styles')
|
|
1707
|
+
</head>
|
|
1708
|
+
<body>
|
|
1709
|
+
<header>
|
|
1710
|
+
<nav>
|
|
1711
|
+
<a href="/">Home</a>
|
|
1712
|
+
<a href="/about">About</a>
|
|
1713
|
+
<a href="/contact">Contact</a>
|
|
1714
|
+
</nav>
|
|
1715
|
+
</header>
|
|
1716
|
+
|
|
1717
|
+
<main>
|
|
1718
|
+
{{ slot }}
|
|
1719
|
+
</main>
|
|
1720
|
+
|
|
1721
|
+
<footer>
|
|
1722
|
+
<p>© {{ new Date().getFullYear() }} My App</p>
|
|
1723
|
+
</footer>
|
|
1724
|
+
|
|
1725
|
+
@yield('scripts')
|
|
1726
|
+
</body>
|
|
1727
|
+
</html>`}function ko(){return`<script>
|
|
1728
|
+
// Article metadata
|
|
1729
|
+
const title = "My Blog Post"
|
|
1730
|
+
const author = "Your Name"
|
|
1731
|
+
const date = new Date().toLocaleDateString('en-US', {
|
|
1732
|
+
year: 'numeric',
|
|
1733
|
+
month: 'long',
|
|
1734
|
+
day: 'numeric'
|
|
1735
|
+
})
|
|
1736
|
+
const tags = ["stx", "tutorial", "web development"]
|
|
1737
|
+
const readingTime = "5 min read"
|
|
1738
|
+
</script>
|
|
1739
|
+
|
|
1740
|
+
@layout('layouts/blog')
|
|
1741
|
+
|
|
1742
|
+
@section('title')
|
|
1743
|
+
{{ title }}
|
|
1744
|
+
@endsection
|
|
1745
|
+
|
|
1746
|
+
@section('content')
|
|
1747
|
+
<article class="blog-post">
|
|
1748
|
+
<header class="blog-post__header">
|
|
1749
|
+
<h1>{{ title }}</h1>
|
|
1750
|
+
<div class="blog-post__meta">
|
|
1751
|
+
<span class="author">By {{ author }}</span>
|
|
1752
|
+
<span class="date">{{ date }}</span>
|
|
1753
|
+
<span class="reading-time">{{ readingTime }}</span>
|
|
1754
|
+
</div>
|
|
1755
|
+
<div class="blog-post__tags">
|
|
1756
|
+
@foreach(tags as tag)
|
|
1757
|
+
<span class="tag">#{{ tag }}</span>
|
|
1758
|
+
@endforeach
|
|
1759
|
+
</div>
|
|
1760
|
+
</header>
|
|
1761
|
+
|
|
1762
|
+
<div class="blog-post__content">
|
|
1763
|
+
<p>Your content goes here...</p>
|
|
1764
|
+
|
|
1765
|
+
<h2>Introduction</h2>
|
|
1766
|
+
<p>Start writing your blog post content.</p>
|
|
1767
|
+
|
|
1768
|
+
<h2>Conclusion</h2>
|
|
1769
|
+
<p>Wrap up your thoughts here.</p>
|
|
1770
|
+
</div>
|
|
1771
|
+
</article>
|
|
1772
|
+
@endsection`}function To(){return`<script>
|
|
1773
|
+
// API endpoint configuration
|
|
1774
|
+
const endpoint = "/api/data"
|
|
1775
|
+
const method = "GET"
|
|
1776
|
+
|
|
1777
|
+
// Mock data - replace with actual data fetching
|
|
1778
|
+
const data = {
|
|
1779
|
+
success: true,
|
|
1780
|
+
message: "Data retrieved successfully",
|
|
1781
|
+
items: [
|
|
1782
|
+
{ id: 1, name: "Item 1" },
|
|
1783
|
+
{ id: 2, name: "Item 2" },
|
|
1784
|
+
{ id: 3, name: "Item 3" }
|
|
1785
|
+
],
|
|
1786
|
+
meta: {
|
|
1787
|
+
total: 3,
|
|
1788
|
+
page: 1,
|
|
1789
|
+
perPage: 10
|
|
1979
1790
|
}
|
|
1980
|
-
|
|
1981
|
-
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// For error responses
|
|
1794
|
+
const error = null
|
|
1795
|
+
</script>
|
|
1796
|
+
|
|
1797
|
+
@if(error)
|
|
1798
|
+
{
|
|
1799
|
+
"success": false,
|
|
1800
|
+
"error": {
|
|
1801
|
+
"code": "{{ error.code || 'UNKNOWN_ERROR' }}",
|
|
1802
|
+
"message": "{{ error.message || 'An error occurred' }}"
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
@else
|
|
1806
|
+
{{ JSON.stringify(data, null, 2) }}
|
|
1807
|
+
@endif`}function $o(){return`<!DOCTYPE html>
|
|
1808
|
+
<html lang="en">
|
|
1809
|
+
<head>
|
|
1810
|
+
<meta charset="UTF-8">
|
|
1811
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1812
|
+
<title>{{ title }} - stx App</title>
|
|
1813
|
+
<script>
|
|
1814
|
+
const title = "My App"
|
|
1815
|
+
</script>
|
|
1816
|
+
<style>
|
|
1817
|
+
:root {
|
|
1818
|
+
--bg: #1a1a2e;
|
|
1819
|
+
--bg-dark: #16213e;
|
|
1820
|
+
--fg: #eaeaea;
|
|
1821
|
+
--primary: #e94560;
|
|
1822
|
+
--secondary: #0f3460;
|
|
1823
|
+
--success: #00d9ff;
|
|
1824
|
+
--border: #2a2a4a;
|
|
1982
1825
|
}
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1826
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1827
|
+
body {
|
|
1828
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
1829
|
+
background: var(--bg);
|
|
1830
|
+
color: var(--fg);
|
|
1831
|
+
min-height: 100vh;
|
|
1987
1832
|
}
|
|
1988
|
-
.
|
|
1989
|
-
|
|
1990
|
-
|
|
1833
|
+
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
|
|
1834
|
+
.header { text-align: center; margin-bottom: 2rem; }
|
|
1835
|
+
.header h1 { color: var(--primary); margin-bottom: 0.5rem; }
|
|
1836
|
+
.card {
|
|
1837
|
+
background: var(--bg-dark);
|
|
1838
|
+
border: 1px solid var(--border);
|
|
1839
|
+
border-radius: 12px;
|
|
1991
1840
|
padding: 1.5rem;
|
|
1992
|
-
margin-bottom:
|
|
1993
|
-
font-size: 0.9rem;
|
|
1994
|
-
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
1995
|
-
border-left: 4px solid #ddd;
|
|
1841
|
+
margin-bottom: 1rem;
|
|
1996
1842
|
}
|
|
1997
|
-
.
|
|
1998
|
-
|
|
1999
|
-
|
|
1843
|
+
.btn {
|
|
1844
|
+
background: var(--primary);
|
|
1845
|
+
color: white;
|
|
1846
|
+
border: none;
|
|
1847
|
+
padding: 0.75rem 1.5rem;
|
|
1848
|
+
border-radius: 8px;
|
|
1849
|
+
cursor: pointer;
|
|
1850
|
+
font-size: 1rem;
|
|
1851
|
+
transition: opacity 0.2s;
|
|
2000
1852
|
}
|
|
2001
|
-
.
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
1853
|
+
.btn:hover { opacity: 0.9; }
|
|
1854
|
+
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
1855
|
+
.btn--secondary { background: var(--secondary); }
|
|
1856
|
+
.btn--success { background: var(--success); color: var(--bg); }
|
|
1857
|
+
.input {
|
|
1858
|
+
width: 100%;
|
|
1859
|
+
background: var(--bg);
|
|
1860
|
+
border: 1px solid var(--border);
|
|
1861
|
+
color: var(--fg);
|
|
1862
|
+
padding: 0.75rem 1rem;
|
|
1863
|
+
border-radius: 8px;
|
|
1864
|
+
font-size: 1rem;
|
|
1865
|
+
margin-bottom: 1rem;
|
|
2005
1866
|
}
|
|
2006
|
-
|
|
1867
|
+
.input:focus { outline: none; border-color: var(--primary); }
|
|
1868
|
+
.flex { display: flex; gap: 1rem; align-items: center; }
|
|
1869
|
+
.flex-between { justify-content: space-between; }
|
|
1870
|
+
.text-muted { color: #888; }
|
|
1871
|
+
.text-success { color: var(--success); }
|
|
1872
|
+
.mb-1 { margin-bottom: 1rem; }
|
|
1873
|
+
.hidden { display: none; }
|
|
2007
1874
|
</style>
|
|
2008
1875
|
</head>
|
|
2009
1876
|
<body>
|
|
2010
|
-
|
|
2011
|
-
|
|
1877
|
+
<div class="container">
|
|
1878
|
+
<header class="header">
|
|
1879
|
+
<h1>{{ title }}</h1>
|
|
1880
|
+
<p class="text-muted">Built with stx</p>
|
|
1881
|
+
</header>
|
|
2012
1882
|
|
|
2013
|
-
|
|
1883
|
+
<!-- Counter Example -->
|
|
1884
|
+
<div class="card">
|
|
1885
|
+
<h2 class="mb-1">Counter Example</h2>
|
|
1886
|
+
<div class="flex flex-between">
|
|
1887
|
+
<span id="counterDisplay">Count: 0</span>
|
|
1888
|
+
<div class="flex">
|
|
1889
|
+
<button class="btn btn--secondary" onclick="window.app?.decrement()">-</button>
|
|
1890
|
+
<button class="btn" onclick="window.app?.increment()">+</button>
|
|
1891
|
+
<button class="btn btn--success" onclick="window.app?.reset()">Reset</button>
|
|
1892
|
+
</div>
|
|
1893
|
+
</div>
|
|
1894
|
+
</div>
|
|
1895
|
+
|
|
1896
|
+
<!-- Todo List Example -->
|
|
1897
|
+
<div class="card">
|
|
1898
|
+
<h2 class="mb-1">Todo List</h2>
|
|
1899
|
+
<div class="flex mb-1">
|
|
1900
|
+
<input
|
|
1901
|
+
type="text"
|
|
1902
|
+
id="todoInput"
|
|
1903
|
+
class="input"
|
|
1904
|
+
placeholder="Add a new todo..."
|
|
1905
|
+
onkeypress="if(event.key==='Enter') window.app?.addTodo()"
|
|
1906
|
+
style="margin-bottom:0"
|
|
1907
|
+
/>
|
|
1908
|
+
<button class="btn" onclick="window.app?.addTodo()">Add</button>
|
|
1909
|
+
</div>
|
|
1910
|
+
<div id="todoList"></div>
|
|
1911
|
+
<p id="todoCount" class="text-muted">0 items</p>
|
|
1912
|
+
</div>
|
|
1913
|
+
|
|
1914
|
+
<!-- Toggle Example -->
|
|
1915
|
+
<div class="card">
|
|
1916
|
+
<h2 class="mb-1">Toggle Example</h2>
|
|
1917
|
+
<button
|
|
1918
|
+
id="toggleBtn"
|
|
1919
|
+
class="btn btn--secondary"
|
|
1920
|
+
onclick="window.app?.toggle()"
|
|
1921
|
+
>Inactive</button>
|
|
1922
|
+
<div id="toggleContent" class="mt-1" style="margin-top:1rem;display:none">
|
|
1923
|
+
<p class="text-success">This content is visible when active!</p>
|
|
1924
|
+
</div>
|
|
1925
|
+
</div>
|
|
1926
|
+
</div>
|
|
2014
1927
|
|
|
1928
|
+
<!-- Simple Store Implementation -->
|
|
2015
1929
|
<script>
|
|
2016
|
-
|
|
1930
|
+
(function() {
|
|
1931
|
+
// Create a simple reactive store
|
|
1932
|
+
function createStore(initialState) {
|
|
1933
|
+
let state = { ...initialState };
|
|
1934
|
+
const listeners = [];
|
|
1935
|
+
return {
|
|
1936
|
+
get() { return state; },
|
|
1937
|
+
set(newState) {
|
|
1938
|
+
state = { ...state, ...newState };
|
|
1939
|
+
listeners.forEach(fn => fn(state));
|
|
1940
|
+
},
|
|
1941
|
+
subscribe(fn) {
|
|
1942
|
+
listeners.push(fn);
|
|
1943
|
+
fn(state); // Call immediately
|
|
1944
|
+
return () => listeners.splice(listeners.indexOf(fn), 1);
|
|
1945
|
+
}
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
// Initialize app store
|
|
1950
|
+
const appStore = createStore({
|
|
1951
|
+
count: 0,
|
|
1952
|
+
todos: [],
|
|
1953
|
+
isActive: false
|
|
1954
|
+
});
|
|
1955
|
+
|
|
1956
|
+
// App methods
|
|
1957
|
+
window.app = {
|
|
1958
|
+
increment() {
|
|
1959
|
+
const { count } = appStore.get();
|
|
1960
|
+
appStore.set({ count: count + 1 });
|
|
1961
|
+
},
|
|
1962
|
+
decrement() {
|
|
1963
|
+
const { count } = appStore.get();
|
|
1964
|
+
appStore.set({ count: Math.max(0, count - 1) });
|
|
1965
|
+
},
|
|
1966
|
+
reset() {
|
|
1967
|
+
appStore.set({ count: 0 });
|
|
1968
|
+
},
|
|
1969
|
+
toggle() {
|
|
1970
|
+
const { isActive } = appStore.get();
|
|
1971
|
+
appStore.set({ isActive: !isActive });
|
|
1972
|
+
},
|
|
1973
|
+
addTodo() {
|
|
1974
|
+
const input = document.getElementById('todoInput');
|
|
1975
|
+
const text = input.value.trim();
|
|
1976
|
+
if (!text) return;
|
|
1977
|
+
const { todos } = appStore.get();
|
|
1978
|
+
appStore.set({ todos: [...todos, { id: Date.now(), text, done: false }] });
|
|
1979
|
+
input.value = '';
|
|
1980
|
+
},
|
|
1981
|
+
toggleTodo(id) {
|
|
1982
|
+
const { todos } = appStore.get();
|
|
1983
|
+
appStore.set({
|
|
1984
|
+
todos: todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
|
|
1985
|
+
});
|
|
1986
|
+
},
|
|
1987
|
+
deleteTodo(id) {
|
|
1988
|
+
const { todos } = appStore.get();
|
|
1989
|
+
appStore.set({ todos: todos.filter(t => t.id !== id) });
|
|
1990
|
+
}
|
|
1991
|
+
};
|
|
1992
|
+
|
|
1993
|
+
// Update UI based on state
|
|
1994
|
+
function updateUI(state) {
|
|
1995
|
+
// Update counter
|
|
1996
|
+
const counterDisplay = document.getElementById('counterDisplay');
|
|
1997
|
+
if (counterDisplay) counterDisplay.textContent = 'Count: ' + state.count;
|
|
1998
|
+
|
|
1999
|
+
// Update todo count
|
|
2000
|
+
const todoCount = document.getElementById('todoCount');
|
|
2001
|
+
if (todoCount) todoCount.textContent = state.todos.length + ' items';
|
|
2002
|
+
|
|
2003
|
+
// Update toggle button
|
|
2004
|
+
const toggleBtn = document.getElementById('toggleBtn');
|
|
2005
|
+
if (toggleBtn) {
|
|
2006
|
+
toggleBtn.textContent = state.isActive ? 'Active' : 'Inactive';
|
|
2007
|
+
toggleBtn.className = 'btn ' + (state.isActive ? 'btn--success' : 'btn--secondary');
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
// Show/hide toggle content
|
|
2011
|
+
const toggleContent = document.getElementById('toggleContent');
|
|
2012
|
+
if (toggleContent) toggleContent.style.display = state.isActive ? 'block' : 'none';
|
|
2013
|
+
|
|
2014
|
+
// Render todo list
|
|
2015
|
+
const list = document.getElementById('todoList');
|
|
2016
|
+
if (list) {
|
|
2017
|
+
list.innerHTML = state.todos.map(todo => \`
|
|
2018
|
+
<div style="display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0;border-bottom:1px solid var(--border)">
|
|
2019
|
+
<input type="checkbox" \${todo.done ? 'checked' : ''} onchange="window.app?.toggleTodo(\${todo.id})" />
|
|
2020
|
+
<span style="\${todo.done ? 'text-decoration:line-through;opacity:0.5' : ''}">\${todo.text}</span>
|
|
2021
|
+
<button onclick="window.app?.deleteTodo(\${todo.id})" style="margin-left:auto;background:none;border:none;color:var(--primary);cursor:pointer">\xD7</button>
|
|
2022
|
+
</div>
|
|
2023
|
+
\`).join('');
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
// Subscribe to store changes
|
|
2028
|
+
appStore.subscribe(updateUI);
|
|
2029
|
+
})();
|
|
2017
2030
|
</script>
|
|
2018
2031
|
</body>
|
|
2019
|
-
</html>
|
|
2020
|
-
|
|
2021
|
-
${ce(R,x)}`);continue}let I=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:R,params:L}=pr(I,{page:!0});u.push({pattern:R,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ce(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=zi({port:y,async fetch(v){let x=new URL(v.url),T=Ae.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(T)&&Ze.statSync(T).isFile()){let _=Bun.file(T),I=Ae.extname(T).toLowerCase(),R="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":R}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let _ of u){let I=x.pathname.match(_.pattern);if(I){let R=m[_.routeTemplate];if(R){let L={};for(let ee=0;ee<_.paramNames.length;ee++)L[_.paramNames[ee]]=decodeURIComponent(I[ee+1]);let B=R.content,G=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${G}
|
|
2022
|
-
</head>`);else B=G+B;k={...R,content:B}}break}}if(k)return f(k.content).then((_)=>{if(_.includes("</head>"))_=_.replace("</head>",`${yn}
|
|
2023
|
-
</head>`);return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Ae.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let _=Bun.file(H),I=Ae.extname(H).toLowerCase(),R="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":R}})}if(x.pathname!=="/"&&m["/"]){let _=re(v);return f(m["/"].content).then((I)=>{if(_){let R=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(R){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=L?L[1]:"",G=`<!DOCTYPE html><html><head><title>${Wn(B)}</title></head><body><main>${R[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...E(),"Cache-Control":Pe,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{headers:{"Content-Type":"text/html",...E(),"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}
|
|
2024
|
-
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
2025
|
-
${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(`
|
|
2026
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
2027
|
-
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
|
|
2028
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Ni}=globalThis.Bun;import xe from"fs";import ie from"path";async function qn(t){try{return Et(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function $n(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-fqge0zn8.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-10jwyvm0.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!xe.existsSync(T)&&!g._layerPageDirs?.some((O)=>xe.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],_=[];for(let{dir:O,prefix:F}of H)if(xe.existsSync(O)){let z=N(ie.dirname(O),{pagesDir:ie.basename(O)});for(let V of z){let ve=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:ve},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await uo(u,s.stxOptions?.shell),L){if(R=await Tr(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}nt(),await st(u);let B=rt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},ee=null;try{let{loadStxConfig:O}=await import("./chunk-fqge0zn8.js"),F=await O(u);if(F?.apiRouter)ee=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-56mkcxvb.js"),ve=F.broadcasting;await z(ve);let We=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let ye=new Map,De=new Set,ae=async(O)=>{let F=fr(T,O);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},U=new Map,j=async(O,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-fqge0zn8.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-c3v5zmnq.js"),ke=await We(u),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(u,pe)},M={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,ue=M.cache!==!1;if(ue&&be){let pe=J.get(O.filePath);if(pe)try{if((await xe.promises.stat(O.filePath)).mtime.getTime()<=pe.mtime){let Be=!0;for(let Ee of pe.dependencies){if(!xe.existsSync(Ee)){Be=!1;break}if((await xe.promises.stat(Ee)).mtime.getTime()>pe.mtime){Be=!1;break}}if(Be){let Ee=pe.output;if(R)Ee=he(Ee,{preserveHead:!0});let gt=U.get(O.filePath);return{route:O,content:Ee,status:gt?.status??await qn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(O.filePath,M);if(Ie){let je=Ie;if(R)je=he(je,{preserveHead:!0});let Be=U.get(O.filePath);return{route:O,content:je,status:Be?.status??await qn(O.filePath),headers:Be?.headers}}}let ge=ue?await q(O.filePath):await Bun.file(O.filePath).text(),Re=Et(ge),{classifyAllScripts:Y}=await import("./chunk-fqge0zn8.js"),Le=Y(ge),Ve=Le.server.map((pe)=>pe.content),fe=ge;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let me={__filename:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,me,O.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,me,O.filePath,M,Ke);let Ie=performance.now()-pe,je=ie.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,O.filePath,M,Ke);if(!R)Me=await Ge(Me,{router:M.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-sn5c0x7q.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Ie;return`<script${je}>${pe(Be,me)}</script>`})}if(R)Me=he(Me,{preserveHead:!0});if(ue&&be)await Z(O.filePath,Me,Ke,M);let{extractStreamBoundaries:Kn}=await import("./chunk-00dp53cx.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=me.streamBoundaries||{},Ie={...M,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...me,$boundary:gt},O.filePath,Ie,new Set)}})),Be=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!Be.has(Ee.id)),...je]}if(lt&<.length>0)De.add(O.pattern);else lt=void 0;let Kt=He(me),Xt=Ue(me);if(be)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,z),null}},Ne=8,qe=async()=>{ye.clear(),I.clear();for(let O=0;O<k.length;O+=Ne){let F=k.slice(O,O+Ne),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let O=0;O<_.length;O+=Ne){let F=_.slice(O,O+Ne),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await _t(u);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let O=s.hmrPort||et+1;l=Ct({wsPort:O,verbose:!1}),m=l.start(O)}let Lt=(O,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${V}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+O};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ni({port:et,async fetch(O){let F=new URL(O.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),ve=ie.join(u,F.pathname),We=ie.join($e,F.pathname);if([V,ve,We].some((M)=>w(M,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Z]=await Promise.all([xe.promises.stat(V).catch(()=>null),xe.promises.stat(ve).catch(()=>null),xe.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(oe?.isFile()&&!w(ve,u,S))return qt(ve);if(Z?.isFile()&&!w(We,u,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${M}.stx`),ue,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-zfypzka2.js"),be=await M(O,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(ee)try{let M=await ee.handleRequest(O);if(M.status!==404)return M}catch{}if(G[F.pathname])try{return await G[F.pathname](O)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(O);if(q)return q;let J=kn(F.pathname,k);if(J){let M=ye.get(J.route.pattern),be=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let ue=await j(J.route,J.params);if(ue)M=ue}if(M){let ue=M.status??200,ge=M.headers??{},Re=(J.route.filePath?ze(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await ae(404);if(Ve){let fe=Ve;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=ot(F.pathname,J.params,Re,F.search),Ve=it(Le,null,O,{isServer:!0}),fe=await at(Re.middleware,Ve);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${me}</head>`)}}let Y=M.content;if(R&&po(O)){let Le=Ce(Y),Ve=le(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?lo(fe[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=se(Y,Ke),new Response(Y,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[hi]:xs(),...E(),"Cache-Control":Pe}})}if(R)Y=In(R,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-00dp53cx.js");return Ve(Le(Y,M.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",...E(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(_.length>0){let M=_.map((ue)=>ue.route),be=kn(F.pathname,M);if(be){let ue=I.get(be.route.pattern);if(ue){let ge=ue.content;if(R)ge=In(R,ge);if(Object.keys(be.params).length>0)ge=Lt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let ge=I.get(ue)||I.get(ue+"/");if(ge){let Re=ge.content;if(R)Re=In(R,Re);if(Re=await f(Re,u),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(tt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=ye.get("/");if(ke){let M=ke.content;if(M=await f(M,u),c)M=Xe(M,m);if(s.native)if(M.includes("<head>"))M=M.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
2029
|
-
${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
2030
|
-
${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(`
|
|
2031
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
2032
|
-
${e.yellow}Routes:${e.reset}`);let jt=[...gr(k,u)];for(let{route:O}of _)jt.push(`${O.pattern}`);if(jt.forEach((O,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${O}`)}),console.log(`
|
|
2033
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let O,F=ie.join(T,"index.stx");if(xe.existsSync(F)){let V=await Bun.file(F).text();O=St(V)}let z=g?.app?.window??{};await dt(et,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),F=(oe)=>{let Z=oe.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},z=new Map,V=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>ie.dirname(Z))??[]].filter((Z)=>xe.existsSync(Z)).map((Z)=>xe.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!xe.existsSync(q))continue;let J=xe.realpathSync(q);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Z,q]of z)if(!oe.has(Z))q.close(),z.delete(Z);for(let Z of oe)if(!z.has(Z)&&xe.existsSync(Z))z.set(Z,xe.watch(Z,{recursive:!0},(q,J)=>{We(Z,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},ve=Promise.resolve(),We=(oe,Z,q)=>(ve=ve.catch(()=>{}).then(()=>Ge(oe,Z,q)),ve),Ge=async(oe,Z,q)=>{if(!q||$t(q))return;if(Tt(q)){if(g._layerGraph){let J=await h(u);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(O(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-c3v5zmnq.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(L&&q){if(ie.resolve(oe,q)===L||ie.basename(L)===q){let ke=await Tr(L,s.stxOptions||{});if(ke)R=ke}}if(await qe(),await an(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-c3v5zmnq.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(kt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let oe of z.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Xs,Js,Ys,Zs,wr,Qs,eo,to,Xi,Ji,vr,xr,En,Tn,$n};
|
|
2032
|
+
</html>`}var no="f9c3713";function Ji(t){return t}function Yi(t){return t}function Js(t,s){let i=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}import Me from"fs";import Te from"path";function _n(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function At(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ai(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Ln(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var In=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Mi(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=Me.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of In){let S=Te.join(u,w),C=Di(S);if(C!==null)p.push({name:w,version:C,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=Te.join(S,x.name,"node_modules");if(Me.existsSync(T))l(T,h+1)}continue}let C=Te.join(S,"node_modules");if(Me.existsSync(C))l(C,h+1)}}let m=Te.join(i,"node_modules");if(Me.existsSync(m))l(m,0);return p}function _i(t){let s=[];for(let i of In){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function xr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ai,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of _i(Mi(s)))c.push(h);let u=Ln(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,y=_n(h),w=g?_n(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${At(w,p)}) is OLDER than src/signals.ts (${At(y,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${At(y,p)}, dist ${At(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),C=null;try{C=Me.lstatSync(S)}catch{C=null}if(!C)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function Sr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
|
|
2033
|
+
`)}export{Js,Ys,Zs,Qs,vr,eo,to,no,Ji,Yi,xr,Sr,Tn,$n,Rn};
|