@stacksjs/stx 0.2.870 → 0.2.872
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-6mjd3pqd.js → chunk-18a3vdnq.js} +3 -3
- package/dist/{chunk-cwmfxbhz.js → chunk-1c8j9zdp.js} +1 -1
- package/dist/{chunk-nkwj7eq3.js → chunk-1p9rb7rt.js} +1 -1
- package/dist/{chunk-9ffvh6cr.js → chunk-2jccw1km.js} +2 -2
- package/dist/chunk-2nd3h37q.js +2 -0
- package/dist/{chunk-81n2s24z.js → chunk-2yrd286h.js} +1 -1
- package/dist/chunk-3k5g4tbn.js +2 -0
- package/dist/chunk-3qewdhvh.js +2 -0
- package/dist/{chunk-tjwzy9xq.js → chunk-40h07m5w.js} +1 -1
- package/dist/{chunk-tv61s6fc.js → chunk-4ay62hs9.js} +1 -1
- package/dist/chunk-4es07dwb.js +2 -0
- package/dist/{chunk-zbvfjm4a.js → chunk-4nb7egk0.js} +2 -2
- package/dist/{chunk-q58f5wk2.js → chunk-4p51hk75.js} +5 -5
- package/dist/{chunk-m4k6ndf5.js → chunk-4v70bs2q.js} +1 -1
- package/dist/{chunk-6ggme8xx.js → chunk-5nj2k8zf.js} +1 -1
- package/dist/{chunk-sbvkk4cn.js → chunk-6mkn81pd.js} +2 -2
- package/dist/{chunk-sb3dx4dd.js → chunk-6s7q8kw3.js} +2 -2
- package/dist/chunk-71hjqg16.js +177 -0
- package/dist/{chunk-3ryp43f3.js → chunk-73k579v7.js} +1 -1
- package/dist/{chunk-3f51tn2b.js → chunk-7cvbz4eq.js} +2 -2
- package/dist/{chunk-4vtw6f0c.js → chunk-7j0qkye5.js} +2 -2
- package/dist/chunk-7mqnbn1x.js +2 -0
- package/dist/chunk-7q3ar8ay.js +2 -0
- package/dist/chunk-808fbm83.js +2 -0
- package/dist/chunk-832m6nwr.js +2051 -0
- package/dist/{chunk-1mqcttg3.js → chunk-8tk8yf91.js} +2 -2
- package/dist/{chunk-wb7s2cnb.js → chunk-9bnggqhj.js} +8 -8
- package/dist/{chunk-t5ekex4s.js → chunk-9c07p1vq.js} +4 -4
- package/dist/{chunk-rpep1ve3.js → chunk-9fyw1xkh.js} +2 -2
- package/dist/{chunk-311mrz2n.js → chunk-a8164hnf.js} +1 -1
- package/dist/chunk-asrzmw7w.js +2 -0
- package/dist/{chunk-pfr3cazq.js → chunk-av2vknrs.js} +2 -2
- package/dist/chunk-b2kkezey.js +2 -0
- package/dist/{chunk-dg4zxpbq.js → chunk-b8vs32dw.js} +3 -3
- package/dist/{chunk-y1cvab1b.js → chunk-ba86dkhs.js} +1 -1
- package/dist/{chunk-d9k8j44b.js → chunk-bbq79tap.js} +6 -6
- package/dist/chunk-bfvr4byj.js +21 -0
- package/dist/{chunk-gesktj4m.js → chunk-bmbqr2br.js} +1 -1
- package/dist/chunk-bqs9wyje.js +2 -0
- package/dist/chunk-c63027nw.js +2 -0
- package/dist/{chunk-0tyyad6q.js → chunk-csymxc5a.js} +8 -8
- package/dist/chunk-cv9vmz5x.js +2 -0
- package/dist/{chunk-6ksyrmpp.js → chunk-d0h18m2r.js} +1 -1
- package/dist/{chunk-sb8n32rn.js → chunk-dhbpbjt3.js} +1 -1
- package/dist/{chunk-3v7xht2q.js → chunk-dv1edvz8.js} +1 -1
- package/dist/{chunk-1dt8e7ew.js → chunk-e2t7mk29.js} +2 -2
- package/dist/{chunk-4t5t33yj.js → chunk-e549f7a9.js} +2 -2
- package/dist/{chunk-adqh1gp1.js → chunk-e7s109j6.js} +1 -1
- package/dist/chunk-eczy00w6.js +2 -0
- package/dist/{chunk-h0nxd9xg.js → chunk-f5gg0pxj.js} +1 -1
- package/dist/chunk-gc4bgven.js +2 -0
- package/dist/{chunk-7chzhef2.js → chunk-gvz0kqkz.js} +1 -1
- package/dist/{chunk-5d0csn7w.js → chunk-hcaedzck.js} +1 -1
- package/dist/{chunk-drdr0a53.js → chunk-hd4vn78w.js} +1 -1
- package/dist/{chunk-dy7vqv1x.js → chunk-hhbt8grm.js} +2 -2
- package/dist/{chunk-gcsy3z1e.js → chunk-j89p53vx.js} +3 -3
- package/dist/{chunk-y0msz738.js → chunk-jcr69v95.js} +4 -4
- package/dist/{chunk-rt55f47q.js → chunk-jf3n1f32.js} +3 -3
- package/dist/chunk-jkevn2jy.js +2 -0
- package/dist/{chunk-xr3x6wk6.js → chunk-jnj9s2yw.js} +1 -1
- package/dist/{chunk-dwqjrbse.js → chunk-jpgc0j8x.js} +2 -2
- package/dist/{chunk-mwxehpse.js → chunk-kkevjppm.js} +2 -2
- package/dist/{chunk-z8x86cr7.js → chunk-kx6y1cqw.js} +5 -5
- package/dist/{chunk-cbpxd3qa.js → chunk-kzhget9h.js} +1 -1
- package/dist/{chunk-mnx6njd4.js → chunk-m131znxe.js} +6 -6
- package/dist/chunk-me7cxs0e.js +2 -0
- package/dist/{chunk-w1rrfj39.js → chunk-mm00bb1p.js} +1 -1
- package/dist/{chunk-fcvgf88g.js → chunk-my6tp8rn.js} +1 -1
- package/dist/chunk-p2kqsb5k.js +2 -0
- package/dist/chunk-pc8jnkb3.js +2 -0
- package/dist/{chunk-zpgj4asv.js → chunk-pj1znb6y.js} +1 -1
- package/dist/{chunk-hze3158c.js → chunk-pnqdwqw9.js} +56 -56
- package/dist/{chunk-79y9amt1.js → chunk-pywz8q4k.js} +5 -5
- package/dist/{chunk-k7m8659h.js → chunk-q50x1gfd.js} +2 -2
- package/dist/{chunk-1637r8fg.js → chunk-q8d0wf0w.js} +1 -1
- package/dist/{chunk-qmr5xsjj.js → chunk-qk1fkfvj.js} +1 -1
- package/dist/{chunk-7wae4311.js → chunk-qt4dha3g.js} +4 -4
- package/dist/{chunk-n7w8n327.js → chunk-qvxtq5vb.js} +1 -1
- package/dist/{chunk-7d6jq5j8.js → chunk-rvbw12e1.js} +2 -2
- package/dist/{chunk-vrcr4b13.js → chunk-s584xnzx.js} +1 -1
- package/dist/{chunk-pdpmtmfj.js → chunk-s70e5jbq.js} +10 -10
- package/dist/chunk-tahw02kf.js +2 -0
- package/dist/{chunk-zfq2vvex.js → chunk-tc36b3r4.js} +24 -24
- package/dist/{chunk-d4zcwtna.js → chunk-teahvty8.js} +1 -1
- package/dist/chunk-tfsf9pes.js +2 -0
- package/dist/chunk-thyxsg54.js +2 -0
- package/dist/chunk-txjtd4gj.js +2 -0
- package/dist/{chunk-mrh08821.js → chunk-tyvm49be.js} +2 -2
- package/dist/{chunk-m1a3a32y.js → chunk-v4ab2jzz.js} +1 -1
- package/dist/{chunk-12sk3dtm.js → chunk-v99hgmsx.js} +1 -1
- package/dist/chunk-vf91b9b9.js +20 -0
- package/dist/chunk-vmq773pb.js +2 -0
- package/dist/{chunk-3asy7ev5.js → chunk-vv9anbw1.js} +1 -1
- package/dist/{chunk-hvx6j4a2.js → chunk-vvxcebpn.js} +2 -2
- package/dist/{chunk-5h9d6jew.js → chunk-wk2rge05.js} +3 -3
- package/dist/{chunk-wk188ph7.js → chunk-y48ykf1n.js} +4 -4
- package/dist/chunk-y69hhxn8.js +2 -0
- package/dist/{chunk-ca9x39p1.js → chunk-ycb07ppz.js} +1 -1
- package/dist/chunk-z0qxrx9r.js +3 -0
- package/dist/chunk-z2wfgva6.js +2 -0
- package/dist/{chunk-x7redxyd.js → chunk-z9xe3xkg.js} +2 -2
- package/dist/{chunk-stdddhk9.js → chunk-zfrzdje6.js} +2 -2
- package/dist/cli.js +14 -14
- package/dist/component-library.js +140 -36
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/accessibility.d.ts +15 -0
- package/dist/native/accessibility.js +14 -4
- package/dist/native/compiler/html-to-ir.js +56 -1
- package/dist/pwa.js +3 -3
- package/dist/signal-processing.js +4 -1
- package/dist/ssg.js +5 -5
- package/package.json +5 -5
- package/dist/chunk-04f6r2kh.js +0 -2
- package/dist/chunk-0jchm9gg.js +0 -2
- package/dist/chunk-5sbtbfj3.js +0 -2
- package/dist/chunk-79sr2kxg.js +0 -2
- package/dist/chunk-8cf6995c.js +0 -2
- package/dist/chunk-8cgn4re9.js +0 -2
- package/dist/chunk-94e6kmjm.js +0 -2
- package/dist/chunk-aa6ztwdq.js +0 -2
- package/dist/chunk-bz1jgrx8.js +0 -2
- package/dist/chunk-eh1rdapx.js +0 -2
- package/dist/chunk-hb6r4pxp.js +0 -2
- package/dist/chunk-jksjr12b.js +0 -2
- package/dist/chunk-khe30jmk.js +0 -3
- package/dist/chunk-ndrgek64.js +0 -2
- package/dist/chunk-nxecjev1.js +0 -2
- package/dist/chunk-ps6m8n9n.js +0 -2
- package/dist/chunk-pxce4aag.js +0 -2
- package/dist/chunk-qm0qn2xa.js +0 -177
- package/dist/chunk-qxxvaxee.js +0 -2
- package/dist/chunk-rhhq8k9f.js +0 -2
- package/dist/chunk-s2a9vfdg.js +0 -2
- package/dist/chunk-sew1z7cv.js +0 -21
- package/dist/chunk-swzxhkh2.js +0 -2042
- package/dist/chunk-tg7kt56m.js +0 -2
- package/dist/chunk-ttr8ay8h.js +0 -2
- package/dist/chunk-w2hqjv5e.js +0 -2
- package/dist/chunk-xb34eyne.js +0 -2
- package/dist/chunk-y0dee635.js +0 -2
- package/dist/chunk-yx3vghee.js +0 -2
- package/dist/chunk-zf9n3esr.js +0 -20
package/dist/chunk-swzxhkh2.js
DELETED
|
@@ -1,2042 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{L,vn,Bt,Ft,h,s,be,g}from"./chunk-hze3158c.js";import{kt,Ne,hc,ps,zo,Ho,i}from"./chunk-zfq2vvex.js";import{fe,se,Or,$e,W,Rn}from"./chunk-0tyyad6q.js";import{$t,wr,Ns,Ds,Ms,Rt,At,Pt,It,Ot,Nt,ot}from"./chunk-dy7vqv1x.js";import{$s,a,M}from"./chunk-y0msz738.js";import{wt,en,Ae,H,wa,So,Qr,Je,va,Ye,Pe}from"./chunk-7wae4311.js";import{hr,yr}from"./chunk-nkwj7eq3.js";import{e,mn,dr,x}from"./chunk-pfr3cazq.js";import{tt}from"./chunk-pdpmtmfj.js";import{Oe}from"./chunk-9zrvh3pz.js";import{Dn}from"./chunk-gesktj4m.js";import{Q,ke,_e}from"./chunk-q58f5wk2.js";import{l}from"./chunk-46pxmpeb.js";import{Z}from"./chunk-rpep1ve3.js";import{c,f}from"./chunk-fd1bpv35.js";async function Wn(t){try{let n=await Bun.file(t).text(),r=Vn(n),p=qn(n,t),o=Kn(n,r),d=Xn(n,r);return{file:t,metrics:r,issues:p,suggestions:o,performance:d}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Vn(t){let n=t.split(`
|
|
3
|
-
`),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
|
|
4
|
-
`).length,d={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};d.total=d.conditionals+d.loops+d.includes+d.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,b=u+m+y,w=(t.match(/<[A-Z][^>]*>/g)||[]).length,S=(t.match(/@(?:layout|extends)\(/g)||[]).length,T=0,R=0;for(let C of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,T=Math.max(T,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let k=T>=4?3:0,v=Math.min(10,Math.ceil(d.total*0.5+b*0.1+w*0.3+(o>10?o*0.05:0)+k));return{lines:n.length,characters:t.length,directives:d,expressions:b,components:w,layouts:S,scriptLines:o,complexity:v}}function qn(t,n){let r=[],p=Yt(t,"if","endif");if(p>0)r.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Yt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let m=t.match(/<img[^>]*>/g);if(m){let w=m.filter((S)=>!S.includes("alt="));if(w.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${w.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
|
|
5
|
-
`).filter((w)=>w.length>120);if(y.length>0)r.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let b=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(b>3)r.push({type:"info",category:"maintainability",message:`Found ${b} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Kn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function Xn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let p;if(n.expressions===0&&n.directives.total===0)p="high";else if(n.expressions<5&&n.directives.total<3)p="medium";else p="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(p==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:p,recommendations:o}}function Yt(t,n,r){let p=t.replace(/<!--[\s\S]*?-->/g,""),o=(p.match(new RegExp(`@${n}\\b`,"g"))||[]).length,d=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-d)}async function ia(t=["**/*.stx"],n){let r=[],p=[];for(let d of t){let u=await Array.fromAsync(new Bun.Glob(d).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...u.filter((m)=>m.endsWith(".stx")))}for(let d of p)try{let u=await Wn(d);r.push(u)}catch(u){console.warn(`Failed to analyze ${d}:`,u)}let o=Gn(r);return{results:r,summary:o}}function Gn(t){let n=t.length,r=t.reduce((b,w)=>b+w.metrics.lines,0),p=n>0?t.reduce((b,w)=>b+w.metrics.complexity,0)/n:0,o=t.reduce((b,w)=>b+w.issues.length,0),d={};t.forEach((b)=>{b.issues.forEach((w)=>{d[w.category]=(d[w.category]||0)+1})});let u=n>0?t.reduce((b,w)=>b+w.performance.estimatedRenderTime,0)/n:0,m=Math.max(1,Math.min(10,Math.round(10-u/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(d.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(p*100)/100,totalIssues:o,issuesByCategory:d,performanceScore:m,recommendations:y}}import{mkdir as Jn,readFile as Yn,readdir as Qn,stat as Qt,writeFile as Zn}from"fs/promises";import Te from"path";function sn(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 an=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function er(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let n=[];async function r(p){let o=await Qn(p,{withFileTypes:!0});o.sort((d,u)=>d.name.localeCompare(u.name));for(let d of o){let u=Te.join(p,d.name);if(d.isDirectory()){if(!d.name.startsWith(".")&&d.name!=="node_modules")await r(u)}else if(d.isFile()&&d.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(d.name))n.push(u)}}return await r(t),n}function or(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let p=r[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function sr(t,n){let r={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of p){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let d;try{d=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(y){throw Error(`${n}: failed to transpile <script client> (${y.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,m;while(m=u.exec(d)){let y=m[1];if(an.has(y))throw Error(`${n}: client ${sn(y)}`);let b=u.lastIndex,w=1,S="",T=!1,R=b;for(;R<d.length&&w>0;R++){let v=d[R];if(T){T=!1;continue}if(S){if(v==="\\")T=!0;else if(v===S)S="";continue}if(v==='"'||v==="'"||v==="`")S=v;else if(v==="{")w++;else if(v==="}")w--}if(w!==0)throw Error(`${n}: unterminated client function "${y}"`);let k=m[0].includes("async")?"async ":"";r[y]=`${k}${y}(${m[2]}) {${d.slice(b,R-1)}}`,u.lastIndex=R}}return r}function ir(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Zt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
6
|
-
|
|
7
|
-
`)}function ar(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function cr(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 lr(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 pr(t){let n=[],r=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,d,u=(y)=>{if(p[y]!=="(")return null;let b=0,w="";for(let S=y;S<p.length;S++){let T=p[S];if(w!==""){if(T==="\\")S++;else if(T===w)w="";continue}if(T==="'"||T==='"'||T==="`"){w=T;continue}if(T==="(")b++;else if(T===")"){if(b--,b===0)return{expression:p.slice(y+1,S),end:S+1}}}return null},m=(y)=>{if(y==="")return;let b=0,w=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,S;while(S=w.exec(y)){if(S.index>b)n.push(`out += ${JSON.stringify(y.slice(b,S.index))};`);n.push(S[1]!==void 0?`out += __raw(${S[1]});`:`out += __escape(${S[2]});`),b=S.index+S[0].length}if(b<y.length)n.push(`out += ${JSON.stringify(y.slice(b))};`)};while(d=o.exec(p)){m(p.slice(r,d.index)),r=d.index+d[0].length;let b=d[1]==="if"||d[1]==="elseif"||d[1]==="foreach"?u(r):null;if(b)r=b.end,o.lastIndex=b.end;let w=b?.expression;switch(d[1]){case"if":n.push(`if (${w}) {`);break;case"elseif":n.push(`} else if (${w}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let S=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((w||"").trim());if(!S){n.push(`out += ${JSON.stringify(d[0]+(b?`(${w})`:""))};`);break}let[,T,R,k]=S;n.push(R?`for (const [${R}, ${k}] of __entries(${T})) {`:`for (const ${k} of __values(${T})) {`);break}}}return m(p.slice(r)),n.join(`
|
|
8
|
-
`)}function ut(t,n,r,p){if(t[n]!==r)return-1;let o=0,d=null;for(let u=n;u<t.length;u++){let m=t[u];if(d){if(m==="\\"){u++;continue}if(m===d)d=null;continue}if(m==="'"||m==='"'||m==="`"){d=m;continue}if(m===r)o++;else if(m===p){if(p===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function _t(t,n,r){let p=r?"([{<":"([{",o=r?")]}>":")]}",d=[],u=0,m=null,y="";for(let b=0;b<t.length;b++){let w=t[b];if(m){if(y+=w,w==="\\"){y+=t[++b]??"";continue}if(w===m)m=null;continue}if(w==="'"||w==='"'||w==="`"){m=w,y+=w;continue}if(p.includes(w))u++;else if(o.includes(w))u--;if(u===0&&n.includes(w)){d.push(y),y="";continue}y+=w}return d.push(y),d.map((b)=>b.trim()).filter(Boolean)}function ur(t){let n=0,r=null;for(let p=0;p<t.length;p++){let o=t[p];if(r){if(o==="\\"){p++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let d=t[p-1];if(t[p+1]==="="||d==="="||d==="!"||d==="<"||d===">")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 fr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let O=r.exec(t);O&&O.index<n.index;O=r.exec(t))p=O.index+O[0].indexOf(O[1]);if(p===-1)return null;let o={},d={},u=[],m={},y=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),b=()=>{while(y<t.length&&/\s/.test(t[y]))y++},w;if(t[y]==="{"){let O=ut(t,y,"{","}");if(O===-1)return null;w=t.slice(y,O),y=O}else{let O=/^[A-Za-z_$][\w$]*/.exec(t.slice(y));if(!O)return null;w=O[0],y+=O[0].length}if(b(),t[y]!=="=")return null;y++,b();let S=/^withDefaults\s*\(\s*/.exec(t.slice(y)),T=Boolean(S);if(S)y+=S[0].length;let R=/^defineProps\b/.exec(t.slice(y));if(!R)return null;y+=R[0].length;let k="";if(b(),t[y]==="<"){let O=ut(t,y,"<",">");if(O===-1)return null;k=t.slice(y+1,O-1).trim(),y=O}if(b(),t[y]!=="(")return null;let v=ut(t,y,"(",")");if(v===-1)return null;let C=t.slice(y+1,v-1).trim();if(y=v,T){if(b(),t[y]===",")y++,b();if(t[y]==="{"){let O=ut(t,y,"{","}");if(O===-1)return null;for(let[P,D]of Lt(t.slice(y,O)))d[P]=D;y=O}if(b(),t[y]===",")y++,b();if(t[y]===")")y++}if(t[y]===";")y++;let I=/^[A-Za-z_$][\w$]*$/.test(k)?k:void 0;if(k.startsWith("{"))for(let O of _t(k.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let P=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(O);if(P)o[P[1]]=P[2].trim()}if(C.startsWith("{"))for(let[O,P]of Lt(C)){if(u.push(O),!P.startsWith("{")){let D=tn(P);if(D)o[O]=D;continue}for(let[D,E]of Lt(P))if(D==="default")d[O]=E;else if(D==="type"){let _=tn(E);if(_)o[O]=_}}else if(C.startsWith("["))for(let O of _t(C.slice(1,-1),",",!1))u.push(O.replace(/^['"`]/,"").replace(/['"`]$/,""));if(w.startsWith("{")){u.length=0;for(let O of _t(w.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let P=ur(O),D=P===-1?O:O.slice(0,P),E=D.split(":")[0].trim().replace(/^\.\.\./,"");if(!E)continue;if(u.push(E),m[E]=D.trim(),P!==-1)d[E]=O.slice(P+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(p,y),propNames:u,propBindings:m,defaults:d,declared:o,typeName:I}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],p=0;while(p<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=p;let d=o.exec(n);if(!d)break;p=o.lastIndex;let u=0,m="",y=p;while(p<n.length){let w=n[p];if(m){if(w==="\\")p++;else if(w===m)m=""}else if(w==="'"||w==='"'||w==="`")m=w;else if(w==="{"||w==="["||w==="(")u++;else if(w==="}"||w==="]"||w===")")u--;else if(w===","&&u===0)break;p++}let b=n.slice(y,p).trim();if(b)r.push([d[1],b]);p++}return r}function mr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((R)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(R[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let d=o[2],u=[],m=[],y={},b={},w={};d=d.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(R)=>{if(/from\s*['"]stx['"]/.test(R))return"";return u.push(R.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(k,v,C,I)=>{let O=Te.resolve(Te.dirname(n),C),P=Te.relative(r,O);return`${v}${P.startsWith(".")?P:`./${P}`}${I}`})),""});let S=fr(d);if(S)m.push(...S.propNames),Object.assign(y,S.propBindings),Object.assign(b,S.defaults),Object.assign(w,S.declared),d=d.replace(S.text,"");let T={};for(let R of d.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let k=[];for(let v of R[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))w[v[1]]=v[2].trim(),k.push(v[1]);T[R[1]]=k}if(S&&S.propNames.length===0&&S.typeName){for(let R of T[S.typeName]??[])if(!m.includes(R))m.push(R)}return d=d.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:d.trim(),propNames:m,propBindings:y,defaults:b,declared:w}}function gr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,o,d,u,m)=>{let y=o.toLowerCase();n.add(y);let b=(d||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${m}"${b?` data-stx-mod-${y}="${b}"`:""}`}),eventTypes:[...n].sort()}}function br(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,o,d,u)=>{let m=n.length;return n.push({id:m,name:o,expression:u}),` data-stx-bind-${m}=""`}),bindings:n}}function xr(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function vr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function nn(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function Sr(t,n,r){let p=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),o=await Yn(p,"utf8"),d=or(o,p),u=Te.basename(p,".stx"),m=n.name||d.name||er(u),y=`${jt(r.prefix||"stx")}-${jt(u)}`,b=n.tag||d.tag||y;if(!m||!/^[A-Za-z_$][\w$]*$/.test(m))throw Error(`${p}: invalid component class name "${m}"`);if(!tr(b))throw Error(`${p}: invalid custom-element tag "${b}"; tags must be lowercase and contain a hyphen`);let w=n.properties||d.properties||d.props||{},S=Object.fromEntries(Object.entries(w).map(([P,D])=>[P,nn(P,D)])),T=gr(ir(o)),R=br(T.template),k=mr(o,p,Te.resolve(r.outputDir)),v=pr(R.template);for(let P of k.propNames){if(S[P])continue;let D=k.defaults[P];S[P]=nn(P,{type:ar(k.declared[P])??cr(D),...D===void 0?{}:{default:lr(D)}})}let C=d.methods||{},I=n.methods||{},O=sr(o,p);return{file:Te.relative(t,p),sourcePath:p,name:m,tag:b,description:n.description||d.description||"",template:R.template,styles:Zt(o),shadowMode:nr(n.shadowDOM??d.shadowDOM??r.shadowDOM),progressive:n.progressive??d.progressive??r.progressive??!0,properties:S,events:n.events||d.events||{},methods:{...C,...I,...O},eventTypes:T.eventTypes,bindings:R.bindings,slots:xr(R.template),cssProperties:vr(Zt(o)),scope:k,render:v}}function kr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=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
|
-
const first = parts.shift();
|
|
17
|
-
// Render bindings read declared props, including attributes whose names
|
|
18
|
-
// also belong to the native DOM API. The public element keeps that API.
|
|
19
|
-
let value = host._values && Object.prototype.hasOwnProperty.call(host._values, first)
|
|
20
|
-
? host._values[first]
|
|
21
|
-
: host[first];
|
|
22
|
-
for (const part of parts) value = value?.[part];
|
|
23
|
-
return typeof value === 'function' ? value.call(host) : value;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
const deserialize = (value, type, fallback) => {
|
|
27
|
-
if (value === null) return type === 'boolean' ? false : fallback;
|
|
28
|
-
if (type === 'boolean') return value !== 'false' && value !== '0';
|
|
29
|
-
if (type === 'number') return Number(value);
|
|
30
|
-
if (type === 'object' || type === 'array') {
|
|
31
|
-
try { return JSON.parse(value); }
|
|
32
|
-
catch { return fallback; }
|
|
33
|
-
}
|
|
34
|
-
return value;
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
const serialize = (value, type) => {
|
|
38
|
-
if (value == null || value === false) return null;
|
|
39
|
-
if (type === 'boolean') return '';
|
|
40
|
-
if (type === 'object' || type === 'array') return JSON.stringify(value);
|
|
41
|
-
return String(value);
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
const cloneDefault = (value, type) => {
|
|
45
|
-
if (value == null || (type !== 'object' && type !== 'array')) return value;
|
|
46
|
-
if (typeof structuredClone === 'function') return structuredClone(value);
|
|
47
|
-
return JSON.parse(JSON.stringify(value));
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
const defaultFor = property => cloneDefault(
|
|
51
|
-
property.default ?? ({ string: '', number: 0, boolean: false, object: {}, array: [] })[property.type],
|
|
52
|
-
property.type,
|
|
53
|
-
);
|
|
54
|
-
|
|
55
|
-
export class StxElement extends HTMLElementBase {
|
|
56
|
-
static definition = {};
|
|
57
|
-
static get observedAttributes() { return this.definition.observedAttributes || []; }
|
|
58
|
-
|
|
59
|
-
constructor() {
|
|
60
|
-
super();
|
|
61
|
-
this._values = Object.create(null);
|
|
62
|
-
this._reflecting = false;
|
|
63
|
-
this._connected = false;
|
|
64
|
-
this._hasConnected = false;
|
|
65
|
-
this._initializing = false;
|
|
66
|
-
this._updatePending = false;
|
|
67
|
-
this._listeners = new Map();
|
|
68
|
-
const definition = this.constructor.definition;
|
|
69
|
-
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
70
|
-
this._values[name] = defaultFor(property);
|
|
71
|
-
}
|
|
72
|
-
if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
|
|
73
|
-
this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
get updateComplete() { return this._updateComplete || Promise.resolve(); }
|
|
78
|
-
get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
|
|
79
|
-
|
|
80
|
-
connectedCallback() {
|
|
81
|
-
if (this._connected) return;
|
|
82
|
-
this._connected = true;
|
|
83
|
-
this._initializing = true;
|
|
84
|
-
const definition = this.constructor.definition;
|
|
85
|
-
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
86
|
-
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
87
|
-
if (attribute && this.hasAttribute?.(attribute)) this._values[name] = deserialize(this.getAttribute(attribute), property.type, defaultFor(property));
|
|
88
|
-
}
|
|
89
|
-
// Properties assigned before customElements.define() become own properties.
|
|
90
|
-
// Upgrade them after attributes so imperative state wins, matching the
|
|
91
|
-
// platform's property-first custom-element initialization convention.
|
|
92
|
-
for (const name of Object.keys(definition.properties || {})) this._upgradeProperty(name);
|
|
93
|
-
this._initializing = false;
|
|
94
|
-
const root = this.renderRoot;
|
|
95
|
-
const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
|
|
96
|
-
const firstConnection = !this._hasConnected;
|
|
97
|
-
if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
|
|
98
|
-
else this._upgradeDeclarativeEvents();
|
|
99
|
-
this._bindEvents();
|
|
100
|
-
if (firstConnection) {
|
|
101
|
-
this._hasConnected = true;
|
|
102
|
-
this.setAttribute?.('hydrated', '');
|
|
103
|
-
this.dispatchEvent?.(new CustomEvent('stx:hydrated', { bubbles: true, composed: true }));
|
|
104
|
-
}
|
|
105
|
-
// Called last, so a component that acquires something sees its own rendered
|
|
106
|
-
// markup and its events already bound. Reported rather than rethrown: a
|
|
107
|
-
// component that fails to set up must not take the element down with it.
|
|
108
|
-
try { this.onConnect?.(); }
|
|
109
|
-
catch (error) { console.error('[stx] onConnect failed', error); }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
disconnectedCallback() {
|
|
113
|
-
this._connected = false;
|
|
114
|
-
// Called before the framework releases anything, so the element is still
|
|
115
|
-
// intact for a component that needs to read it on the way out, and inside
|
|
116
|
-
// try/finally so a throwing hook cannot leak the framework's own listeners.
|
|
117
|
-
try { this.onDisconnect?.(); }
|
|
118
|
-
catch (error) { console.error('[stx] onDisconnect failed', error); }
|
|
119
|
-
finally {
|
|
120
|
-
for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
|
|
121
|
-
this._listeners.clear();
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
attributeChangedCallback(attribute, oldValue, newValue) {
|
|
126
|
-
if (oldValue === newValue || this._reflecting) return;
|
|
127
|
-
const definition = this.constructor.definition;
|
|
128
|
-
const name = definition.attributeToProperty?.[attribute];
|
|
129
|
-
if (!name) return;
|
|
130
|
-
const property = definition.properties[name];
|
|
131
|
-
const value = deserialize(newValue, property.type, defaultFor(property));
|
|
132
|
-
if (!Object.is(this._values[name], value)) {
|
|
133
|
-
this._values[name] = value;
|
|
134
|
-
this.requestUpdate();
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* The props a compiled render reads.
|
|
140
|
-
*
|
|
141
|
-
* Its own method rather than _values directly, so a component that sets a
|
|
142
|
-
* property before upgrade still sees it, and so the generated code has one
|
|
143
|
-
* name to depend on rather than a private field's shape.
|
|
144
|
-
*/
|
|
145
|
-
_props() {
|
|
146
|
-
return this._values;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
requestUpdate() {
|
|
150
|
-
if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
|
|
151
|
-
this._updatePending = true;
|
|
152
|
-
this._updateComplete = new Promise((resolve) => {
|
|
153
|
-
queueMicrotask(() => {
|
|
154
|
-
this._updatePending = false;
|
|
155
|
-
if (this._connected) this._render();
|
|
156
|
-
resolve();
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
return this._updateComplete;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
emit(name, detail, options = {}) {
|
|
163
|
-
return this.dispatchEvent(new CustomEvent(name, {
|
|
164
|
-
detail, bubbles: true, composed: true, ...options,
|
|
165
|
-
}));
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
_upgradeProperty(name) {
|
|
169
|
-
if (!Object.prototype.hasOwnProperty.call(this, name)) return;
|
|
170
|
-
const value = this[name];
|
|
171
|
-
delete this[name];
|
|
172
|
-
this[name] = value;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
_upgradeDeclarativeEvents() {
|
|
176
|
-
for (const element of this.renderRoot.querySelectorAll?.('*') || []) {
|
|
177
|
-
const names = element.getAttributeNames?.() || [...(element.attributes || [])].filter(Boolean).map(attribute => attribute.name);
|
|
178
|
-
for (const attributeName of names) {
|
|
179
|
-
if (!attributeName?.startsWith('@')) continue;
|
|
180
|
-
const [event, ...modifiers] = attributeName.slice(1).split('.');
|
|
181
|
-
element.setAttribute('data-stx-on-' + event, element.getAttribute(attributeName));
|
|
182
|
-
if (modifiers.length) element.setAttribute('data-stx-mod-' + event, modifiers.join(' '));
|
|
183
|
-
element.removeAttribute(attributeName);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
_bindEvents() {
|
|
189
|
-
for (const event of this.constructor.definition.eventTypes || []) {
|
|
190
|
-
if (this._listeners.has(event)) continue;
|
|
191
|
-
const listener = ($event) => {
|
|
192
|
-
const selector = '[data-stx-on-' + event + ']';
|
|
193
|
-
const target = $event.target?.closest?.(selector);
|
|
194
|
-
if (!target || !this.renderRoot.contains(target)) return;
|
|
195
|
-
const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
|
|
196
|
-
if (modifiers.includes('prevent')) $event.preventDefault();
|
|
197
|
-
if (modifiers.includes('stop')) $event.stopPropagation();
|
|
198
|
-
const method = target.getAttribute('data-stx-on-' + event);
|
|
199
|
-
if (typeof this[method] === 'function') this[method]($event);
|
|
200
|
-
};
|
|
201
|
-
this.renderRoot.addEventListener(event, listener);
|
|
202
|
-
this._listeners.set(event, listener);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
_render() {
|
|
207
|
-
const definition = this.constructor.definition;
|
|
208
|
-
const root = this.renderRoot;
|
|
209
|
-
const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
|
|
210
|
-
const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
|
|
211
|
-
const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
|
|
212
|
-
// A compiled component renders itself: the control flow and the derived
|
|
213
|
-
// values were turned into JavaScript at build time, so there is nothing to
|
|
214
|
-
// interpret here and nothing that needs an eval the page's CSP forbids.
|
|
215
|
-
// The string template remains for components that carry no logic.
|
|
216
|
-
let html = typeof this.render === 'function'
|
|
217
|
-
? this.render(RENDER_HELPERS)
|
|
218
|
-
: definition.template
|
|
219
|
-
.replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
|
|
220
|
-
.replace(new RegExp(${n}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
|
|
221
|
-
if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
|
|
222
|
-
root.innerHTML = html;
|
|
223
|
-
this._applyBindings();
|
|
224
|
-
this._bindEvents();
|
|
225
|
-
if (focusKey) {
|
|
226
|
-
const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
|
|
227
|
-
const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
|
|
228
|
-
next?.focus?.();
|
|
229
|
-
if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
|
|
230
|
-
}
|
|
231
|
-
this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
_applyBindings() {
|
|
235
|
-
for (const binding of this.constructor.definition.bindings || []) {
|
|
236
|
-
const element = this.renderRoot.querySelector('[data-stx-bind-' + binding.id + ']');
|
|
237
|
-
if (!element) continue;
|
|
238
|
-
const value = valueAt(this, binding.expression);
|
|
239
|
-
if (binding.name === 'class') element.className = value || '';
|
|
240
|
-
else if (binding.name === 'style' && typeof value === 'object') {
|
|
241
|
-
Object.assign(element.style, value);
|
|
242
|
-
}
|
|
243
|
-
else if (typeof value === 'boolean') {
|
|
244
|
-
element.toggleAttribute(binding.name, value);
|
|
245
|
-
if (binding.name in element) element[binding.name] = value;
|
|
246
|
-
}
|
|
247
|
-
else if (value == null || value === false) element.removeAttribute(binding.name);
|
|
248
|
-
else element.setAttribute(binding.name, String(value));
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/**
|
|
254
|
-
* What a compiled render is handed.
|
|
255
|
-
*
|
|
256
|
-
* Passed in rather than closed over so the generated code names no globals, and
|
|
257
|
-
* a component module stays readable on its own: __escape is visibly a
|
|
258
|
-
* parameter, not something the bundler happened to leave in scope.
|
|
259
|
-
*/
|
|
260
|
-
const RENDER_HELPERS = {
|
|
261
|
-
escape: escapeHTML,
|
|
262
|
-
// The raw form is the author declaring the value is markup. Null becomes an
|
|
263
|
-
// empty string rather than the word "null", which is the only sensible
|
|
264
|
-
// reading of a missing fragment.
|
|
265
|
-
raw: (value) => String(value ?? ''),
|
|
266
|
-
// A loop over something absent runs zero times. Throwing here would fail a
|
|
267
|
-
// whole page over one empty list, which is never what the author meant.
|
|
268
|
-
values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
|
|
269
|
-
entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
export function defineComponent(Component, definition) {
|
|
273
|
-
const properties = definition.properties || {};
|
|
274
|
-
const attributeToProperty = {};
|
|
275
|
-
const observedAttributes = [];
|
|
276
|
-
for (const [name, property] of Object.entries(properties)) {
|
|
277
|
-
const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
|
|
278
|
-
if (attribute) {
|
|
279
|
-
attributeToProperty[attribute] = name;
|
|
280
|
-
observedAttributes.push(attribute);
|
|
281
|
-
}
|
|
282
|
-
// A style prop is an attribute value, not a replacement for the browser's
|
|
283
|
-
// CSSStyleDeclaration. Native event handler accessors must survive too.
|
|
284
|
-
if (name in HTMLElementBase.prototype) {
|
|
285
|
-
if (!attribute) throw new TypeError('STX prop "' + name + '" overlaps the native DOM API and needs an attribute binding');
|
|
286
|
-
continue;
|
|
287
|
-
}
|
|
288
|
-
Object.defineProperty(Component.prototype, name, {
|
|
289
|
-
configurable: true,
|
|
290
|
-
enumerable: true,
|
|
291
|
-
get() { return this._values[name]; },
|
|
292
|
-
set(value) {
|
|
293
|
-
const oldValue = this._values[name];
|
|
294
|
-
if (Object.is(oldValue, value)) return;
|
|
295
|
-
this._values[name] = value;
|
|
296
|
-
if (property.reflect && attribute && !this._reflecting) {
|
|
297
|
-
const serialized = serialize(value, property.type);
|
|
298
|
-
this._reflecting = true;
|
|
299
|
-
if (serialized === null) this.removeAttribute(attribute);
|
|
300
|
-
else this.setAttribute(attribute, serialized);
|
|
301
|
-
this._reflecting = false;
|
|
302
|
-
}
|
|
303
|
-
this.requestUpdate();
|
|
304
|
-
this.dispatchEvent?.(new CustomEvent(name + '-changed', {
|
|
305
|
-
detail: { value, oldValue }, bubbles: true, composed: true,
|
|
306
|
-
}));
|
|
307
|
-
},
|
|
308
|
-
});
|
|
309
|
-
}
|
|
310
|
-
Component.definition = { ...definition, attributeToProperty, observedAttributes };
|
|
311
|
-
const registry = globalThis.customElements || globalThis.window?.customElements;
|
|
312
|
-
if (registry && !registry.get(definition.tag)) {
|
|
313
|
-
registry.define(definition.tag, Component);
|
|
314
|
-
}
|
|
315
|
-
return Component;
|
|
316
|
-
}
|
|
317
|
-
`}function Tr(t){let n=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),r=Object.entries(t.methods).map(([m,y])=>{if(an.has(m))throw Error(`${t.sourcePath}: ${sn(m)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${m}($event) {
|
|
318
|
-
${y}
|
|
319
|
-
}`}).join(`
|
|
320
|
-
|
|
321
|
-
`),p=t.scope,o=[...new Set([...Object.keys(t.properties),...p.propNames])].map((m)=>{let y=p.propBindings[m]||m;return p.defaults[m]===void 0?y:`${y} = ${p.defaults[m]}`}).join(", "),d=(m)=>m.split(`
|
|
322
|
-
`).map((y)=>y.trim()===""?y:` ${y}`).join(`
|
|
323
|
-
`),u="";if(t.render.trim()!==""||p.body!==""||o!==""){let m=[o?`const { ${o} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
|
|
324
|
-
`),y;try{let b=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
|
|
325
|
-
${m}
|
|
326
|
-
}`),w=b.indexOf("{"),S=b.lastIndexOf("}");y=b.slice(w+1,S).trim()}catch(b){throw Error(`${t.sourcePath}: failed to compile render (${b.message})`)}u=`
|
|
327
|
-
render(__helpers) {
|
|
328
|
-
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
329
|
-
${d(y.trim())}
|
|
330
|
-
}
|
|
331
|
-
`}return`import { StxElement, defineComponent } from './runtime.js';
|
|
332
|
-
${p.imports.length?`${p.imports.join(`
|
|
333
|
-
`)}
|
|
334
|
-
`:""}
|
|
335
|
-
/** ${t.description||`${t.name} web component generated from ${t.file}.`} */
|
|
336
|
-
export class ${t.name} extends StxElement {
|
|
337
|
-
${r}${u}
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
defineComponent(${t.name}, ${n});
|
|
341
|
-
export default ${t.name};
|
|
342
|
-
`}function Ht(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 $r(t){let n=Object.entries(t.properties).map(([o,d])=>` ${o}${d.required?"":"?"}: ${Ht(d)}`).join(`
|
|
343
|
-
`),r=Object.entries(t.events).map(([o,d])=>` ${JSON.stringify(o)}: CustomEvent<${d.detailType||"unknown"}>`).join(`
|
|
344
|
-
`),p=Object.keys(t.methods).map((o)=>` ${o}($event?: Event): unknown`).join(`
|
|
345
|
-
`);return`export interface ${t.name}Props {
|
|
346
|
-
${n}
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
export interface ${t.name}EventMap {
|
|
350
|
-
${r}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
export interface ${t.name} extends Required<Pick<${t.name}Props, Exclude<keyof ${t.name}Props, keyof HTMLElement>>> {}
|
|
354
|
-
|
|
355
|
-
export declare class ${t.name} extends HTMLElement {
|
|
356
|
-
${p}
|
|
357
|
-
readonly updateComplete: Promise<void>
|
|
358
|
-
requestUpdate(): Promise<void>
|
|
359
|
-
emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
declare global {
|
|
363
|
-
interface HTMLElementTagNameMap {
|
|
364
|
-
${JSON.stringify(t.tag)}: ${t.name}
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
export default ${t.name}
|
|
369
|
-
`}function Cr(t){return`declare global {
|
|
370
|
-
namespace JSX {
|
|
371
|
-
interface IntrinsicElements {
|
|
372
|
-
${t.map((r)=>{let p=Object.entries(r.properties).map(([d,u])=>` ${JSON.stringify(d)}?: ${Ht(u)}`).join(`
|
|
373
|
-
`),o=Object.keys(r.events).map((d)=>` ${`on${d.split(/[-:]/).map((m)=>m.charAt(0).toUpperCase()+m.slice(1)).join("")}`}?: (event: CustomEvent<${r.events[d].detailType||"unknown"}>) => void`).join(`
|
|
374
|
-
`);return` ${JSON.stringify(r.tag)}: {
|
|
375
|
-
${p}
|
|
376
|
-
${o}
|
|
377
|
-
children?: unknown
|
|
378
|
-
slot?: string
|
|
379
|
-
class?: string
|
|
380
|
-
className?: string
|
|
381
|
-
}`}).join(`
|
|
382
|
-
`)}
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
export {}
|
|
388
|
-
`}function Rr(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([r,p])=>({kind:"field",name:r,description:p.description,type:{text:Ht(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||jt(r),reflects:p.reflect})),events:Object.entries(n.events).map(([r,p])=>({name:r,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function rn(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
|
|
389
|
-
${n}
|
|
390
|
-
}`}function on(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Er(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),d=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
|
|
391
|
-
`);return`const definitions = ${JSON.stringify(o,null,2)};
|
|
392
|
-
const escapeHTML = (value) => String(value ?? '')
|
|
393
|
-
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
394
|
-
.replaceAll('"', '"').replaceAll("'", ''');
|
|
395
|
-
const valueAt = (values, path) => path.trim().split('.').reduce((value, part) => value?.[part], values);
|
|
396
|
-
|
|
397
|
-
export function renderComponent(tag, props = {}, slots = {}) {
|
|
398
|
-
const definition = definitions[tag];
|
|
399
|
-
if (!definition) throw new Error('Unknown STX component: ' + tag);
|
|
400
|
-
const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
|
|
401
|
-
Object.assign(values, props);
|
|
402
|
-
let template = definition.template
|
|
403
|
-
.replace(new RegExp(${n}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
|
|
404
|
-
.replace(new RegExp(${r}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
|
|
405
|
-
.replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
|
|
406
|
-
const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
|
|
407
|
-
if (property.attribute === false || !(name in props)) return [];
|
|
408
|
-
const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
409
|
-
const value = props[name];
|
|
410
|
-
if (value == null || value === false) return [];
|
|
411
|
-
if (value === true) return [attribute];
|
|
412
|
-
const serialized = typeof value === 'object' ? JSON.stringify(value) : value;
|
|
413
|
-
return [attribute + '=\\"' + escapeHTML(serialized) + '\\"'];
|
|
414
|
-
}).join(' ');
|
|
415
|
-
if (definition.shadowMode) {
|
|
416
|
-
template = '<template shadowrootmode="' + definition.shadowMode + '">' +
|
|
417
|
-
(definition.styles ? '<style>' + definition.styles + '</style>' : '') + template + '</template>' +
|
|
418
|
-
String(slots.default ?? '');
|
|
419
|
-
}
|
|
420
|
-
return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
${d}
|
|
424
|
-
`}async function aa(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Qt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await rr(n)).map((v)=>({file:v}));if(!o.length)throw Error(`No .stx components found in ${n}`);let d=await Promise.all(o.map((v)=>Sr(n,v,t)));d.sort((v,C)=>v.tag.localeCompare(C.tag));let u=d.filter((v,C)=>d.findIndex((I)=>I.tag===v.tag)!==C);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let m=d.filter((v,C)=>d.findIndex((I)=>I.name===v.name)!==C);if(m.length)throw Error(`Duplicate component class name: ${m[0].name}`);await Jn(r,{recursive:!0});let y=[],b=async(v,C)=>{let I=Te.join(r,v);return await Zn(I,C.endsWith(`
|
|
425
|
-
`)?C:`${C}
|
|
426
|
-
`,"utf8"),y.push(I),I};await b("runtime.js",kr());for(let v of d){if(await b(`${v.tag}.js`,Tr(v)),t.declarations!==!1)await b(`${v.tag}.d.ts`,$r(v));if(t.css!==!1&&v.styles){let C=v.shadowMode?v.styles:rn(v);await b(`${v.tag}.css`,t.minify?on(C):C)}}let w=d.map((v)=>`export { ${v.name}, default as ${v.name}Element } from './${v.tag}.js';`).join(`
|
|
427
|
-
`);if(await b("index.js",w),await b("ssr.js",Er(d)),t.declarations!==!1)await b("index.d.ts",d.map((v)=>`export * from './${v.tag}.js'`).join(`
|
|
428
|
-
`)),await b("custom-elements.d.ts",Cr(d)),await b("ssr.d.ts",`${d.map((v)=>`export declare const render${v.name}: (props?: ${v.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
429
|
-
`)}
|
|
430
|
-
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
431
|
-
${d.map((v)=>`import type { ${v.name}Props } from './${v.tag}.js'`).join(`
|
|
432
|
-
`)}`);let S;if(t.manifest!==!1)S=await b("custom-elements.json",JSON.stringify(Rr(d),null,2));let T;if(t.css!==!1){let v=d.filter((C)=>!C.shadowMode&&C.styles).map(rn).join(`
|
|
433
|
-
|
|
434
|
-
`);if(v)T=await b("bundle.css",t.minify?on(v):v)}let R;if(t.bundle!==!1){R=Te.join(r,"bundle.js");let v;try{v=await Bun.build({entrypoints:[Te.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let I=C instanceof AggregateError?C.errors:[C],O=I.map((P)=>String(P).trim()).filter(Boolean).join(`
|
|
435
|
-
`);throw AggregateError(I,`Failed to bundle component library${O?`
|
|
436
|
-
${O}`:""}`)}if(!v.success){let C=v.logs.map((I)=>String(I).trim()).filter(Boolean).join(`
|
|
437
|
-
`);throw AggregateError(v.logs,`Failed to bundle component library${C?`
|
|
438
|
-
${C}`:""}`)}if(y.push(R),t.sourcemap==="external")y.push(`${R}.map`)}let k=await Promise.all(y.map(async(v)=>(await Qt(v)).size));return{components:d.map((v)=>({name:v.name,tag:v.tag,source:v.sourcePath,module:Te.join(r,`${v.tag}.js`)})),files:y,manifest:S,bundle:R,cssBundle:T,totalBytes:k.reduce((v,C)=>v+C,0)}}var{serve:Br}=globalThis.Bun;import Ut from"fs";import nt from"path";function ft(){return`
|
|
439
|
-
/* Theme selector for code blocks */
|
|
440
|
-
.theme-selector {
|
|
441
|
-
margin: 1rem 0;
|
|
442
|
-
padding: 0.5rem;
|
|
443
|
-
background: #f8f8f8;
|
|
444
|
-
border-radius: 4px;
|
|
445
|
-
text-align: right;
|
|
446
|
-
}
|
|
447
|
-
select {
|
|
448
|
-
padding: 0.25rem 0.5rem;
|
|
449
|
-
border-radius: 3px;
|
|
450
|
-
border: 1px solid #ddd;
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
/* Dark mode body styles */
|
|
454
|
-
body.dark-mode {
|
|
455
|
-
background-color: #121212;
|
|
456
|
-
color: #e1e4e8;
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
body.dark-mode h1,
|
|
460
|
-
body.dark-mode h2,
|
|
461
|
-
body.dark-mode h3 {
|
|
462
|
-
color: #e1e4e8;
|
|
463
|
-
border-color: #2f363d;
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
body.dark-mode .theme-selector {
|
|
467
|
-
background: #2f363d;
|
|
468
|
-
color: #e1e4e8;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
body.dark-mode select {
|
|
472
|
-
background: #24292e;
|
|
473
|
-
color: #e1e4e8;
|
|
474
|
-
border-color: #444;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
body.dark-mode blockquote {
|
|
478
|
-
background: #24292e;
|
|
479
|
-
color: #e1e4e8;
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
body.dark-mode .frontmatter {
|
|
483
|
-
background: #24292e;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
body.dark-mode a {
|
|
487
|
-
color: #58a6ff;
|
|
488
|
-
}`}function mt(t){return`
|
|
489
|
-
<div class="theme-selector">
|
|
490
|
-
Theme:
|
|
491
|
-
<select id="themeSelector" onchange="changeTheme()">
|
|
492
|
-
${t}
|
|
493
|
-
</select>
|
|
494
|
-
</div>`}function gt(){return`
|
|
495
|
-
function changeTheme() {
|
|
496
|
-
const theme = document.getElementById('themeSelector').value;
|
|
497
|
-
|
|
498
|
-
// Toggle dark mode class based on theme
|
|
499
|
-
// Dark themes typically include these keywords in their names
|
|
500
|
-
if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
|
|
501
|
-
theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
|
|
502
|
-
document.body.classList.add('dark-mode');
|
|
503
|
-
}
|
|
504
|
-
else {
|
|
505
|
-
document.body.classList.remove('dark-mode');
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// Initialize theme on page load
|
|
510
|
-
document.addEventListener('DOMContentLoaded', changeTheme);`}function ht(t){if(Object.keys(t).length===0)return"";return`
|
|
511
|
-
<div class="frontmatter">
|
|
512
|
-
<h3>Frontmatter</h3>
|
|
513
|
-
${Object.entries(t).map(([n,r])=>`
|
|
514
|
-
<div class="frontmatter-item">
|
|
515
|
-
<span class="frontmatter-label">${n}:</span>
|
|
516
|
-
<span>${Array.isArray(r)?r.join(", "):String(r)}</span>
|
|
517
|
-
</div>`).join("")}
|
|
518
|
-
</div>`}async function Pr(t){let{default:n}=await import("net");return new Promise((r)=>{let p=n.createServer();p.once("error",()=>r(!1)),p.once("listening",()=>{p.close(()=>r(!0))}),p.listen(t,"0.0.0.0")})}async function Ar(t){let{default:n}=await import("net");return new Promise((r)=>{let p=n.createServer();p.once("error",()=>r(!1)),p.once("listening",()=>{p.close(()=>r(!0))}),p.listen(t,"::")})}async function Dr(t){if(!await Pr(t))return!1;return await Ar(t)}async function qe(t,n=20){t=Number(t);for(let r=0;r<n;r++){let p=t+r;if(await Dr(p))return p}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Mr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function _r(){try{let t=await import("./chunk-7chzhef2.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function et(t,n={}){let r={...Mr,...n},p=await _r();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 o=await p.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function yt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let d=o[1];try{let u=`
|
|
519
|
-
${d}
|
|
520
|
-
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
521
|
-
`,y=Function(u)();if(y)return y}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let o=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function zt(){console.log(`
|
|
522
|
-
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Lr(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 Ir(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ke(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let p="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(p+=o,p.endsWith("\r")||p.endsWith(`
|
|
523
|
-
`)){let d=p.trim().toLowerCase();p="",jr(d,t,n,r)}})}function jr(t,n,r,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ir(n);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Lr(n);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Wt(t,n={}){let r=n.port||3000,p=n.watch!==!1,o=nt.resolve(t);if(!Ut.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let d=null,u=async()=>{try{let{content:S,data:T}=await Ne(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:M.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||M.markdown?.syntaxHighlighting,k=R?.defaultTheme||"github-dark",v=["github-dark"],C=R?.additionalThemes||[],O=[...new Set([...v,...C])].map((P)=>`<option value="${P}"${P===k?" selected":""}>${P}</option>`).join(`
|
|
524
|
-
`);return d=`
|
|
525
|
-
<!DOCTYPE html>
|
|
526
|
-
<html lang="en">
|
|
527
|
-
<head>
|
|
528
|
-
<meta charset="UTF-8">
|
|
529
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
530
|
-
<title>${Hr(T.title||nt.basename(o))}</title>
|
|
531
|
-
<!-- Syntax highlighting styles -->
|
|
532
|
-
<style id="syntax-theme">
|
|
533
|
-
:root {
|
|
534
|
-
--shiki-color-text: #24292e;
|
|
535
|
-
--shiki-color-background: #ffffff;
|
|
536
|
-
--shiki-token-constant: #005cc5;
|
|
537
|
-
--shiki-token-string: #032f62;
|
|
538
|
-
--shiki-token-comment: #6a737d;
|
|
539
|
-
--shiki-token-keyword: #d73a49;
|
|
540
|
-
--shiki-token-parameter: #24292e;
|
|
541
|
-
--shiki-token-function: #6f42c1;
|
|
542
|
-
--shiki-token-string-expression: #032f62;
|
|
543
|
-
--shiki-token-punctuation: #24292e;
|
|
544
|
-
--shiki-token-link: #032f62;
|
|
545
|
-
}
|
|
546
|
-
pre {
|
|
547
|
-
background-color: var(--shiki-color-background);
|
|
548
|
-
padding: 1rem;
|
|
549
|
-
border-radius: 4px;
|
|
550
|
-
}
|
|
551
|
-
code {
|
|
552
|
-
color: var(--shiki-color-text);
|
|
553
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
554
|
-
}
|
|
555
|
-
.dark-mode {
|
|
556
|
-
--shiki-color-text: #e1e4e8;
|
|
557
|
-
--shiki-color-background: #24292e;
|
|
558
|
-
--shiki-token-constant: #79b8ff;
|
|
559
|
-
--shiki-token-string: #9ecbff;
|
|
560
|
-
--shiki-token-comment: #6a737d;
|
|
561
|
-
--shiki-token-keyword: #f97583;
|
|
562
|
-
--shiki-token-parameter: #e1e4e8;
|
|
563
|
-
--shiki-token-function: #b392f0;
|
|
564
|
-
--shiki-token-string-expression: #9ecbff;
|
|
565
|
-
--shiki-token-punctuation: #e1e4e8;
|
|
566
|
-
--shiki-token-link: #9ecbff;
|
|
567
|
-
}
|
|
568
|
-
</style>
|
|
569
|
-
<style>
|
|
570
|
-
body {
|
|
571
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
572
|
-
line-height: 1.6;
|
|
573
|
-
color: #333;
|
|
574
|
-
max-width: 800px;
|
|
575
|
-
margin: 0 auto;
|
|
576
|
-
padding: 2rem;
|
|
577
|
-
}
|
|
578
|
-
pre, code {
|
|
579
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
580
|
-
}
|
|
581
|
-
pre {
|
|
582
|
-
border-radius: 4px;
|
|
583
|
-
padding: 0;
|
|
584
|
-
margin: 1.5rem 0;
|
|
585
|
-
overflow-x: auto;
|
|
586
|
-
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
587
|
-
}
|
|
588
|
-
pre code {
|
|
589
|
-
display: block;
|
|
590
|
-
padding: 1rem;
|
|
591
|
-
overflow-x: auto;
|
|
592
|
-
}
|
|
593
|
-
/* Apply background color to code blocks based on theme */
|
|
594
|
-
pre.syntax-highlighter {
|
|
595
|
-
background-color: var(--shiki-color-background) !important;
|
|
596
|
-
}
|
|
597
|
-
.dark-mode pre.syntax-highlighter {
|
|
598
|
-
background-color: var(--shiki-color-background) !important;
|
|
599
|
-
}
|
|
600
|
-
code {
|
|
601
|
-
padding: 0.2rem 0.4rem;
|
|
602
|
-
border-radius: 3px;
|
|
603
|
-
}
|
|
604
|
-
h1, h2, h3, h4 {
|
|
605
|
-
margin-top: 2rem;
|
|
606
|
-
margin-bottom: 1rem;
|
|
607
|
-
}
|
|
608
|
-
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
609
|
-
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
610
|
-
h3 { color: #444; }
|
|
611
|
-
img {
|
|
612
|
-
max-width: 100%;
|
|
613
|
-
border-radius: 4px;
|
|
614
|
-
margin: 1rem 0;
|
|
615
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
616
|
-
}
|
|
617
|
-
blockquote {
|
|
618
|
-
border-left: 4px solid #ddd;
|
|
619
|
-
padding-left: 1rem;
|
|
620
|
-
margin-left: 0;
|
|
621
|
-
color: #555;
|
|
622
|
-
background: #f9f9f9;
|
|
623
|
-
padding: 0.5rem 1rem;
|
|
624
|
-
margin: 1.5rem 0;
|
|
625
|
-
}
|
|
626
|
-
table {
|
|
627
|
-
border-collapse: collapse;
|
|
628
|
-
width: 100%;
|
|
629
|
-
margin: 1.5rem 0;
|
|
630
|
-
}
|
|
631
|
-
th, td {
|
|
632
|
-
border: 1px solid #ddd;
|
|
633
|
-
padding: 0.5rem;
|
|
634
|
-
}
|
|
635
|
-
th {
|
|
636
|
-
background: #f0f0f0;
|
|
637
|
-
text-align: left;
|
|
638
|
-
}
|
|
639
|
-
tr:nth-child(even) {
|
|
640
|
-
background-color: #f8f8f8;
|
|
641
|
-
}
|
|
642
|
-
a {
|
|
643
|
-
color: #0066cc;
|
|
644
|
-
text-decoration: none;
|
|
645
|
-
}
|
|
646
|
-
a:hover {
|
|
647
|
-
text-decoration: underline;
|
|
648
|
-
}
|
|
649
|
-
hr {
|
|
650
|
-
border: 0;
|
|
651
|
-
border-top: 1px solid #eee;
|
|
652
|
-
margin: 2rem 0;
|
|
653
|
-
}
|
|
654
|
-
.frontmatter {
|
|
655
|
-
background: #f8f8f8;
|
|
656
|
-
border-radius: 4px;
|
|
657
|
-
padding: 1.5rem;
|
|
658
|
-
margin-bottom: 2rem;
|
|
659
|
-
font-size: 0.9rem;
|
|
660
|
-
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
661
|
-
border-left: 4px solid #ddd;
|
|
662
|
-
}
|
|
663
|
-
.frontmatter-item {
|
|
664
|
-
margin-bottom: 0.5rem;
|
|
665
|
-
display: flex;
|
|
666
|
-
}
|
|
667
|
-
.frontmatter-label {
|
|
668
|
-
font-weight: bold;
|
|
669
|
-
min-width: 100px;
|
|
670
|
-
color: #555;
|
|
671
|
-
}
|
|
672
|
-
${ft()}
|
|
673
|
-
</style>
|
|
674
|
-
</head>
|
|
675
|
-
<body>
|
|
676
|
-
${ht(T)}
|
|
677
|
-
${mt(O)}
|
|
678
|
-
|
|
679
|
-
${S}
|
|
680
|
-
|
|
681
|
-
<script>
|
|
682
|
-
${gt()}
|
|
683
|
-
</script>
|
|
684
|
-
</body>
|
|
685
|
-
</html>
|
|
686
|
-
`,!0}catch(S){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,S),!1}};if(!await u())return!1;let y=r;try{if(y=await qe(r),y!==r)console.log(`${e.yellow}Port ${r} 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 b=Br({port:y,fetch(S){if(new URL(S.url).pathname==="/")return new Response(d,{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(S){return new Response(`<pre>${S}
|
|
687
|
-
${S.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
688
|
-
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
689
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
690
|
-
${e.yellow}Routes:${e.reset}`);let w=nt.relative(process.cwd(),o);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${w}${e.reset}`),console.log(`
|
|
691
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(b.url.toString(),()=>{if(p)Ut.watch(nt.dirname(o),{recursive:!0}).close();b.stop()}),n.native)await et(y,{title:nt.basename(o,".md")});if(p){let S=nt.dirname(o);console.log(`${e.blue}Watching ${e.bright}${S}${e.reset} for changes...`);let T=Ut.watch(S,{recursive:!0},async(R,k)=>{if(k&&k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{T.close(),b.stop(),process.exit(0)})}return!0}function Hr(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:zr}=globalThis.Bun;import Fe from"fs";import he from"path";class cn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let p=0;p<r;p++)try{if(this.server=Bun.serve({port:n,fetch(o,d){if(d.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,d)=>{let u=typeof d==="string"?d:d.toString();if(u==="ping")return;try{let m=JSON.parse(u);if(m.type==="console"&&Array.isArray(m.args)){let y=m.args.join(" "),w={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[m.level]??"\x1B[36m";console.log(`${w}[browser]${m.level!=="log"?` ${m.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let p of this.clients)try{if(p.readyState===1)p.send(n),r++}catch{this.clients.delete(p)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Fr(t,n={}){let{showOverlay:r=!0,reconnectInterval:p=1000,maxReconnectAttempts:o=10}=n;return`
|
|
692
|
-
<script>
|
|
693
|
-
(function() {
|
|
694
|
-
// stx Hot Reload Client
|
|
695
|
-
var wsUrl = 'ws://' + window.location.hostname + ':${t}';
|
|
696
|
-
var reconnectAttempts = 0;
|
|
697
|
-
var maxAttempts = ${o};
|
|
698
|
-
var reconnectInterval = ${p};
|
|
699
|
-
var socket = null;
|
|
700
|
-
var overlay = null;
|
|
701
|
-
var wasConnected = false; // Track if we ever connected successfully
|
|
702
|
-
|
|
703
|
-
${r?`
|
|
704
|
-
// Create connection status overlay
|
|
705
|
-
function createOverlay() {
|
|
706
|
-
overlay = document.createElement('div');
|
|
707
|
-
overlay.id = 'stx-hmr-overlay';
|
|
708
|
-
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;';
|
|
709
|
-
document.body.appendChild(overlay);
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
function showOverlay(message, isError) {
|
|
713
|
-
// Only show overlay if we were previously connected (don't show during initial connection)
|
|
714
|
-
if (!wasConnected && !isError) return;
|
|
715
|
-
if (!overlay) createOverlay();
|
|
716
|
-
overlay.textContent = message;
|
|
717
|
-
overlay.style.background = isError ? '#ef4444' : '#f59e0b';
|
|
718
|
-
overlay.style.color = isError ? '#fff' : '#000';
|
|
719
|
-
overlay.style.display = 'block';
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
function hideOverlay() {
|
|
723
|
-
if (overlay) overlay.style.display = 'none';
|
|
724
|
-
}
|
|
725
|
-
`:`
|
|
726
|
-
function showOverlay() {}
|
|
727
|
-
function hideOverlay() {}
|
|
728
|
-
`}
|
|
729
|
-
|
|
730
|
-
function connect() {
|
|
731
|
-
try {
|
|
732
|
-
socket = new WebSocket(wsUrl);
|
|
733
|
-
}
|
|
734
|
-
catch (e) {
|
|
735
|
-
// Silent fail for initial connection attempts
|
|
736
|
-
if (wasConnected) {
|
|
737
|
-
scheduleReconnect();
|
|
738
|
-
}
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
socket.onopen = function() {
|
|
743
|
-
// connected silently
|
|
744
|
-
wasConnected = true;
|
|
745
|
-
reconnectAttempts = 0;
|
|
746
|
-
hideOverlay();
|
|
747
|
-
};
|
|
748
|
-
|
|
749
|
-
socket.onmessage = function(event) {
|
|
750
|
-
try {
|
|
751
|
-
var msg = JSON.parse(event.data);
|
|
752
|
-
|
|
753
|
-
switch (msg.type) {
|
|
754
|
-
case 'reload':
|
|
755
|
-
console.log('[stx] Reloading...', msg.path || '');
|
|
756
|
-
// Use SPA router for progressive update instead of full page reload.
|
|
757
|
-
// Falls back to hard reload only when the router isn't available.
|
|
758
|
-
// Call the ROUTER directly, not window.navigate: the runtime helper
|
|
759
|
-
// takes (url, options) and silently dropped the third argument, so
|
|
760
|
-
// force never arrived and the same-URL early return made this a
|
|
761
|
-
// no-op on every page that had the router (#1807). pushState=false
|
|
762
|
-
// keeps the address bar untouched (this is a reload, not a
|
|
763
|
-
// navigation) and force=true bypasses the early return.
|
|
764
|
-
if (window.stxRouter && typeof window.stxRouter.navigate === 'function') {
|
|
765
|
-
window.stxRouter.navigate(window.location.pathname + window.location.search, false, true);
|
|
766
|
-
} else {
|
|
767
|
-
window.location.reload();
|
|
768
|
-
}
|
|
769
|
-
break;
|
|
770
|
-
|
|
771
|
-
case 'css-update':
|
|
772
|
-
console.log('[stx] CSS update:', msg.path);
|
|
773
|
-
updateCss(msg.path, msg.content);
|
|
774
|
-
break;
|
|
775
|
-
|
|
776
|
-
case 'error':
|
|
777
|
-
console.error('[stx] Error:', msg.content);
|
|
778
|
-
showOverlay('Build Error: ' + msg.content, true);
|
|
779
|
-
break;
|
|
780
|
-
|
|
781
|
-
case 'connected':
|
|
782
|
-
break;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
catch (e) {
|
|
786
|
-
console.error('[stx] Invalid message:', e);
|
|
787
|
-
}
|
|
788
|
-
};
|
|
789
|
-
|
|
790
|
-
socket.onclose = function() {
|
|
791
|
-
socket = null;
|
|
792
|
-
// Only log and show overlay if we were previously connected
|
|
793
|
-
if (wasConnected) {
|
|
794
|
-
console.log('[stx] Connection closed, reconnecting...');
|
|
795
|
-
scheduleReconnect();
|
|
796
|
-
}
|
|
797
|
-
else {
|
|
798
|
-
// Silently retry initial connection
|
|
799
|
-
setTimeout(connect, reconnectInterval);
|
|
800
|
-
}
|
|
801
|
-
};
|
|
802
|
-
|
|
803
|
-
socket.onerror = function() {
|
|
804
|
-
// Errors are handled in onclose
|
|
805
|
-
};
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
function scheduleReconnect() {
|
|
809
|
-
if (reconnectAttempts < maxAttempts) {
|
|
810
|
-
reconnectAttempts++;
|
|
811
|
-
showOverlay('Reconnecting... (' + reconnectAttempts + '/' + maxAttempts + ')');
|
|
812
|
-
setTimeout(connect, reconnectInterval);
|
|
813
|
-
}
|
|
814
|
-
else {
|
|
815
|
-
showOverlay('Connection lost. Refresh to reconnect.', true);
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
// CSS hot update without full reload
|
|
820
|
-
function updateCss(path, content) {
|
|
821
|
-
// Try to find and update existing stylesheet
|
|
822
|
-
var links = document.querySelectorAll('link[rel="stylesheet"]');
|
|
823
|
-
for (var i = 0; i < links.length; i++) {
|
|
824
|
-
var href = links[i].getAttribute('href');
|
|
825
|
-
if (href && href.indexOf(path) !== -1) {
|
|
826
|
-
// Add cache-busting query param
|
|
827
|
-
var newHref = href.split('?')[0] + '?t=' + Date.now();
|
|
828
|
-
links[i].setAttribute('href', newHref);
|
|
829
|
-
return;
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// If content provided, inject as style tag
|
|
834
|
-
if (content) {
|
|
835
|
-
var style = document.createElement('style');
|
|
836
|
-
style.setAttribute('data-stx-hmr', path);
|
|
837
|
-
style.textContent = content;
|
|
838
|
-
|
|
839
|
-
// Remove old injected style
|
|
840
|
-
var old = document.querySelector('style[data-stx-hmr="' + path + '"]');
|
|
841
|
-
if (old) old.remove();
|
|
842
|
-
|
|
843
|
-
document.head.appendChild(style);
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
// Start connection when DOM is ready
|
|
848
|
-
if (document.readyState === 'loading') {
|
|
849
|
-
document.addEventListener('DOMContentLoaded', connect);
|
|
850
|
-
}
|
|
851
|
-
else {
|
|
852
|
-
connect();
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
// Forward browser console to the dev server terminal
|
|
856
|
-
var _origLog = console.log;
|
|
857
|
-
var _origError = console.error;
|
|
858
|
-
var _origWarn = console.warn;
|
|
859
|
-
var _origInfo = console.info;
|
|
860
|
-
|
|
861
|
-
function _fwd(level, args) {
|
|
862
|
-
if (socket && socket.readyState === 1) {
|
|
863
|
-
try {
|
|
864
|
-
socket.send(JSON.stringify({
|
|
865
|
-
type: 'console',
|
|
866
|
-
level: level,
|
|
867
|
-
args: Array.prototype.slice.call(args).map(function(a) {
|
|
868
|
-
if (a === null) return 'null';
|
|
869
|
-
if (a === undefined) return 'undefined';
|
|
870
|
-
if (typeof a === 'object') { try { return JSON.stringify(a); } catch(e) { return String(a); } }
|
|
871
|
-
return String(a);
|
|
872
|
-
})
|
|
873
|
-
}));
|
|
874
|
-
} catch(e) {}
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
console.log = function() { _origLog.apply(console, arguments); _fwd('log', arguments); };
|
|
879
|
-
console.error = function() { _origError.apply(console, arguments); _fwd('error', arguments); };
|
|
880
|
-
console.warn = function() { _origWarn.apply(console, arguments); _fwd('warn', arguments); };
|
|
881
|
-
console.info = function() { _origInfo.apply(console, arguments); _fwd('info', arguments); };
|
|
882
|
-
|
|
883
|
-
// Expose for debugging
|
|
884
|
-
window.__stxHmr = {
|
|
885
|
-
reconnect: connect,
|
|
886
|
-
status: function() { return socket ? socket.readyState : -1; }
|
|
887
|
-
};
|
|
888
|
-
})();
|
|
889
|
-
</script>
|
|
890
|
-
`}function We(t,n,r={}){let p=Fr(n,r),o=c(t);if(o!==-1)return t.slice(0,o)+p+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function bt(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function xt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>n.endsWith(p))}function vt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var rt=null;function St(t){if(!rt)rt=new cn(t);return rt}function ct(){if(rt)rt.stop(),rt=null}import Tt from"path";var st={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},p=new Set,o=r.webComponents?.enabled?`./${Tt.relative(Tt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",d=[];if(r.webComponents?.enabled)try{let u=await $s(r,p);if(d.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(r.cache&&r.cachePath){let v=await hr(u,r);if(v){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:v,loader:"html"}}}let y=await $e(()=>Bun.file(u).text(),"",(v)=>{throw new Or(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${v.message}`)});if(!y)throw new Or(`stx file is empty: ${u}`,u);let{scriptContent:b,templateContent:w,allScripts:S}=fe.time("script-extraction",()=>{let v=y,C=L(y);if(C)v=C.content.trim();let I=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],O="",P=[];for(let E of I){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=E.match(/<script\b([^>]*)>/i),X=B?B[1]:"";if(/\bserver\b/i.test(X))O=_;else P.push(E)}let D=v.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:O,templateContent:D,allScripts:P}}),T={__filename:u,__dirname:Tt.dirname(u),__stx:{webComponentsPath:o,builtComponents:d}};await $e(()=>h(b,T,u),void 0,(v)=>{let C=new se(`Script execution failed in ${u}: ${v.message}`,u,void 0,void 0,b.substring(0,100));if(W.log(C,{filePath:u,scriptContent:b}),r.debug)throw C});let k=await fe.timeAsync("directive-processing",async()=>await i(w,T,u,r,m));if(S.length>0){let{interpolateScriptsInTemplate:v}=await import("./chunk-h0nxd9xg.js"),C=v(S.join(`
|
|
891
|
-
`),T),I=k.search(/<\/body>/i);if(I!==-1)k=k.slice(0,I)+C+`
|
|
892
|
-
`+k.slice(I);else k+=`
|
|
893
|
-
${C}`}if(k=await _e(k),m.forEach((v)=>p.add(v)),r.cache&&r.cachePath){if(await yr(u,k,m,r),r.debug)console.log(`Cached template ${u} with ${m.size} dependencies`)}return{contents:k,loader:"html"}}catch(m){let y=m instanceof Error?m:new se(`Plugin processing failed: ${String(m)}`,u);if(W.log(y,{filePath:u,buildConfig:t.config}),Rn.logDetailedError(y,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",y);let b=y,w=b.line||null,S=b.context||null;return{contents:r.debug||Z()?`<!DOCTYPE html>
|
|
894
|
-
<html lang="en">
|
|
895
|
-
<head>
|
|
896
|
-
<meta charset="UTF-8">
|
|
897
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
898
|
-
<title>stx Rendering Error</title>
|
|
899
|
-
<style>
|
|
900
|
-
body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; }
|
|
901
|
-
.error-header { color: #dc3545; border-left: 4px solid #dc3545; padding-left: 16px; margin-bottom: 24px; }
|
|
902
|
-
.error-details { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 16px; margin: 16px 0; }
|
|
903
|
-
.error-code { background: #2d3748; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: 'Monaco', 'Menlo', monospace; font-size: 14px; }
|
|
904
|
-
.help-section { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 16px; margin-top: 24px; }
|
|
905
|
-
.file-path { font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px; }
|
|
906
|
-
</style>
|
|
907
|
-
</head>
|
|
908
|
-
<body>
|
|
909
|
-
<div class="error-header">
|
|
910
|
-
<h1>stx Template Error</h1>
|
|
911
|
-
<p>An error occurred while processing your stx template.</p>
|
|
912
|
-
</div>
|
|
913
|
-
|
|
914
|
-
<div class="error-details">
|
|
915
|
-
<h3>Error Details</h3>
|
|
916
|
-
<p><strong>File:</strong> <span class="file-path">${g(u)}</span></p>
|
|
917
|
-
<p><strong>Error:</strong> ${g(y.message)}</p>
|
|
918
|
-
${w?`<p><strong>Line:</strong> ${g(String(w))}</p>`:""}
|
|
919
|
-
${S?`<p><strong>Context:</strong> ${g(String(S))}</p>`:""}
|
|
920
|
-
</div>
|
|
921
|
-
|
|
922
|
-
${y.stack?`
|
|
923
|
-
<div class="error-details">
|
|
924
|
-
<h3>Stack Trace</h3>
|
|
925
|
-
<pre class="error-code">${g(y.stack)}</pre>
|
|
926
|
-
</div>`:""}
|
|
927
|
-
|
|
928
|
-
<div class="help-section">
|
|
929
|
-
<h3>Troubleshooting Tips</h3>
|
|
930
|
-
<ul>
|
|
931
|
-
<li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
|
|
932
|
-
<li>Verify that all variables used in the template are properly defined</li>
|
|
933
|
-
<li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
|
|
934
|
-
<li>Run <code>stx debug ${g(Tt.basename(u))}</code> for detailed analysis</li>
|
|
935
|
-
<li>Enable debug mode in your stx config for more detailed error messages</li>
|
|
936
|
-
</ul>
|
|
937
|
-
</div>
|
|
938
|
-
</body>
|
|
939
|
-
</html>`:`<!DOCTYPE html>
|
|
940
|
-
<html lang="en">
|
|
941
|
-
<head>
|
|
942
|
-
<meta charset="UTF-8">
|
|
943
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
944
|
-
<title>Error</title>
|
|
945
|
-
<style>
|
|
946
|
-
body { font-family: system-ui, -apple-system, sans-serif; max-width: 600px; margin: 80px auto; padding: 20px; text-align: center; color: #333; }
|
|
947
|
-
</style>
|
|
948
|
-
</head>
|
|
949
|
-
<body>
|
|
950
|
-
<h1>Something went wrong</h1>
|
|
951
|
-
<p>An internal error occurred. Please try again later.</p>
|
|
952
|
-
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function Kr(t,n={}){let r=n.port||3000,p=n.watch!==!1,o=n.hotReload!==!1&&p,d=null,u=n.hmrPort||r+1,m=he.resolve(t);if(!Fe.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Wt(m,n);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let y=l(process.cwd(),"output");Fe.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let b=null,w=async()=>{try{let _={name:"public-assets",setup(ve){ve.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},B=await Bun.build({entrypoints:[m],outdir:y,plugins:[_,st],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let X=B.outputs.find((ve)=>ve.path.endsWith(".html"));if(!X)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return b=await Bun.file(X.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await w())return!1;let T=he.dirname(m);await mn(T);let R=r;try{if(R=await qe(r),R!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let _=n.hmrPort||R+1;d=St({wsPort:_,verbose:!1}),u=d.start(_)}let k={},v=null,C;try{let{loadStxConfig:_}=await import("./chunk-bz1jgrx8.js"),B=await _();if(C=n.stxOptions?.serverApi??B.serverApi,B?.apiRouter)v=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){k=B.apiRoutes;let X=Object.keys(k).length;if(X>0)console.log(`${e.blue}Loaded ${e.bright}${X} API route${X>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:X,loadChannels:ee}=await import("./chunk-rqa92xm4.js"),ve=B.broadcasting;await X(ve);let pe=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${pe}/ws${e.reset}`);let Re=he.join(process.cwd(),"channels.ts");if(Fe.existsSync(Re))try{let ie=await ee(Re);console.log(`${e.blue}Loaded ${e.bright}${ie} broadcast channel${ie!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ie){console.warn(`${e.yellow}Failed to load channels.ts: ${ie.message}${e.reset}`)}}catch(X){console.warn(`${e.yellow}Broadcasting failed to start: ${X.message}${e.reset}`)}}catch{}let{createServerApi:I,isServerApiSource:O}=await import("./chunk-3asy7ev5.js"),P=await I(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let D=zr({port:R,async fetch(_){return Dn(_,await(async()=>{let B=new URL(_.url);if([y,he.dirname(m),he.join(process.cwd(),"public")].some((ie)=>O(he.join(ie,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(v)try{let ie=await v.handleRequest(_);if(ie.status!==404)return ie}catch{}if(k[B.pathname])try{return await k[B.pathname](_)}catch(ie){return new Response(JSON.stringify({error:ie.message}),{status:500,headers:{"Content-Type":"application/json"}})}let X=await P(_);if(X)return X;if(B.pathname==="/")return(async()=>{let U=await x(b||"");if(o)U=We(U,u);if(n.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(n.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 ee=he.join(y,B.pathname);if(Fe.existsSync(ee)&&Fe.statSync(ee).isFile()){let ie=Bun.file(ee),U=he.extname(ee).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ie.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{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(ie,{headers:{"Content-Type":j}})}let ve=he.dirname(m),pe=he.join(ve,B.pathname);if(Fe.existsSync(pe)&&Fe.statSync(pe).isFile()){let ie=Bun.file(pe),U=he.extname(pe).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ie.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{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(ie,{headers:{"Content-Type":j}})}let Re=he.join(process.cwd(),"public",B.pathname);if(Fe.existsSync(Re)&&Fe.statSync(Re).isFile()){let ie=Bun.file(Re),U=he.extname(Re).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let ze=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ie.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{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(ie,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
954
|
-
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
|
-
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
957
|
-
${e.yellow}Routes:${e.reset}`);let E=he.relative(process.cwd(),m);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
|
|
958
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(D.url.toString(),()=>{if(p)Fe.watch(he.dirname(m),{recursive:!0}).close();D.stop()}),n.native){let _=await Bun.file(m).text(),B=yt(_);await et(R,{title:he.basename(m,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(p){let _=he.dirname(m);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let B=Fe.watch(_,{recursive:!0},async(X,ee)=>{if(!ee||vt(ee))return;if(xt(ee)){console.log(`${e.yellow}File ${e.bright}${ee}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),be();let ve=await w();if(await dr(T),o&&d)if(ve)d.reload(ee);else d.error("Build failed - check console for details")}else if(bt(ee)){if(console.log(`${e.cyan}CSS ${e.bright}${ee}${e.cyan} changed${e.reset}`),o&&d)d.updateCss(ee)}});process.on("SIGINT",()=>{if(B.close(),d)ct();D.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Ce from"path";var ln=`
|
|
959
|
-
<script data-stx-helpers>
|
|
960
|
-
(function() {
|
|
961
|
-
'use strict'
|
|
962
|
-
|
|
963
|
-
if (window.__stxHelpers) return
|
|
964
|
-
window.__stxHelpers = true
|
|
965
|
-
|
|
966
|
-
window.stx = window.stx || {}
|
|
967
|
-
|
|
968
|
-
// ===== FORMATTERS =====
|
|
969
|
-
|
|
970
|
-
stx.formatCurrency = function(val, currency, locale) {
|
|
971
|
-
return new Intl.NumberFormat(locale || 'en-US', {
|
|
972
|
-
style: 'currency',
|
|
973
|
-
currency: currency || 'USD',
|
|
974
|
-
}).format(val)
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
stx.formatNumber = function(val, decimals, locale) {
|
|
978
|
-
var opts = {}
|
|
979
|
-
if (typeof decimals === 'number') {
|
|
980
|
-
opts.minimumFractionDigits = decimals
|
|
981
|
-
opts.maximumFractionDigits = decimals
|
|
982
|
-
}
|
|
983
|
-
return new Intl.NumberFormat(locale || 'en-US', opts).format(val)
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
stx.formatDate = function(val, format, locale) {
|
|
987
|
-
locale = locale || 'en-US'
|
|
988
|
-
var d = val instanceof Date ? val : new Date(val)
|
|
989
|
-
if (isNaN(d.getTime())) return String(val)
|
|
990
|
-
|
|
991
|
-
if (format === 'long') return d.toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' })
|
|
992
|
-
if (format === 'relative') {
|
|
993
|
-
var diff = Date.now() - d.getTime()
|
|
994
|
-
var mins = Math.floor(diff / 60000)
|
|
995
|
-
if (mins < 1) return 'just now'
|
|
996
|
-
if (mins < 60) return mins + 'm ago'
|
|
997
|
-
var hrs = Math.floor(mins / 60)
|
|
998
|
-
if (hrs < 24) return hrs + 'h ago'
|
|
999
|
-
var days = Math.floor(hrs / 24)
|
|
1000
|
-
if (days < 7) return days + 'd ago'
|
|
1001
|
-
return d.toLocaleDateString(locale)
|
|
1002
|
-
}
|
|
1003
|
-
return d.toLocaleDateString(locale)
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
stx.formatPhone = function(phone) {
|
|
1007
|
-
var n = String(phone).replace(/\\D/g, '')
|
|
1008
|
-
if (n.length === 10) return \`(\${n.slice(0,3)}) \${n.slice(3,6)}-\${n.slice(6)}\`
|
|
1009
|
-
if (n.length === 11 && n[0] === '1') return \`+1 (\${n.slice(1,4)}) \${n.slice(4,7)}-\${n.slice(7)}\`
|
|
1010
|
-
return phone
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
stx.renderStars = function(rating, max) {
|
|
1014
|
-
max = max || 5
|
|
1015
|
-
var full = Math.floor(rating)
|
|
1016
|
-
var half = rating - full >= 0.5
|
|
1017
|
-
var h = ''
|
|
1018
|
-
for (var i = 0; i < max; i++) {
|
|
1019
|
-
if (i < full || (i === full && half))
|
|
1020
|
-
h += '<span style="color: var(--badge-amber-text, #f59e0b)">\\u2605</span>'
|
|
1021
|
-
else
|
|
1022
|
-
h += '<span style="color: var(--text-muted, #6b7280)">\\u2606</span>'
|
|
1023
|
-
}
|
|
1024
|
-
return h
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
// ===== BADGE SYSTEM =====
|
|
1028
|
-
|
|
1029
|
-
var badgeMaps = {
|
|
1030
|
-
status: {
|
|
1031
|
-
'Active Repair': 'badge-amber', 'Completed': 'badge-emerald',
|
|
1032
|
-
'Pending Pickup': 'badge-blue', 'Pending Estimate': 'badge-slate',
|
|
1033
|
-
'Approved': 'badge-emerald', 'In Review': 'badge-blue',
|
|
1034
|
-
'Supplement': 'badge-amber', 'Draft': 'badge-slate', 'Rejected': 'badge-red',
|
|
1035
|
-
'Delivered': 'badge-emerald', 'Shipped': 'badge-blue', 'Processing': 'badge-amber',
|
|
1036
|
-
'In Stock': 'badge-emerald', 'Backordered': 'badge-red', 'Low Stock': 'badge-amber',
|
|
1037
|
-
},
|
|
1038
|
-
priority: { 'Rush': 'badge-red', 'High': 'badge-amber', 'Normal': 'badge-blue', 'Low': 'badge-slate' },
|
|
1039
|
-
severity: { 'light': 'severity-light', 'moderate': 'severity-moderate', 'heavy': 'severity-heavy' },
|
|
1040
|
-
type: { 'OEM': 'badge-blue', 'Aftermarket': 'badge-amber', 'Recycled': 'badge-emerald', 'Reman': 'badge-slate' },
|
|
1041
|
-
drp: { 'Active DRP': 'badge-emerald', 'Preferred': 'badge-blue', 'Standard': 'badge-slate' },
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
stx.registerBadgeMap = function(name, map) {
|
|
1045
|
-
badgeMaps[name] = Object.assign(badgeMaps[name] || {}, map)
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
stx.badgeClass = function(value, mapName) {
|
|
1049
|
-
var map = badgeMaps[mapName || 'status'] || badgeMaps.status
|
|
1050
|
-
return map[value] || 'badge-slate'
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
stx.badge = function(value, mapName) {
|
|
1054
|
-
return \`<span class="inline-flex px-2.5 py-1 rounded-full text-xs font-medium \${stx.badgeClass(value, mapName)}">\${value}</span>\`
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
// ===== DETAIL PANEL BUILDER =====
|
|
1058
|
-
|
|
1059
|
-
function esc(v) { return v != null ? v : '\\u2014' }
|
|
1060
|
-
|
|
1061
|
-
stx.detail = {
|
|
1062
|
-
panel: function(opts) {
|
|
1063
|
-
if (!opts || !opts.title) return ''
|
|
1064
|
-
var badges = ''
|
|
1065
|
-
if (opts.badges) {
|
|
1066
|
-
opts.badges.forEach(function(b) { badges += stx.badge(b.text, b.map) })
|
|
1067
|
-
}
|
|
1068
|
-
return \`
|
|
1069
|
-
<div style="display:flex;align-items:center;justify-content:space-between;padding:1.25rem 1.5rem;border-bottom:1px solid var(--border-main)">
|
|
1070
|
-
<div>
|
|
1071
|
-
<h2 style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${opts.title}</h2>
|
|
1072
|
-
\${opts.subtitle ? \`<p style="font-size:0.75rem;color:var(--text-muted);margin-top:0.25rem">\${opts.subtitle}</p>\` : ''}
|
|
1073
|
-
</div>
|
|
1074
|
-
<div style="display:flex;align-items:center;gap:0.75rem">
|
|
1075
|
-
\${badges}
|
|
1076
|
-
<button onclick="closeSlideOver()" style="padding:0.5rem;border-radius:0.5rem;color:var(--text-muted);background:none;border:none;cursor:pointer;font-size:1.5rem;line-height:1" aria-label="Close">×</button>
|
|
1077
|
-
</div>
|
|
1078
|
-
</div>\`
|
|
1079
|
-
},
|
|
1080
|
-
|
|
1081
|
-
section: function(label, rows) {
|
|
1082
|
-
var inner = ''
|
|
1083
|
-
if (rows) {
|
|
1084
|
-
if (!Array.isArray(rows) && typeof rows === 'object') {
|
|
1085
|
-
Object.keys(rows).forEach(function(k) { inner += stx.detail.row(k, rows[k]) })
|
|
1086
|
-
}
|
|
1087
|
-
else {
|
|
1088
|
-
rows.forEach(function(r) {
|
|
1089
|
-
if (Array.isArray(r)) inner += stx.detail.row(r[0], r[1])
|
|
1090
|
-
else inner += stx.detail.row(r.label, r.value)
|
|
1091
|
-
})
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
return \`
|
|
1095
|
-
<div class="detail-section">
|
|
1096
|
-
<div class="detail-label">\${label}</div>
|
|
1097
|
-
\${inner}
|
|
1098
|
-
</div>\`
|
|
1099
|
-
},
|
|
1100
|
-
|
|
1101
|
-
row: function(label, value) {
|
|
1102
|
-
return \`
|
|
1103
|
-
<div class="detail-row">
|
|
1104
|
-
<span class="detail-row-label">\${label}</span>
|
|
1105
|
-
<span class="detail-row-value">\${esc(value)}</span>
|
|
1106
|
-
</div>\`
|
|
1107
|
-
},
|
|
1108
|
-
|
|
1109
|
-
stats: function(items) {
|
|
1110
|
-
var list = Array.isArray(items)
|
|
1111
|
-
? items
|
|
1112
|
-
: Object.keys(items).map(function(k) { return { label: k, value: items[k] } })
|
|
1113
|
-
|
|
1114
|
-
var cards = list.map(function(item) {
|
|
1115
|
-
return \`
|
|
1116
|
-
<div style="padding:0.75rem;border-radius:0.5rem;background:var(--bg-subtle);text-align:center">
|
|
1117
|
-
<div style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${item.value}</div>
|
|
1118
|
-
<div style="font-size:0.6875rem;color:var(--text-muted);margin-top:0.25rem">\${item.label}</div>
|
|
1119
|
-
</div>\`
|
|
1120
|
-
}).join('')
|
|
1121
|
-
|
|
1122
|
-
return \`<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:0.75rem;padding:0 1.5rem 1rem">\${cards}</div>\`
|
|
1123
|
-
},
|
|
1124
|
-
|
|
1125
|
-
timeline: function(items) {
|
|
1126
|
-
var entries = items.map(function(item, i) {
|
|
1127
|
-
var color = item.color || 'var(--text-accent)'
|
|
1128
|
-
var isLast = i === items.length - 1
|
|
1129
|
-
|
|
1130
|
-
return \`
|
|
1131
|
-
<div style="display:flex;gap:0.75rem">
|
|
1132
|
-
<div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0">
|
|
1133
|
-
<div style="width:10px;height:10px;border-radius:50%;background:\${color};flex-shrink:0"></div>
|
|
1134
|
-
\${!isLast ? '<div style="width:2px;flex:1;background:var(--bar-track);min-height:24px"></div>' : ''}
|
|
1135
|
-
</div>
|
|
1136
|
-
<div style="padding-bottom:\${isLast ? '0' : '1rem'};flex:1">
|
|
1137
|
-
<div style="font-size:0.8125rem;font-weight:500;color:var(--text-primary)">\${item.title}</div>
|
|
1138
|
-
\${item.description ? \`<div style="font-size:0.75rem;color:var(--text-muted);margin-top:0.125rem">\${item.description}</div>\` : ''}
|
|
1139
|
-
\${item.meta ? \`<div style="font-size:0.6875rem;color:var(--text-tertiary);margin-top:0.25rem">\${item.meta}</div>\` : ''}
|
|
1140
|
-
</div>
|
|
1141
|
-
</div>\`
|
|
1142
|
-
}).join('')
|
|
1143
|
-
|
|
1144
|
-
return \`<div style="padding:0 1.5rem 1rem">\${entries}</div>\`
|
|
1145
|
-
},
|
|
1146
|
-
|
|
1147
|
-
open: function(html) {
|
|
1148
|
-
if (typeof openSlideOver === 'function') openSlideOver(html)
|
|
1149
|
-
},
|
|
1150
|
-
}
|
|
1151
|
-
|
|
1152
|
-
// ===== DATA TABLE HELPERS =====
|
|
1153
|
-
|
|
1154
|
-
stx.table = {
|
|
1155
|
-
filter: function(opts) {
|
|
1156
|
-
var searchEl = document.getElementById(opts.searchId)
|
|
1157
|
-
var search = searchEl ? searchEl.value.toLowerCase() : ''
|
|
1158
|
-
var rows = document.querySelectorAll(opts.rowSelector || 'tbody tr')
|
|
1159
|
-
var filters = opts.filters || []
|
|
1160
|
-
var matched = []
|
|
1161
|
-
|
|
1162
|
-
rows.forEach(function(row) {
|
|
1163
|
-
var text = row.textContent.toLowerCase()
|
|
1164
|
-
var matchSearch = !search || text.indexOf(search) !== -1
|
|
1165
|
-
var matchFilters = filters.every(function(f) {
|
|
1166
|
-
var el = document.getElementById(f.id)
|
|
1167
|
-
if (!el) return true
|
|
1168
|
-
var val = el.value
|
|
1169
|
-
if (!val || val === f.allValue) return true
|
|
1170
|
-
return row.getAttribute(\`data-\${f.attr}\`) === val
|
|
1171
|
-
})
|
|
1172
|
-
|
|
1173
|
-
if (matchSearch && matchFilters) matched.push(row)
|
|
1174
|
-
else row.style.display = 'none'
|
|
1175
|
-
})
|
|
1176
|
-
|
|
1177
|
-
return matched
|
|
1178
|
-
},
|
|
1179
|
-
|
|
1180
|
-
sort: function(rows, sortBy, direction) {
|
|
1181
|
-
direction = direction || 'asc'
|
|
1182
|
-
return rows.slice().sort(function(a, b) {
|
|
1183
|
-
var aVal = a.getAttribute(\`data-\${sortBy}\`) || a.textContent
|
|
1184
|
-
var bVal = b.getAttribute(\`data-\${sortBy}\`) || b.textContent
|
|
1185
|
-
var aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''))
|
|
1186
|
-
var bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''))
|
|
1187
|
-
if (!isNaN(aNum) && !isNaN(bNum)) return direction === 'asc' ? aNum - bNum : bNum - aNum
|
|
1188
|
-
return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
|
|
1189
|
-
})
|
|
1190
|
-
},
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
// ===== PAGINATION =====
|
|
1194
|
-
|
|
1195
|
-
stx.pagination = function(opts) {
|
|
1196
|
-
var page = opts.page || 1
|
|
1197
|
-
var perPage = opts.perPage || 10
|
|
1198
|
-
var items = opts.items || []
|
|
1199
|
-
var total = items.length
|
|
1200
|
-
var totalPages = Math.max(1, Math.ceil(total / perPage))
|
|
1201
|
-
if (page > totalPages) page = totalPages
|
|
1202
|
-
|
|
1203
|
-
var start = (page - 1) * perPage
|
|
1204
|
-
var end = Math.min(start + perPage, total)
|
|
1205
|
-
|
|
1206
|
-
items.forEach(function(el, i) { el.style.display = (i >= start && i < end) ? '' : 'none' })
|
|
1207
|
-
|
|
1208
|
-
var ids = { count: opts.countId, total: opts.totalId, empty: opts.emptyId, bar: opts.barId }
|
|
1209
|
-
if (ids.count) { var el = document.getElementById(ids.count); if (el) el.textContent = total === 0 ? '0' : \`\${start + 1}\\u2013\${end}\` }
|
|
1210
|
-
if (ids.total) { var el = document.getElementById(ids.total); if (el) el.textContent = total }
|
|
1211
|
-
if (ids.empty) { var el = document.getElementById(ids.empty); if (el) el.style.display = total === 0 ? 'block' : 'none' }
|
|
1212
|
-
if (ids.bar) { var el = document.getElementById(ids.bar); if (el) el.style.display = total === 0 ? 'none' : '' }
|
|
1213
|
-
|
|
1214
|
-
if (opts.buttonsId) {
|
|
1215
|
-
var wrap = document.getElementById(opts.buttonsId)
|
|
1216
|
-
if (wrap) {
|
|
1217
|
-
var go = opts.goToPage
|
|
1218
|
-
var pages = stx.pagination.getPages(page, totalPages)
|
|
1219
|
-
|
|
1220
|
-
var btn = function(label, target, disabled) {
|
|
1221
|
-
return \`<button onclick="\${go}(\${target})" \${disabled ? 'disabled' : ''}
|
|
1222
|
-
class="px-3 py-1.5 rounded-lg text-sm cursor-pointer"
|
|
1223
|
-
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>\`
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
var h = btn('Previous', page - 1, page === 1)
|
|
1227
|
-
pages.forEach(function(p) {
|
|
1228
|
-
if (p === '...') {
|
|
1229
|
-
h += '<span class="px-2 text-sm" style="color:var(--text-muted)">\\u2026</span>'
|
|
1230
|
-
}
|
|
1231
|
-
else if (p === page) {
|
|
1232
|
-
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>\`
|
|
1233
|
-
}
|
|
1234
|
-
else {
|
|
1235
|
-
h += btn(p, p, false)
|
|
1236
|
-
}
|
|
1237
|
-
})
|
|
1238
|
-
h += btn('Next', page + 1, page === totalPages)
|
|
1239
|
-
wrap.innerHTML = h
|
|
1240
|
-
}
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
return { page: page, totalPages: totalPages, total: total, start: start, end: end }
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
stx.pagination.getPages = function(current, total) {
|
|
1247
|
-
if (total <= 7) return Array.from({ length: total }, function(_, i) { return i + 1 })
|
|
1248
|
-
var pages = [1]
|
|
1249
|
-
if (current > 3) pages.push('...')
|
|
1250
|
-
for (var i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) pages.push(i)
|
|
1251
|
-
if (current < total - 2) pages.push('...')
|
|
1252
|
-
pages.push(total)
|
|
1253
|
-
return pages
|
|
1254
|
-
}
|
|
1255
|
-
|
|
1256
|
-
// ===== UTILITIES =====
|
|
1257
|
-
|
|
1258
|
-
stx.debounce = function(fn, delay) {
|
|
1259
|
-
var timer
|
|
1260
|
-
return function() {
|
|
1261
|
-
var args = arguments, ctx = this
|
|
1262
|
-
clearTimeout(timer)
|
|
1263
|
-
timer = setTimeout(function() { fn.apply(ctx, args) }, delay || 250)
|
|
1264
|
-
}
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
})()
|
|
1268
|
-
</script>
|
|
1269
|
-
`;function pn(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((p)=>p.split(Ce.sep)),r=[];for(let p=0;p<n[0].length;p++){let o=n[0][p];if(n.every((d)=>d[p]===o))r.push(o);else break}return r.join(Ce.sep)}async function Gr(t,n={}){let r=n.port||3000,p=n.watch!==!1;for(let k of t){let v=Ce.resolve(k);if(!Xe.existsSync(v))return console.error(`${e.red}Error: File not found: ${e.bright}${v}${e.reset}`),!1;if(!v.endsWith(".stx")&&!v.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${v}${e.reset}. Only .stx and .md files are supported.`),!1}let o=l(process.cwd(),"output");Xe.mkdirSync(o,{recursive:!0});let d=pn(t.map((k)=>Ce.dirname(Ce.resolve(k))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},m=[],y=async()=>{try{for(let k of t){let v=Ce.resolve(k);if(v.endsWith(".md"))try{let{content:I,data:O}=await Ne(v,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:M.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),P=n.markdown?.syntaxHighlighting||M.markdown?.syntaxHighlighting,D=P?.defaultTheme||"github-dark",E=["github-dark"],_=P?.additionalThemes||[],X=[...new Set([...E,..._])].map((Re)=>`<option value="${Re}"${Re===D?" selected":""}>${Re}</option>`).join(`
|
|
1270
|
-
`),ee=`
|
|
1271
|
-
<!DOCTYPE html>
|
|
1272
|
-
<html lang="en">
|
|
1273
|
-
<head>
|
|
1274
|
-
<meta charset="UTF-8">
|
|
1275
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1276
|
-
<title>${dn(O.title||Ce.basename(v))}</title>
|
|
1277
|
-
<!-- Syntax highlighting styles -->
|
|
1278
|
-
<style id="syntax-theme">
|
|
1279
|
-
:root {
|
|
1280
|
-
--shiki-color-text: #24292e;
|
|
1281
|
-
--shiki-color-background: #ffffff;
|
|
1282
|
-
--shiki-token-constant: #005cc5;
|
|
1283
|
-
--shiki-token-string: #032f62;
|
|
1284
|
-
--shiki-token-comment: #6a737d;
|
|
1285
|
-
--shiki-token-keyword: #d73a49;
|
|
1286
|
-
--shiki-token-parameter: #24292e;
|
|
1287
|
-
--shiki-token-function: #6f42c1;
|
|
1288
|
-
--shiki-token-string-expression: #032f62;
|
|
1289
|
-
--shiki-token-punctuation: #24292e;
|
|
1290
|
-
--shiki-token-link: #032f62;
|
|
1291
|
-
}
|
|
1292
|
-
pre {
|
|
1293
|
-
background-color: var(--shiki-color-background);
|
|
1294
|
-
padding: 1rem;
|
|
1295
|
-
border-radius: 4px;
|
|
1296
|
-
}
|
|
1297
|
-
code {
|
|
1298
|
-
color: var(--shiki-color-text);
|
|
1299
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1300
|
-
}
|
|
1301
|
-
.dark-mode {
|
|
1302
|
-
--shiki-color-text: #e1e4e8;
|
|
1303
|
-
--shiki-color-background: #24292e;
|
|
1304
|
-
--shiki-token-constant: #79b8ff;
|
|
1305
|
-
--shiki-token-string: #9ecbff;
|
|
1306
|
-
--shiki-token-comment: #6a737d;
|
|
1307
|
-
--shiki-token-keyword: #f97583;
|
|
1308
|
-
--shiki-token-parameter: #e1e4e8;
|
|
1309
|
-
--shiki-token-function: #b392f0;
|
|
1310
|
-
--shiki-token-string-expression: #9ecbff;
|
|
1311
|
-
--shiki-token-punctuation: #e1e4e8;
|
|
1312
|
-
--shiki-token-link: #9ecbff;
|
|
1313
|
-
}
|
|
1314
|
-
</style>
|
|
1315
|
-
<style>
|
|
1316
|
-
body {
|
|
1317
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
|
|
1318
|
-
line-height: 1.6;
|
|
1319
|
-
color: #333;
|
|
1320
|
-
max-width: 800px;
|
|
1321
|
-
margin: 0 auto;
|
|
1322
|
-
padding: 2rem;
|
|
1323
|
-
}
|
|
1324
|
-
pre, code {
|
|
1325
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1326
|
-
}
|
|
1327
|
-
pre {
|
|
1328
|
-
border-radius: 4px;
|
|
1329
|
-
padding: 0;
|
|
1330
|
-
margin: 1.5rem 0;
|
|
1331
|
-
overflow-x: auto;
|
|
1332
|
-
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
|
1333
|
-
}
|
|
1334
|
-
pre code {
|
|
1335
|
-
display: block;
|
|
1336
|
-
padding: 1rem;
|
|
1337
|
-
overflow-x: auto;
|
|
1338
|
-
}
|
|
1339
|
-
/* Apply background color to code blocks based on theme */
|
|
1340
|
-
pre.syntax-highlighter {
|
|
1341
|
-
background-color: var(--shiki-color-background) !important;
|
|
1342
|
-
}
|
|
1343
|
-
.dark-mode pre.syntax-highlighter {
|
|
1344
|
-
background-color: var(--shiki-color-background) !important;
|
|
1345
|
-
}
|
|
1346
|
-
code {
|
|
1347
|
-
padding: 0.2rem 0.4rem;
|
|
1348
|
-
border-radius: 3px;
|
|
1349
|
-
}
|
|
1350
|
-
h1, h2, h3, h4 {
|
|
1351
|
-
margin-top: 2rem;
|
|
1352
|
-
margin-bottom: 1rem;
|
|
1353
|
-
}
|
|
1354
|
-
h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
|
|
1355
|
-
h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
|
|
1356
|
-
h3 { color: #444; }
|
|
1357
|
-
img {
|
|
1358
|
-
max-width: 100%;
|
|
1359
|
-
border-radius: 4px;
|
|
1360
|
-
margin: 1rem 0;
|
|
1361
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
1362
|
-
}
|
|
1363
|
-
blockquote {
|
|
1364
|
-
border-left: 4px solid #ddd;
|
|
1365
|
-
padding-left: 1rem;
|
|
1366
|
-
margin-left: 0;
|
|
1367
|
-
color: #555;
|
|
1368
|
-
background: #f9f9f9;
|
|
1369
|
-
padding: 0.5rem 1rem;
|
|
1370
|
-
margin: 1.5rem 0;
|
|
1371
|
-
}
|
|
1372
|
-
table {
|
|
1373
|
-
border-collapse: collapse;
|
|
1374
|
-
width: 100%;
|
|
1375
|
-
margin: 1.5rem 0;
|
|
1376
|
-
}
|
|
1377
|
-
th, td {
|
|
1378
|
-
border: 1px solid #ddd;
|
|
1379
|
-
padding: 0.5rem;
|
|
1380
|
-
}
|
|
1381
|
-
th {
|
|
1382
|
-
background: #f0f0f0;
|
|
1383
|
-
text-align: left;
|
|
1384
|
-
}
|
|
1385
|
-
tr:nth-child(even) {
|
|
1386
|
-
background-color: #f8f8f8;
|
|
1387
|
-
}
|
|
1388
|
-
a {
|
|
1389
|
-
color: #0066cc;
|
|
1390
|
-
text-decoration: none;
|
|
1391
|
-
}
|
|
1392
|
-
a:hover {
|
|
1393
|
-
text-decoration: underline;
|
|
1394
|
-
}
|
|
1395
|
-
hr {
|
|
1396
|
-
border: 0;
|
|
1397
|
-
border-top: 1px solid #eee;
|
|
1398
|
-
margin: 2rem 0;
|
|
1399
|
-
}
|
|
1400
|
-
.frontmatter {
|
|
1401
|
-
background: #f8f8f8;
|
|
1402
|
-
border-radius: 4px;
|
|
1403
|
-
padding: 1.5rem;
|
|
1404
|
-
margin-bottom: 2rem;
|
|
1405
|
-
font-size: 0.9rem;
|
|
1406
|
-
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
|
1407
|
-
border-left: 4px solid #ddd;
|
|
1408
|
-
}
|
|
1409
|
-
.frontmatter-item {
|
|
1410
|
-
margin-bottom: 0.5rem;
|
|
1411
|
-
display: flex;
|
|
1412
|
-
}
|
|
1413
|
-
.frontmatter-label {
|
|
1414
|
-
font-weight: bold;
|
|
1415
|
-
min-width: 100px;
|
|
1416
|
-
color: #555;
|
|
1417
|
-
}
|
|
1418
|
-
${ft()}
|
|
1419
|
-
</style>
|
|
1420
|
-
</head>
|
|
1421
|
-
<body>
|
|
1422
|
-
${ht(O)}
|
|
1423
|
-
${mt(X)}
|
|
1424
|
-
|
|
1425
|
-
${I}
|
|
1426
|
-
|
|
1427
|
-
<script>
|
|
1428
|
-
${gt()}
|
|
1429
|
-
</script>
|
|
1430
|
-
</body>
|
|
1431
|
-
</html>
|
|
1432
|
-
`,pe=`/${Ce.relative(d,v).replace(/\.md$/,"")}`;if(pe.endsWith("/index"))pe=pe.slice(0,-6)||"/";u[pe||"/"]={filePath:v,content:ee,fileType:"md"}}catch(I){console.error(`${e.red}Error processing Markdown file ${e.bright}${k}${e.reset}:`,I);continue}else{let I={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(_)=>({path:_.path,external:!0}))}},O;try{let E=await Bun.build({entrypoints:[v],outdir:o,plugins:[I,st],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${k}${e.reset}:`,Oe(E.logs,v));continue}let _=E.outputs.find((B)=>B.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${k}${e.reset}`);continue}O=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${k}${e.reset}:
|
|
1433
|
-
${Oe(E,v)}`);continue}let D=`/${Ce.relative(d,v).replace(/\.stx$/,"")}`;if(D.endsWith("/index"))D=D.slice(0,-6)||"/";if(D.includes("[")){let{regex:E,params:_}=Ns(D,{page:!0});m.push({pattern:E,paramNames:_,filePath:v,routeTemplate:D,fileType:"stx"}),u[D]={filePath:v,content:O,fileType:"stx"}}else u[D||"/"]={filePath:v,content:O,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(k){return console.error(`${e.red}Error processing files:${e.reset}`,Oe(k)),!1}};if(!await y())return!1;let w=r;try{if(w=await qe(r),w!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${w} 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:${w}/${e.reset}...`);let S=Nr({port:w,async fetch(k){let v=new URL(k.url),C=Ce.join(process.cwd(),"public",v.pathname);if(Xe.existsSync(C)&&Xe.statSync(C).isFile()){let P=Bun.file(C),D=Ce.extname(C).toLowerCase(),E="application/octet-stream";if(D===".ts"||D===".tsx"){let _=new Bun.Transpiler({loader:D===".tsx"?"tsx":"ts"}),B=await P.text(),X=_.transformSync(B);return new Response(X,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(D){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(P,{headers:{"Content-Type":E}})}let I=u[v.pathname];if(!I&&!v.pathname.endsWith("/"))I=u[`${v.pathname}/`];if(!I)for(let P of m){let D=v.pathname.match(P.pattern);if(D){let E=u[P.routeTemplate];if(E){let _={};for(let ee=0;ee<P.paramNames.length;ee++)_[P.paramNames[ee]]=decodeURIComponent(D[ee+1]);let B=E.content,X=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(B.includes("</head>"))B=f(B,X);else B=X+B;I={...E,content:B}}break}}if(I)return x(I.content).then((P)=>{if(P.includes("</head>"))P=f(P,ln);return new Response(P,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let O=Ce.join(o,v.pathname);if(Xe.existsSync(O)&&Xe.statSync(O).isFile()){let P=Bun.file(O),D=Ce.extname(O).toLowerCase(),E="text/plain";if(D===".ts"||D===".tsx"){let _=new Bun.Transpiler({loader:D===".tsx"?"tsx":"ts"}),B=await P.text(),X=_.transformSync(B);return new Response(X,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(D){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(P,{headers:{"Content-Type":E}})}if(v.pathname!=="/"&&u["/"]){let P=Ae(k);return x(u["/"].content).then((D)=>{if(P){let E=D.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=D.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=_?_[1]:"",X=`<!DOCTYPE html><html><head><title>${dn(B)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(X,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...H(),"Cache-Control":wt,Pragma:"no-cache",Expires:"0"}})}}return new Response(D,{headers:{"Content-Type":"text/html",...H(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(k){return new Response(`<pre>${k}
|
|
1434
|
-
${k.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1435
|
-
${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(`
|
|
1436
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${w}/${e.reset}`),console.log(`
|
|
1437
|
-
${e.yellow}Routes:${e.reset}`);let T=new Set(m.map((k)=>k.routeTemplate)),R=Object.entries(u).filter(([k])=>!T.has(k)).sort(([k],[v])=>k.localeCompare(v)).map(([k,v])=>({route:k==="/"?"/":k,filePath:Ce.relative(process.cwd(),v.filePath),fileType:v.fileType}));for(let k of m){let v=k.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:v,filePath:Ce.relative(process.cwd(),k.filePath),fileType:"stx"})}if(R.sort((k,v)=>k.route.localeCompare(v.route)),R.forEach((k,v)=>{let I=v===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",O=k.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${I}${k.route}${e.reset} \u2192 ${e.bright}${k.filePath}${e.reset} ${O}`)}),console.log(`
|
|
1438
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(S.url.toString(),()=>{if(p)Xe.watch(d,{recursive:!0}).close();S.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let k=Xe.watch(d,{recursive:!0},async(v,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),be(),await y()});process.on("SIGINT",()=>{k.close(),S.stop(),process.exit(0)})}return!0}function dn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Ur}=globalThis.Bun;import ge from"fs";import oe from"path";async function un(t){try{return vn(await Bun.file(t).text())}catch{return}}function Vt(t){let n=Bun.file(t),r=oe.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"},d=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":p[r]||"application/octet-stream",...d}})}async function Xr(t=".",n={}){let r=n.port||3000,p=n.watch!==!1,o=n.hotReload!==!1&&p,d=null,u=n.hmrPort||r+1,m=oe.resolve(t),{loadStxConfig:y}=await import("./chunk-bz1jgrx8.js"),b=await y(m),{createServerApi:w,isServerApiSource:S}=await import("./chunk-3asy7ev5.js"),T=n.stxOptions?.serverApi??b.serverApi,R=await w(m,T),k=b.root&&b.root!=="."?oe.join(m,b.root):m,v=n.pagesDir||b.pagesDir||"pages",C=oe.join(k,v);if(!ge.existsSync(C)&&!b._layerPageDirs?.some((A)=>ge.existsSync(A)))return console.error(`${e.red}Error: No '${v}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${v}/index.stx for the homepage.${e.reset}`),!1;let I=Q(k,{pagesDir:v,pagesDirs:b._layerPageDirs?[C,...b._layerPageDirs.slice(1)]:void 0});if(I.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${I.length}${e.blue} routes${e.reset}`);let O=b?._pluginPageDirs||[],P=[];for(let{dir:A,prefix:F}of O)if(ge.existsSync(A)){let V=Q(oe.dirname(A),{pagesDir:oe.basename(A)});for(let te of V){let G=F==="/"?te.pattern:`${F}${te.pattern==="/"?"":te.pattern}`;P.push({route:{...te,pattern:G},prefix:F})}if(V.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${V.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let D=new Map,E=null,_=null;if(n.stxOptions?.shell!==!1){if(_=await wa(m,n.stxOptions?.shell),_){if(E=await So(_,n.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(m,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Rt(),await Pt(m);let B=At();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let X={},ee=null;try{let{loadStxConfig:A}=await import("./chunk-bz1jgrx8.js"),F=await A(m);if(F?.apiRouter)ee=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){X=F.apiRoutes;let V=Object.keys(X).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:te}=await import("./chunk-rqa92xm4.js"),G=F.broadcasting;await V(G);let Ee=G.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ee}/ws${e.reset}`);let we=oe.join(process.cwd(),"channels.ts");if(ge.existsSync(we))try{let q=await te(we);console.log(`${e.blue}Loaded ${e.bright}${q} broadcast channel${q!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(q){console.warn(`${e.yellow}Failed to load channels.ts: ${q.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let ve=l(m,"output");ge.mkdirSync(ve,{recursive:!0});let pe=new Map,Re=new Set,ie=async(A)=>{let F=Ds(C,A);if(!F)return null;try{let V=await Bun.build({entrypoints:[F],outdir:ve,plugins:[st],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!V.success)return null;let te=V.outputs.find((G)=>G.path.endsWith(".html"));if(!te)return null;return await Bun.file(te.path).text()}catch{return null}},U=new Map,j=async(A,F)=>{try{let{processDirectives:V,extractVariables:te,defaultConfig:G,loadStxConfig:Ee,injectRouterScript:we}=await import("./chunk-bz1jgrx8.js"),{checkCache:q,cacheTemplate:Y,readFileCached:K,templateCache:ue}=await import("./chunk-m1a3a32y.js"),J=await Ee(m),Ve=(le)=>{if(!le)return le;if(oe.isAbsolute(le))return le;return oe.resolve(m,le)},de={...G,...J,...n.stxOptions,autoShell:!0};if(n.debugDirectives)de.debug=!0;de.partialsDir=Ve(de.partialsDir),de.componentsDir=Ve(de.componentsDir),de.layoutsDir=Ve(de.layoutsDir),de.storesDir=Ve(de.storesDir||"stores"),de.cachePath=Ve(de.cachePath)??l(m,"cache");let z=!F&&!n.profile,ae=de.cache!==!1;if(ae&&z){let le=ue.get(A.filePath);if(le)try{if((await ge.promises.stat(A.filePath)).mtime.getTime()<=le.mtime){let He=!0;for(let Se of le.dependencies){if(!ge.existsSync(Se)){He=!1;break}if((await ge.promises.stat(Se)).mtime.getTime()>le.mtime){He=!1;break}}if(He){let Se=le.output;if(E)Se=Je(Se,{preserveHead:!0});let at=U.get(A.filePath);return{route:A,content:Se,status:at?.status??await un(A.filePath),headers:at?.headers}}}}catch{}let je=await q(A.filePath,de);if(je){let Be=je;if(E)Be=Je(Be,{preserveHead:!0});let He=U.get(A.filePath);return{route:A,content:Be,status:He?.status??await un(A.filePath),headers:He?.headers}}}let ne=ae?await K(A.filePath):await Bun.file(A.filePath).text(),ce=vn(ne),{classifyAllScripts:me}=await import("./chunk-bz1jgrx8.js"),N=me(ne),Ie=N.server.map((le)=>le.content),Me=ne;for(let le of N.server)Me=Me.replace(le.fullTag,"");let re={__filename:A.filePath,__dirname:oe.dirname(A.filePath),__stx_options:de,params:F??{},__stx_runtime_head:{}};for(let le of Ie)try{await te(le,re,A.filePath)}catch(je){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,je?.message||je)}let De=new Set,ye;if(n.profile){let le=performance.now();ye=await V(Me,re,A.filePath,de,De);let je=performance.now()-le,Be=oe.relative(m,A.filePath)||A.filePath;console.log(`[stx:profile] ${Be} \u2192 ${je.toFixed(2)}ms`)}else ye=await V(Me,re,A.filePath,de,De);if(!E)ye=await we(ye,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-h0nxd9xg.js");ye=ye.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(je,Be,He)=>{if(!/function\s+__stx_setup_/.test(He))return je;return`<script${Be}>${le(He,re)}</script>`})}if(E)ye=Je(ye,{preserveHead:!0});if(ae&&z)await Y(A.filePath,ye,De,de);let{extractStreamBoundaries:pt}=await import("./chunk-04f6r2kh.js"),Ze=pt(re),it=re.__streamTemplates;if(it&&typeof it==="object"&&Object.keys(it).length>0){let le=re.streamBoundaries||{},je={...de,autoShell:!1},Be=Object.keys(it).map((Se)=>({id:Se,render:async()=>{let at=typeof le[Se]==="function"?await le[Se]():void 0;return V(it[Se],{...re,$boundary:at},A.filePath,je,new Set)}})),He=new Set(Be.map((Se)=>Se.id));Ze=[...(Ze||[]).filter((Se)=>!He.has(Se.id)),...Be]}if(Ze&&Ze.length>0)Re.add(A.pattern);else Ze=void 0;let Xt=Bt(re),Gt=Ft(re);if(z)U.set(A.filePath,{status:Xt,headers:Gt});return{route:A,content:ye,status:Xt??ce,headers:Gt,boundaries:Ze}}catch(V){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,V),null}},ze=8,Ue=async()=>{let A=new Set(pe.keys()),F=new Set(D.keys());pe.clear(),D.clear();let V=n.prebuild===!1?I.filter((G)=>A.has(G.pattern)):I,te=n.prebuild===!1?P.filter(({route:G})=>F.has(G.pattern)):P;for(let G=0;G<V.length;G+=ze){let Ee=V.slice(G,G+ze),we=await Promise.all(Ee.map((q)=>j(q)));for(let q of we)if(q)pe.set(q.route.pattern,q)}for(let G=0;G<te.length;G+=ze){let Ee=te.slice(G,G+ze),we=await Promise.all(Ee.map(({route:q})=>j(q)));for(let q of we)if(q)D.set(q.route.pattern,q)}return pe.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?I.length+P.length>0:await Ue()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await mn(m);let Ge=r;try{if(Ge=await qe(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let A=n.hmrPort||Ge+1;d=St({wsPort:A,verbose:!1}),u=d.start(A)}let Et=(A,F)=>{let te=`<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(A.includes("</head>"))return f(A,te,"");if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${te}`);return te+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Ur({port:Ge,hostname:n.hostname,async fetch(A){let F=new URL(A.url),V=n.stxOptions?.offline??b.offline;if(F.pathname===zo&&V?.enabled){if(!["GET","HEAD"].includes(A.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(A.method==="HEAD"?null:Ho(V,ps()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let te=b?.publicDir||"public",G=oe.join(m,te,F.pathname),Ee=oe.join(m,F.pathname),we=oe.join(ve,F.pathname);if([G,Ee,we].some((z)=>S(z,m,T)))return new Response("Not Found",{status:404});let[q,Y,K]=await Promise.all([ge.promises.stat(G).catch(()=>null),ge.promises.stat(Ee).catch(()=>null),ge.promises.stat(we).catch(()=>null)]);if(q?.isFile()&&!S(G,m,T))return Vt(G);if(Y?.isFile()&&!S(Ee,m,T))return Vt(Ee);if(K?.isFile()&&!S(we,m,T))return Vt(we);if(F.pathname.startsWith("/_stx/component/")){let z=decodeURIComponent(F.pathname.slice(16));if(z)try{let ae=`<${z} />`,ne={...buildConfig,autoShell:!1},ce=await processDirectives(ae,{},oe.join(m,"components",`${z}.stx`),ne,new Set);return new Response(ce,{headers:{"Content-Type":"text/html"}})}catch(ae){return new Response(`<div class="stx-async-error">${ae.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:z}=await import("./chunk-hb6r4pxp.js"),ae=await z(A,{publicDir:oe.join(m,te),cacheDir:l(m,"cache","img")});if(ae)return ae}if(ee)try{let z=await ee.handleRequest(A);if(z.status!==404)return z}catch{}if(X[F.pathname])try{return await X[F.pathname](A)}catch(z){return new Response(JSON.stringify({error:z.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await R(A);if(ue)return ue;let J=wr(F.pathname,I);if(J){let z=pe.get(J.route.pattern),ae=Re.has(J.route.pattern);if(!z||J.route.isDynamic&&Object.keys(J.params).length>0||ae){let ne=await j(J.route,J.params);if(ne){if(z=ne,!J.route.isDynamic&&!ae)pe.set(J.route.pattern,ne)}}if(z){let ne=z.status??200,ce=z.headers??{},me=(J.route.filePath?kt(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(me.validate){if(!await me.validate({params:J.params})){let Me=await ie(404);if(Me){let re=Me;if(re=await x(re,m),o)re=We(re,u);return new Response(re,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(me.middleware){let Ie=It(F.pathname,J.params,me,F.search),Me=Ot(Ie,null,A,{isServer:!0}),re=await Nt(me.middleware,Me);if(re.redirect){let De=re.redirect.path,ye=re.redirect.options.redirectCode||302,pt=new Headers(re.responseHeaders);return pt.set("Location",De),new Response(null,{status:ye,headers:pt})}if(re.abort){let{statusCode:De,message:ye}=re.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${ye}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(re.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(re.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;z.content=f(z.content,De,"")}}let N=z.content;if(E&&va(A)&&Ye(N,b?.router?.container||"main")){let Ie=ot(N),Me=ke(N),re=N.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=re?en(re[1].trim()):"";if(Object.keys(J.params).length>0)N=Et(N,J.params);N=await x(N,m);let ye=b?.router?.container||"main";return N=Pe(N,ye,!0),new Response(N,{status:ne,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ie.layout,"X-STX-Layout-Group":Ie.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[hc]:ps(),...H(),"Cache-Control":wt}})}if(E)N=Qr(E,N);if(Object.keys(J.params).length>0)N=Et(N,J.params);if(N=await x(N,m),o)N=We(N,u);if(n.native)if(N.includes("<head>"))N=N.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 N="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+N;if(n.titlebarHidden)if(N.includes("<head>"))N=N.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 N=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${N}`;if(z.boundaries&&z.boundaries.length>0){let{renderStreamingPage:Ie,streamToResponse:Me}=await import("./chunk-04f6r2kh.js");return Me(Ie(N,z.boundaries,{timeoutMs:30000}),{status:ne,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(N,{status:ne,headers:{"Content-Type":"text/html",...H(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ce}})}}if(P.length>0){let z=P.map((ne)=>ne.route),ae=wr(F.pathname,z);if(ae){let ne=D.get(ae.route.pattern);if(!ne||ae.route.isDynamic){let ce=await j(ae.route,ae.params);if(ce){if(ne=ce,!ae.route.isDynamic)D.set(ae.route.pattern,ce)}}if(ne){let ce=ne.content;if(E)ce=Qr(E,ce);if(Object.keys(ae.params).length>0)ce=Et(ce,ae.params);if(ce=await x(ce,m),o)ce=We(ce,u);return new Response(ce,{status:ne.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ne}of O)if(ne!=="/"&&F.pathname.startsWith(ne)){let ce=D.get(ne)||D.get(ne+"/");if(!ce){let me=P.find(({route:N})=>N.pattern===ne||N.pattern===`${ne}/`);if(me){let N=await j(me.route);if(N)ce=N,D.set(me.route.pattern,N)}}if(ce){let me=ce.content;if(E)me=Qr(E,me);if(me=await x(me,m),o)me=We(me,u);return new Response(me,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if($t(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ve=pe.get("/");if(Ve){let z=Ve.content;if(z=await x(z,m),o)z=We(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;return new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await ie(404);if(de){let z=de;if(z=await x(z,m),o)z=We(z,u);return new Response(z,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let F=await ie(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1439
|
-
${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1440
|
-
${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(`
|
|
1441
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1442
|
-
${e.yellow}Routes:${e.reset}`);let Mt=[...Ms(I,m)];for(let{route:A}of P)Mt.push(`${A.pattern}`);if(Mt.forEach((A,F)=>{let te=F===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${te}${e.reset}${A}`)}),console.log(`
|
|
1443
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Dt.url.toString(),()=>{if(d)ct();Dt.stop()}),n.native){let A,F=oe.join(C,"index.stx");if(ge.existsSync(F)){let te=await Bun.file(F).text();A=yt(te)}let V=b?.app?.window??{};await et(Ge,{title:b?.app?.head?.title||oe.basename(m)||"stx App",width:V.width,height:V.height,darkMode:V.darkMode,hotReload:V.hotReload,titlebarHidden:V.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(q)=>q.startsWith("public/")||q.startsWith("public\\"),F=(q)=>{let Y=q.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},V=new Map,te=()=>{let q=new Set([m,...b._layerGraph?.layers.map((Y)=>Y.root)??[],...b._layerGraph?.configDependencies.map((Y)=>oe.dirname(Y))??[]].filter((Y)=>ge.existsSync(Y)).map((Y)=>ge.realpathSync(Y)));for(let Y of b._layerGraph?.layers??[])for(let K of Object.values(Y.resources)){if(!ge.existsSync(K))continue;let ue=ge.realpathSync(K);if(![...q].some((J)=>ue===J||ue.startsWith(`${J}${oe.sep}`)))q.add(ue)}for(let[Y,K]of V)if(!q.has(Y))K.close(),V.delete(Y);for(let Y of q)if(!V.has(Y)&&ge.existsSync(Y))V.set(Y,ge.watch(Y,{recursive:!0},(K,ue)=>{Ee(Y,K,ue).catch((J)=>console.error("[stx] Layer rebuild failed:",J))}))},G=Promise.resolve(),Ee=(q,Y,K)=>(G=G.catch(()=>{}).then(()=>we(q,Y,K)),G),we=async(q,Y,K)=>{if(!K||vt(K))return;if(xt(K)){if(b._layerGraph){let ue=await y(m);Object.assign(b,ue),I.splice(0,I.length,...Q(k,{pagesDir:v,pagesDirs:ue._layerPageDirs?[C,...ue._layerPageDirs.slice(1)]:void 0})),te()}if(A(K)){if(console.log(`${e.cyan}${K} changed${e.reset}`),o&&d)d.reload(K)}else if(F(K)){console.log(`${e.yellow}${K} changed, rebuilding...${e.reset}`),tt.clear(),be();try{let{invalidateFileCache:ue,templateCache:J}=await import("./chunk-m1a3a32y.js");ue(oe.resolve(q,K)),J.delete(oe.resolve(q,K))}catch{}if(_&&K){if(oe.resolve(q,K)===_||oe.basename(_)===K){let J=await So(_,n.stxOptions||{});if(J)E=J}}if(await Ue(),await dr(m),o&&d)d.reload(K)}else{console.log(`${e.yellow}${K} changed, rebuilding...${e.reset}`),tt.clear(),be();try{let{invalidateFileCache:ue,templateCache:J}=await import("./chunk-m1a3a32y.js");ue(oe.resolve(q,K)),J.delete(oe.resolve(q,K))}catch{}if(await Ue(),o&&d)d.reload(K)}}else if(bt(K)){if(console.log(`${e.cyan}CSS ${K} changed${e.reset}`),o&&d)d.updateCss(K)}};te(),process.on("SIGINT",()=>{for(let q of V.values())q.close();if(d)ct();Dt.stop(),process.exit(0)})}return!0}import qt from"fs";import lt from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let p=r[1],o=[],d=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=d.exec(p))!==null){let m=u[1],y=u[2]||u[3]||u[4];if(!y)continue;let b={name:y},w=m.match(/@type\s+\{([^}]+)\}/i);if(w)b.type=w[1].trim();if(m.match(/@required/i))b.required=!0;let T=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(T)b.default=T[1].trim();let R=m.split(`
|
|
1444
|
-
`).map((k)=>k.trim().replace(/^\*\s*/,"")).filter((k)=>!k.startsWith("@")&&k.length>0);b.description=R.join(" ").trim(),o.push(b)}if(o.length===0){let m=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(m){let b=m[1].split(",").map((w)=>w.trim()).filter(Boolean);for(let w of b){let[S]=w.split(":").map((T)=>T.trim());if(S)o.push({name:S})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Vr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
|
|
1445
|
-
`).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,n=!1,r){let p=lt.basename(t,".stx"),o=await Wr(t),d=await Vr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let m=o.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
|
|
1446
|
-
`);u=`<${p}
|
|
1447
|
-
${m}
|
|
1448
|
-
/>`}return{name:p,path:t,description:d,props:o,example:u,isWebComponent:n,tag:r}}async function fn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await qt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let p of n){let o=lt.join(t,p.name);if(p.isDirectory()){let d=await fn(o);r.push(...d)}else if(p.isFile()&&p.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Jr(t,n){try{if(!await s(t))return[];let r=await fn(t),p=[],o=new Map;if(n?.components?.length)for(let d of n.components)o.set(d.file,d);for(let d of r){let u=o.get(d),m=!!u,y=u?.tag,b=await qr(d,m,y);p.push(b)}return p}catch(r){return console.error("Error generating component docs:",r),[]}}async function Yr(t){try{if(!await s(t))return[];let n=await qt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let p of n){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let o=lt.join(t,p.name),d=await Bun.file(o).text(),u=lt.basename(o,".stx"),m=d.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||d.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=m?m[1].split(`
|
|
1449
|
-
`).map((v)=>v.trim().replace(/^\*\s*/,"")).join(" ").trim():"",b=/@component\(\s*['"]([^'"]+)['"]/g,w=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,S=new Set,T;while((T=b.exec(d))!==null)S.add(T[1]);while((T=w.exec(d))!==null)if(T[1]&&T[1]!=="slot")S.add(T[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,k=new Set;while((T=R.exec(d))!==null)k.add(T[1]);r.push({name:u,path:o,description:y,components:[...S],directives:[...k]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function Zr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1450
|
-
<p>Welcome, {{ user.name }}!</p>
|
|
1451
|
-
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
1452
|
-
<p>Welcome back!</p>
|
|
1453
|
-
@else
|
|
1454
|
-
<p>Please log in</p>
|
|
1455
|
-
@endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
|
|
1456
|
-
<p>A</p>
|
|
1457
|
-
@elseif(score > 80)
|
|
1458
|
-
<p>B</p>
|
|
1459
|
-
@elseif(score > 70)
|
|
1460
|
-
<p>C</p>
|
|
1461
|
-
@endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
|
|
1462
|
-
<p>Please log in</p>
|
|
1463
|
-
@endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
|
|
1464
|
-
<li>{{ item.name }}</li>
|
|
1465
|
-
@endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
|
|
1466
|
-
<p>Page {{ page }}</p>
|
|
1467
|
-
@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
|
|
1468
|
-
{{ This will be displayed as-is }}
|
|
1469
|
-
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let r of t)n.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function eo(t=[],n=[],r=[],p){let o=`# stx Documentation
|
|
1470
|
-
|
|
1471
|
-
`;if(p)o+=`${p}
|
|
1472
|
-
|
|
1473
|
-
`;if(t.length>0){o+=`## Components
|
|
1474
|
-
|
|
1475
|
-
`;for(let d of t){if(o+=`### ${d.name}
|
|
1476
|
-
|
|
1477
|
-
`,d.description)o+=`${d.description}
|
|
1478
|
-
|
|
1479
|
-
`;if(d.isWebComponent)o+=`**Web Component Tag:** \`${d.tag}\`
|
|
1480
|
-
|
|
1481
|
-
`;if(d.props.length>0){o+=`#### Properties
|
|
1482
|
-
|
|
1483
|
-
`,o+=`| Name | Type | Required | Default | Description |
|
|
1484
|
-
`,o+=`| ---- | ---- | -------- | ------- | ----------- |
|
|
1485
|
-
`;for(let u of d.props)o+=`| ${u.name} | ${u.type||"any"} | ${u.required?"Yes":"No"} | ${u.default||"-"} | ${u.description||"-"} |
|
|
1486
|
-
`;o+=`
|
|
1487
|
-
`}if(d.example)o+=`#### Example
|
|
1488
|
-
|
|
1489
|
-
`,o+="```html\n",o+=d.example,o+="\n```\n\n"}}if(n.length>0){o+=`## Templates
|
|
1490
|
-
|
|
1491
|
-
`;for(let d of n){if(o+=`### ${d.name}
|
|
1492
|
-
|
|
1493
|
-
`,d.description)o+=`${d.description}
|
|
1494
|
-
|
|
1495
|
-
`;if(d.components&&d.components.length>0)o+=`**Components Used:** ${d.components.join(", ")}
|
|
1496
|
-
|
|
1497
|
-
`;if(d.directives&&d.directives.length>0)o+=`**Directives Used:** ${d.directives.join(", ")}
|
|
1498
|
-
|
|
1499
|
-
`}}if(r.length>0){o+=`## Directives
|
|
1500
|
-
|
|
1501
|
-
`,o+=`| Directive | Description | Has End Tag |
|
|
1502
|
-
`,o+=`| --------- | ----------- | ----------- |
|
|
1503
|
-
`;for(let d of r)o+=`| @${d.name} | ${d.description||"-"} | ${d.hasEndTag?"Yes":"No"} |
|
|
1504
|
-
`;o+=`
|
|
1505
|
-
`;for(let d of r)if(d.example)o+=`### @${d.name}
|
|
1506
|
-
|
|
1507
|
-
`,o+=`${d.description||""}
|
|
1508
|
-
|
|
1509
|
-
`,o+=`#### Example
|
|
1510
|
-
|
|
1511
|
-
`,o+="```html\n",o+=d.example,o+="\n```\n\n"}return o}function to(t=[],n=[],r=[],p){let o=`<!DOCTYPE html>
|
|
1512
|
-
<html lang="en">
|
|
1513
|
-
<head>
|
|
1514
|
-
<meta charset="UTF-8">
|
|
1515
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1516
|
-
<title>stx Documentation</title>
|
|
1517
|
-
<style>
|
|
1518
|
-
body {
|
|
1519
|
-
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
|
1520
|
-
line-height: 1.6;
|
|
1521
|
-
color: #333;
|
|
1522
|
-
max-width: 1200px;
|
|
1523
|
-
margin: 0 auto;
|
|
1524
|
-
padding: 2rem;
|
|
1525
|
-
}
|
|
1526
|
-
h1, h2, h3, h4 { margin-top: 2rem; }
|
|
1527
|
-
table {
|
|
1528
|
-
border-collapse: collapse;
|
|
1529
|
-
width: 100%;
|
|
1530
|
-
margin: 1rem 0;
|
|
1531
|
-
}
|
|
1532
|
-
th, td {
|
|
1533
|
-
text-align: left;
|
|
1534
|
-
padding: 0.5rem;
|
|
1535
|
-
border-bottom: 1px solid #ddd;
|
|
1536
|
-
}
|
|
1537
|
-
th { border-bottom: 2px solid #ddd; }
|
|
1538
|
-
pre {
|
|
1539
|
-
background: #f5f5f5;
|
|
1540
|
-
padding: 1rem;
|
|
1541
|
-
border-radius: 4px;
|
|
1542
|
-
overflow-x: auto;
|
|
1543
|
-
}
|
|
1544
|
-
code {
|
|
1545
|
-
background: #f5f5f5;
|
|
1546
|
-
padding: 0.2rem 0.4rem;
|
|
1547
|
-
border-radius: 4px;
|
|
1548
|
-
font-size: 0.9em;
|
|
1549
|
-
}
|
|
1550
|
-
</style>
|
|
1551
|
-
</head>
|
|
1552
|
-
<body>
|
|
1553
|
-
<h1>stx Documentation</h1>
|
|
1554
|
-
`;if(p)o+=`<div>${p}</div>`;if(t.length>0){o+="<h2>Components</h2>";for(let d of t){if(o+=`<h3>${d.name}</h3>`,d.description)o+=`<p>${d.description}</p>`;if(d.isWebComponent)o+=`<p><strong>Web Component Tag:</strong> <code>${d.tag}</code></p>`;if(d.props.length>0){o+="<h4>Properties</h4>",o+=`<table>
|
|
1555
|
-
<thead>
|
|
1556
|
-
<tr>
|
|
1557
|
-
<th>Name</th>
|
|
1558
|
-
<th>Type</th>
|
|
1559
|
-
<th>Required</th>
|
|
1560
|
-
<th>Default</th>
|
|
1561
|
-
<th>Description</th>
|
|
1562
|
-
</tr>
|
|
1563
|
-
</thead>
|
|
1564
|
-
<tbody>`;for(let u of d.props)o+=`<tr>
|
|
1565
|
-
<td>${u.name}</td>
|
|
1566
|
-
<td>${u.type||"any"}</td>
|
|
1567
|
-
<td>${u.required?"Yes":"No"}</td>
|
|
1568
|
-
<td>${u.default||"-"}</td>
|
|
1569
|
-
<td>${u.description||"-"}</td>
|
|
1570
|
-
</tr>`;o+="</tbody></table>"}if(d.example)o+="<h4>Example</h4>",o+=`<pre><code>${d.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}}if(n.length>0){o+="<h2>Templates</h2>";for(let d of n){if(o+=`<h3>${d.name}</h3>`,d.description)o+=`<p>${d.description}</p>`;if(d.components&&d.components.length>0)o+=`<p><strong>Components Used:</strong> ${d.components.join(", ")}</p>`;if(d.directives&&d.directives.length>0)o+=`<p><strong>Directives Used:</strong> ${d.directives.join(", ")}</p>`}}if(r.length>0){o+="<h2>Directives</h2>",o+=`<table>
|
|
1571
|
-
<thead>
|
|
1572
|
-
<tr>
|
|
1573
|
-
<th>Directive</th>
|
|
1574
|
-
<th>Description</th>
|
|
1575
|
-
<th>Has End Tag</th>
|
|
1576
|
-
</tr>
|
|
1577
|
-
</thead>
|
|
1578
|
-
<tbody>`;for(let d of r)o+=`<tr>
|
|
1579
|
-
<td>@${d.name}</td>
|
|
1580
|
-
<td>${d.description||"-"}</td>
|
|
1581
|
-
<td>${d.hasEndTag?"Yes":"No"}</td>
|
|
1582
|
-
</tr>`;o+="</tbody></table>";for(let d of r)if(d.example)o+=`<h3>@${d.name}</h3>`,o+=`<p>${d.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${d.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return o+="</body></html>",o}function no(t=[],n=[],r=[],p){return JSON.stringify({components:t,templates:n,directives:r,extraContent:p||""},null,2)}async function ro(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:p,customDirectives:o,config:d}=t;if(!d.enabled)return!1;let u=d.outputDir||"docs";if(await qt.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let m=[];if(d.components!==!1&&n)console.log("Generating component documentation..."),m=await Jr(n,p),console.log(`Found ${m.length} components`);let y=[];if(d.templates!==!1&&r)console.log("Generating template documentation..."),y=await Yr(r),console.log(`Found ${y.length} templates`);let b=[];if(d.directives!==!1)console.log("Generating directive documentation..."),b=await Zr(o),console.log(`Found ${b.length} directives`);let w=d.format||"markdown",S=d.extraContent,T="",R="";switch(w){case"markdown":T=eo(m,y,b,S),R="md";break;case"html":T=to(m,y,b,S),R="html";break;case"json":T=no(m,y,b,S),R="json";break;default:throw Error(`Unsupported documentation format: ${w}`)}let k=lt.join(u,`stx-docs.${R}`);return await Bun.write(k,T),console.log(`Documentation generated: ${k}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function ca(t){let n={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},r=t.componentsDir||M.componentsDir,p=t.templatesDir||".";return ro({componentsDir:r,templatesDir:p,webComponentsConfig:M.webComponents,customDirectives:M.customDirectives,config:n})}var hn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function go(t,n={}){let r={...hn,...n};if(t.trim()==="")return`
|
|
1583
|
-
`;let p=t;if(r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=io(p,r),p=po(p,r),p=ao(p,r),r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
|
|
1584
|
-
`).replace(/\r/g,`
|
|
1585
|
-
`),!p.endsWith(`
|
|
1586
|
-
`))p+=`
|
|
1587
|
-
`;return p}function la(t,n={}){let r={...hn,...n};if(t.trim()==="")return`
|
|
1588
|
-
`;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(o,d,u,m,y)=>{let b=m.split(`
|
|
1589
|
-
`),w=b.filter((v)=>v.trim().length>0);if(w.length===0)return o;let S=Math.min(...w.map((v)=>{let C=v.match(/^( *)/);return C?C[1].length:0})),T=b.map((v)=>{if(v.trim().length===0)return"";return v.substring(S)}).join(`
|
|
1590
|
-
`),k=go(T,r).trimEnd().split(`
|
|
1591
|
-
`).map((v)=>{if(v.trim().length===0)return"";return d+v}).join(`
|
|
1592
|
-
`);return`${d}\`\`\`${u}
|
|
1593
|
-
${k}
|
|
1594
|
-
${d}\`\`\``}),r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
|
|
1595
|
-
`).replace(/\r/g,`
|
|
1596
|
-
`),!p.endsWith(`
|
|
1597
|
-
`))p+=`
|
|
1598
|
-
`;return p}function so(t){let n=t,r=[],p="__PROTECTED_BLOCK_";return n=n.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(o)=>{let d=r.length;return r.push(o),`${p}${d}__`}),n=n.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1599
|
-
$1
|
|
1600
|
-
`),n=n.replace(/(@end\w+)/g,`
|
|
1601
|
-
$1
|
|
1602
|
-
`),n=n.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1603
|
-
$1
|
|
1604
|
-
`),n=n.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
|
|
1605
|
-
$1
|
|
1606
|
-
`),n=n.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(o,d,u,m)=>{let y=m.substring(u+o.length,Math.min(m.length,u+o.length+20)),b=o.match(/<(\w+)/)?.[1];if(b&&y.match(new RegExp(`^</${b}>`)))return o;return`
|
|
1607
|
-
${o}`}),n=n.replace(/(>)(<\/)/g,(o,d,u,m,y)=>{let b=y.substring(Math.max(0,m-50),m),S=y.substring(m+o.length,Math.min(y.length,m+o.length+20)).match(/^(\w+)>/)?.[1],T=b.match(/<(\w+)[^>]*$/)?.[1];if(T&&S&&T===S)return o;return`${d}
|
|
1608
|
-
${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,d,u,m)=>{let y=m.substring(Math.max(0,u-20),u),b=o.match(/<\/(\w+)>/)?.[1],w=new RegExp(`<${b}[^>]*>$`);if(b&&y.match(w))return o;return`${o}
|
|
1609
|
-
`}),n=n.replace(new RegExp(`${p}(\\d+)__`,"g"),(o,d)=>r[Number.parseInt(d,10)]),n=n.replace(/\n{2,}/g,`
|
|
1610
|
-
`),n=n.split(`
|
|
1611
|
-
`).map((o)=>o.trim()).join(`
|
|
1612
|
-
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function io(t,n){let p=so(t).split(`
|
|
1613
|
-
`),o=[],d=0,u=!1,m=n.useTabs?"\t":" ".repeat(n.indentSize);for(let y=0;y<p.length;y++){let b=p[y],w=b.trim();if(w===""){o.push("");continue}let S=w.match(/<script\b/i),T=w.match(/<\/script>/i);if(u&&!T){o.push(b);continue}let R=w===">";if(gn(w)&&!w.startsWith("<")&&!w.startsWith("@")){o.push(m.repeat(d)+w);continue}let k=w.startsWith("@end"),v=w.startsWith("@else")||w.startsWith("@elseif"),C=w.startsWith("@")&&lo(w),I=w.startsWith("<!DOCTYPE")||w.startsWith("<!doctype"),O=w.startsWith("<!--"),P=w.startsWith("</"),D=w.startsWith("<")&&!P&&!O&&!I,E=w.includes("/>")||co(w),_=gn(w);if(P||k)d=Math.max(0,d-1);let B=v?Math.max(0,d-1):d;if(R)o.push(b);else o.push(m.repeat(B)+w);if(D&&!E&&!_&&!R||C)d++;if(S)u=!0;if(T)u=!1}return o.join(`
|
|
1614
|
-
`)}function ao(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,p,o)=>{let d=o.trim().replace(/\s+/g," ");return`@${p}(${d})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,p,o)=>{if(o.trim()==="")return`@${p}`;return`@${p}(${o.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,p)=>`{!! ${p.trim()} !!}`);return t}function co(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let r=t.match(/<(\w+)/);if(r){let p=r[1];return n.includes(p.toLowerCase())}return!1}function gn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function lo(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of n)if(t.startsWith(`@${r}`))return!t.includes(`@end${r}`);return!1}function po(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(r,p,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
|
|
1615
|
-
`)||o.includes("@"))return r;let d=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],m;while((m=d.exec(o))!==null)u.push({name:m[1],value:m[2]});u.sort((b,w)=>{if(b.name==="id")return-1;if(w.name==="id")return 1;if(b.name==="class")return-1;if(w.name==="class")return 1;return b.name.localeCompare(w.name)});let y=u.map((b)=>b.value?`${b.name}=${b.value}`:b.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import yn from"fs";import Kt from"path";async function ua(t="index.stx",n={}){try{let r=n.force||!1,p=Kt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Kt.dirname(p);if(!yn.existsSync(o))yn.mkdirSync(o,{recursive:!0});let d;if(n.template){let u=Kt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);d=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)d=bn(n.preset),console.warn(`Using '${n.preset}' preset template`);else d=bn("basic");return await Bun.write(p,d),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function bn(t){switch(t){case"basic":return xn();case"component":return uo();case"layout":return fo();case"blog":return yo();case"api":return bo();case"app":return xo();default:return xn()}}function xn(){return`<script>
|
|
1616
|
-
const title = "My stx Page"
|
|
1617
|
-
const description = "A page built with stx"
|
|
1618
|
-
const features = [
|
|
1619
|
-
{ name: "Single File Components", desc: "Script, style, and template in one .stx file" },
|
|
1620
|
-
{ name: "Component System", desc: "Import components with @component('name', {})" },
|
|
1621
|
-
{ name: "Blade Directives", desc: "@if, @foreach, @switch, @layout and more" }
|
|
1622
|
-
]
|
|
1623
|
-
</script>
|
|
1624
|
-
|
|
1625
|
-
@section('content')
|
|
1626
|
-
<header>
|
|
1627
|
-
<h1>{{ title }}</h1>
|
|
1628
|
-
<p>{{ description }}</p>
|
|
1629
|
-
</header>
|
|
1630
|
-
|
|
1631
|
-
<main>
|
|
1632
|
-
<h2>Features</h2>
|
|
1633
|
-
@foreach(features as feature)
|
|
1634
|
-
<div class="card">
|
|
1635
|
-
<h3>{{ feature.name }}</h3>
|
|
1636
|
-
<p>{{ feature.desc }}</p>
|
|
1637
|
-
</div>
|
|
1638
|
-
@endforeach
|
|
1639
|
-
</main>
|
|
1640
|
-
@endsection`}function uo(){return`{{-- Component: Card --}}
|
|
1641
|
-
{{-- Props: title, variant, collapsible --}}
|
|
1642
|
-
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1643
|
-
<script>
|
|
1644
|
-
// Props with defaults
|
|
1645
|
-
const title = props.title || 'Card Title'
|
|
1646
|
-
const variant = props.variant || 'default'
|
|
1647
|
-
const collapsible = props.collapsible || false
|
|
1648
|
-
</script>
|
|
1649
|
-
|
|
1650
|
-
<div class="card card--{{ variant }}">
|
|
1651
|
-
<div class="card__header" onclick="this.parentElement.classList.toggle('collapsed')">
|
|
1652
|
-
<h3 class="card__title">{{ title }}</h3>
|
|
1653
|
-
@if(collapsible)
|
|
1654
|
-
<span class="card__toggle">\u25BC</span>
|
|
1655
|
-
@endif
|
|
1656
|
-
</div>
|
|
1657
|
-
<div class="card__body">
|
|
1658
|
-
{{ slot }}
|
|
1659
|
-
</div>
|
|
1660
|
-
</div>
|
|
1661
|
-
|
|
1662
|
-
<style scoped>
|
|
1663
|
-
.card {
|
|
1664
|
-
border-radius: 8px;
|
|
1665
|
-
background: #fff;
|
|
1666
|
-
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
1667
|
-
overflow: hidden;
|
|
1668
|
-
}
|
|
1669
|
-
.card--primary { border-top: 3px solid #3498db; }
|
|
1670
|
-
.card--success { border-top: 3px solid #2ecc71; }
|
|
1671
|
-
.card--warning { border-top: 3px solid #f39c12; }
|
|
1672
|
-
.card--danger { border-top: 3px solid #e74c3c; }
|
|
1673
|
-
.card__header {
|
|
1674
|
-
padding: 1rem;
|
|
1675
|
-
background: #f8f9fa;
|
|
1676
|
-
display: flex;
|
|
1677
|
-
justify-content: space-between;
|
|
1678
|
-
align-items: center;
|
|
1679
|
-
}
|
|
1680
|
-
.card__title { margin: 0; font-size: 1.1rem; }
|
|
1681
|
-
.card__toggle { transition: transform 0.2s; }
|
|
1682
|
-
.card.collapsed .card__toggle { transform: rotate(-90deg); }
|
|
1683
|
-
.card__body { padding: 1rem; }
|
|
1684
|
-
.card.collapsed .card__body { display: none; }
|
|
1685
|
-
</style>`}function fo(){return`<!DOCTYPE html>
|
|
1686
|
-
<html lang="en">
|
|
1687
|
-
<head>
|
|
1688
|
-
<meta charset="UTF-8">
|
|
1689
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1690
|
-
<title>@yield('title', 'My App')</title>
|
|
1691
|
-
@yield('head')
|
|
1692
|
-
<style>
|
|
1693
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1694
|
-
body {
|
|
1695
|
-
font-family: system-ui, sans-serif;
|
|
1696
|
-
min-height: 100vh;
|
|
1697
|
-
display: flex;
|
|
1698
|
-
flex-direction: column;
|
|
1699
|
-
}
|
|
1700
|
-
header, footer {
|
|
1701
|
-
background: #2c3e50;
|
|
1702
|
-
color: white;
|
|
1703
|
-
padding: 1rem 2rem;
|
|
1704
|
-
}
|
|
1705
|
-
main {
|
|
1706
|
-
flex: 1;
|
|
1707
|
-
padding: 2rem;
|
|
1708
|
-
max-width: 1200px;
|
|
1709
|
-
margin: 0 auto;
|
|
1710
|
-
width: 100%;
|
|
1711
|
-
}
|
|
1712
|
-
nav a { color: white; margin-right: 1rem; text-decoration: none; }
|
|
1713
|
-
nav a:hover { text-decoration: underline; }
|
|
1714
|
-
</style>
|
|
1715
|
-
@yield('styles')
|
|
1716
|
-
</head>
|
|
1717
|
-
<body>
|
|
1718
|
-
<header>
|
|
1719
|
-
<nav>
|
|
1720
|
-
<a href="/">Home</a>
|
|
1721
|
-
<a href="/about">About</a>
|
|
1722
|
-
<a href="/contact">Contact</a>
|
|
1723
|
-
</nav>
|
|
1724
|
-
</header>
|
|
1725
|
-
|
|
1726
|
-
<main>
|
|
1727
|
-
{{ slot }}
|
|
1728
|
-
</main>
|
|
1729
|
-
|
|
1730
|
-
<footer>
|
|
1731
|
-
<p>© {{ new Date().getFullYear() }} My App</p>
|
|
1732
|
-
</footer>
|
|
1733
|
-
|
|
1734
|
-
@yield('scripts')
|
|
1735
|
-
</body>
|
|
1736
|
-
</html>`}function yo(){return`<script>
|
|
1737
|
-
// Article metadata
|
|
1738
|
-
const title = "My Blog Post"
|
|
1739
|
-
const author = "Your Name"
|
|
1740
|
-
const date = new Date().toLocaleDateString('en-US', {
|
|
1741
|
-
year: 'numeric',
|
|
1742
|
-
month: 'long',
|
|
1743
|
-
day: 'numeric'
|
|
1744
|
-
})
|
|
1745
|
-
const tags = ["stx", "tutorial", "web development"]
|
|
1746
|
-
const readingTime = "5 min read"
|
|
1747
|
-
</script>
|
|
1748
|
-
|
|
1749
|
-
@layout('layouts/blog')
|
|
1750
|
-
|
|
1751
|
-
@section('title')
|
|
1752
|
-
{{ title }}
|
|
1753
|
-
@endsection
|
|
1754
|
-
|
|
1755
|
-
@section('content')
|
|
1756
|
-
<article class="blog-post">
|
|
1757
|
-
<header class="blog-post__header">
|
|
1758
|
-
<h1>{{ title }}</h1>
|
|
1759
|
-
<div class="blog-post__meta">
|
|
1760
|
-
<span class="author">By {{ author }}</span>
|
|
1761
|
-
<span class="date">{{ date }}</span>
|
|
1762
|
-
<span class="reading-time">{{ readingTime }}</span>
|
|
1763
|
-
</div>
|
|
1764
|
-
<div class="blog-post__tags">
|
|
1765
|
-
@foreach(tags as tag)
|
|
1766
|
-
<span class="tag">#{{ tag }}</span>
|
|
1767
|
-
@endforeach
|
|
1768
|
-
</div>
|
|
1769
|
-
</header>
|
|
1770
|
-
|
|
1771
|
-
<div class="blog-post__content">
|
|
1772
|
-
<p>Your content goes here...</p>
|
|
1773
|
-
|
|
1774
|
-
<h2>Introduction</h2>
|
|
1775
|
-
<p>Start writing your blog post content.</p>
|
|
1776
|
-
|
|
1777
|
-
<h2>Conclusion</h2>
|
|
1778
|
-
<p>Wrap up your thoughts here.</p>
|
|
1779
|
-
</div>
|
|
1780
|
-
</article>
|
|
1781
|
-
@endsection`}function bo(){return`<script>
|
|
1782
|
-
// API endpoint configuration
|
|
1783
|
-
const endpoint = "/api/data"
|
|
1784
|
-
const method = "GET"
|
|
1785
|
-
|
|
1786
|
-
// Mock data - replace with actual data fetching
|
|
1787
|
-
const data = {
|
|
1788
|
-
success: true,
|
|
1789
|
-
message: "Data retrieved successfully",
|
|
1790
|
-
items: [
|
|
1791
|
-
{ id: 1, name: "Item 1" },
|
|
1792
|
-
{ id: 2, name: "Item 2" },
|
|
1793
|
-
{ id: 3, name: "Item 3" }
|
|
1794
|
-
],
|
|
1795
|
-
meta: {
|
|
1796
|
-
total: 3,
|
|
1797
|
-
page: 1,
|
|
1798
|
-
perPage: 10
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
|
|
1802
|
-
// For error responses
|
|
1803
|
-
const error = null
|
|
1804
|
-
</script>
|
|
1805
|
-
|
|
1806
|
-
@if(error)
|
|
1807
|
-
{
|
|
1808
|
-
"success": false,
|
|
1809
|
-
"error": {
|
|
1810
|
-
"code": "{{ error.code || 'UNKNOWN_ERROR' }}",
|
|
1811
|
-
"message": "{{ error.message || 'An error occurred' }}"
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
@else
|
|
1815
|
-
{{ JSON.stringify(data, null, 2) }}
|
|
1816
|
-
@endif`}function xo(){return`<!DOCTYPE html>
|
|
1817
|
-
<html lang="en">
|
|
1818
|
-
<head>
|
|
1819
|
-
<meta charset="UTF-8">
|
|
1820
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1821
|
-
<title>{{ title }} - stx App</title>
|
|
1822
|
-
<script>
|
|
1823
|
-
const title = "My App"
|
|
1824
|
-
</script>
|
|
1825
|
-
<style>
|
|
1826
|
-
:root {
|
|
1827
|
-
--bg: #1a1a2e;
|
|
1828
|
-
--bg-dark: #16213e;
|
|
1829
|
-
--fg: #eaeaea;
|
|
1830
|
-
--primary: #e94560;
|
|
1831
|
-
--secondary: #0f3460;
|
|
1832
|
-
--success: #00d9ff;
|
|
1833
|
-
--border: #2a2a4a;
|
|
1834
|
-
}
|
|
1835
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1836
|
-
body {
|
|
1837
|
-
font-family: system-ui, -apple-system, sans-serif;
|
|
1838
|
-
background: var(--bg);
|
|
1839
|
-
color: var(--fg);
|
|
1840
|
-
min-height: 100vh;
|
|
1841
|
-
}
|
|
1842
|
-
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
|
|
1843
|
-
.header { text-align: center; margin-bottom: 2rem; }
|
|
1844
|
-
.header h1 { color: var(--primary); margin-bottom: 0.5rem; }
|
|
1845
|
-
.card {
|
|
1846
|
-
background: var(--bg-dark);
|
|
1847
|
-
border: 1px solid var(--border);
|
|
1848
|
-
border-radius: 12px;
|
|
1849
|
-
padding: 1.5rem;
|
|
1850
|
-
margin-bottom: 1rem;
|
|
1851
|
-
}
|
|
1852
|
-
.btn {
|
|
1853
|
-
background: var(--primary);
|
|
1854
|
-
color: white;
|
|
1855
|
-
border: none;
|
|
1856
|
-
padding: 0.75rem 1.5rem;
|
|
1857
|
-
border-radius: 8px;
|
|
1858
|
-
cursor: pointer;
|
|
1859
|
-
font-size: 1rem;
|
|
1860
|
-
transition: opacity 0.2s;
|
|
1861
|
-
}
|
|
1862
|
-
.btn:hover { opacity: 0.9; }
|
|
1863
|
-
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
1864
|
-
.btn--secondary { background: var(--secondary); }
|
|
1865
|
-
.btn--success { background: var(--success); color: var(--bg); }
|
|
1866
|
-
.input {
|
|
1867
|
-
width: 100%;
|
|
1868
|
-
background: var(--bg);
|
|
1869
|
-
border: 1px solid var(--border);
|
|
1870
|
-
color: var(--fg);
|
|
1871
|
-
padding: 0.75rem 1rem;
|
|
1872
|
-
border-radius: 8px;
|
|
1873
|
-
font-size: 1rem;
|
|
1874
|
-
margin-bottom: 1rem;
|
|
1875
|
-
}
|
|
1876
|
-
.input:focus { outline: none; border-color: var(--primary); }
|
|
1877
|
-
.flex { display: flex; gap: 1rem; align-items: center; }
|
|
1878
|
-
.flex-between { justify-content: space-between; }
|
|
1879
|
-
.text-muted { color: #888; }
|
|
1880
|
-
.text-success { color: var(--success); }
|
|
1881
|
-
.mb-1 { margin-bottom: 1rem; }
|
|
1882
|
-
.hidden { display: none; }
|
|
1883
|
-
</style>
|
|
1884
|
-
</head>
|
|
1885
|
-
<body>
|
|
1886
|
-
<div class="container">
|
|
1887
|
-
<header class="header">
|
|
1888
|
-
<h1>{{ title }}</h1>
|
|
1889
|
-
<p class="text-muted">Built with stx</p>
|
|
1890
|
-
</header>
|
|
1891
|
-
|
|
1892
|
-
<!-- Counter Example -->
|
|
1893
|
-
<div class="card">
|
|
1894
|
-
<h2 class="mb-1">Counter Example</h2>
|
|
1895
|
-
<div class="flex flex-between">
|
|
1896
|
-
<span id="counterDisplay">Count: 0</span>
|
|
1897
|
-
<div class="flex">
|
|
1898
|
-
<button class="btn btn--secondary" onclick="window.app?.decrement()">-</button>
|
|
1899
|
-
<button class="btn" onclick="window.app?.increment()">+</button>
|
|
1900
|
-
<button class="btn btn--success" onclick="window.app?.reset()">Reset</button>
|
|
1901
|
-
</div>
|
|
1902
|
-
</div>
|
|
1903
|
-
</div>
|
|
1904
|
-
|
|
1905
|
-
<!-- Todo List Example -->
|
|
1906
|
-
<div class="card">
|
|
1907
|
-
<h2 class="mb-1">Todo List</h2>
|
|
1908
|
-
<div class="flex mb-1">
|
|
1909
|
-
<input
|
|
1910
|
-
type="text"
|
|
1911
|
-
id="todoInput"
|
|
1912
|
-
class="input"
|
|
1913
|
-
placeholder="Add a new todo..."
|
|
1914
|
-
onkeypress="if(event.key==='Enter') window.app?.addTodo()"
|
|
1915
|
-
style="margin-bottom:0"
|
|
1916
|
-
/>
|
|
1917
|
-
<button class="btn" onclick="window.app?.addTodo()">Add</button>
|
|
1918
|
-
</div>
|
|
1919
|
-
<div id="todoList"></div>
|
|
1920
|
-
<p id="todoCount" class="text-muted">0 items</p>
|
|
1921
|
-
</div>
|
|
1922
|
-
|
|
1923
|
-
<!-- Toggle Example -->
|
|
1924
|
-
<div class="card">
|
|
1925
|
-
<h2 class="mb-1">Toggle Example</h2>
|
|
1926
|
-
<button
|
|
1927
|
-
id="toggleBtn"
|
|
1928
|
-
class="btn btn--secondary"
|
|
1929
|
-
onclick="window.app?.toggle()"
|
|
1930
|
-
>Inactive</button>
|
|
1931
|
-
<div id="toggleContent" class="mt-1" style="margin-top:1rem;display:none">
|
|
1932
|
-
<p class="text-success">This content is visible when active!</p>
|
|
1933
|
-
</div>
|
|
1934
|
-
</div>
|
|
1935
|
-
</div>
|
|
1936
|
-
|
|
1937
|
-
<!-- Simple Store Implementation -->
|
|
1938
|
-
<script>
|
|
1939
|
-
(function() {
|
|
1940
|
-
// Create a simple reactive store
|
|
1941
|
-
function createStore(initialState) {
|
|
1942
|
-
let state = { ...initialState };
|
|
1943
|
-
const listeners = [];
|
|
1944
|
-
return {
|
|
1945
|
-
get() { return state; },
|
|
1946
|
-
set(newState) {
|
|
1947
|
-
state = { ...state, ...newState };
|
|
1948
|
-
listeners.forEach(fn => fn(state));
|
|
1949
|
-
},
|
|
1950
|
-
subscribe(fn) {
|
|
1951
|
-
listeners.push(fn);
|
|
1952
|
-
fn(state); // Call immediately
|
|
1953
|
-
return () => listeners.splice(listeners.indexOf(fn), 1);
|
|
1954
|
-
}
|
|
1955
|
-
};
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
// Initialize app store
|
|
1959
|
-
const appStore = createStore({
|
|
1960
|
-
count: 0,
|
|
1961
|
-
todos: [],
|
|
1962
|
-
isActive: false
|
|
1963
|
-
});
|
|
1964
|
-
|
|
1965
|
-
// App methods
|
|
1966
|
-
window.app = {
|
|
1967
|
-
increment() {
|
|
1968
|
-
const { count } = appStore.get();
|
|
1969
|
-
appStore.set({ count: count + 1 });
|
|
1970
|
-
},
|
|
1971
|
-
decrement() {
|
|
1972
|
-
const { count } = appStore.get();
|
|
1973
|
-
appStore.set({ count: Math.max(0, count - 1) });
|
|
1974
|
-
},
|
|
1975
|
-
reset() {
|
|
1976
|
-
appStore.set({ count: 0 });
|
|
1977
|
-
},
|
|
1978
|
-
toggle() {
|
|
1979
|
-
const { isActive } = appStore.get();
|
|
1980
|
-
appStore.set({ isActive: !isActive });
|
|
1981
|
-
},
|
|
1982
|
-
addTodo() {
|
|
1983
|
-
const input = document.getElementById('todoInput');
|
|
1984
|
-
const text = input.value.trim();
|
|
1985
|
-
if (!text) return;
|
|
1986
|
-
const { todos } = appStore.get();
|
|
1987
|
-
appStore.set({ todos: [...todos, { id: Date.now(), text, done: false }] });
|
|
1988
|
-
input.value = '';
|
|
1989
|
-
},
|
|
1990
|
-
toggleTodo(id) {
|
|
1991
|
-
const { todos } = appStore.get();
|
|
1992
|
-
appStore.set({
|
|
1993
|
-
todos: todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
|
|
1994
|
-
});
|
|
1995
|
-
},
|
|
1996
|
-
deleteTodo(id) {
|
|
1997
|
-
const { todos } = appStore.get();
|
|
1998
|
-
appStore.set({ todos: todos.filter(t => t.id !== id) });
|
|
1999
|
-
}
|
|
2000
|
-
};
|
|
2001
|
-
|
|
2002
|
-
// Update UI based on state
|
|
2003
|
-
function updateUI(state) {
|
|
2004
|
-
// Update counter
|
|
2005
|
-
const counterDisplay = document.getElementById('counterDisplay');
|
|
2006
|
-
if (counterDisplay) counterDisplay.textContent = 'Count: ' + state.count;
|
|
2007
|
-
|
|
2008
|
-
// Update todo count
|
|
2009
|
-
const todoCount = document.getElementById('todoCount');
|
|
2010
|
-
if (todoCount) todoCount.textContent = state.todos.length + ' items';
|
|
2011
|
-
|
|
2012
|
-
// Update toggle button
|
|
2013
|
-
const toggleBtn = document.getElementById('toggleBtn');
|
|
2014
|
-
if (toggleBtn) {
|
|
2015
|
-
toggleBtn.textContent = state.isActive ? 'Active' : 'Inactive';
|
|
2016
|
-
toggleBtn.className = 'btn ' + (state.isActive ? 'btn--success' : 'btn--secondary');
|
|
2017
|
-
}
|
|
2018
|
-
|
|
2019
|
-
// Show/hide toggle content
|
|
2020
|
-
const toggleContent = document.getElementById('toggleContent');
|
|
2021
|
-
if (toggleContent) toggleContent.style.display = state.isActive ? 'block' : 'none';
|
|
2022
|
-
|
|
2023
|
-
// Render todo list
|
|
2024
|
-
const list = document.getElementById('todoList');
|
|
2025
|
-
if (list) {
|
|
2026
|
-
list.innerHTML = state.todos.map(todo => \`
|
|
2027
|
-
<div style="display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0;border-bottom:1px solid var(--border)">
|
|
2028
|
-
<input type="checkbox" \${todo.done ? 'checked' : ''} onchange="window.app?.toggleTodo(\${todo.id})" />
|
|
2029
|
-
<span style="\${todo.done ? 'text-decoration:line-through;opacity:0.5' : ''}">\${todo.text}</span>
|
|
2030
|
-
<button onclick="window.app?.deleteTodo(\${todo.id})" style="margin-left:auto;background:none;border:none;color:var(--primary);cursor:pointer">\xD7</button>
|
|
2031
|
-
</div>
|
|
2032
|
-
\`).join('');
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
|
|
2036
|
-
// Subscribe to store changes
|
|
2037
|
-
appStore.subscribe(updateUI);
|
|
2038
|
-
})();
|
|
2039
|
-
</script>
|
|
2040
|
-
</body>
|
|
2041
|
-
</html>`}var da="f9c3713";function Fl(t){return t}function zl(t){return t}function oa(t,n){let r=[],p=`${n}=`;for(let o=0;o<t.length;o++){let d=t[o];if(d.startsWith(p)){let u=d.slice(p.length);if(u)r.push(u);continue}if(d===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import Le from"fs";import xe from"path";function Pn(t){try{return Le.statSync(t).mtimeMs}catch{return null}}function Ct(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function Ri(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function On(t,n="stx"){let r=xe.resolve(t);for(let p=0;p<10;p++){let o=xe.join(r,"pantry","@stacksjs",n);if(Le.existsSync(o))return o;let d=xe.dirname(r);if(d===r)break;r=d}return null}var An=["@stacksjs/stx","bun-plugin-stx"];function Ei(t){try{let n=Le.readFileSync(xe.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Pi(t,n=6){let r=xe.resolve(t),p=[],o=new Set;function d(m,y){if(y>n)return;let b;try{b=Le.realpathSync(m)}catch{return}if(o.has(b))return;o.add(b);for(let S of An){let T=xe.join(m,S),R=Ei(T);if(R!==null)p.push({name:S,version:R,dir:xe.relative(r,T)||T,nested:y>0})}let w;try{w=Le.readdirSync(m,{withFileTypes:!0})}catch{return}for(let S of w){if(!S.isDirectory()&&!S.isSymbolicLink())continue;if(S.name===".bin"||S.name===".cache")continue;let T=xe.join(m,S.name);if(S.name.startsWith("@")){let k;try{k=Le.readdirSync(T,{withFileTypes:!0})}catch{continue}for(let v of k){let C=xe.join(T,v.name,"node_modules");if(Le.existsSync(C))d(C,y+1)}continue}let R=xe.join(T,"node_modules");if(Le.existsSync(R))d(R,y+1)}}let u=xe.join(r,"node_modules");if(Le.existsSync(u))d(u,0);return p}function Oi(t){let n=[];for(let r of An){let p=t.filter((u)=>u.name===r);if(p.length<=1)continue;let o=[...new Set(p.map((u)=>u.version))],d=p.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${p.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${d}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function mo(t={}){let n=t.cwd?xe.resolve(t.cwd):process.cwd(),r=t.resolve??Ri,p=Date.now(),o=[],d=r("@stacksjs/stx",n);o.push(d?{name:"@stacksjs/stx resolves to",status:"ok",detail:d}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let y of Oi(Pi(n)))o.push(y);let m=On(n,"stx");if(!m)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=xe.join(m,"src/signals.ts"),b=[xe.join(m,"dist/index.js"),xe.join(m,"dist/signals.js")].find((k)=>Le.existsSync(k))||null,w=Pn(y),S=b?Pn(b):null;if(w==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${m} but no src/signals.ts to compare`});else if(S==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${m} && bun build.ts`});else if(S<w){let k=Math.round((w-S)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Ct(S,p)}) is OLDER than src/signals.ts (${Ct(w,p)}) by ${k}s \u2014 your edit isn't built`,fix:`cd ${m} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Ct(w,p)}, dist ${Ct(S,p)})`});let T=xe.join(n,"node_modules/@stacksjs/stx"),R=null;try{R=Le.lstatSync(T)}catch{R=null}if(!R)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let k=null;try{k=Le.realpathSync(T)}catch{}let v=(()=>{try{return Le.realpathSync(m)}catch{return m}})();o.push(k===v?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${k||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let b=t.generateRuntime().length;o.push(b>1000?{name:"signals runtime",status:"ok",detail:`generated ${b.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${b} chars \u2014 suspiciously short`})}catch(y){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:o,ok:!o.some((y)=>y.status==="error")}}function ho(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let p of t.checks)if(r.push(` ${n[p.status]} ${p.name}: ${p.detail}`),p.fix)r.push(` \u2192 ${p.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
|
|
2042
|
-
`)}export{oa,ia,aa,ca,go,la,ua,da,Fl,zl,mo,ho,Kr,Gr,Xr};
|