@stacksjs/stx 0.2.512 → 0.2.514

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.
Files changed (80) hide show
  1. package/dist/{chunk-hkc9hezx.js → chunk-03mkxevd.js} +1 -1
  2. package/dist/chunk-1wbmg22q.js +2 -0
  3. package/dist/chunk-2bdxrryj.js +2 -0
  4. package/dist/{chunk-26b39qx2.js → chunk-2hsp5gee.js} +1 -1
  5. package/dist/{chunk-gq8xkhxx.js → chunk-2yegk32c.js} +1 -1
  6. package/dist/{chunk-epy4ycvv.js → chunk-38x0j2tz.js} +1 -1
  7. package/dist/{chunk-t6ttge9g.js → chunk-4a9tt7cd.js} +1 -1
  8. package/dist/{chunk-ftyen64y.js → chunk-4njn89w1.js} +2 -2
  9. package/dist/chunk-4yrk774b.js +2 -0
  10. package/dist/{chunk-8pknhtv7.js → chunk-518kr9jb.js} +1 -1
  11. package/dist/{chunk-thm0rq9y.js → chunk-5a4wj7t4.js} +2 -2
  12. package/dist/{chunk-76tar7ak.js → chunk-5pzhcesm.js} +1 -1
  13. package/dist/chunk-6bay462v.js +2 -0
  14. package/dist/{chunk-e8hj8v9s.js → chunk-6tmbgcv9.js} +4 -4
  15. package/dist/{chunk-sq9zp9c3.js → chunk-7smpjzzh.js} +1 -1
  16. package/dist/{chunk-vyhtz9k2.js → chunk-7tzf1e7f.js} +1 -1
  17. package/dist/{chunk-q6k3w27m.js → chunk-a59nwgg6.js} +1 -1
  18. package/dist/chunk-a9anp4pr.js +2 -0
  19. package/dist/{chunk-qnmtzvm1.js → chunk-bqz4wenr.js} +1 -1
  20. package/dist/chunk-bvq2hx8a.js +2 -0
  21. package/dist/{chunk-tbh9k246.js → chunk-dhrzmvbj.js} +1 -1
  22. package/dist/{chunk-02m9mhkd.js → chunk-dq6v78fd.js} +1 -1
  23. package/dist/{chunk-p2ckxfs8.js → chunk-epbnttw5.js} +1 -1
  24. package/dist/{chunk-dc46t9tn.js → chunk-fjet17jc.js} +1 -1
  25. package/dist/{chunk-j9dq3q4z.js → chunk-fp7dzqze.js} +1 -1
  26. package/dist/{chunk-a3zn6rc9.js → chunk-fxxrrq9n.js} +1 -1
  27. package/dist/{chunk-wxgs36py.js → chunk-gbfap7rv.js} +1 -1
  28. package/dist/{chunk-8wrxmtce.js → chunk-gynes6rm.js} +1 -1
  29. package/dist/{chunk-e32b0446.js → chunk-h5nv63qx.js} +1 -1
  30. package/dist/{chunk-k3p8vgct.js → chunk-hnz2zh9q.js} +1 -1
  31. package/dist/{chunk-2fabc38n.js → chunk-j49qp4z7.js} +1 -1
  32. package/dist/{chunk-rk153jft.js → chunk-jc25dv0f.js} +1 -1
  33. package/dist/{chunk-wjcfwfms.js → chunk-jf59xwba.js} +1 -1
  34. package/dist/chunk-jg62944p.js +2 -0
  35. package/dist/chunk-md8m0mpb.js +2 -0
  36. package/dist/{chunk-k2fxyvn8.js → chunk-mwac03ak.js} +1 -1
  37. package/dist/chunk-ntx4axaf.js +2 -0
  38. package/dist/{chunk-ctz541w3.js → chunk-pjayjj2m.js} +1 -1
  39. package/dist/{chunk-vfjjp7cf.js → chunk-q9kq007t.js} +1072 -1072
  40. package/dist/chunk-qavbh6vm.js +2 -0
  41. package/dist/{chunk-aadtwt3f.js → chunk-qfx532hv.js} +2 -2
  42. package/dist/{chunk-ss0b1sss.js → chunk-qm8atahn.js} +1 -1
  43. package/dist/{chunk-1eq6nj35.js → chunk-rgh54rqz.js} +1 -1
  44. package/dist/{chunk-4vc67zkb.js → chunk-shqtn2bj.js} +2 -2
  45. package/dist/chunk-skve9q8q.js +2 -0
  46. package/dist/{chunk-1j7na0de.js → chunk-sqf60k0y.js} +1 -1
  47. package/dist/{chunk-s2e33mdf.js → chunk-vdzhw78w.js} +1 -1
  48. package/dist/{chunk-gvqmcf6z.js → chunk-x1v0qyf9.js} +1 -1
  49. package/dist/chunk-x4xxfpn7.js +2 -0
  50. package/dist/chunk-xqgzwexs.js +2 -0
  51. package/dist/{chunk-yd62qhpz.js → chunk-xs48j158.js} +2357 -2357
  52. package/dist/chunk-y3480mx8.js +2 -0
  53. package/dist/{chunk-mrbfx4t7.js → chunk-z6gbf119.js} +1 -1
  54. package/dist/{chunk-68sc0w22.js → chunk-zgg589w4.js} +1 -1
  55. package/dist/{chunk-yy6cqwnj.js → chunk-zsdhaj58.js} +6 -6
  56. package/dist/{chunk-b7fx8rsm.js → chunk-zvg1nqgw.js} +1 -1
  57. package/dist/cli.js +8 -8
  58. package/dist/craft-entry.js +1 -1
  59. package/dist/craft.js +1 -1
  60. package/dist/database.js +2 -2
  61. package/dist/native/runtime/craft-bridge.js +10 -2
  62. package/dist/native/runtime/craft.d.ts +5 -0
  63. package/dist/pwa.js +1 -1
  64. package/dist/ssg.js +2 -2
  65. package/package.json +5 -5
  66. package/dist/chunk-0gzf18jm.js +0 -2
  67. package/dist/chunk-55z4hn0d.js +0 -2
  68. package/dist/chunk-7ceqp9yv.js +0 -2
  69. package/dist/chunk-bf60qqjt.js +0 -2
  70. package/dist/chunk-c331r7za.js +0 -2
  71. package/dist/chunk-ecdffs66.js +0 -2
  72. package/dist/chunk-he7ykm3x.js +0 -2
  73. package/dist/chunk-m8n4gyb7.js +0 -2
  74. package/dist/chunk-qnewez0a.js +0 -2
  75. package/dist/chunk-r96zmdxa.js +0 -2
  76. package/dist/chunk-r9cqq4bk.js +0 -2
  77. package/dist/chunk-rfd1pwk7.js +0 -2
  78. package/dist/chunk-va6x7pkt.js +0 -2
  79. package/dist/chunk-wpcam5kp.js +0 -2
  80. /package/dist/{chunk-jtaqygzg.js → chunk-365ktg70.js} +0 -0
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{aa,xl,ca,la,Sl,kl}from"./chunk-mwac03ak.js";import"./chunk-xs48j158.js";import"./chunk-fxxrrq9n.js";import"./chunk-c57j92td.js";import"./chunk-kp4mzspk.js";import"./chunk-dq6v78fd.js";import"./chunk-6k4f583z.js";import"./chunk-gbfap7rv.js";import"./chunk-gynes6rm.js";import"./chunk-365ktg70.js";import"./chunk-ba88n1j7.js";import"./chunk-yxdyh23k.js";import"./chunk-1aw9qbdf.js";import"./chunk-e6y6s7q8.js";export{kl as applySlots,Sl as extractSlotContent,xl as parseSlotElement,aa as parseSlots,la as processSlots,ca as renderSlot};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{y}from"./chunk-yxdyh23k.js";import{I,At}from"./chunk-ba88n1j7.js";import{w,Ve,L,o}from"./chunk-yd62qhpz.js";import{ie,yt,bt}from"./chunk-1eq6nj35.js";import{Ie,qt,pt,H}from"./chunk-2fb4yx25.js";import f from"path";var l=new Map;function v(a,s){for(let n of a.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(n[1])s.add(n[1]);for(let n of a.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let r of(n[1]??"").split(",")){let i=((r.includes(":")?r.split(":").pop():r)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(i))s.add(i)}for(let n of a.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let r of(n[1]??"").split(",")){let c=r.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(c))s.add(c)}}async function nd(a){let s;if(a)s=f.resolve(a);else{let t=await o();s=f.resolve(t.root||process.cwd(),t.storesDir||"stores")}let n=new Bun.Glob("*.ts"),r=[];try{for await(let t of n.scan({cwd:s,absolute:!0})){let e=f.basename(t,".ts");if(["index","types"].includes(e))continue;if(t.includes(".d.ts"))continue;r.push(t)}}catch{return H(l,s,"",""),null}let c=()=>[...new Set([...r,...r.flatMap((t)=>ie(t))])],i=Ie(c()),d=pt(l,s,i);if(d!==void 0)return d||null;if(r.length===0)return H(l,s,i,""),null;let p=[];for(let t of r){let e=await Bun.file(t).text();p.push({file:t,hasUseStore:/useStore\s*\(/.test(e)})}p.sort((t,e)=>{if(t.hasUseStore===e.hasUseStore)return 0;return t.hasUseStore?1:-1});let h=p.map((t)=>t.file),u=[],m=new Set,b=L({loader:"ts",target:"browser",define:w()});for(let t of h)try{let e=await Bun.file(t).text(),x=f.basename(t,".ts");if(v(e,m),yt(e))e=await bt(e,t,{projectRoot:process.cwd(),externalizeUserModules:!1});e=Ve(e),e=I(e),e=At(e),e=e.replace(/^export\s+(default\s+)?/gm,""),e=b.transformSync(e),u.push(`// Store: ${x}
2
+ import{y}from"./chunk-yxdyh23k.js";import{I,At}from"./chunk-ba88n1j7.js";import{w,Ve,L,o}from"./chunk-xs48j158.js";import{ie,yt,bt}from"./chunk-rgh54rqz.js";import{Ie,qt,pt,H}from"./chunk-2fb4yx25.js";import f from"path";var l=new Map;function v(a,s){for(let n of a.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(n[1])s.add(n[1]);for(let n of a.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*=/g))for(let r of(n[1]??"").split(",")){let i=((r.includes(":")?r.split(":").pop():r)??"").replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(i))s.add(i)}for(let n of a.matchAll(/\b(?:const|let|var)\s*\[([^\]]*)\]\s*=/g))for(let r of(n[1]??"").split(",")){let c=r.replace(/=.*$/s,"").replace(/^\s*\.\.\./,"").trim();if(/^[A-Z_a-z$][\w$]*$/.test(c))s.add(c)}}async function nd(a){let s;if(a)s=f.resolve(a);else{let t=await o();s=f.resolve(t.root||process.cwd(),t.storesDir||"stores")}let n=new Bun.Glob("*.ts"),r=[];try{for await(let t of n.scan({cwd:s,absolute:!0})){let e=f.basename(t,".ts");if(["index","types"].includes(e))continue;if(t.includes(".d.ts"))continue;r.push(t)}}catch{return H(l,s,"",""),null}let c=()=>[...new Set([...r,...r.flatMap((t)=>ie(t))])],i=Ie(c()),d=pt(l,s,i);if(d!==void 0)return d||null;if(r.length===0)return H(l,s,i,""),null;let p=[];for(let t of r){let e=await Bun.file(t).text();p.push({file:t,hasUseStore:/useStore\s*\(/.test(e)})}p.sort((t,e)=>{if(t.hasUseStore===e.hasUseStore)return 0;return t.hasUseStore?1:-1});let h=p.map((t)=>t.file),u=[],m=new Set,b=L({loader:"ts",target:"browser",define:w()});for(let t of h)try{let e=await Bun.file(t).text(),x=f.basename(t,".ts");if(v(e,m),yt(e))e=await bt(e,t,{projectRoot:process.cwd(),externalizeUserModules:!1});e=Ve(e),e=I(e),e=At(e),e=e.replace(/^export\s+(default\s+)?/gm,""),e=b.transformSync(e),u.push(`// Store: ${x}
3
3
  ${e.trim()}`)}catch(e){console.warn(`[stx] Failed to load store ${t}:`,e)}if(u.length===0)return H(l,s,i,""),null;let g=u.join(`
4
4
 
5
5
  `),S=`;(function(){
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{b,u,n,g,R}from"./chunk-yd62qhpz.js";import q from"path";var M={enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},C=/<!-- @section:([\w-]+) -->([\s\S]*?)<!-- @endsection:\1 -->/g;var O=/<!-- @suspense:([\w-]+) -->([\s\S]*?)<!-- @endsuspense:\1 -->/g;function z(e){let t=[],o=0,s;O.lastIndex=0;while((s=O.exec(e))!==null){if(s.index>o){let a=e.slice(o,s.index);if(a.trim())t.push({type:t.length===0?"shell":"content",content:a})}let r=s[1],i=s[2];t.push({type:"suspense",name:r,content:i}),o=s.index+s[0].length}if(o<e.length){let r=e.slice(o);if(r.trim())t.push({type:t.length===0?"shell":"content",content:r})}if(t.length===0)t.push({type:"shell",content:e});return t}async function ld(e,t={},o={}){let s={...R,...o,streaming:{...M,...o.streaming}},r=s.streaming?.bufferSize||16384;return new ReadableStream({async start(i){try{let a=await Bun.file(e).text(),w=a.match(/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i),m=w?w[1]:"",c=a.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),y={...t,__filename:e,__dirname:q.dirname(e)};if(m.trim())await u(m,y,e);let T=z(c),l=new Set;if(!T.some((h)=>h.type==="suspense")){let h=s.streaming?.strategy||"auto",S=new RegExp(C.source,"g");if(!(h!=="manual"&&S.test(c))){let p=await n(c,y,e,s,l);for(let x=0;x<p.length;x+=r)i.enqueue(p.slice(x,x+r)),await new Promise((f)=>setTimeout(f,0))}else{let p=[],x=new RegExp(C.source,"g"),f;while((f=x.exec(c))!==null)p.push({name:f[1],content:f[2],start:f.index,end:f.index+f[0].length});let E=0;for(let _ of p){if(_.start>E){let k=c.slice(E,_.start);if(k.trim()){let D=await n(k,y,e,s,l);i.enqueue(D),await new Promise((H)=>setTimeout(H,0))}}let I=await n(_.content,y,e,s,l);i.enqueue(I),await new Promise((k)=>setTimeout(k,0)),E=_.end}if(E<c.length){let _=c.slice(E);if(_.trim()){let I=await n(_,y,e,s,l);i.enqueue(I)}}}}else{let h=new Map;for(let d of T)if(d.type==="shell"||d.type==="content"){let p=await n(d.content,y,e,s,l);i.enqueue(p)}else if(d.type==="suspense"&&d.name){let p=`stx-suspense-${d.name}`;i.enqueue(`<div id="${p}" data-suspense="${d.name}" style="display:contents;">
2
+ import{b,u,n,g,R}from"./chunk-xs48j158.js";import q from"path";var M={enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},C=/<!-- @section:([\w-]+) -->([\s\S]*?)<!-- @endsection:\1 -->/g;var O=/<!-- @suspense:([\w-]+) -->([\s\S]*?)<!-- @endsuspense:\1 -->/g;function z(e){let t=[],o=0,s;O.lastIndex=0;while((s=O.exec(e))!==null){if(s.index>o){let a=e.slice(o,s.index);if(a.trim())t.push({type:t.length===0?"shell":"content",content:a})}let r=s[1],i=s[2];t.push({type:"suspense",name:r,content:i}),o=s.index+s[0].length}if(o<e.length){let r=e.slice(o);if(r.trim())t.push({type:t.length===0?"shell":"content",content:r})}if(t.length===0)t.push({type:"shell",content:e});return t}async function ld(e,t={},o={}){let s={...R,...o,streaming:{...M,...o.streaming}},r=s.streaming?.bufferSize||16384;return new ReadableStream({async start(i){try{let a=await Bun.file(e).text(),w=a.match(/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i),m=w?w[1]:"",c=a.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),y={...t,__filename:e,__dirname:q.dirname(e)};if(m.trim())await u(m,y,e);let T=z(c),l=new Set;if(!T.some((h)=>h.type==="suspense")){let h=s.streaming?.strategy||"auto",S=new RegExp(C.source,"g");if(!(h!=="manual"&&S.test(c))){let p=await n(c,y,e,s,l);for(let x=0;x<p.length;x+=r)i.enqueue(p.slice(x,x+r)),await new Promise((f)=>setTimeout(f,0))}else{let p=[],x=new RegExp(C.source,"g"),f;while((f=x.exec(c))!==null)p.push({name:f[1],content:f[2],start:f.index,end:f.index+f[0].length});let E=0;for(let _ of p){if(_.start>E){let k=c.slice(E,_.start);if(k.trim()){let D=await n(k,y,e,s,l);i.enqueue(D),await new Promise((H)=>setTimeout(H,0))}}let I=await n(_.content,y,e,s,l);i.enqueue(I),await new Promise((k)=>setTimeout(k,0)),E=_.end}if(E<c.length){let _=c.slice(E);if(_.trim()){let I=await n(_,y,e,s,l);i.enqueue(I)}}}}else{let h=new Map;for(let d of T)if(d.type==="shell"||d.type==="content"){let p=await n(d.content,y,e,s,l);i.enqueue(p)}else if(d.type==="suspense"&&d.name){let p=`stx-suspense-${d.name}`;i.enqueue(`<div id="${p}" data-suspense="${d.name}" style="display:contents;">
3
3
  <template data-suspense-fallback>Loading...</template>
4
4
  </div>`),h.set(d.name,n(d.content,y,e,s,l))}i.enqueue(`
5
5
  <script>
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ni,Li,ji}from"./chunk-yxdyh23k.js";import{V,Dn,Xt,jr,Br,On,Gt,Jt,Fr,Mn}from"./chunk-x81vcxzs.js";function z(r,d,u,s,i){let y=!0,h=new Set,f=(a)=>s.get?s.get(a):a,l=()=>f(r());return Object.defineProperty(l,"_isSignal",{value:!0}),Object.defineProperty(l,"modifiers",{get:d}),l.set=(a)=>{if(!y)return;let v=d(),g=s.set?s.set(a,v):a;if(v.trim&&typeof g==="string")g=g.trim();if(v.number&&typeof g==="string"&&g!==""){let t=Number(g);if(!Number.isNaN(t))g=t}if(Object.is(r(),g))return;r.set(g),u(g)},l.update=(a)=>l.set(a(l())),l.input=(a)=>{if(!d().lazy)l.set(a)},l.change=(a)=>{if(d().lazy)l.set(a)},l.subscribe=(a)=>{if(!y)return()=>{};let v=r.subscribe((g,t)=>a(f(g),f(t)));return h.add(v),()=>{v(),h.delete(v)}},Object.defineProperty(l,"value",{get:l,set:l.set}),i(()=>{y=!1,h.forEach((a)=>a()),h.clear()}),l}function X(r,d=!0,u){if(!d||!r||typeof window>"u")return;let s=window;if(!s.__STX_DATA__){let y=document.querySelector("script[data-stx-server-data]");try{let h=JSON.parse(y?.textContent||"{}");s.__STX_DATA__=h&&typeof h==="object"&&!Array.isArray(h)?h:{}}catch{s.__STX_DATA__={}}}let i=s.__STX_DATA__;if(i&&Object.prototype.hasOwnProperty.call(i,r))try{return{data:u?u(i[r]):i[r]}}catch(y){return{data:null,error:y instanceof Error?y:Error(String(y))}}return}function Q(r){if(typeof window>"u")return;let d=window;if(r===void 0)d.__STX_DATA__={};else{if(!d.__STX_DATA__)try{let u=JSON.parse(document.querySelector("script[data-stx-server-data]")?.textContent||"{}");d.__STX_DATA__=u&&typeof u==="object"&&!Array.isArray(u)?u:{}}catch{d.__STX_DATA__={}}if(d.__STX_DATA__)delete d.__STX_DATA__[r]}}function G(r){let d=null;try{d=typeof indexedDB<"u"?indexedDB:null}catch{d=null}if(!d)return null;let u=d,s=r||"stx-kept",i=null,y=()=>{if(!i)i=new Promise((f,l)=>{let a=u.open(s,1);a.onupgradeneeded=()=>{a.result.createObjectStore("kv")},a.onsuccess=()=>f(a.result),a.onerror=()=>l(a.error),a.onblocked=()=>l(Error("blocked"))}),i.catch(()=>{i=null});return i},h=(f,l)=>y().then((a)=>new Promise((v,g)=>{let t=a.transaction("kv",f),o=l(t.objectStore("kv"));t.oncomplete=()=>v(o?o.result:void 0),t.onerror=()=>g(t.error),t.onabort=()=>g(t.error)}));return{get:(f)=>h("readonly",(l)=>l.get(f)),set:(f,l)=>h("readwrite",(a)=>{a.put(l,f)}),remove:(f)=>h("readwrite",(l)=>{l.delete(f)}),removePrefix:(f)=>h("readwrite",(l)=>{l.delete(IDBKeyRange.bound(f,`${f}\uFFFF`))})}}function J(r,d){let u=r||{},s=null;if(u.storage!==void 0)s=u.storage;else try{s=typeof localStorage<"u"?localStorage:null}catch{s=null}let i=null,y=u.backend!==void 0;if(y)i=u.backend||null;let h=()=>{if(y)return i;y=!0;try{i=d?d():null}catch{i=null}if(i){let e=i;e.get("__stx_probe__").catch(()=>{if(i===e)i=null})}return i},f=u.limit||32768,l=u.defer||((e)=>{let n=typeof requestIdleCallback==="function"?requestIdleCallback:null;if(n)n(e,{timeout:200});else setTimeout(e,16)}),a=new Map,v=new Set,g=new Map,t=!1,o=Promise.resolve(),m=(e)=>{try{return JSON.parse(e)}catch{return e}},p=(e,n)=>{if(!s)return!1;try{return s.setItem(e,n),!0}catch{return!1}},T=(e)=>{try{if(s)s.removeItem(e)}catch{}},S=()=>{if(t=!1,!g.size)return o;let e=Array.from(g.entries());return g.clear(),o=o.then(()=>Promise.all(e.map(([n,c])=>{if(!i){v.delete(n);try{p(n,JSON.stringify(c===void 0?null:c))}catch{}return}let _;try{return _={v:c},i.set(n,_).catch(()=>{let w;try{w=JSON.stringify(c)}catch{return}return i?i.set(n,{j:w}).catch(()=>{p(n,w)}):void 0})}catch{return}}))).then(()=>{}),o},N=(e,n)=>{if(g.set(e,n),v.add(e),t)return;t=!0,l(()=>{S()})},O=(e)=>{if(!e||typeof e!=="object")return;let n=e;if("v"in n)return{value:n.v};if(typeof n.j==="string")return{value:m(n.j)};return},E={peek(e){if(a.has(e))return{value:a.get(e)};let n=null;try{n=s?s.getItem(e):null}catch{n=null}if(n===null||n===void 0)return;let c=m(n);return a.set(e,c),{value:c}},load(e){let n=E.peek(e),c=n?null:h();if(n||!c)return Promise.resolve(n);return c.get(e).then((_)=>{if(a.has(e))return{value:a.get(e)};let w=O(_);if(w)a.set(e,w.value),v.add(e);return w},()=>{return})},set(e,n){if(a.set(e,n),i&&v.has(e)){N(e,n);return}let c;try{c=JSON.stringify(n===void 0?null:n)}catch{return}if(c.length<=f&&p(e,c))return;if(!h()){if(c.length>f)p(e,c);return}T(e),N(e,n)},forget(e){for(let c of Array.from(a.keys()))if(c.indexOf(e)===0)a.delete(c);for(let c of Array.from(g.keys()))if(c.indexOf(e)===0)g.delete(c);for(let c of Array.from(v))if(c.indexOf(e)===0)v.delete(c);try{if(s)for(let c=s.length-1;c>=0;c--){let _=s.key(c);if(_&&_.indexOf(e)===0)s.removeItem(_)}}catch{}let n=h();if(!n)return o;return o=o.then(()=>n.removePrefix(e)).catch(()=>{}),o},flush(){return S()}};try{if(typeof document<"u"&&document.addEventListener)document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")S()});if(typeof addEventListener==="function")addEventListener("pagehide",()=>{S()})}catch{}return E}function Y(r,d){if(!r)return!1;if(r===d.key)return!0;if(!d.url)return!1;if(r===d.url)return!0;try{let u=typeof location<"u"&&location.origin&&location.origin!=="null"?location.origin:"http://localhost",s=new URL(r,u),i=new URL(d.url,u);if(s.origin!==i.origin||s.pathname!==i.pathname)return!1;return!s.search||s.search===i.search}catch{return!1}}function Z(r){let d=r.prefix||"stx:kept:",u=r.matches||((t,o)=>t===o.key||t===o.url),s=new Set,i=new Map,y,h=(t)=>t===void 0?y:t,f=(t,o)=>{let m=h(o);if(m===!1||m===null||m==="")return null;return`${d}${m===void 0?"":`${m}:`}query:${t}`},l=(t)=>{let o=t&&t.value;if(!o||typeof o!=="object"||!("d"in o))return;return{data:o.d,at:Number(o.at)||0}},a=()=>{let t=globalThis;return t.__stx_outboxes instanceof Map?t.__stx_outboxes:null},v={setScope(t){y=t},scope:()=>y,keyFor:f,seed(t,o){let m=f(t,o);return m?l(r.kept.peek(m)):void 0},restore(t,o){let m=f(t,o);return m?r.kept.load(m).then(l):Promise.resolve(void 0)},persist(t,o,m){let p=f(t,m);if(p)r.kept.set(p,{d:o,at:Date.now()})},overlay(t,o,m){let p=a();if(!p||!p.size)return o;let T=o;return p.forEach((S)=>{try{T=S.overlay(t,T,m)}catch{}}),T},watch(t){return s.add(t),()=>{s.delete(t)}},cachedQuery(t,o){let m=i.get(t);if(m){if(o&&m.__options)m.__options(o);return m}let p=o||{},T=p.initial===void 0?null:p.initial,S=()=>typeof p.scope==="function"?p.scope():p.scope,N=()=>(typeof p.url==="function"?p.url():p.url)||null,O=()=>({key:t,url:N()}),E=S(),e=T,n=0,c=null,_=v.seed(t,E);if(_)e=_.data;let w=r.state(v.overlay(O(),e)),H=r.state(!1),q=r.state(!1),B=r.state(null),I=r.state(_?_.at:0),R=0,P=()=>{w.set(v.overlay(O(),e))},W=(b)=>{let x=R;v.restore(t,b).then((C)=>{if(!C||x!==R||n)return;e=C.data,I.set(C.at),P()})};if(!_)W(E);let ee=()=>{let b=S();if(b===E)return;E=b,R++,c=null,n=0;let x=v.seed(t,E);if(e=x?x.data:T,I.set(x?x.at:0),P(),!x)W(E)},te=(b)=>{let x=N(),C=p.timeoutMs||15000,A=typeof AbortController<"u"?new AbortController:null,k=null,ne=new Promise((D,L)=>{k=setTimeout(()=>{if(A)A.abort();L(Error("The request took too long."))},C)}),K;if(p.load)K=p.load({force:b,url:x,signal:A?A.signal:void 0});else if(x){let D=p.fetch||((M,F)=>fetch(M,F)),L={method:"GET",headers:{Accept:"application/json"}};if(b)L.cache="no-cache";if(A)L.signal=A.signal;K=D(x,L).then((M)=>{if(!M.ok)return M.json().catch(()=>null).then((F)=>{throw Error(F&&(F.error||F.message)||`Request failed (${M.status})`)});return M.json()})}else return Promise.resolve(w());return Promise.race([K,ne]).then((D)=>{if(k)clearTimeout(k);return p.transform?p.transform(D):D},(D)=>{if(k)clearTimeout(k);throw D})},U=(b)=>{if(c)return c;let x=R;if(q.set(!0),n===0&&!I())H.set(!0);let C=()=>{if(x!==R)return;c=null,q.set(!1),H.set(!1)},A=te(b).then((k)=>{if(x!==R)return w();return e=k,n=Date.now(),I.set(n),B.set(null),v.persist(t,k,E),P(),C(),w()},(k)=>{if(x===R)B.set(k&&k.message?k.message:"Could not load.");return C(),w()});return c=A,A},j={data:w,loading:H,isFetching:q,error:B,updatedAt:I,get key(){return t},load(b){if(ee(),!b&&n&&Date.now()-n<(p.staleTime||0))return Promise.resolve(w());return U(!!b)},refresh(){return j.load(!0)},set(b){e=typeof b==="function"?b(e):b,v.persist(t,e,E),P()},invalidate(){n=0},__options(b){p={...p,...b}}};if(s.add({target:O,updated:()=>{if(n||I())U(!1)},outbox:(b)=>{if(b)e=v.overlay(O(),e,b.id),n=0,U(!0);P()}}),i.set(t,j),p.immediate)j.load();return j}},g=typeof window<"u"?window:typeof addEventListener==="function"?globalThis:null;if(r.listen!==!1&&g&&typeof g.addEventListener==="function")g.addEventListener("stx:updated",(t)=>{let o=t.detail||{};if(o.kind!=="api"||typeof o.url!=="string")return;s.forEach((m)=>{if(u(o.url,m.target()))m.updated()})}),g.addEventListener("stx:outbox",(t)=>{let o=t.detail||{},m=o.sent&&typeof o.sent.id==="string"?o.sent:null;s.forEach((p)=>{if(m){let T=Array.isArray(m.affects)?m.affects:[],S=p.target();if(!T.some((N)=>u(N,S)))return}p.outbox(m)})});return v}function De(){let r=re(Kt());try{let u=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(r);return u=u.replace(/\}(var |let |const |function )/g,"};$1"),u}catch{return r}}function re(r){let d=[],u=0,s="console.log(";while(u<r.length){let i=r.indexOf(s,u);if(i===-1){d.push(r.slice(u));break}d.push(r.slice(u,i));let y=1,h=i+s.length;while(h<r.length&&y>0){let f=r[h];if(f==='"'||f==="'"||f==="`"){let l=f;h++;while(h<r.length&&r[h]!==l){if(r[h]==="\\")h++;h++}h++;continue}if(f==="(")y++;else if(f===")")y--;h++}d.push("0"),u=h}return d.join("")}function Kt(){return`
2
+ import{Ni,Li,ji}from"./chunk-yxdyh23k.js";import{V,Dn,Xt,jr,Br,On,Gt,Jt,Fr,Mn}from"./chunk-x81vcxzs.js";function z(r,d=!0,u){if(!d||!r||typeof window>"u")return;let s=window;if(!s.__STX_DATA__){let y=document.querySelector("script[data-stx-server-data]");try{let h=JSON.parse(y?.textContent||"{}");s.__STX_DATA__=h&&typeof h==="object"&&!Array.isArray(h)?h:{}}catch{s.__STX_DATA__={}}}let i=s.__STX_DATA__;if(i&&Object.prototype.hasOwnProperty.call(i,r))try{return{data:u?u(i[r]):i[r]}}catch(y){return{data:null,error:y instanceof Error?y:Error(String(y))}}return}function X(r){if(typeof window>"u")return;let d=window;if(r===void 0)d.__STX_DATA__={};else{if(!d.__STX_DATA__)try{let u=JSON.parse(document.querySelector("script[data-stx-server-data]")?.textContent||"{}");d.__STX_DATA__=u&&typeof u==="object"&&!Array.isArray(u)?u:{}}catch{d.__STX_DATA__={}}if(d.__STX_DATA__)delete d.__STX_DATA__[r]}}function Q(r){let d=null;try{d=typeof indexedDB<"u"?indexedDB:null}catch{d=null}if(!d)return null;let u=d,s=r||"stx-kept",i=null,y=()=>{if(!i)i=new Promise((f,l)=>{let a=u.open(s,1);a.onupgradeneeded=()=>{a.result.createObjectStore("kv")},a.onsuccess=()=>f(a.result),a.onerror=()=>l(a.error),a.onblocked=()=>l(Error("blocked"))}),i.catch(()=>{i=null});return i},h=(f,l)=>y().then((a)=>new Promise((v,g)=>{let t=a.transaction("kv",f),o=l(t.objectStore("kv"));t.oncomplete=()=>v(o?o.result:void 0),t.onerror=()=>g(t.error),t.onabort=()=>g(t.error)}));return{get:(f)=>h("readonly",(l)=>l.get(f)),set:(f,l)=>h("readwrite",(a)=>{a.put(l,f)}),remove:(f)=>h("readwrite",(l)=>{l.delete(f)}),removePrefix:(f)=>h("readwrite",(l)=>{l.delete(IDBKeyRange.bound(f,`${f}\uFFFF`))})}}function G(r,d){let u=r||{},s=null;if(u.storage!==void 0)s=u.storage;else try{s=typeof localStorage<"u"?localStorage:null}catch{s=null}let i=null,y=u.backend!==void 0;if(y)i=u.backend||null;let h=()=>{if(y)return i;y=!0;try{i=d?d():null}catch{i=null}if(i){let e=i;e.get("__stx_probe__").catch(()=>{if(i===e)i=null})}return i},f=u.limit||32768,l=u.defer||((e)=>{let n=typeof requestIdleCallback==="function"?requestIdleCallback:null;if(n)n(e,{timeout:200});else setTimeout(e,16)}),a=new Map,v=new Set,g=new Map,t=!1,o=Promise.resolve(),m=(e)=>{try{return JSON.parse(e)}catch{return e}},p=(e,n)=>{if(!s)return!1;try{return s.setItem(e,n),!0}catch{return!1}},T=(e)=>{try{if(s)s.removeItem(e)}catch{}},S=()=>{if(t=!1,!g.size)return o;let e=Array.from(g.entries());return g.clear(),o=o.then(()=>Promise.all(e.map(([n,c])=>{if(!i){v.delete(n);try{p(n,JSON.stringify(c===void 0?null:c))}catch{}return}let _;try{return _={v:c},i.set(n,_).catch(()=>{let w;try{w=JSON.stringify(c)}catch{return}return i?i.set(n,{j:w}).catch(()=>{p(n,w)}):void 0})}catch{return}}))).then(()=>{}),o},N=(e,n)=>{if(g.set(e,n),v.add(e),t)return;t=!0,l(()=>{S()})},O=(e)=>{if(!e||typeof e!=="object")return;let n=e;if("v"in n)return{value:n.v};if(typeof n.j==="string")return{value:m(n.j)};return},E={peek(e){if(a.has(e))return{value:a.get(e)};let n=null;try{n=s?s.getItem(e):null}catch{n=null}if(n===null||n===void 0)return;let c=m(n);return a.set(e,c),{value:c}},load(e){let n=E.peek(e),c=n?null:h();if(n||!c)return Promise.resolve(n);return c.get(e).then((_)=>{if(a.has(e))return{value:a.get(e)};let w=O(_);if(w)a.set(e,w.value),v.add(e);return w},()=>{return})},set(e,n){if(a.set(e,n),i&&v.has(e)){N(e,n);return}let c;try{c=JSON.stringify(n===void 0?null:n)}catch{return}if(c.length<=f&&p(e,c))return;if(!h()){if(c.length>f)p(e,c);return}T(e),N(e,n)},forget(e){for(let c of Array.from(a.keys()))if(c.indexOf(e)===0)a.delete(c);for(let c of Array.from(g.keys()))if(c.indexOf(e)===0)g.delete(c);for(let c of Array.from(v))if(c.indexOf(e)===0)v.delete(c);try{if(s)for(let c=s.length-1;c>=0;c--){let _=s.key(c);if(_&&_.indexOf(e)===0)s.removeItem(_)}}catch{}let n=h();if(!n)return o;return o=o.then(()=>n.removePrefix(e)).catch(()=>{}),o},flush(){return S()}};try{if(typeof document<"u"&&document.addEventListener)document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")S()});if(typeof addEventListener==="function")addEventListener("pagehide",()=>{S()})}catch{}return E}function J(r,d){if(!r)return!1;if(r===d.key)return!0;if(!d.url)return!1;if(r===d.url)return!0;try{let u=typeof location<"u"&&location.origin&&location.origin!=="null"?location.origin:"http://localhost",s=new URL(r,u),i=new URL(d.url,u);if(s.origin!==i.origin||s.pathname!==i.pathname)return!1;return!s.search||s.search===i.search}catch{return!1}}function Y(r){let d=r.prefix||"stx:kept:",u=r.matches||((t,o)=>t===o.key||t===o.url),s=new Set,i=new Map,y,h=(t)=>t===void 0?y:t,f=(t,o)=>{let m=h(o);if(m===!1||m===null||m==="")return null;return`${d}${m===void 0?"":`${m}:`}query:${t}`},l=(t)=>{let o=t&&t.value;if(!o||typeof o!=="object"||!("d"in o))return;return{data:o.d,at:Number(o.at)||0}},a=()=>{let t=globalThis;return t.__stx_outboxes instanceof Map?t.__stx_outboxes:null},v={setScope(t){y=t},scope:()=>y,keyFor:f,seed(t,o){let m=f(t,o);return m?l(r.kept.peek(m)):void 0},restore(t,o){let m=f(t,o);return m?r.kept.load(m).then(l):Promise.resolve(void 0)},persist(t,o,m){let p=f(t,m);if(p)r.kept.set(p,{d:o,at:Date.now()})},overlay(t,o,m){let p=a();if(!p||!p.size)return o;let T=o;return p.forEach((S)=>{try{T=S.overlay(t,T,m)}catch{}}),T},watch(t){return s.add(t),()=>{s.delete(t)}},cachedQuery(t,o){let m=i.get(t);if(m){if(o&&m.__options)m.__options(o);return m}let p=o||{},T=p.initial===void 0?null:p.initial,S=()=>typeof p.scope==="function"?p.scope():p.scope,N=()=>(typeof p.url==="function"?p.url():p.url)||null,O=()=>({key:t,url:N()}),E=S(),e=T,n=0,c=null,_=v.seed(t,E);if(_)e=_.data;let w=r.state(v.overlay(O(),e)),H=r.state(!1),q=r.state(!1),B=r.state(null),I=r.state(_?_.at:0),R=0,P=()=>{w.set(v.overlay(O(),e))},W=(b)=>{let x=R;v.restore(t,b).then((C)=>{if(!C||x!==R||n)return;e=C.data,I.set(C.at),P()})};if(!_)W(E);let ee=()=>{let b=S();if(b===E)return;E=b,R++,c=null,n=0;let x=v.seed(t,E);if(e=x?x.data:T,I.set(x?x.at:0),P(),!x)W(E)},te=(b)=>{let x=N(),C=p.timeoutMs||15000,A=typeof AbortController<"u"?new AbortController:null,k=null,ne=new Promise((D,L)=>{k=setTimeout(()=>{if(A)A.abort();L(Error("The request took too long."))},C)}),K;if(p.load)K=p.load({force:b,url:x,signal:A?A.signal:void 0});else if(x){let D=p.fetch||((M,F)=>fetch(M,F)),L={method:"GET",headers:{Accept:"application/json"}};if(b)L.cache="no-cache";if(A)L.signal=A.signal;K=D(x,L).then((M)=>{if(!M.ok)return M.json().catch(()=>null).then((F)=>{throw Error(F&&(F.error||F.message)||`Request failed (${M.status})`)});return M.json()})}else return Promise.resolve(w());return Promise.race([K,ne]).then((D)=>{if(k)clearTimeout(k);return p.transform?p.transform(D):D},(D)=>{if(k)clearTimeout(k);throw D})},U=(b)=>{if(c)return c;let x=R;if(q.set(!0),n===0&&!I())H.set(!0);let C=()=>{if(x!==R)return;c=null,q.set(!1),H.set(!1)},A=te(b).then((k)=>{if(x!==R)return w();return e=k,n=Date.now(),I.set(n),B.set(null),v.persist(t,k,E),P(),C(),w()},(k)=>{if(x===R)B.set(k&&k.message?k.message:"Could not load.");return C(),w()});return c=A,A},j={data:w,loading:H,isFetching:q,error:B,updatedAt:I,get key(){return t},load(b){if(ee(),!b&&n&&Date.now()-n<(p.staleTime||0))return Promise.resolve(w());return U(!!b)},refresh(){return j.load(!0)},set(b){e=typeof b==="function"?b(e):b,v.persist(t,e,E),P()},invalidate(){n=0},__options(b){p={...p,...b}}};if(s.add({target:O,updated:()=>{if(n||I())U(!1)},outbox:(b)=>{if(b)e=v.overlay(O(),e,b.id),n=0,U(!0);P()}}),i.set(t,j),p.immediate)j.load();return j}},g=typeof window<"u"?window:typeof addEventListener==="function"?globalThis:null;if(r.listen!==!1&&g&&typeof g.addEventListener==="function")g.addEventListener("stx:updated",(t)=>{let o=t.detail||{};if(o.kind!=="api"||typeof o.url!=="string")return;s.forEach((m)=>{if(u(o.url,m.target()))m.updated()})}),g.addEventListener("stx:outbox",(t)=>{let o=t.detail||{},m=o.sent&&typeof o.sent.id==="string"?o.sent:null;s.forEach((p)=>{if(m){let T=Array.isArray(m.affects)?m.affects:[],S=p.target();if(!T.some((N)=>u(N,S)))return}p.outbox(m)})});return v}function Z(r,d,u,s,i){let y=!0,h=new Set,f=(a)=>s.get?s.get(a):a,l=()=>f(r());return Object.defineProperty(l,"_isSignal",{value:!0}),Object.defineProperty(l,"modifiers",{get:d}),l.set=(a)=>{if(!y)return;let v=d(),g=s.set?s.set(a,v):a;if(v.trim&&typeof g==="string")g=g.trim();if(v.number&&typeof g==="string"&&g!==""){let t=Number(g);if(!Number.isNaN(t))g=t}if(Object.is(r(),g))return;r.set(g),u(g)},l.update=(a)=>l.set(a(l())),l.input=(a)=>{if(!d().lazy)l.set(a)},l.change=(a)=>{if(d().lazy)l.set(a)},l.subscribe=(a)=>{if(!y)return()=>{};let v=r.subscribe((g,t)=>a(f(g),f(t)));return h.add(v),()=>{v(),h.delete(v)}},Object.defineProperty(l,"value",{get:l,set:l.set}),i(()=>{y=!1,h.forEach((a)=>a()),h.clear()}),l}function De(){let r=re(Kt());try{let u=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(r);return u=u.replace(/\}(var |let |const |function )/g,"};$1"),u}catch{return r}}function re(r){let d=[],u=0,s="console.log(";while(u<r.length){let i=r.indexOf(s,u);if(i===-1){d.push(r.slice(u));break}d.push(r.slice(u,i));let y=1,h=i+s.length;while(h<r.length&&y>0){let f=r[h];if(f==='"'||f==="'"||f==="`"){let l=f;h++;while(h<r.length&&r[h]!==l){if(r[h]==="\\")h++;h++}h++;continue}if(f==="(")y++;else if(f===")")y--;h++}d.push("0"),u=h}return d.join("")}function Kt(){return`
3
3
  // STX Signals Runtime (Development Build)
4
4
  console.log('[stx] signals runtime loading');
5
5
  // Pre-initialization shim: capture onMount/onDestroy calls made before the runtime IIFE runs
@@ -1385,8 +1385,8 @@ finally {
1385
1385
  // Declarative Data Fetching (Feature #6 - useFetch)
1386
1386
  // ==========================================================================
1387
1387
 
1388
- var readHydratedData = ${X.toString()};
1389
- var clearServerData = ${Q.toString()};
1388
+ var readHydratedData = ${z.toString()};
1389
+ var clearServerData = ${X.toString()};
1390
1390
 
1391
1391
  function useFetch(urlOrFn, options = {}) {
1392
1392
  const hydrated = readHydratedData(options.key, options.hydrate !== false, options.transform);
@@ -6517,8 +6517,8 @@ catch (e) {} }
6517
6517
  // off the critical path and read back asynchronously. Values kept before it
6518
6518
  // are read where they are.
6519
6519
  var STX_KEPT_PREFIX = 'stx:kept:';
6520
- var __stxKept = (${J.toString()})(undefined, ${G.toString()});
6521
- var __stxQueries = (${Z.toString()})({ state: state, kept: __stxKept, prefix: STX_KEPT_PREFIX, matches: ${Y.toString()} });
6520
+ var __stxKept = (${G.toString()})(undefined, ${Q.toString()});
6521
+ var __stxQueries = (${Y.toString()})({ state: state, kept: __stxKept, prefix: STX_KEPT_PREFIX, matches: ${J.toString()} });
6522
6522
  function stxKeptPrefix(scope) {
6523
6523
  return STX_KEPT_PREFIX + (scope === undefined || scope === null || scope === '' ? '' : String(scope) + ':');
6524
6524
  }
@@ -6643,7 +6643,7 @@ catch (e) {} }
6643
6643
  return normalizedPrefix + '-' + __stxGeneratedIdCounter;
6644
6644
  }
6645
6645
 
6646
- var createModelSignal = ${z.toString()};
6646
+ var createModelSignal = ${Z.toString()};
6647
6647
  function useModel(name, options) {
6648
6648
  if (typeof name !== 'string') { options = name || {}; name = 'modelValue'; }
6649
6649
  options = options || {};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{De,Kt,sd}from"./chunk-yy6cqwnj.js";import{V,Dn,Xt,jr,Br,On,od,id,ad,Gt,Jt,Fr,Mn,cd}from"./chunk-x81vcxzs.js";import"./chunk-yxdyh23k.js";export{jr as batch,sd as default,Dn as derived,Xt as effect,De as generateSignalsRuntime,Kt as generateSignalsRuntimeDev,Jt as isDerived,Gt as isSignal,On as onDestroy,Br as onMount,Mn as peek,ad as pendingLifecycleCounts,id as runDestroyCallbacks,od as runMountCallbacks,V as state,Fr as untrack,cd as useOptimistic};
2
+ import{De,Kt,sd}from"./chunk-zsdhaj58.js";import{V,Dn,Xt,jr,Br,On,od,id,ad,Gt,Jt,Fr,Mn,cd}from"./chunk-x81vcxzs.js";import"./chunk-yxdyh23k.js";export{jr as batch,sd as default,Dn as derived,Xt as effect,De as generateSignalsRuntime,Kt as generateSignalsRuntimeDev,Jt as isDerived,Gt as isSignal,On as onDestroy,Br as onMount,Mn as peek,ad as pendingLifecycleCounts,id as runDestroyCallbacks,od as runMountCallbacks,V as state,Fr as untrack,cd as useOptimistic};
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import"./chunk-jtaqygzg.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import{U}from"./chunk-yd62qhpz.js";import"./chunk-8wrxmtce.js";import"./chunk-wxgs36py.js";import"./chunk-6k4f583z.js";import"./chunk-02m9mhkd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import"./chunk-8xpyzcq2.js";import"./chunk-gte0wmh8.js";import"./chunk-n34kagea.js";import"./chunk-67actssw.js";import"./chunk-jcmgj8kk.js";import"./chunk-2j04bc8c.js";import"./chunk-ftyen64y.js";import"./chunk-xx2pk2ay.js";import"./chunk-1j7na0de.js";import"./chunk-yy6cqwnj.js";import"./chunk-4hz4g5ym.js";import"./chunk-h6q8jafh.js";import"./chunk-hkc9hezx.js";import"./chunk-01rz8h7x.js";import"./chunk-gq8xkhxx.js";import"./chunk-fesb4h31.js";import"./chunk-vyhtz9k2.js";import"./chunk-k3p8vgct.js";import"./chunk-68sc0w22.js";import"./chunk-1c407nky.js";import"./chunk-3s9s1mdt.js";import"./chunk-s9mq9x2k.js";import"./chunk-2hc5mbw8.js";import{mt,ht}from"./chunk-1eq6nj35.js";import"./chunk-dc46t9tn.js";import"./chunk-q6k3w27m.js";import"./chunk-vp827ah7.js";import"./chunk-ygetbydb.js";import"./chunk-3y8ykqpx.js";import"./chunk-zv0vgamy.js";import"./chunk-8fb1mqw1.js";import"./chunk-mrbfx4t7.js";import"./chunk-k2fxyvn8.js";import{Ks,Xs,Gs,Js,hr,Ys,Zs,Qs,yr,br,Cn,En,$n}from"./chunk-vfjjp7cf.js";import"./chunk-4vc67zkb.js";import"./chunk-er7y8hk9.js";import{yi}from"./chunk-a3zn6rc9.js";import{d}from"./chunk-yn2d8x8m.js";import{spawn as R}from"child_process";import S from"fs";import W from"os";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.512";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new V("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>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")),i=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:i}}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(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>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("["),H=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(p)}function L(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(p))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 p}async function G(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!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),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.join(W.tmpdir(),`stx-test-report-${Date.now()}.xml`);x.push("--reporter",p.reporter),x.push("--reporter-outfile",c)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.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:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(r)=>{let u=((performance.now()-i)/1000).toFixed(2);if(r===0)c(!0);else c(!1)}),n.on("SIGINT",()=>{console.log(`
3
+ import"./chunk-365ktg70.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import{U}from"./chunk-xs48j158.js";import"./chunk-gynes6rm.js";import"./chunk-gbfap7rv.js";import"./chunk-6k4f583z.js";import"./chunk-dq6v78fd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import"./chunk-8xpyzcq2.js";import"./chunk-gte0wmh8.js";import"./chunk-n34kagea.js";import"./chunk-67actssw.js";import"./chunk-jcmgj8kk.js";import"./chunk-2j04bc8c.js";import"./chunk-4njn89w1.js";import"./chunk-xx2pk2ay.js";import"./chunk-sqf60k0y.js";import"./chunk-zsdhaj58.js";import"./chunk-4hz4g5ym.js";import"./chunk-h6q8jafh.js";import"./chunk-03mkxevd.js";import"./chunk-01rz8h7x.js";import"./chunk-2yegk32c.js";import"./chunk-fesb4h31.js";import"./chunk-7tzf1e7f.js";import"./chunk-hnz2zh9q.js";import"./chunk-zgg589w4.js";import"./chunk-1c407nky.js";import"./chunk-3s9s1mdt.js";import"./chunk-s9mq9x2k.js";import"./chunk-2hc5mbw8.js";import{mt,ht}from"./chunk-rgh54rqz.js";import"./chunk-fjet17jc.js";import"./chunk-a59nwgg6.js";import"./chunk-vp827ah7.js";import"./chunk-ygetbydb.js";import"./chunk-3y8ykqpx.js";import"./chunk-zv0vgamy.js";import"./chunk-8fb1mqw1.js";import"./chunk-z6gbf119.js";import"./chunk-mwac03ak.js";import{Ks,Xs,Gs,Js,hr,Ys,Zs,Qs,yr,br,Cn,En,$n}from"./chunk-q9kq007t.js";import"./chunk-shqtn2bj.js";import"./chunk-er7y8hk9.js";import{yi}from"./chunk-fxxrrq9n.js";import{d}from"./chunk-yn2d8x8m.js";import{spawn as R}from"child_process";import S from"fs";import M from"os";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.514";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new V("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>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")),i=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:i}}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(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>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("["),H=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(p)}function L(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(p))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 p}async function G(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!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),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.join(M.tmpdir(),`stx-test-report-${Date.now()}.xml`);x.push("--reporter",p.reporter),x.push("--reporter-outfile",c)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.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:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(r)=>{let u=((performance.now()-i)/1000).toFixed(2);if(r===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 J=n.argv.length>=3&&(H(n.argv[2])&&S.existsSync(n.argv[2])||O(n.argv[2]));if(J){let h=n.argv[2],p={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=B(n.argv[++x]);if(!e.isValid)F(e);p.port=Number.parseInt(n.argv[x],10)}else if(t==="--no-watch")p.watch=!1;else if(t==="--highlight-theme"&&x+1<n.argv.length){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.defaultTheme=n.argv[++x]}else if(t==="--no-highlight"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.enabled=!1}else if(t==="--no-highlight-unknown"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(t==="--no-cache")p.cache=!1;else if(t==="--native")p.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"),r=(await Array.fromAsync(s.scan({cwd:o,onlyFiles:!0,absolute:!0}))).filter((l)=>/\[.+\]/.test(f.basename(l)));for(let l of r)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 En(t,p))n.exit(1)}catch(x){console.error("Failed to process files:",x),n.exit(1)}else Cn(h,p).catch((x)=>{console.error("Failed to start dev server:",x),n.exit(1)})}else{let h=function(t,e){let o=[];for(let i=0;i<=e.length;i++)o[i]=[i];for(let i=0;i<=t.length;i++)o[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=t.length;s++)if(e.charAt(i-1)===t.charAt(s-1))o[i][s]=o[i-1][s-1];else o[i][s]=Math.min(o[i-1][s-1]+1,o[i][s-1]+1,o[i-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 Js(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:i}=await import("./chunk-ktvr45qg.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((r,l)=>l[1].total-r[1].total);console.log(`Available collections:
7
7
  `);for(let[r,l]of c){let u=l;console.log(` ${r.padEnd(30)} ${u.name} (${u.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"),r=e.icons?e.icons.split(",").map((l)=>l.trim()):void 0;await i(s,c,r),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:i}=await import("./chunk-rn2w32kh.js"),{loadConfig:s}=await import("./chunk-va6x7pkt.js");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:i}=await import("./chunk-rn2w32kh.js"),{loadConfig:s}=await import("./chunk-x4xxfpn7.js");console.log(`
11
11
  \uD83D\uDD0D Running PWA audit...
12
12
  `);let c=await s(),r=e.output||"dist",l=o(c,r);if(console.log(i(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 i=B(e.port);if(!i.isValid)F(i);e.port=Number.parseInt(String(e.port),10)}if(e.timeout!==void 0){let i=z(e.timeout);if(!i.isValid)F(i)}let o={syntaxHighlighting:{enabled:e.highlight!==!1,serverSide:!0,defaultTheme:e.highlightTheme||"github-dark",highlightUnknownLanguages:e.highlightUnknown!==!1}};if(!t){if(!await $n(".",{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 i=await import("fs");if(i.existsSync(t)&&i.statSync(t).isDirectory()){if(!await $n(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 i=await U.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),s=t.endsWith(".stx")?i.filter((u)=>u.endsWith(".stx")):t.endsWith(".md")?i.filter((u)=>u.endsWith(".md")):i.filter((u)=>u.endsWith(".stx")||u.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(/\/$/,"")||".",r=f.resolve(c);try{let u=new Bun.Glob("**/*.stx"),m=(await Array.fromAsync(u.scan({cwd:r,onlyFiles:!0,absolute:!0}))).filter((g)=>/\[.+\]/.test(f.basename(g)));for(let g of m)if(!s.includes(g))s.push(g)}catch{}if(console.log(`Found ${s.length} ${s.length===1?"file":"files"} matching ${t}`),!await En(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 Cn(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:i,scannedFiles:s}=await yi(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: ${r} 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 i=f.resolve(e.pages),s=f.resolve(e.out);if(!t&&!S.existsSync(i))console.error(`
71
71
  Pages directory not found: ${i}`),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-r9cqq4bk.js");ht();let r=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:(u)=>console.log(` Generating: ${u}`),onPageEnd:(u,a)=>console.log(` Generated: ${u} (${a.length} bytes)`),onError:(u,a)=>console.error(` Error in ${a}: ${u.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)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-a9anp4pr.js");ht();let r=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:(u)=>console.log(` Generating: ${u}`),onPageEnd:(u,a)=>console.log(` Generated: ${u} (${a.length} bytes)`),onError:(u,a)=>console.error(` Error in ${a}: ${u.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)console.log(`
73
73
  Build complete! (SSR)
74
74
  `),console.log(` Pages compiled: ${r.ssr.pageCount}`),console.log(` Output: ${r.ssr.outputDir}`),console.log(` Duration: ${l}s
75
75
  `);else if(r.ssg){if(console.log(`
@@ -84,7 +84,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
84
84
  Build completed with ${r.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-qnewez0a.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){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-6bay462v.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:i,DeployError:s}=await import("./chunk-1mkyksne.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${j}\x1B[0m`),e.init){console.log(`
89
89
  \uD83D\uDCDD Initializing Netlify configuration...
90
90
  `);let r=await i({directory:t||n.cwd(),siteId:e.siteId});if(console.log(`\u2713 Created ${r.configPath}`),r.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(m){console.error(`\u274C Error formatting ${f.relative(n.cwd(),a)}:`,m),u++}if(e.check&&u>0)console.log(`
125
125
  ${u} 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){U.clear(),console.log("\u2705 Performance statistics cleared");return}let o=U.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[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),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:i}=await import("./chunk-0gzf18jm.js"),{resolveStxTargets:s}=await import("./chunk-9s3tf3m3.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await s(r);if(l.length===0){console.log(`
127
+ `);for(let[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),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:i}=await import("./chunk-2bdxrryj.js"),{resolveStxTargets:s}=await import("./chunk-9s3tf3m3.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await s(r);if(l.length===0){console.log(`
128
128
  No .stx files matched ${r.join(", ")}
129
129
  `);return}let u=Ks(n.argv,"--lib"),a=u.length>0?u:e.lib?Array.isArray(e.lib)?e.lib:[e.lib]:[],m=await i(l,{client:e.client!==!1,server:e.server!==!1,templates:e.templates!==!1,extraLibs:a});if(m.failure)console.error(`
130
130
  Type-check did not run.
@@ -136,7 +136,7 @@ ${u} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.chec
136
136
  ${o(m.diagnostics)}
137
137
  `);if(console.log(` Checked ${m.blockCount} script block(s) and ${m.expressionCount} template expression(s) in ${m.checkedFiles.length} file(s) \u2014 `+`${g.length} error(s), ${m.diagnostics.length-g.length} warning(s)
138
138
  `),g.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:i}=await import("./chunk-802qf0vz.js"),s=globalThis.Bun.Glob,c=Array.isArray(t)?t:t?[t]:[],r=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 u=new Set,a=[],m=0,g=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)g.add(f.resolve(n.cwd(),w))}catch{}for(let b of r)for await(let w of new s(b).scan({cwd:n.cwd(),absolute:!0})){if(w.includes("/node_modules/")||w.includes("/dist/")||u.has(w)||g.has(w))continue;u.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),m++}if(console.error(i(a,Boolean(e.fix))),e.fix)console.error(`
139
- ${m} 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 i=await import("./chunk-b7fx8rsm.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await yr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(br(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}
139
+ ${m} 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 i=await import("./chunk-zvg1nqgw.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await yr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(br(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 i={};if(e.context)try{i=JSON.parse(e.context)}catch(r){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:`),u.forEach((a)=>{let m=a.issues.filter((g)=>s[g.type]>=c).length;if(m>0)console.log(` ${f.relative(n.cwd(),a.file)} (${m} issues)`)});if(e.saveReport){let a={summary:l,results:u,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-4k65naeg.js"),i=t||"dist";try{let s=await o(i,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(j)}),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-he7ykm3x.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let s=S.readFileSync(i,"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: ${i}`),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:i,getAvailableFormats:s}=await import("./chunk-ctz541w3.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let r=i();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: ${r.join(", ")}`),n.exit(1);let l=e.target||r[0],u=s(l);if(e.format&&!u.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${u.join(", ")}`),n.exit(1);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(j)}),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-qavbh6vm.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let s=S.readFileSync(i,"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: ${i}`),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:i,getAvailableFormats:s}=await import("./chunk-pjayjj2m.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let r=i();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: ${r.join(", ")}`),n.exit(1);let l=e.target||r[0],u=s(l);if(e.format&&!u.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${u.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:L(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-aadtwt3f.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-p4gbvge6.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-wy36z6qp.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-qnmtzvm1.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(r)),r.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:i}=await import("./chunk-e8hj8v9s.js"),s=await i(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(i){console.error(i instanceof Error?i.message:String(i)),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-0eptxhzy.js"),i=f.resolve(t);if(!S.existsSync(i))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(`
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-qfx532hv.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-p4gbvge6.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-wy36z6qp.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-bqz4wenr.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(r)),r.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:i}=await import("./chunk-6tmbgcv9.js"),s=await i(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(i){console.error(i instanceof Error?i.message:String(i)),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-0eptxhzy.js"),i=f.resolve(t);if(!S.existsSync(i))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 r=S.readFileSync(i,"utf-8"),l=await o(r,{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}),u=f.resolve(e.output);if(!S.existsSync(u))S.mkdirSync(u,{recursive:!0});let a=f.basename(t,f.extname(t)),m=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",g=f.join(u,`${a}.${m}`);S.writeFileSync(g,l.code);let b=f.join(u,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(u,`${a}.${m}.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(u,`${a}.${w}.${m}`);S.writeFileSync(v,k)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${g}`),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(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Hr,Ao,Po}from"./chunk-tkagcknf.js";import"./chunk-jtaqygzg.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import"./chunk-yd62qhpz.js";import"./chunk-8wrxmtce.js";import"./chunk-wxgs36py.js";import"./chunk-6k4f583z.js";import"./chunk-02m9mhkd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import{wd,ko,vd,xd,Co,zr,Eo,Sd,$o,kd,Cd,_o,To,Ro}from"./chunk-thm0rq9y.js";import"./chunk-4vc67zkb.js";import"./chunk-a3zn6rc9.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(`
2
+ import{Hr,Ao,Po}from"./chunk-tkagcknf.js";import"./chunk-365ktg70.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import"./chunk-xs48j158.js";import"./chunk-gynes6rm.js";import"./chunk-gbfap7rv.js";import"./chunk-6k4f583z.js";import"./chunk-dq6v78fd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import{wd,ko,vd,xd,Co,zr,Eo,Sd,$o,kd,Cd,_o,To,Ro}from"./chunk-5a4wj7t4.js";import"./chunk-shqtn2bj.js";import"./chunk-fxxrrq9n.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{Hr,Ao,Po}from"./chunk-tkagcknf.js";import"./chunk-jtaqygzg.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import"./chunk-yd62qhpz.js";import"./chunk-8wrxmtce.js";import"./chunk-wxgs36py.js";import"./chunk-6k4f583z.js";import"./chunk-02m9mhkd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import{wd,ko,vd,xd,Co,zr,Eo,Sd,$o,kd,Cd,_o,To,Ro}from"./chunk-thm0rq9y.js";import"./chunk-4vc67zkb.js";import"./chunk-a3zn6rc9.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(`
2
+ import{Hr,Ao,Po}from"./chunk-tkagcknf.js";import"./chunk-365ktg70.js";import"./chunk-c57j92td.js";import"./chunk-1aw9qbdf.js";import"./chunk-yxdyh23k.js";import"./chunk-ba88n1j7.js";import"./chunk-xs48j158.js";import"./chunk-gynes6rm.js";import"./chunk-gbfap7rv.js";import"./chunk-6k4f583z.js";import"./chunk-dq6v78fd.js";import"./chunk-e6y6s7q8.js";import"./chunk-kp4mzspk.js";import{wd,ko,vd,xd,Co,zr,Eo,Sd,$o,kd,Cd,_o,To,Ro}from"./chunk-5a4wj7t4.js";import"./chunk-shqtn2bj.js";import"./chunk-fxxrrq9n.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/database.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new p(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new p(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new p(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",m=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[m]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((m)=>b(s,m))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class p extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=await W(h,m),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m]=o;try{let d=v(h),w=await J(d,m),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,m,d]=o;try{let w=m?JSON.parse(m):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
2
+ var u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},k={},C={},f=new Map,P=[];function z(t){u={...u,...t}}function V(){return{...u}}function G(){u={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let t of Object.keys(k))delete k[t];f.clear(),P.length=0}function X(t,e){k[t]=e}function g(t){let e=t||u.default;if(k[e])return k[e];let r=u.connections[e];if(!r)throw Error(`Database connection "${e}" not configured`);let s=N(r);return k[e]=s,s}function N(t){switch(t.driver){case"sqlite":return D(t);case"postgres":return S(t);case"mysql":return L(t);default:throw Error(`Unsupported database driver: ${t.driver}`)}}function D(t){let e=null,r=!1;return{async connect(){if(r)return;let{Database:s}=await import("bun:sqlite");e=new s(t.database,{create:!0,readwrite:!0}),r=!0},async disconnect(){if(e)e.close(),e=null,r=!1},async query(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).all(...n);if(u.logging)y(s,n,performance.now()-i);return o}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.lastInsertRowid}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!r)await this.connect();let i=performance.now();try{let o=e.prepare(s).run(...n);if(u.logging)y(s,n,performance.now()-i);return o.changes}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!r)await this.connect();e.run("BEGIN TRANSACTION")},async commit(){e.run("COMMIT")},async rollback(){e.run("ROLLBACK")},isConnected(){return r}}}function S(t){let e=!1,r=null;return{async connect(){if(e)return;try{let{Client:s}=await import("pg");r=new s({host:t.host||"localhost",port:t.port||5432,database:t.database,user:t.username,password:t.password,ssl:t.ssl}),await r.connect(),e=!0}catch(s){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rows}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(`${s} RETURNING id`,n);if(u.logging)y(s,n,performance.now()-i);return a.rows[0]?.id}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let a=await r.query(s,n);if(u.logging)y(s,n,performance.now()-i);return a.rowCount||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();await r.query("BEGIN")},async commit(){await r.query("COMMIT")},async rollback(){await r.query("ROLLBACK")},isConnected(){return e}}}function L(t){let e=!1,r=null;return{async connect(){if(e)return;try{let s=await import("mysql2/promise");r=s.createPool({host:t.host||"localhost",port:t.port||3306,database:t.database,user:t.username,password:t.password,waitForConnections:!0,connectionLimit:t.poolSize||10,queueLimit:0}),e=!0}catch(s){throw Error(`MySQL connection failed. Install 'mysql2' package: ${s}`)}},async disconnect(){if(r)await r.end(),r=null,e=!1},async query(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a}catch(a){throw new m(`Query failed: ${a}`,s,n)}},async insert(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.insertId}catch(a){throw new m(`Insert failed: ${a}`,s,n)}},async execute(s,n=[]){if(!e)await this.connect();let i=performance.now();try{let[a]=await r.execute(s,n);if(u.logging)y(s,n,performance.now()-i);return a.affectedRows||0}catch(a){throw new m(`Execute failed: ${a}`,s,n)}},async beginTransaction(){if(!e)await this.connect();let s=await r.getConnection();return await s.beginTransaction(),s},async commit(){await r.execute("COMMIT")},async rollback(){await r.execute("ROLLBACK")},isConnected(){return e}}}class x{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(t){if(t)this._table=t}table(t){return this._table=t,this}from(t){return this.table(t)}connection(t){return this._connection=t,this}select(...t){return this._columns=t.length>0?t:["*"],this}addSelect(...t){if(this._columns[0]==="*")this._columns=t;else this._columns.push(...t);return this}distinct(){return this._distinct=!0,this}where(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"and"}),this}orWhere(t,e,r){let s="=",n=e;if(r!==void 0)s=e,n=r;return this._wheres.push({column:t,operator:s,value:n,boolean:"or"}),this}whereIn(t,e){return this._wheres.push({column:t,operator:"in",value:e,boolean:"and"}),this}whereNotIn(t,e){return this._wheres.push({column:t,operator:"not in",value:e,boolean:"and"}),this}whereNull(t){return this._wheres.push({column:t,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(t){return this._wheres.push({column:t,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(t,e,r){return this._wheres.push({column:t,operator:"between",value:[e,r],boolean:"and"}),this}whereLike(t,e){return this._wheres.push({column:t,operator:"like",value:e,boolean:"and"}),this}join(t,e,r,s){return this._joins.push({type:"inner",table:t,first:e,operator:r,second:s}),this}leftJoin(t,e,r,s){return this._joins.push({type:"left",table:t,first:e,operator:r,second:s}),this}rightJoin(t,e,r,s){return this._joins.push({type:"right",table:t,first:e,operator:r,second:s}),this}orderBy(t,e="asc"){return this._orders.push({column:t,direction:e}),this}orderByDesc(t){return this.orderBy(t,"desc")}groupBy(...t){return this._groupBy.push(...t),this}having(t,e,r){return this._having.push({column:t,operator:e,value:r,boolean:"and"}),this}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}async get(){let{sql:t,bindings:e}=this.toSql();if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e),i=Q(n);if(i!==void 0)return i}let s=await g(this._connection).query(t,e);if(u.cacheTTL&&u.cacheTTL>0){let n=this.getCacheKey(t,e);B(n,s,u.cacheTTL)}return s}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let t=await this.first();if(!t)throw Error("No results found");return t}async find(t,e="id"){return this.where(e,t).first()}async value(t){let e=await this.select(t).first();return e?e[t]:null}async pluck(t){return(await this.select(t).get()).map((r)=>r[t])}async exists(){return(await this.select(_("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(t="*"){let e=await this.select(_(`COUNT(${t}) as count`)).first();return Number(e?.count||0)}async max(t){return(await this.select(_(`MAX(${t}) as max`)).first())?.max}async min(t){return(await this.select(_(`MIN(${t}) as min`)).first())?.min}async sum(t){let e=await this.select(_(`SUM(${t}) as sum`)).first();return Number(e?.sum||0)}async avg(t){return(await this.select(_(`AVG(${t}) as avg`)).first())?.avg}async insert(t){let e=Object.keys(t),r=e.map(()=>"?").join(", "),s=Object.values(t),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES (${r})`,i=g(this._connection);return T(this._table),i.insert(n,s)}async insertAll(t){if(t.length===0)return;let e=Object.keys(t[0]),r=t.map(()=>`(${e.map(()=>"?").join(", ")})`).join(", "),s=t.flatMap((a)=>Object.values(a)),n=`INSERT INTO ${this._table} (${e.join(", ")}) VALUES ${r}`,i=g(this._connection);T(this._table),await i.execute(n,s)}async update(t){this._bindings=[];let e=this.buildWhereClause(),r=[...this._bindings],s=Object.keys(t).map((o)=>`${o} = ?`).join(", "),n=[...Object.values(t),...r],i=`UPDATE ${this._table} SET ${s}${e}`,a=g(this._connection);return T(this._table),a.execute(i,n)}async increment(t,e=1){this._bindings=[];let r=this.buildWhereClause(),s=`UPDATE ${this._table} SET ${t} = ${t} + ?${r}`,n=g(this._connection);return T(this._table),n.execute(s,[e,...this._bindings])}async decrement(t,e=1){return this.increment(t,-e)}async delete(){this._bindings=[];let t=this.buildWhereClause(),e=`DELETE FROM ${this._table}${t}`,r=g(this._connection);return T(this._table),r.execute(e,this._bindings)}async truncate(){let t=g(this._connection);T(this._table),await t.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let t="SELECT ";if(this._distinct)t+="DISTINCT ";t+=this._columns.map((e)=>{if(typeof e==="object"&&e.__raw)return e.sql;return e}).join(", "),t+=` FROM ${this._table}`;for(let e of this._joins)t+=` ${e.type.toUpperCase()} JOIN ${e.table} ON ${e.first} ${e.operator} ${e.second}`;if(t+=this.buildWhereClause(),this._groupBy.length>0)t+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let e=this._having.map((r,s)=>{let n=s===0?"":` ${r.boolean.toUpperCase()} `;return this._bindings.push(r.value),`${n}${r.column} ${r.operator} ?`});t+=` HAVING ${e.join("")}`}if(this._orders.length>0)t+=` ORDER BY ${this._orders.map((e)=>`${e.column} ${e.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)t+=` LIMIT ${this._limit}`;if(this._offset!==void 0)t+=` OFFSET ${this._offset}`;return{sql:t,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((e,r)=>{let s=r===0?" WHERE ":` ${e.boolean.toUpperCase()} `;switch(e.operator){case"in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} IN (${i})`}case"not in":{let n=e.value,i=n.map(()=>"?").join(", ");return this._bindings.push(...n),`${s}${e.column} NOT IN (${i})`}case"between":{let[n,i]=e.value;return this._bindings.push(n,i),`${s}${e.column} BETWEEN ? AND ?`}case"is null":return`${s}${e.column} IS NULL`;case"is not null":return`${s}${e.column} IS NOT NULL`;default:return this._bindings.push(e.value),`${s}${e.column} ${e.operator} ?`}}).join("")}getCacheKey(t,e){return`${this._table}:${t}:${JSON.stringify(e)}`}clone(){let t=new x(this._table);return t._columns=[...this._columns],t._wheres=[...this._wheres],t._orders=[...this._orders],t._joins=[...this._joins],t._groupBy=[...this._groupBy],t._having=[...this._having],t._limit=this._limit,t._offset=this._offset,t._distinct=this._distinct,t._connection=this._connection,t}}function l(t){return new x(t)}function Y(t){return l(t)}function _(t,e=[]){return{__raw:!0,sql:t,bindings:e}}function H(t,e){let r=e.primaryKey||"id",s={name:t,definition:e,async find(n){let i=await l(e.table).where(r,n).first();return i?b(s,i):null},async findOrFail(n){let i=await this.find(n);if(!i)throw Error(`${t} not found with ${r} = ${n}`);return i},async all(){return(await l(e.table).get()).map((i)=>b(s,i))},async create(n){let i={...e.defaults,...n},a=e.fillable?Object.fromEntries(Object.entries(i).filter(([c])=>e.fillable.includes(c))):i;if(e.timestamps!==!1){let c=new Date().toISOString(),h=typeof e.timestamps==="object"?e.timestamps.createdAt||"created_at":"created_at",p=typeof e.timestamps==="object"?e.timestamps.updatedAt||"updated_at":"updated_at";a[h]=c,a[p]=c}let o=await l(e.table).insert(a);return this.findOrFail(o)},async update(n){return l(e.table).update(n)},async destroy(n){let i=Array.isArray(n)?n:[n];return l(e.table).whereIn(r,i).delete()},query(){return l(e.table)},where(n,i,a){return this.query().where(n,i,a)},async first(){let n=await this.query().first();return n?b(s,n):null},async get(){return(await this.query().get()).map((i)=>b(s,i))},async count(){return this.query().count()}};return C[t]=s,s}function v(t){let e=C[t];if(!e)throw Error(`Model "${t}" not defined. Use defineModel() first.`);return e}function Z(t){return t in C}function b(t,e){let{definition:r}=t,s=r.primaryKey||"id",n={...e},i={...e};if(r.casts){for(let[o,c]of Object.entries(r.casts))if(o in i)i[o]=q(i[o],c)}let a={exists:!0,original:n,attributes:i,get(o){return i[o]},set(o,c){i[o]=c},toJSON(){let o={...i};if(r.hidden)for(let c of r.hidden)delete o[c];return o},async save(){let o={};for(let c of Object.keys(i))if(i[c]!==n[c])o[c]=i[c];if(Object.keys(o).length>0){if(r.timestamps!==!1){let c=typeof r.timestamps==="object"?r.timestamps.updatedAt||"updated_at":"updated_at";o[c]=new Date().toISOString()}await l(r.table).where(s,n[s]).update(o),Object.assign(n,o)}},async delete(){if(r.softDeletes){let o=typeof r.softDeletes==="string"?r.softDeletes:"deleted_at";await l(r.table).where(s,n[s]).update({[o]:new Date().toISOString()})}else await l(r.table).where(s,n[s]).delete();a.exists=!1},async refresh(){let o=await l(r.table).where(s,n[s]).first();if(o)Object.assign(n,o),Object.assign(i,o)},isDirty(o){if(o)return i[o]!==n[o];return Object.keys(i).some((c)=>i[c]!==n[c])}};if(r.relationships)for(let[o,c]of Object.entries(r.relationships))Object.defineProperty(a,o,{value:async()=>j(a,c,t),enumerable:!1});return new Proxy(a,{get(o,c){if(c in o)return o[c];return i[c]},set(o,c,h){if(c in o)o[c]=h;else i[c]=h;return!0}})}async function j(t,e,r){let s=v(e.model),n=r.definition.primaryKey||"id";switch(e.type){case"hasOne":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`,a=await l(s.definition.table).where(i,t.get(n)).first();return a?b(s,a):null}case"hasMany":{let i=e.foreignKey||`${r.name.toLowerCase()}_id`;return(await l(s.definition.table).where(i,t.get(n)).get()).map((o)=>b(s,o))}case"belongsTo":{let i=e.foreignKey||`${e.model.toLowerCase()}_id`,a=e.localKey||"id",o=await l(s.definition.table).where(a,t.get(i)).first();return o?b(s,o):null}case"belongsToMany":{let i=e.pivotTable||[r.name,e.model].sort().join("_").toLowerCase(),a=e.pivotForeignKey||`${r.name.toLowerCase()}_id`,o=e.pivotRelatedKey||`${e.model.toLowerCase()}_id`,c=s.definition.primaryKey||"id";return(await l(s.definition.table).join(i,`${s.definition.table}.${c}`,"=",`${i}.${o}`).where(`${i}.${a}`,t.get(n)).get()).map((p)=>b(s,p))}default:return null}}function q(t,e){if(t===null||t===void 0)return t;switch(e){case"string":return String(t);case"number":return Number(t);case"boolean":return Boolean(t);case"date":return new Date(t);case"json":case"array":return typeof t==="string"?JSON.parse(t):t;default:return t}}async function tt(t,e){let r=g(e);await r.beginTransaction();try{let s=await t();return await r.commit(),s}catch(s){throw await r.rollback(),s}}function Q(t){let e=f.get(t);if(!e)return;if(Date.now()-e.timestamp>e.ttl*1000){f.delete(t);return}return e.result}function B(t,e,r){if(f.size>=(u.maxCacheSize||1000)){let s=f.keys().next().value;if(s)f.delete(s)}f.set(t,{result:e,timestamp:Date.now(),ttl:r})}function T(t){for(let e of f.keys())if(e.startsWith(`${t}:`))f.delete(e)}function et(){f.clear()}function nt(){return{size:f.size,keys:[...f.keys()]}}function y(t,e,r){if(P.push({sql:t,bindings:e,duration:r,timestamp:new Date}),P.length>1000)P.shift()}function rt(){return[...P]}function st(){P.length=0}function it(t=!0){u.logging=t}class m extends Error{sql;bindings;constructor(t,e,r){super(t);this.sql=e;this.bindings=r;this.name="DatabaseError"}}async function K(t,e,r,s){let n=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=await W(h,p),w=`$${h}`;e[w]=d,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- DB Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function U(t,e,r,s){let n=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p]=o;try{let d=v(h),w=await J(d,p),E=`$${h.toLowerCase()}`;e[E]=w,i=i.replace(c,"")}catch(d){i=i.replace(c,`<!-- Model Error: ${d instanceof Error?d.message:String(d)} -->`)}}return i}async function F(t,e,r,s){let n=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,i=t,a=[...t.matchAll(n)];for(let o of a){let[c,h,p,d]=o;try{let w=p?JSON.parse(p):[],A=await g().query(h,w);e[`$${d}`]=A,i=i.replace(c,"")}catch(w){i=i.replace(c,`<!-- Query Error: ${w instanceof Error?w.message:String(w)} -->`)}}return i}async function W(t,e){let r=l(t),s=/->(\w+)\(([^)]*)\)/g,n=[...e.matchAll(s)],i=r;for(let[,a,o]of n){let c=O(o);if(typeof i[a]==="function"){if(i=i[a](...c),i instanceof Promise){i=await i;break}}}if(i instanceof x)i=await i.get();return i}async function J(t,e){let r=/->(\w+)\(([^)]*)\)/g,s=[...e.matchAll(r)],n=t;for(let[,i,a]of s){let o=O(a);if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}else if(n instanceof x){if(typeof n[i]==="function"){if(n=n[i](...o),n instanceof Promise)n=await n}}}if(n instanceof x)n=await n.get();return n}function O(t){if(!t.trim())return[];let e=[],r="",s=0,n=!1,i="";for(let a=0;a<t.length;a++){let o=t[a];if(!n&&(o==='"'||o==="'"))n=!0,i=o,r+=o;else if(n&&o===i)n=!1,r+=o;else if(!n&&(o==="["||o==="{"||o==="("))s++,r+=o;else if(!n&&(o==="]"||o==="}"||o===")"))s--,r+=o;else if(!n&&s===0&&o===",")e.push(R(r.trim())),r="";else r+=o}if(r.trim())e.push(R(r.trim()));return e}function R(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let e=Number(t);if(!Number.isNaN(e))return e;try{return JSON.parse(t)}catch{return t}}async function ot(t,e,r,s){let n=t;return n=await F(n,e,r,s),n=await U(n,e,r,s),n=await K(n,e,r,s),n}class I{_connection;connection(t){return this._connection=t,this}async create(t,e){let r=new M(t);e(r);let s=r.toCreateSQL();await g(this._connection).execute(s)}async drop(t){await g(this._connection).execute(`DROP TABLE IF EXISTS ${t}`)}async rename(t,e){await g(this._connection).execute(`ALTER TABLE ${t} RENAME TO ${e}`)}async hasTable(t){let e=g(this._connection);try{return await e.query(`SELECT 1 FROM ${t} LIMIT 1`),!0}catch{return!1}}}class M{table;columns=[];indices=[];constructor(t){this.table=t}id(t="id"){return this.columns.push(`${t} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(t,e=255){return this.columns.push(`${t} VARCHAR(${e})`),this}text(t){return this.columns.push(`${t} TEXT`),this}integer(t){return this.columns.push(`${t} INTEGER`),this}boolean(t){return this.columns.push(`${t} BOOLEAN DEFAULT 0`),this}datetime(t){return this.columns.push(`${t} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(t){return this.columns.push(`${t} TEXT`),this}foreignId(t){return this.columns.push(`${t} INTEGER`),this}index(t){let e=Array.isArray(t)?t:[t],r=`idx_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}unique(t){let e=Array.isArray(t)?t:[t],r=`uniq_${this.table}_${e.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${r} ON ${this.table} (${e.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
3
3
  ${this.columns.join(`,
4
4
  `)}
5
- )`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,p as DatabaseError,x as QueryBuilder,I as SchemaBuilder,et as clearQueryCache,st as clearQueryLog,z as configureDatabase,H as defineModel,it as enableQueryLogging,g as getAdapter,V as getDatabaseConfig,v as getModel,nt as getQueryCacheStats,rt as getQueryLog,Z as hasModel,ot as processDatabaseDirectives,K as processDbDirective,U as processModelDirective,F as processQueryDirective,l as query,_ as raw,X as registerAdapter,G as resetDatabaseConfig,at as schema,Y as table,tt as transaction};
5
+ )`}getIndexSQL(){return this.indices}}function at(){return new I}export{M as Blueprint,m as DatabaseError,x as QueryBuilder,I as SchemaBuilder,et as clearQueryCache,st as clearQueryLog,z as configureDatabase,H as defineModel,it as enableQueryLogging,g as getAdapter,V as getDatabaseConfig,v as getModel,nt as getQueryCacheStats,rt as getQueryLog,Z as hasModel,ot as processDatabaseDirectives,K as processDbDirective,U as processModelDirective,F as processQueryDirective,l as query,_ as raw,X as registerAdapter,G as resetDatabaseConfig,at as schema,Y as table,tt as transaction};
@@ -398,7 +398,7 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
398
398
  target.dispatchEvent(new target.CustomEvent("craftPushToken", { detail: { token } }));
399
399
  });
400
400
  }
401
- if (capabilities.has("health"))
401
+ if (capabilities.has("health")) {
402
402
  craft.health = {
403
403
  requestAuthorization: (types, options = {}) => ask("Health", "requestAuthorization", [types, options]),
404
404
  getData: (type, options = {}) => request("Health", "getData", [type, options]),
@@ -408,8 +408,16 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
408
408
  getHeartRateSamples: (options = {}) => request("Health", "getHeartRateSamples", [options]),
409
409
  getSleepIntervals: (options = {}) => request("Health", "getSleepIntervals", [options]),
410
410
  saveMindfulSession: (session) => request("Health", "saveMindfulSession", [session]),
411
- getMindfulSessions: (options = {}) => request("Health", "getMindfulSessions", [options])
411
+ getMindfulSessions: (options = {}) => request("Health", "getMindfulSessions", [options]),
412
+ startHeartRateUpdates: (options = {}) => request("Health", "startHeartRateUpdates", [{ since: typeof options.since === "number" ? options.since : null }]),
413
+ stopHeartRateUpdates: () => request("Health", "stopHeartRateUpdates", [{}])
412
414
  };
415
+ if (capabilities.has("healthAvailability")) {
416
+ craft.health.availability = () => request("Health", "availability", []);
417
+ craft.health.grantedTypes = () => request("Health", "grantedTypes", []).then((types) => Array.isArray(types) ? types.filter((type) => typeof type === "string") : []);
418
+ craft.health.openSettings = () => ask("Health", "openSettings", []).then(Boolean);
419
+ }
420
+ }
413
421
  craft.scheduleNotification = craft.notifications.schedule;
414
422
  craft.cancelNotification = craft.notifications.cancel;
415
423
  craft.cancelAllNotifications = craft.notifications.cancelAll;
@@ -191,6 +191,11 @@ export declare interface NativeCraft {
191
191
  getSleepIntervals: (options?: { startDate?: number, endDate?: number }) => Promise<Array<Record<string, unknown>>>
192
192
  saveMindfulSession: (session: { id: string, startDate: number, endDate: number }) => Promise<{ id: string, externalId: string, existing: boolean }>
193
193
  getMindfulSessions: (options?: { startDate?: number, endDate?: number, limit?: number }) => Promise<Array<Record<string, unknown>>>
194
+ startHeartRateUpdates: (options?: { since?: number }) => Promise<boolean>
195
+ stopHeartRateUpdates: () => Promise<boolean>
196
+ availability?: () => Promise<'available' | 'updateRequired' | 'unavailable'>
197
+ grantedTypes?: () => Promise<string[]>
198
+ openSettings?: () => Promise<boolean>
194
199
  }
195
200
  scheduledWorkouts?: {
196
201
  isSupported: () => Promise<boolean>
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  import{Ln,Oe,Bo,Wa}from"./chunk-4c1afy15.js";import{Nn,Vr,Ha,Va,Ua}from"./chunk-jbvg29t0.js";import{No,Lo,jo,Fa,za}from"./chunk-e62nw7zk.js";import{oe,gt,Ur}from"./chunk-hkjqqx92.js";import{Xc,Gc,Jc,Yc,fr,mu}from"./chunk-3ynfz6h8.js";import B from"fs";import w from"path";import O from"fs";import u from"path";var v=[72,96,128,144,152,192,384,512],S=[120,152,167,180],P=[16,32];async function M(n,t){let e={success:!0,generatedFiles:[],errors:[],warnings:[]},r=n.pwa?.icons;if(!r?.src)return e.errors.push("No source icon specified in pwa.icons.src"),e.success=!1,e;let o=u.isAbsolute(r.src)?r.src:u.resolve(process.cwd(),r.src);if(!await Bun.file(o).exists())return e.errors.push(`Source icon not found: ${o}`),e.success=!1,e;let a=u.resolve(t,r.outputDir||"pwa-icons");try{O.mkdirSync(a,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${a}`),e.success=!1,e}let s=r.sizes||v,l=r.generateWebP??!0,p=r.generateAppleIcons??!0;try{let c;try{c=await import("sharp")}catch{return e.errors.push(`sharp is not installed. Install it with: bun add sharp
3
- Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-7ceqp9yv.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
3
+ Icon generation requires the sharp package for image processing.`),e.success=!1,e}let g=await c.default(o).metadata();if(g.width&&g.width<512)e.warnings.push(`Source icon is ${g.width}x${g.height}. Recommend using at least 512x512 for best quality.`);for(let i of s){let d=u.join(a,`icon-${i}x${i}.png`);if(await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d),l){let x=u.join(a,`icon-${i}x${i}.webp`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toFile(x),e.generatedFiles.push(x)}}if(p){for(let d of S){let x=u.join(a,`apple-touch-icon-${d}x${d}.png`);await c.default(o).resize(d,d,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(x),e.generatedFiles.push(x)}let i=u.join(a,"apple-touch-icon.png");await c.default(o).resize(180,180,{fit:"contain",background:{r:255,g:255,b:255,alpha:1}}).png().toFile(i),e.generatedFiles.push(i)}for(let i of P){let d=u.join(a,`favicon-${i}x${i}.png`);await c.default(o).resize(i,i,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).png().toFile(d),e.generatedFiles.push(d)}let f=512,y=u.join(a,`icon-maskable-${f}x${f}.png`),m=Math.floor(f*0.1),k=f-m*2;await c.default(o).resize(k,k,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).extend({top:m,bottom:m,left:m,right:m,background:{r:255,g:255,b:255,alpha:1}}).png().toFile(y),e.generatedFiles.push(y)}catch(c){let h=c instanceof Error?c.message:String(c);e.errors.push(`Icon generation failed: ${h}`),e.success=!1}return e}function N(n){let t=n.sizes||v,e=n.outputDir?`/${n.outputDir}`:"/pwa-icons",r=n.generateWebP??!0,o=n.generateAppleIcons??!0,a=[];for(let s of t)if(a.push(`${e}/icon-${s}x${s}.png`),r)a.push(`${e}/icon-${s}x${s}.webp`);if(o){a.push(`${e}/apple-touch-icon.png`);for(let s of S)a.push(`${e}/apple-touch-icon-${s}x${s}.png`)}for(let s of P)a.push(`${e}/favicon-${s}x${s}.png`);return a.push(`${e}/icon-maskable-512x512.png`),a}async function I(){try{return await import("sharp"),!0}catch{return!1}}function A(n,t,e,r){let o=[],a=r.join(" ");for(let s of n)if(o.push({src:`${t}/icon-${s}x${s}.png`,sizes:`${s}x${s}`,type:"image/png",purpose:a}),e)o.push({src:`${t}/icon-${s}x${s}.webp`,sizes:`${s}x${s}`,type:"image/webp",purpose:a});return o}function C(n){return n.map((t)=>({name:t.name,short_name:t.shortName,description:t.description,url:t.url,icons:t.icons?.map((e)=>({src:e.src,sizes:e.sizes,type:e.type}))}))}function T(n){let t=n.pwa?.shareTarget;if(!t?.enabled)return;let e={action:t.action||"/share",method:t.method||"POST",enctype:t.enctype||"multipart/form-data",params:{title:t.params?.title||"title",text:t.params?.text||"text",url:t.params?.url||"url"}};if(t.acceptFiles&&t.acceptFiles.length>0)e.params.files=t.acceptFiles.map((r)=>({name:r.name,accept:r.accept}));return e}function H(n){let t=n.pwa?.fileHandlers;if(!t?.enabled||!t.accept)return;let e=[{action:t.action||"/",accept:t.accept,launch_type:t.launchType||"single-client"}];if(t.icons)e[0].icons=t.icons.map((r)=>({src:r.src,sizes:r.sizes,type:r.type}));return e}function W(n){let t=n.pwa?.protocolHandlers;if(!t||t.length===0)return;return t.map((e)=>({protocol:e.protocol,url:e.url}))}function j(n){let t=n.pwa;if(!t?.enabled||!t.manifest)return null;let{manifest:e,icons:r}=t,o=r?.sizes||[72,96,128,144,152,192,384,512],a=r?.outputDir?`/${r.outputDir}`:"/pwa-icons",s=r?.generateWebP??!0,l=r?.purpose||["any","maskable"],p={name:e.name,short_name:e.shortName||e.name,description:e.description,start_url:e.startUrl||"/",display:e.display||"standalone",display_override:e.displayOverride,orientation:e.orientation,theme_color:e.themeColor,background_color:e.backgroundColor,scope:e.scope||"/",lang:e.lang,dir:e.dir,id:e.id,categories:e.categories,icons:A(o,a,s,l)};if(e.shortcuts&&e.shortcuts.length>0)p.shortcuts=C(e.shortcuts);if(e.screenshots&&e.screenshots.length>0)p.screenshots=e.screenshots.map((f)=>({src:f.src,sizes:f.sizes,type:f.type,label:f.label,form_factor:f.platform}));let c=T(n);if(c)p.share_target=c;let h=H(n);if(h)p.file_handlers=h;let g=W(n);if(g)p.protocol_handlers=g;if(e.launchHandler)p.launch_handler={client_mode:e.launchHandler};if(e.handleLinks)p.handle_links=e.handleLinks;if(e.edgeSidePanel?.enabled)p.edge_side_panel={preferred_width:e.edgeSidePanel.preferredWidth};return p}function _(n){let t=j(n);if(!t)return"";let e=JSON.parse(JSON.stringify(t));return JSON.stringify(e,null,2)}function q(n,t){return{...t,...n,shortcuts:n.shortcuts||t.shortcuts,screenshots:n.screenshots||t.screenshots,categories:n.categories||t.categories}}function D(n){let t=[],e=n.pwa;if(!e?.enabled)return t;let r=e.manifest;if(!r)return t.push("PWA manifest configuration is missing"),t;if(!r.name)t.push("Manifest name is required");let o=["fullscreen","standalone","minimal-ui","browser"];if(r.display&&!o.includes(r.display))t.push(`Invalid display mode: ${r.display}. Must be one of: ${o.join(", ")}`);let a=["any","natural","landscape","landscape-primary","landscape-secondary","portrait","portrait-primary","portrait-secondary"];if(r.orientation&&!a.includes(r.orientation))t.push(`Invalid orientation: ${r.orientation}`);let s=/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;if(r.themeColor&&!s.test(r.themeColor))t.push(`Invalid theme color: ${r.themeColor}. Must be a valid hex color.`);if(r.backgroundColor&&!s.test(r.backgroundColor))t.push(`Invalid background color: ${r.backgroundColor}. Must be a valid hex color.`);if(e.shareTarget?.enabled){if(!e.shareTarget.action)t.push("Share target action URL is required")}if(e.fileHandlers?.enabled){if(!e.fileHandlers.accept||Object.keys(e.fileHandlers.accept).length===0)t.push("File handlers must specify accepted MIME types")}if(e.protocolHandlers)for(let l of e.protocolHandlers){if(!l.protocol)t.push("Protocol handler missing protocol");if(!l.url||!l.url.includes("%s"))t.push(`Protocol handler URL must contain %s placeholder: ${l.protocol}`)}return t}import z from"path";async function F(n){let t=n.pwa?.offline;if(!t?.enabled)return"";if(t.page){let e=z.isAbsolute(t.page)?t.page:z.resolve(process.cwd(),t.page);if(await Bun.file(e).exists())try{let{processDirectives:r}=await import("./chunk-skve9q8q.js"),o=await Bun.file(e).text();return await r(o,{},e,n,new Set)}catch(r){console.warn(`[PWA] Failed to process custom offline page: ${r}`)}else console.warn(`[PWA] Custom offline page not found: ${e}`)}return E(n)}function E(n){let t=n.pwa?.offline,e=n.pwa?.manifest,r=t?.fallbackTitle||"You are offline",o=t?.fallbackMessage||"Please check your internet connection and try again.",a=e?.themeColor||"#4f46e5",s=e?.shortName||e?.name||"App";return`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">