@stacksjs/stx 0.2.792 → 0.2.794
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-dmp1k1eb.js → chunk-0675z8hj.js} +15 -15
- package/dist/{chunk-gg0e8d09.js → chunk-15ckxpq7.js} +1 -1
- package/dist/chunk-1ds97d9m.js +2 -0
- package/dist/{chunk-rprq0jys.js → chunk-1hajf3wc.js} +1 -1
- package/dist/{chunk-qh8xm4v0.js → chunk-1stvxcjv.js} +1 -1
- package/dist/{chunk-8frvdh1c.js → chunk-2m5h2mtr.js} +4 -4
- package/dist/{chunk-z1r3v2zp.js → chunk-488kx8j5.js} +2 -2
- package/dist/{chunk-gda2zgwg.js → chunk-5gppagt3.js} +1 -1
- package/dist/{chunk-kana8xe2.js → chunk-5v5w0cd2.js} +1 -1
- package/dist/{chunk-9p8ad0xr.js → chunk-66b56g2z.js} +2 -2
- package/dist/{chunk-gwwq4drq.js → chunk-6pt4158p.js} +1 -1
- package/dist/{chunk-yprmv7na.js → chunk-7fr038wx.js} +1 -1
- package/dist/{chunk-5hsjpyre.js → chunk-7mrr4ke5.js} +1 -1
- package/dist/{chunk-evnryzyv.js → chunk-7sartb04.js} +1 -1
- package/dist/chunk-7tzzzvdg.js +2 -0
- package/dist/{chunk-yt4tm14c.js → chunk-8a5txj4f.js} +1 -1
- package/dist/{chunk-0ec2fmqc.js → chunk-8e23zh2y.js} +1 -1
- package/dist/{chunk-8sqctywt.js → chunk-8q63njnd.js} +1 -1
- package/dist/{chunk-qp2jk2pp.js → chunk-8rmb79zw.js} +1 -1
- package/dist/chunk-8rwnzmvb.js +2 -0
- package/dist/{chunk-sj5fx57w.js → chunk-8ztgy5y4.js} +5 -5
- package/dist/{chunk-nj4jfxba.js → chunk-90pxjq62.js} +1 -1
- package/dist/{chunk-4whrqhn7.js → chunk-9s4ggstz.js} +1 -1
- package/dist/{chunk-m64nb7ex.js → chunk-9xdz8r73.js} +1 -1
- package/dist/{chunk-dwytxk6y.js → chunk-agvykxs8.js} +1 -1
- package/dist/{chunk-xnef5s0n.js → chunk-ay4ep67v.js} +1 -1
- package/dist/{chunk-qs6svx75.js → chunk-bwfncfe1.js} +1 -1
- package/dist/{chunk-gw9253rm.js → chunk-d6arvs57.js} +1 -1
- package/dist/{chunk-0dwas9xw.js → chunk-dsrn2vgp.js} +1 -1
- package/dist/{chunk-vxqcyc6s.js → chunk-e0wxcst7.js} +1 -1
- package/dist/{chunk-43wbenp9.js → chunk-efrc97by.js} +2 -2
- package/dist/{chunk-pr18te9q.js → chunk-enep9r03.js} +2 -2
- package/dist/{chunk-993rvsg3.js → chunk-epcy3r18.js} +6 -6
- package/dist/chunk-fpw03bhv.js +2 -0
- package/dist/chunk-g747k4gg.js +3 -0
- package/dist/chunk-gryrg1c0.js +2 -0
- package/dist/{chunk-dj6xgn71.js → chunk-gvj862m1.js} +1 -1
- package/dist/{chunk-xf7x0z91.js → chunk-h5nrnen8.js} +1 -1
- package/dist/chunk-hagk74x6.js +2 -0
- package/dist/{chunk-cvp0s1rn.js → chunk-hh9t97hr.js} +1 -1
- package/dist/{chunk-qr9etkeb.js → chunk-hv0whj8t.js} +1 -1
- package/dist/{chunk-b1fampss.js → chunk-j56mg28d.js} +1 -1
- package/dist/{chunk-dd1c1j50.js → chunk-j6255z7f.js} +1 -1
- package/dist/{chunk-a6bg2e4v.js → chunk-k2brrhf8.js} +1 -1
- package/dist/{chunk-6qkfrvny.js → chunk-k6ncb5qm.js} +1 -1
- package/dist/{chunk-6sgq4s9g.js → chunk-nbjgytem.js} +1 -1
- package/dist/{chunk-6c87xeb3.js → chunk-ne69yaak.js} +4 -4
- package/dist/{chunk-adhgq97t.js → chunk-nps2whkz.js} +4 -4
- package/dist/chunk-nt7wqqax.js +2 -0
- package/dist/{chunk-gq609sem.js → chunk-nwbq8qvb.js} +29 -6
- package/dist/chunk-pq1qs7bp.js +2 -0
- package/dist/{chunk-jgkv0k6c.js → chunk-pvw58x2j.js} +1 -1
- package/dist/{chunk-ssve2zg1.js → chunk-qk9v0emh.js} +1 -1
- package/dist/{chunk-sehq8bk3.js → chunk-qnj444zc.js} +1 -1
- package/dist/{chunk-gbxssrny.js → chunk-rgz797k3.js} +1 -1
- package/dist/{chunk-082kr8js.js → chunk-sq0qc9sk.js} +1 -1
- package/dist/{chunk-w95wvtyx.js → chunk-ssh2gycr.js} +1 -1
- package/dist/{chunk-17rwn43y.js → chunk-t3ptzpfc.js} +1 -1
- package/dist/{chunk-tm3h0r29.js → chunk-vav9ktgm.js} +1 -1
- package/dist/{chunk-veqyargb.js → chunk-w6taxq7d.js} +3 -3
- package/dist/{chunk-096ztrq9.js → chunk-wk6xsyv3.js} +1 -1
- package/dist/chunk-wmh4yxcs.js +2 -0
- package/dist/chunk-xmae29mn.js +2 -0
- package/dist/{chunk-0kvdx4ap.js → chunk-y0pqpch2.js} +2 -2
- package/dist/{chunk-0nmbjp2b.js → chunk-yyr7vb7k.js} +2 -2
- package/dist/{chunk-55wy94xb.js → chunk-zssf9fdg.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/client/signals-binding-utils-runtime.js +12 -4
- package/dist/client/signals-expression-compiler-runtime.js +4 -1
- package/dist/client/signals-expression-runtime.js +3 -1
- package/dist/client/signals-pipe-runtime.js +10 -0
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/compiler/inline-style.d.ts +0 -1
- package/dist/native/compiler/inline-style.js +5 -1
- package/dist/native/runtime/binding-tree.d.ts +10 -5
- package/dist/native/runtime/binding-tree.js +18 -10
- package/dist/native/runtime/native-host.d.ts +2 -0
- package/dist/native/runtime/native-host.js +166 -77
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-0zgbr23r.js +0 -2
- package/dist/chunk-3fv5twk7.js +0 -3
- package/dist/chunk-7b40ec5m.js +0 -2
- package/dist/chunk-7k1axr1q.js +0 -2
- package/dist/chunk-e5fbnsdn.js +0 -2
- package/dist/chunk-g9ya1qyb.js +0 -2
- package/dist/chunk-kxwft3at.js +0 -2
- package/dist/chunk-q7cnkbxq.js +0 -2
- package/dist/chunk-sx1s4ra0.js +0 -2
- package/dist/chunk-t65y3nsh.js +0 -2
- package/dist/chunk-vknj7kpa.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-
|
|
2
|
+
import{lt,ut,dt}from"./chunk-7qk4exw1.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{m}from"./chunk-epcy3r18.js";import"./chunk-94gyfwpz.js";import"./chunk-27rzdq3n.js";import"./chunk-8e23zh2y.js";import{Vt,eo,Ut,Hi,ct,Vi,to,Wt,Wi,qt}from"./chunk-7gdwvnwc.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{Vi("Config file changed, restarting...");try{await e.onChange()}catch(p){ct(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",pt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:pt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:mt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function mt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
const ws = new WebSocket('${t}');
|
|
@@ -556,7 +556,7 @@ window.__stxPerformance = {
|
|
|
556
556
|
|
|
557
557
|
window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
|
|
558
558
|
</script>
|
|
559
|
-
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-
|
|
559
|
+
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-1ds97d9m.js"),p={},g=h(n);if(g)try{await m(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),u=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:u,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await m(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-1ds97d9m.js"),c={...r},n=h(e);if(n)try{await m(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
560
560
|
`)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
561
561
|
`)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await Wt(t);ut(t,r);let s=qt(t.config,r);dt(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),g=`http://${o}:${e.port}`,y=Wi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let u=await Wt(t);ut(t,u);let f=qt(t.config,u);if(dt(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=g;try{let{exec:l}=await import("child_process"),u=process.platform;l(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:g,close:async()=>{y(),p.stop()}}}async function xt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],g=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((u)=>u.id===p);if(!l)return new Response("Story not found",{status:404});try{let u=await Y(t,l,g,y);return Response.json({html:u.html,css:u.css,js:u.js,errors:u.errors,duration:u.duration})}catch(u){return Response.json({html:"",css:"",js:"",errors:[u instanceof Error?u.message:String(u)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((g)=>g.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function wt(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
|
|
562
562
|
<html lang="en" class="${r.darkClass||"dark"}">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{wf,vf,he,xf,Za,en,tn,wh,Qa,nn,Qn,Sf,kf,_f,rs,rn,Cf,sn,ec,vh}from"./chunk-
|
|
2
|
+
import{wf,vf,he,xf,Za,en,tn,wh,Qa,nn,Qn,Sf,kf,_f,rs,rn,Cf,sn,ec,vh}from"./chunk-j6255z7f.js";import"./chunk-d6arvs57.js";import"./chunk-7sh9fa3q.js";import"./chunk-enep9r03.js";import"./chunk-wk6xsyv3.js";import"./chunk-h0jnatd4.js";import"./chunk-605b93pe.js";import"./chunk-w9nwb8r3.js";import"./chunk-q14d714d.js";import"./chunk-epcy3r18.js";import"./chunk-8e23zh2y.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Qn as MODULE_SPECIFIER_PREFIX,wf as bundleCacheDir,vf as bundleCacheEntryLimit,vh as bundleClientEntriesSplit,sn as bundleClientScript,tn as clearBundleFailures,he as clientBundleDependencies,en as getBundleFailures,nn as hasUserImports,rn as moduleSubstitutionKey,kf as normalizeRegistrySpecifiers,Cf as queueClientBundleBuild,Za as recordBundleFailure,Sf as registryIdForPath,Qa as resolveBundlerFallback,_f as rewriteRegistryImports,wh as setBundlerFallbackMode,xf as shouldLogBundlerDiagnostics,ec as tempBuildName,rs as withModuleSubstitutes};
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{Pe,oe}from"./chunk-
|
|
3
|
+
import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{Pe,oe}from"./chunk-epcy3r18.js";import"./chunk-27rzdq3n.js";import"./chunk-8e23zh2y.js";import"./chunk-h0jnatd4.js";import"./chunk-q14d714d.js";import"./chunk-enep9r03.js";import"./chunk-w9nwb8r3.js";import"./chunk-605b93pe.js";import"./chunk-2m5h2mtr.js";import"./chunk-bwfncfe1.js";import"./chunk-66b56g2z.js";import"./chunk-e0wxcst7.js";import"./chunk-ne69yaak.js";import"./chunk-1stvxcjv.js";import"./chunk-b4r7d6me.js";import"./chunk-c0ejyxfj.js";import"./chunk-0r61tkfe.js";import"./chunk-vkn133cs.js";import"./chunk-v8rfeev5.js";import"./chunk-h0c6jtrj.js";import"./chunk-w6taxq7d.js";import"./chunk-2p4yad7w.js";import"./chunk-t3ptzpfc.js";import"./chunk-nwbq8qvb.js";import"./chunk-5j619xgb.js";import"./chunk-agtvdtx4.js";import"./chunk-vav9ktgm.js";import"./chunk-1y9ez7nz.js";import"./chunk-y0pqpch2.js";import"./chunk-ssh2gycr.js";import"./chunk-2gqhfge6.js";import"./chunk-hh9t97hr.js";import"./chunk-rrb9m2q2.js";import"./chunk-d6arvs57.js";import"./chunk-j56mg28d.js";import"./chunk-15ckxpq7.js";import"./chunk-tnkxww7b.js";import"./chunk-tnn0br4w.js";import"./chunk-gv3bfkdm.js";import"./chunk-7sh9fa3q.js";import{en,tn}from"./chunk-j6255z7f.js";import"./chunk-rgz797k3.js";import"./chunk-pvw58x2j.js";import"./chunk-6v4b0xc1.js";import"./chunk-pa9zfbh6.js";import"./chunk-5a92srn2.js";import"./chunk-e3wmnjz8.js";import"./chunk-vrbcdds3.js";import"./chunk-7fr038wx.js";import"./chunk-7sartb04.js";import{qi,Ki,Xi,Gi,so,Ji,Yi,Zi,oo,io,Fr,zr,Hr}from"./chunk-8ztgy5y4.js";import"./chunk-efrc97by.js";import"./chunk-d18xd9x5.js";import"./chunk-5gppagt3.js";import"./chunk-g747k4gg.js";import"./chunk-qv85c3qy.js";import"./chunk-nps2whkz.js";import"./chunk-w5hhqjwr.js";import{mc}from"./chunk-wk6xsyv3.js";import{g}from"./chunk-0dve54ne.js";import{spawn as R}from"child_process";import S from"fs";import f from"path";import n from"process";import{CLI as z}from"@stacksjs/clapp";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new z("stx");function E(h){let m=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(m))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(m<1024||m>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function A(h){try{if(!S.existsSync(h)){let x=f.dirname(h),t=f.basename(h);if(S.existsSync(x)){let o=S.readdirSync(x).filter((s)=>s.toLowerCase().includes(t.toLowerCase().substring(0,3))||s.endsWith(".stx")||s.endsWith(".md")),r=o.length>0?`File not found. Similar files in ${x}: ${o.slice(0,3).join(", ")}`:`File not found. Directory ${x} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${h}`,suggestion:r}}return{isValid:!1,error:`File does not exist: ${h}`,suggestion:"Check the file path and try again"}}if(S.statSync(h).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${h}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(m){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function I(h){let m=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(m))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(m<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(m>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var O=(h)=>h.includes("*")||h.includes("?")||h.includes("{")||h.includes("["),W=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,m=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(m)}function M(h){if(!h)return;let m;try{m=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof m!=="object"||m===null||Array.isArray(m))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(m))if(typeof t!=="string"&&typeof t!=="number"&&typeof t!=="boolean")console.error(`\u274C --info-plist value for "${x}" must be a string, number or boolean`),n.exit(1);return m}async function V(h,m){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let i=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(i.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...i),m.verbose)console.log(`Found ${i.length} file(s) matching pattern: ${c}`)}catch(i){return console.error(`Error expanding glob pattern ${c}:`,i),!1}else t.push(c);if(t.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(x.push(...t),m.filter)x.push("--pattern",m.filter);if(m.timeout)x.push("--timeout",m.timeout.toString());if(m.reporter&&m.reporter!=="default")if(m.reporter==="junit"){let c=f.resolve("stx-test-report.xml");x.push("--reporter",m.reporter),x.push("--reporter-outfile",c),console.log(`JUnit report: ${c}`)}else console.warn(`Warning: Reporter '${m.reporter}' is not supported. Using default reporter.`);if(m.coverage)x.push("--coverage");if(m.watch)x.push("--watch");x.push("--preload",f.join(__dirname,"../../../test-utils/happy-dom.ts"));let e={...n.env,STX_TEST_MODE:"true",STX_TEST_UI:m.ui?"true":"false",STX_TEST_VERBOSE:m.verbose?"true":"false"},o="bun";if(m.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let r=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(i)=>{let d=((performance.now()-r)/1000).toFixed(2);if(i===0)c(!0);else c(!1)}),n.on("SIGINT",()=>{console.log(`
|
|
4
4
|
Test run interrupted`),s.kill("SIGINT"),n.exit(1)})})}catch(x){return console.error("Error running tests:",x instanceof Error?x.message:String(x)),!1}}var U=n.argv.length>=3&&(W(n.argv[2])&&S.existsSync(n.argv[2])||O(n.argv[2]));if(U){let h=n.argv[2],m={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let x=3;x<n.argv.length;x++){let t=n.argv[x];if(t==="--port"&&x+1<n.argv.length){let e=E(n.argv[++x]);if(!e.isValid)F(e);m.port=Number.parseInt(n.argv[x],10)}else if(t==="--no-watch")m.watch=!1;else if(t==="--highlight-theme"&&x+1<n.argv.length){if(!m.markdown)m.markdown={};if(!m.markdown.syntaxHighlighting)m.markdown.syntaxHighlighting={};m.markdown.syntaxHighlighting.defaultTheme=n.argv[++x]}else if(t==="--no-highlight"){if(!m.markdown)m.markdown={};if(!m.markdown.syntaxHighlighting)m.markdown.syntaxHighlighting={};m.markdown.syntaxHighlighting.enabled=!1}else if(t==="--no-highlight-unknown"){if(!m.markdown)m.markdown={};if(!m.markdown.syntaxHighlighting)m.markdown.syntaxHighlighting={};m.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(t==="--no-cache")m.cache=!1;else if(t==="--native")m.native=!0}if(O(h))try{let x=await Array.fromAsync(new Bun.Glob(h).scan({onlyFiles:!0,absolute:!0})),t=h.endsWith(".stx")?x.filter((s)=>s.endsWith(".stx")):h.endsWith(".md")?x.filter((s)=>s.endsWith(".md")):x.filter((s)=>s.endsWith(".stx")||s.endsWith(".md")),e=h.split("*")[0].replace(/\/$/,"")||".",o=f.resolve(e);try{let s=new Bun.Glob("**/*.stx"),i=(await Array.fromAsync(s.scan({cwd:o,onlyFiles:!0,absolute:!0}))).filter((l)=>/\[.+\]/.test(f.basename(l)));for(let l of i)if(!t.includes(l))t.push(l)}catch{}if(t.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${h}`),n.exit(1);if(!await zr(t,m))n.exit(1)}catch(x){console.error("Failed to process files:",x),n.exit(1)}else Fr(h,m).catch((x)=>{console.error("Failed to start dev server:",x),n.exit(1)})}else{let h=function(t,e){let o=[];for(let r=0;r<=e.length;r++)o[r]=[r];for(let r=0;r<=t.length;r++)o[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++)if(e.charAt(r-1)===t.charAt(s-1))o[r][s]=o[r-1][s-1];else o[r][s]=Math.min(o[r-1][s-1]+1,o[r][s-1]+1,o[r-1][s]+1);return o[e.length][t.length]};y.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(t)=>{try{if(await Gi(t))console.log("Documentation generated successfully."),n.exit(0);else console.error("Documentation generation failed."),n.exit(1)}catch(e){console.error("Error generating documentation:",e),n.exit(1)}}),y.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(t,e)=>{try{let{fetchCollections:o,generatePackage:r}=await import("./chunk-3wkgd883.js");if(t==="list"){console.log(`
|
|
5
5
|
\uD83D\uDCDA Fetching available icon collections...
|
|
6
6
|
`);let s=await o(),c=Object.entries(s).sort((i,l)=>l[1].total-i[1].total);console.log(`Available collections:
|
|
7
7
|
`);for(let[i,l]of c){let d=l;console.log(` ${i.padEnd(30)} ${d.name} (${d.total} icons)`)}console.log(`
|
|
8
8
|
Total: ${c.length} collections`)}else if(t.startsWith("generate")){let s=t==="generate"?"":t.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!s)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),n.exit(1);let c=e.output||f.join(n.cwd(),"packages/collections"),i=e.icons?e.icons.split(",").map((l)=>l.trim()):void 0;await r(s,c,i),console.log(`
|
|
9
9
|
\u2713 Package generated successfully!`),console.log(`
|
|
10
|
-
To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:r}=await import("./chunk-6f6xqzhb.js"),{loadConfig:s}=await import("./chunk-
|
|
10
|
+
To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:r}=await import("./chunk-6f6xqzhb.js"),{loadConfig:s}=await import("./chunk-nbjgytem.js");console.log(`
|
|
11
11
|
\uD83D\uDD0D Running PWA audit...
|
|
12
12
|
`);let c=await s(),i=e.output||"dist",l=o(c,i);if(console.log(r(l)),l.failed>0)n.exit(1)}else console.error(`Unknown pwa command: ${t}`),console.error("Available commands: audit"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("dev [file]","Start a development server for an STX app or file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--pages <dir>",'Directory containing page templates (default: pagesDir from stx.config.ts, else "pages")').option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--titlebar-hidden","Hide the native titlebar but keep the traffic-light buttons (web content draws under a transparent full-size titlebar). Implies --native.").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").option("--no-hmr","Disable HMR / live-reload script injection (useful for clean network traces)").option("--profile","Print per-directive timing for every page render via performanceMonitor").option("--debug-directives","Log directive ordering and intermediate template state during rendering").example("stx dev").example("stx dev --port 8080").example("stx dev --pages src/pages").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev template.stx --native").action(async(t,e)=>{try{if(e.port!==void 0){let r=E(e.port);if(!r.isValid)F(r);e.port=Number.parseInt(String(e.port),10)}if(e.timeout!==void 0){let r=I(e.timeout);if(!r.isValid)F(r)}let o={syntaxHighlighting:{enabled:e.highlight!==!1,serverSide:!0,defaultTheme:e.highlightTheme||"github-dark",highlightUnknownLanguages:e.highlightUnknown!==!1}};if(!t){if(!await Hr(".",{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}if(!O(t))try{let r=await import("fs");if(r.existsSync(t)&&r.statSync(t).isDirectory()){if(!await Hr(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}}catch{}if(O(t)){console.log(`Expanding glob pattern: ${t}`);let r=await oe.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),s=t.endsWith(".stx")?r.filter((d)=>d.endsWith(".stx")):t.endsWith(".md")?r.filter((d)=>d.endsWith(".md")):r.filter((d)=>d.endsWith(".stx")||d.endsWith(".md"));if(s.length===0)console.error(`No STX or Markdown files found matching pattern: ${t}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),n.exit(1);let c=t.split("*")[0].replace(/\/$/,"")||".",i=f.resolve(c);try{let d=new Bun.Glob("**/*.stx"),u=(await Array.fromAsync(d.scan({cwd:i,onlyFiles:!0,absolute:!0}))).filter((p)=>/\[.+\]/.test(f.basename(p)));for(let p of u)if(!s.includes(p))s.push(p)}catch{}if(console.log(`Found ${s.length} ${s.length===1?"file":"files"} matching ${t}`),!await zr(s,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}else{if(!O(t)){let s=A(t);if(!s.isValid)F(s)}if(!await Fr(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}}catch(o){console.error("Error starting dev server:",o),n.exit(1)}}),y.command("a11y [target]","Scan .stx files for accessibility issues (directory, file, or glob)").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example('stx a11y "resources/**/*.stx"').example("stx a11y resources/emails/welcome.stx").example("stx a11y --json --output a11y-report.json").action(async(t=".",e)=>{try{console.log(`Scanning ${t} for accessibility issues...`);let o=e.ignore?e.ignore.split(",").map((l)=>l.trim()):[],{results:r,scannedFiles:s}=await mc(t,{recursive:e.recursive!==!1,ignorePaths:o});if(s.length===0)console.log(`
|
|
13
13
|
No .stx files matched ${t}
|
|
@@ -69,7 +69,7 @@ Total: ${i} issues in ${c} files`),e.output){let l=`
|
|
|
69
69
|
File not found: ${t}`),n.exit(1);if(!t.endsWith(".stx"))console.error(`
|
|
70
70
|
File must have .stx extension: ${t}`),n.exit(1)}let r=f.resolve(e.pages),s=f.resolve(e.out);if(!t&&!S.existsSync(r))console.error(`
|
|
71
71
|
Pages directory not found: ${r}`),console.log(`
|
|
72
|
-
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-
|
|
72
|
+
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-8rmb79zw.js");tn();let i=await c({root:t?f.dirname(t):void 0,debug:e.verbose,ssg:{pagesDir:e.pages,outputDir:e.out,domain:e.domain,baseUrl:e.base,sitemap:e.sitemap,rss:e.rss,minify:e.minify,cache:e.cache!==!1,cleanOutput:e.clean,concurrency:Number.parseInt(e.concurrency,10)||10,publicDir:e.public,trailingSlash:e.trailingSlash,generate404:!0,hooks:e.verbose?{onPageStart:(d)=>console.log(` Generating: ${d}`),onPageEnd:(d,a)=>console.log(` Generated: ${d} (${a.length} bytes)`),onError:(d,a)=>console.error(` Error in ${a}: ${d.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(i.mode==="ssr"&&i.ssr)console.log(`
|
|
73
73
|
Build complete! (SSR)
|
|
74
74
|
`),console.log(` Pages compiled: ${i.ssr.pageCount}`),console.log(` Output: ${i.ssr.outputDir}`),console.log(` Duration: ${l}s
|
|
75
75
|
`);else if(i.ssg){if(console.log(`
|
|
@@ -84,7 +84,7 @@ Total: ${i} issues in ${c} files`),e.output){let l=`
|
|
|
84
84
|
Build completed with ${i.ssg.failedCount} error(s). Fix the issues above and try again.
|
|
85
85
|
`),n.exit(1);console.log(" To preview locally:"),console.log(` cd ${e.out||"dist"} && npx serve
|
|
86
86
|
`)}}catch(o){console.error(`
|
|
87
|
-
Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-
|
|
87
|
+
Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-pq1qs7bp.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){console.error(`
|
|
88
88
|
Failed to start production server:`,e instanceof Error?e.message:String(e)),n.exit(1)}}),y.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(t,e)=>{try{let{deploy:o,initNetlify:r,DeployError:s}=await import("./chunk-kn38mjpp.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${Pe}\x1B[0m`),e.init){console.log(`
|
|
89
89
|
\uD83D\uDCDD Initializing Netlify configuration...
|
|
90
90
|
`);let i=await r({directory:t||n.cwd(),siteId:e.siteId});if(console.log(`\u2713 Created ${i.configPath}`),i.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
|
|
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${t}
|
|
|
124
124
|
\uD83D\uDCDD ${f.relative(n.cwd(),a)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${f.basename(a)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(a,b),console.log(`\u2705 Formatted ${f.relative(n.cwd(),a)}`),l++}catch(u){console.error(`\u274C Error formatting ${f.relative(n.cwd(),a)}:`,u),d++}if(e.check&&d>0)console.log(`
|
|
125
125
|
${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.check&&!e.diff)console.log(`\u2728 Formatted ${l} files successfully`)}catch(o){console.error("Error formatting files:",o),n.exit(1)}}),y.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(t,e)=>{try{if(e.clear){oe.clear(),console.log("\u2705 Performance statistics cleared");return}let o=oe.getStats();if(Object.keys(o).length===0){if(e.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(e.json)console.log(JSON.stringify(o,null,2));else{console.log(`
|
|
126
126
|
\uD83D\uDCCA STX Performance Statistics
|
|
127
|
-
`);for(let[r,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${r}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:r}=await import("./chunk-
|
|
127
|
+
`);for(let[r,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${r}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:r}=await import("./chunk-gryrg1c0.js"),{resolveStxTargets:s}=await import("./chunk-zyf6737j.js"),c=Array.isArray(t)?t:t?[t]:[],i=c.length?c:["**/*.stx"],l=await s(i);if(l.length===0){console.log(`
|
|
128
128
|
No .stx files matched ${i.join(", ")}
|
|
129
129
|
`);return}let d=qi(n.argv,"--lib"),a=d.length>0?d:e.lib?Array.isArray(e.lib)?e.lib:[e.lib]:[],u=await r(l,{client:e.client!==!1,server:e.server!==!1,templates:e.templates!==!1,extraLibs:a});if(u.failure)console.error(`
|
|
130
130
|
Type-check did not run.
|
|
@@ -136,7 +136,7 @@ ${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.chec
|
|
|
136
136
|
${o(u.diagnostics)}
|
|
137
137
|
`);if(console.log(` Checked ${u.blockCount} script block(s) and ${u.expressionCount} template expression(s) in ${u.checkedFiles.length} file(s) \u2014 `+`${p.length} error(s), ${u.diagnostics.length-p.length} warning(s)
|
|
138
138
|
`),p.length>0)n.exit(1)}),y.command("codemod [patterns...]","Find hand-rolled code that an stx primitive already covers").option("--fix","Write the safe rewrites (default is report-only)").option("--rule <rule>","Run one rule only: confirm | tooltip (rewritable) \xB7 alert | route-params | search-params | navigate | "+"fetch | polling | debounce | click-outside | focus | clipboard | watch (report-only)").example("stx codemod").example("stx codemod --rule route-params").example('stx codemod --fix "resources/views/**/*.stx"').action(async(t,e)=>{let{codemodSource:o,formatCodemodFindings:r}=await import("./chunk-v1z6n7wz.js"),s=globalThis.Bun.Glob,c=Array.isArray(t)?t:t?[t]:[],i=c.length?c:["**/*.stx","**/*.ts"],l=e.rule?[e.rule]:void 0;if(e.rule&&e.rule!=="confirm"&&e.rule!=="tooltip")console.error(`Unknown rule "${e.rule}". Expected: confirm | tooltip`),n.exit(1);let d=new Set,a=[],u=0,p=new Set;try{let b=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:n.cwd(),stdout:"pipe",stderr:"pipe"});for(let w of new TextDecoder().decode(b.stdout).split("\x00"))if(w)p.add(f.resolve(n.cwd(),w))}catch{}for(let b of i)for await(let w of new s(b).scan({cwd:n.cwd(),absolute:!0})){if(w.includes("/node_modules/")||w.includes("/dist/")||d.has(w)||p.has(w))continue;d.add(w);let k=await Bun.file(w).text(),v=o(k,{file:w,rules:l});if(a.push(...v.findings),e.fix&&v.code!==k)await Bun.write(w,v.code),u++}if(console.error(r(a,Boolean(e.fix))),e.fix)console.error(`
|
|
139
|
-
${u} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let r=await import("./chunk-
|
|
139
|
+
${u} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let r=await import("./chunk-qnj444zc.js");e=r.generateSignalsRuntime}catch{e=void 0}let o=await oo({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(io(o));if(!o.ok)n.exit(1)}catch(e){console.error("Error running doctor:",e),n.exit(1)}}),y.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(t,e)=>{try{let o=A(t);if(!o.isValid)F(o);console.log(`\uD83D\uDD0D Debugging stx template: ${t}
|
|
140
140
|
`);let r={};if(e.context)try{r=JSON.parse(e.context)}catch(i){console.error("\u274C Invalid JSON in --context option"),n.exit(1)}let s=await Bun.file(t).text();console.log(`\uD83D\uDCC4 Template Content (${s.length} chars):`),console.log("\u2500".repeat(50)),console.log(s.substring(0,500)+(s.length>500?`
|
|
141
141
|
...
|
|
142
142
|
`:"")),console.log("\u2500".repeat(50));let c=s.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(c)console.log(`
|
|
@@ -160,11 +160,11 @@ Press Ctrl+C to stop watching...
|
|
|
160
160
|
\uD83D\uDCC4 Files with issues:`),d.forEach((a)=>{let u=a.issues.filter((p)=>s[p.type]>=c).length;if(u>0)console.log(` ${f.relative(n.cwd(),a.file)} (${u} issues)`)});if(e.saveReport){let a={summary:l,results:d,generatedAt:new Date().toISOString(),commandOptions:e};await Bun.write(e.saveReport,JSON.stringify(a,null,2)),console.log(`
|
|
161
161
|
\uD83D\uDCCB Analysis report saved to: ${e.saveReport}`)}console.log(`
|
|
162
162
|
\u2728 Analysis complete! Use --detailed for more information.`)}catch(o){console.error("Error analyzing templates:",o),n.exit(1)}}),y.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(t,e)=>{let{captureScreenshots:o}=await import("./chunk-kvmpc0sg.js"),r=t||"dist";try{let s=await o(r,e.out,{width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),waitMs:Number.parseInt(e.wait,10),timeoutMs:Number.parseInt(e.timeout,10),fullPage:Boolean(e.fullPage),waitSelector:e.waitSelector,format:e.format,backend:e.backend});for(let c of s)console.log(`\uD83D\uDCF8 ${c.output} (${(c.bytes/1024).toFixed(0)} KB)`);console.log(`
|
|
163
|
-
\u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(Pe)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-
|
|
163
|
+
\u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(Pe)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-7tzzzvdg.js"),o={};if(t.context){let r=f.resolve(t.context);if(S.existsSync(r))try{let s=S.readFileSync(r,"utf-8");o=JSON.parse(s)}catch(s){console.error("Error loading context file:",s),n.exit(1)}else console.error(`Context file not found: ${r}`),n.exit(1)}await e({context:o,cwd:t.cwd?f.resolve(t.cwd):n.cwd(),verbose:t.verbose})}),y.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(t,e)=>{try{let{buildNative:o,getAvailableTargets:r,getAvailableFormats:s}=await import("./chunk-8rwnzmvb.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let i=r();if(e.target&&!["macos","windows","linux","ios","android"].includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${i.join(", ")}`),n.exit(1);let l=e.target||i[0],d=s(l);if(e.format&&!d.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${d.join(", ")}`),n.exit(1);console.log(`
|
|
164
164
|
\uD83D\uDD28 Building native app...`),console.log(` Input: ${t}`),console.log(` Target: ${l}`),console.log(` Format: ${e.format||"default"}`),console.log(` Output: ${e.output}
|
|
165
165
|
`);let a=await o({input:c,output:f.resolve(e.output),target:l,format:e.format,name:e.name,version:e.version,description:e.description,author:e.author,bundleId:e.bundleId,icon:e.icon?f.resolve(e.icon):void 0,window:{title:e.title,width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),frameless:e.frameless,alwaysOnTop:e.alwaysOnTop},systemTray:e.systemTray,menubarOnly:e.menubarOnly,category:e.category,copyright:e.copyright,minimumSystemVersion:e.minSystemVersion,infoPlist:M(e.infoPlist),devTools:e.devTools,craftPath:e.craftPath,verbose:e.verbose});if(a.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${a.outputPath}`),a.duration)console.log(` Duration: ${(a.duration/1000).toFixed(2)}s`);if(l==="macos"&&a.format==="app")console.log(`
|
|
166
166
|
\uD83D\uDCA1 To run: open "${a.outputPath}"`);else if(l==="linux"&&a.format==="appimage")console.log(`
|
|
167
|
-
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-
|
|
167
|
+
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-yyr7vb7k.js");await e({port:t.port?Number.parseInt(t.port,10):6006,open:t.open,host:t.host})}catch(e){console.error(`\u274C Story error: ${e.message}`),n.exit(1)}}),y.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(t)=>{try{let{buildCommand:e}=await import("./chunk-fpn4dren.js");await e({outDir:t.outDir})}catch(e){console.error(`\u274C Story build error: ${e.message}`),n.exit(1)}}),y.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(t)=>{try{let{createContext:e}=await import("./chunk-cgamtmxv.js"),{runVisualTests:o,updateSnapshots:r,formatTestResults:s}=await import("./chunk-6pt4158p.js"),c=await e({mode:"build"});if(t.update){let i=await r(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${i} snapshots`)}else{let i=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(i)),i.failed>0)n.exit(1)}}catch(e){console.error(`\u274C Story test error: ${e.message}`),n.exit(1)}}),y.command("native <action> [file]","Compile .stx screens into the JavaScriptCore bundle Craft renders natively").option("--format <format>","bundle (the JavaScriptCore bundle) or ir (the template as JSON)",{default:"ir"}).option("--output <path>","Write to this file instead of stdout").option("--minify","Minify the bundle",{default:!1}).option("--config <file>","Screens config (default: native.config.json in the working directory)").example("stx native compile Screen.stx --format bundle --output native-screen.js").example("stx native compile --format bundle --output native-screen.js --minify").example("stx native compile Screen.stx").action(async(t,e,o)=>{if(t!=="compile")console.error(`Unknown native command: ${t}`),console.error("Usage: stx native compile [file.stx] --format bundle|ir [--output <file>] [--minify] [--config <file>]"),n.exit(1);try{let{runNativeCompile:r}=await import("./chunk-0675z8hj.js"),s=await r(e,{format:o.format,output:o.output,minify:Boolean(o.minify),config:o.config});for(let c of s.diagnostics)console.warn(`${c.level}: ${c.message}`);if(s.written)console.log(`Compiled: ${e??"screens"} \u2192 ${f.relative(n.cwd(),s.written)||s.written}`);else console.log(s.output)}catch(r){console.error(r instanceof Error?r.message:String(r)),n.exit(1)}}),y.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(t,e)=>{try{let{compileToNative:o}=await import("./chunk-fkkdt6sj.js"),r=f.resolve(t);if(!S.existsSync(r))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let s=["macos","windows","linux","ios","android","universal"];if(!s.includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error(`\uD83D\uDCA1 Available targets: ${s.join(", ")}`),n.exit(1);let c=["zig","typescript","json"];if(!c.includes(e.format))console.error(`\u274C Invalid format: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${c.join(", ")}`),n.exit(1);console.log(`
|
|
168
168
|
\uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${t}`),console.log(` Target: ${e.target}`),console.log(` Format: ${e.format}`),console.log(` Output: ${e.output}
|
|
169
169
|
`);let i=S.readFileSync(r,"utf-8"),l=await o(i,{target:e.target,format:e.format,optimize:e.optimize,treeShake:e.treeShake,hotReload:e.hotReload,debug:e.verbose,sourceMaps:e.sourcemaps,bundle:e.bundle,minify:e.minify}),d=f.resolve(e.output);if(!S.existsSync(d))S.mkdirSync(d,{recursive:!0});let a=f.basename(t,f.extname(t)),u=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",p=f.join(d,`${a}.${u}`);S.writeFileSync(p,l.code);let b=f.join(d,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(d,`${a}.${u}.map`);S.writeFileSync(w,l.sourceMaps)}if(e.target==="universal"&&l.platformCode.size>0)for(let[w,k]of l.platformCode){let v=f.join(d,`${a}.${w}.${u}`);S.writeFileSync(v,k)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${p}`),console.log(` Manifest: ${b}`),console.log(`
|
|
170
170
|
\uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${l.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${l.stats.totalComponents}`),console.log(` Native components: ${l.stats.nativeComponents}`),console.log(` Web fallback components: ${l.stats.webComponents}`),console.log(` Bundle size: ${(l.stats.bundleSize/1024).toFixed(2)}KB`),l.stats.warnings.length>0){console.log(`
|
|
@@ -14,14 +14,22 @@ export const SIGNALS_BINDING_UTILS_RUNTIME = ` // Minimal attribute-only pass f
|
|
|
14
14
|
|
|
15
15
|
function getElementAttributes(el) {
|
|
16
16
|
if (!el || !el.attributes) return [];
|
|
17
|
-
|
|
17
|
+
// A copy, since processing an element removes attributes as it goes. A
|
|
18
|
+
// plain loop: every element of every row comes through here, and
|
|
19
|
+
// Array.from with a map callback was a share of a launch in an interpreter.
|
|
20
|
+
var source = el.attributes;
|
|
21
|
+
// A Map of attributes (some DOMs' clones) has no length: list its entries.
|
|
22
|
+
if (typeof source.length !== 'number') source = Array.from(source);
|
|
23
|
+
var attrs = new Array(source.length);
|
|
24
|
+
for (var i = 0; i < source.length; i++) {
|
|
25
|
+
var attr = source[i];
|
|
18
26
|
// Browser DOM exposes Attr records through NamedNodeMap. HappyDOM and
|
|
19
27
|
// other standards-oriented DOM implementations may expose Map entries
|
|
20
28
|
// for cloned nodes instead. Normalize both shapes so reactive nodes
|
|
21
29
|
// created by :for hydrate exactly like their browser counterparts.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
30
|
+
attrs[i] = Array.isArray(attr) ? { name: attr[0], value: attr[1] } : attr;
|
|
31
|
+
}
|
|
32
|
+
return attrs;
|
|
25
33
|
}
|
|
26
34
|
|
|
27
35
|
function getModelBinding(el) {
|
|
@@ -49,8 +49,11 @@ export const SIGNALS_EXPRESSION_COMPILER_RUNTIME = ` // Compiled expression fun
|
|
|
49
49
|
function __stxCompileScoped(scope, extraParams, body) {
|
|
50
50
|
const keys = [];
|
|
51
51
|
const names = __stxNamesIn(body);
|
|
52
|
+
// A layered view answers from its layers directly: through the proxy,
|
|
53
|
+
// each name cost a trap and a fresh property descriptor.
|
|
54
|
+
const own = __stxOwnOf.get(scope);
|
|
52
55
|
for (let i = 0; i < names.length; i++) {
|
|
53
|
-
if (Object.prototype.propertyIsEnumerable.call(scope, names[i])) keys.push(names[i]);
|
|
56
|
+
if (own !== undefined ? __stxLayerOf(own, names[i]) !== null : Object.prototype.propertyIsEnumerable.call(scope, names[i])) keys.push(names[i]);
|
|
54
57
|
}
|
|
55
58
|
const fn = __stxCompile(extraParams.length ? keys.concat(extraParams) : keys, body);
|
|
56
59
|
// The cache keys on the parameter list, so a function always has these keys.
|
|
@@ -126,8 +126,10 @@ export const SIGNALS_EXPRESSION_RUNTIME = ` // Setup accessors refer to lexical
|
|
|
126
126
|
}
|
|
127
127
|
else layers.push(source);
|
|
128
128
|
}
|
|
129
|
+
// A symbol key, so it is never one of the view's names; assigned rather
|
|
130
|
+
// than defined, which an interpreter makes a far slower path.
|
|
129
131
|
const own = {};
|
|
130
|
-
|
|
132
|
+
own[__STX_LAYERS] = layers;
|
|
131
133
|
const view = new Proxy(own, __stxScopeHandler);
|
|
132
134
|
__stxOwnOf.set(view, own);
|
|
133
135
|
return view;
|
|
@@ -4,7 +4,15 @@ export const SIGNALS_PIPE_RUNTIME = ` // ======================================
|
|
|
4
4
|
|
|
5
5
|
// Parse and execute pipe expressions like "value | fmt" or "value | truncate:20"
|
|
6
6
|
// Must distinguish single | (pipe) from || (logical OR) and ?? (nullish coalescing)
|
|
7
|
+
// Where an expression's top-level pipe is, by its text: every binding
|
|
8
|
+
// evaluation asked, and the answer was a character-by-character scan, which
|
|
9
|
+
// an interpreted engine paid for on each evaluation of each binding.
|
|
10
|
+
const __stxPipeIndex = new Map();
|
|
7
11
|
function parsePipeExpression(expr, scope) {
|
|
12
|
+
// No bar at all, no pipe: the case nearly every expression is.
|
|
13
|
+
if (expr.indexOf('|') === -1) return null;
|
|
14
|
+
const known = __stxPipeIndex.get(expr);
|
|
15
|
+
if (known === -1) return null;
|
|
8
16
|
// Find pipe operators: single | that's not part of || or preceded by ?
|
|
9
17
|
// We need to find | that is:
|
|
10
18
|
// 1. Not preceded by | or ?
|
|
@@ -59,6 +67,8 @@ else if (char === stringChar) {
|
|
|
59
67
|
}
|
|
60
68
|
}
|
|
61
69
|
|
|
70
|
+
if (__stxPipeIndex.size >= 5000) __stxPipeIndex.clear();
|
|
71
|
+
__stxPipeIndex.set(expr, pipeIndex);
|
|
62
72
|
if (pipeIndex === -1) return null;
|
|
63
73
|
|
|
64
74
|
const valueExpr = expr.slice(0, pipeIndex).trim();
|
package/dist/craft-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{vo,ya,ba}from"./chunk-es006emk.js";import"./chunk-3gn1t0pa.js";import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import"./chunk-
|
|
2
|
+
import{vo,ya,ba}from"./chunk-es006emk.js";import"./chunk-3gn1t0pa.js";import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import"./chunk-epcy3r18.js";import"./chunk-27rzdq3n.js";import"./chunk-8e23zh2y.js";import"./chunk-h0jnatd4.js";import"./chunk-q14d714d.js";import"./chunk-enep9r03.js";import"./chunk-w9nwb8r3.js";import"./chunk-605b93pe.js";import"./chunk-bwfncfe1.js";import"./chunk-66b56g2z.js";import"./chunk-2m5h2mtr.js";import"./chunk-e0wxcst7.js";import"./chunk-ne69yaak.js";import"./chunk-y0pqpch2.js";import"./chunk-ssh2gycr.js";import"./chunk-2gqhfge6.js";import"./chunk-c0ejyxfj.js";import{pu,wa,gh,mh,va,xo,Zr,xa,Sa,hh,yh,ka,_a,Ca,Ea}from"./chunk-1hajf3wc.js";import"./chunk-efrc97by.js";import"./chunk-g747k4gg.js";import"./chunk-qv85c3qy.js";import"./chunk-nps2whkz.js";import"./chunk-w5hhqjwr.js";import"./chunk-wk6xsyv3.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
package/dist/craft.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{vo,ya,ba}from"./chunk-es006emk.js";import"./chunk-3gn1t0pa.js";import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import"./chunk-
|
|
2
|
+
import{vo,ya,ba}from"./chunk-es006emk.js";import"./chunk-3gn1t0pa.js";import"./chunk-94gyfwpz.js";import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import"./chunk-epcy3r18.js";import"./chunk-27rzdq3n.js";import"./chunk-8e23zh2y.js";import"./chunk-h0jnatd4.js";import"./chunk-q14d714d.js";import"./chunk-enep9r03.js";import"./chunk-w9nwb8r3.js";import"./chunk-605b93pe.js";import"./chunk-bwfncfe1.js";import"./chunk-66b56g2z.js";import"./chunk-2m5h2mtr.js";import"./chunk-e0wxcst7.js";import"./chunk-ne69yaak.js";import"./chunk-y0pqpch2.js";import"./chunk-ssh2gycr.js";import"./chunk-2gqhfge6.js";import"./chunk-c0ejyxfj.js";import{pu,wa,gh,mh,va,xo,Zr,xa,Sa,hh,yh,ka,_a,Ca,Ea}from"./chunk-1hajf3wc.js";import"./chunk-efrc97by.js";import"./chunk-g747k4gg.js";import"./chunk-qv85c3qy.js";import"./chunk-nps2whkz.js";import"./chunk-w5hhqjwr.js";import"./chunk-wk6xsyv3.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
|
@@ -8,7 +8,6 @@ import type { STXStyle } from './ir';
|
|
|
8
8
|
*/
|
|
9
9
|
export declare function applyNativeLayoutDefaults(style: STXStyle): STXStyle;
|
|
10
10
|
export declare function parseNativeStyle(input: unknown, report?: (diagnostic: NativeStyleDiagnostic) => void, context?: NativeStyleContext): STXStyle;
|
|
11
|
-
/** Resolve all same-element variable declarations before evaluating any style layer. */
|
|
12
11
|
export declare function parseNativeStyleLayers(inputs: unknown[], inheritedVariables: NativeStyleVariables | undefined, report: (diagnostic: NativeStyleDiagnostic) => void): { variables: NativeStyleVariables, styles: STXStyle[] };
|
|
13
12
|
export declare interface NativeStyleContext {
|
|
14
13
|
inheritedVariables?: NativeStyleVariables
|
|
@@ -245,8 +245,12 @@ export function parseNativeStyle(input, report = () => {}, context = {}) {
|
|
|
245
245
|
context.onVariables?.(variables.computed());
|
|
246
246
|
return parseEntries(entries, variables, report);
|
|
247
247
|
}
|
|
248
|
+
const NO_STYLE_VARIABLES = new Map;
|
|
248
249
|
export function parseNativeStyleLayers(inputs, inheritedVariables, report) {
|
|
249
|
-
const layers = inputs.map((input) => styleEntries(input, report))
|
|
250
|
+
const layers = inputs.map((input) => styleEntries(input, report));
|
|
251
|
+
if (layers.every((entries) => entries.length === 0))
|
|
252
|
+
return { variables: inheritedVariables ?? NO_STYLE_VARIABLES, styles: layers.map(() => ({})) };
|
|
253
|
+
const variables = createStyleVariables(layers.flat(), inheritedVariables);
|
|
250
254
|
return { variables: variables.computed(), styles: layers.map((entries) => parseEntries(entries, variables, report)) };
|
|
251
255
|
}
|
|
252
256
|
function parseEntries(entries, variables, report) {
|
|
@@ -2,7 +2,7 @@ import type { BindingManifest } from '../../binding-manifest';
|
|
|
2
2
|
import type { NativeHost, NativeNode } from './native-host';
|
|
3
3
|
import type { STXDocument } from '../compiler/ir';
|
|
4
4
|
/** Clone the DOM-shaped metadata while the host clones the native descriptor. */
|
|
5
|
-
export declare function cloneNativeBindingNode(source: NativeBindingNode, id: string, onClassChange?: (value: string) => void): NativeBindingNode;
|
|
5
|
+
export declare function cloneNativeBindingNode(source: NativeBindingNode, id: string, onClassChange?: (value: string) => void, Element?: BindingElementClass): NativeBindingNode;
|
|
6
6
|
/** Build host handles and a manifest-id lookup from already translated IR. */
|
|
7
7
|
export declare function materializeNativeBindingTree(document: STXDocument, manifest: BindingManifest, host: NativeHost): NativeBindingTree;
|
|
8
8
|
export declare interface NativeBindingNode extends NativeNode {
|
|
@@ -33,13 +33,16 @@ export declare interface NativeBindingTree {
|
|
|
33
33
|
nodes: Map<number, NativeBindingNode>
|
|
34
34
|
scopes: Map<string, NativeBindingNode>
|
|
35
35
|
}
|
|
36
|
+
export type BindingElementClass = new (id: string, type: string, attributes: Array<{ name: string, value: string }>, onClassChange?: (value: string) => void) => BindingElement;
|
|
36
37
|
/**
|
|
37
38
|
* A native node as the shared signals runtime sees it: the DOM element subset
|
|
38
39
|
* it reads and writes. A class, so a screen's hundreds of nodes share their
|
|
39
40
|
* methods; an object literal per node made a dozen closures and accessors for
|
|
40
|
-
* each, which an interpreted engine paid for on every mount.
|
|
41
|
+
* each, which an interpreted engine paid for on every mount. A native host
|
|
42
|
+
* extends it once per screen with its position methods (`measure`,
|
|
43
|
+
* `nextSibling`, ...), so even those cost a node nothing.
|
|
41
44
|
*/
|
|
42
|
-
declare class BindingElement {
|
|
45
|
+
export declare class BindingElement {
|
|
43
46
|
__stxId: string;
|
|
44
47
|
__stxScope: string | undefined;
|
|
45
48
|
nodeType: 1;
|
|
@@ -49,11 +52,13 @@ declare class BindingElement {
|
|
|
49
52
|
parentElement: NativeBindingNode | null;
|
|
50
53
|
childNodes: NativeNode[];
|
|
51
54
|
children: NativeNode[];
|
|
52
|
-
|
|
53
|
-
nextElementSibling: NativeBindingNode | null;
|
|
55
|
+
__stxOwner: NativeNode | null;
|
|
54
56
|
namespaceURI: string;
|
|
55
57
|
isConnected: boolean;
|
|
56
58
|
constructor(id: string, type: string, attributes: Array<{ name: string, value: string }>, onClassChange?: (value: string) => void);
|
|
59
|
+
get nextSibling(): NativeNode | null;
|
|
60
|
+
get nextElementSibling(): NativeBindingNode | null;
|
|
61
|
+
protected classChanged(value: string): void;
|
|
57
62
|
get className(): string;
|
|
58
63
|
set className(value: string);
|
|
59
64
|
get classList(): { add: (...tokens: string[]) => void, remove: (...tokens: string[]) => void };
|
|
@@ -6,7 +6,7 @@ function decodeBindingValue(value) {
|
|
|
6
6
|
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/�?39;/g, "'").replace(/'/gi, "'").replace(/&/g, "&");
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
class BindingElement {
|
|
9
|
+
export class BindingElement {
|
|
10
10
|
__stxId;
|
|
11
11
|
__stxScope = void 0;
|
|
12
12
|
nodeType = 1;
|
|
@@ -16,8 +16,7 @@ class BindingElement {
|
|
|
16
16
|
parentElement = null;
|
|
17
17
|
childNodes = [];
|
|
18
18
|
children = [];
|
|
19
|
-
|
|
20
|
-
nextElementSibling = null;
|
|
19
|
+
__stxOwner = null;
|
|
21
20
|
namespaceURI = "";
|
|
22
21
|
isConnected = !0;
|
|
23
22
|
byName;
|
|
@@ -30,6 +29,15 @@ class BindingElement {
|
|
|
30
29
|
this.byName = new Map(attributes.map((attribute) => [attribute.name, attribute]));
|
|
31
30
|
this.onClassChange = onClassChange;
|
|
32
31
|
}
|
|
32
|
+
get nextSibling() {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
get nextElementSibling() {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
classChanged(value) {
|
|
39
|
+
this.onClassChange?.(value);
|
|
40
|
+
}
|
|
33
41
|
get className() {
|
|
34
42
|
return this.getAttribute("class") ?? "";
|
|
35
43
|
}
|
|
@@ -68,7 +76,7 @@ class BindingElement {
|
|
|
68
76
|
this.byName.set(name, attribute);
|
|
69
77
|
}
|
|
70
78
|
if (name === "class")
|
|
71
|
-
this.
|
|
79
|
+
this.classChanged(String(value));
|
|
72
80
|
}
|
|
73
81
|
removeAttribute(name) {
|
|
74
82
|
if (name === "data-stx-scope")
|
|
@@ -79,7 +87,7 @@ class BindingElement {
|
|
|
79
87
|
this.byName.delete(name);
|
|
80
88
|
}
|
|
81
89
|
if (name === "class")
|
|
82
|
-
this.
|
|
90
|
+
this.classChanged("");
|
|
83
91
|
}
|
|
84
92
|
contains(candidate) {
|
|
85
93
|
for (let current = candidate;current; current = current.parentNode)
|
|
@@ -103,24 +111,24 @@ class BindingElement {
|
|
|
103
111
|
return found;
|
|
104
112
|
}
|
|
105
113
|
}
|
|
106
|
-
function createBindingNode(id, type, bindings, connected = !0, classes = "", onClassChange) {
|
|
114
|
+
function createBindingNode(id, type, bindings, connected = !0, classes = "", onClassChange, Element = BindingElement) {
|
|
107
115
|
const attributes = bindings.map((binding) => ({
|
|
108
116
|
name: binding.name,
|
|
109
117
|
value: decodeBindingValue(binding.value)
|
|
110
118
|
}));
|
|
111
119
|
if (classes && !attributes.some((attribute) => attribute.name === "class"))
|
|
112
120
|
attributes.push({ name: "class", value: classes });
|
|
113
|
-
const node = new
|
|
121
|
+
const node = new Element(id, type, attributes, onClassChange);
|
|
114
122
|
node.isConnected = connected;
|
|
115
123
|
return node;
|
|
116
124
|
}
|
|
117
|
-
export function cloneNativeBindingNode(source, id, onClassChange) {
|
|
125
|
+
export function cloneNativeBindingNode(source, id, onClassChange, Element) {
|
|
118
126
|
const bindings = source.attributes.map((attribute) => ({
|
|
119
127
|
name: attribute.name,
|
|
120
128
|
value: attribute.value,
|
|
121
129
|
kind: "attr"
|
|
122
130
|
}));
|
|
123
|
-
return createBindingNode(id, source.tagName, bindings, !1, source.className, onClassChange);
|
|
131
|
+
return createBindingNode(id, source.tagName, bindings, !1, source.className, onClassChange, Element);
|
|
124
132
|
}
|
|
125
133
|
export function materializeNativeBindingTree(document, manifest, host) {
|
|
126
134
|
const entries = new Map(manifest.entries.map((entry) => [entry.id, entry])), nodes = new Map, scopes = new Map;
|
|
@@ -130,7 +138,7 @@ export function materializeNativeBindingTree(document, manifest, host) {
|
|
|
130
138
|
for (const [name, value] of Object.entries(source.bindings ?? {}))
|
|
131
139
|
if (!runtimeBindings.some((binding) => binding.name.replace(/^[:@]/, "") === name))
|
|
132
140
|
runtimeBindings.push({ name: `:${name}`, value, kind: "attr" });
|
|
133
|
-
const node = createBindingNode(id, source.type, runtimeBindings, !0, source._classes, (value) => host.setAttribute(node, "class", value));
|
|
141
|
+
const node = host.bindingElement ? createBindingNode(id, source.type, runtimeBindings, !0, source._classes, void 0, host.bindingElement) : createBindingNode(id, source.type, runtimeBindings, !0, source._classes, (value) => host.setAttribute(node, "class", value));
|
|
134
142
|
if (source.type === "Checkbox" && source.props.type === "checkbox")
|
|
135
143
|
node.tagName = "INPUT";
|
|
136
144
|
if (source.props["data-stx-native-template"])
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type BindingElementClass } from './binding-tree';
|
|
1
2
|
import { type NativeClassTable } from '../compiler/class-table';
|
|
2
3
|
import { type NativeFocusOptions, type NativeViewBounds, type NativeViewOperations } from './view-operations';
|
|
3
4
|
import { type NativeOverlayEntry } from './overlay-presenter';
|
|
@@ -30,6 +31,7 @@ export declare interface NativeHostOptions {
|
|
|
30
31
|
}
|
|
31
32
|
export declare interface NativeHost {
|
|
32
33
|
readonly isNative: true
|
|
34
|
+
readonly bindingElement?: BindingElementClass
|
|
33
35
|
focus: (node: NativeNode, options?: NativeFocusOptions) => Promise<true>
|
|
34
36
|
measure: (node: NativeNode) => Promise<NativeViewBounds>
|
|
35
37
|
syncOverlays: (entries: NativeOverlayEntry[]) => void
|