@stacksjs/stx 0.2.817 → 0.2.819

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 (201) hide show
  1. package/dist/{chunk-pyytr30r.js → chunk-035m9ada.js} +3 -3
  2. package/dist/chunk-03mtfndv.js +2 -0
  3. package/dist/chunk-0633xsmx.js +2 -0
  4. package/dist/{chunk-hhazm0cs.js → chunk-0s93s6ep.js} +3 -3
  5. package/dist/chunk-0wrmcexg.js +2 -0
  6. package/dist/chunk-12sd0ep5.js +1327 -0
  7. package/dist/chunk-18qxd18d.js +2 -0
  8. package/dist/{chunk-d47m4qat.js → chunk-1a8qtvs1.js} +2 -2
  9. package/dist/{chunk-s9xs2ff4.js → chunk-1ae3megp.js} +5 -5
  10. package/dist/chunk-1cd0w20k.js +2 -0
  11. package/dist/{chunk-549end3k.js → chunk-1hg0zb3p.js} +2 -2
  12. package/dist/{chunk-ccxphr19.js → chunk-1p3vmy65.js} +2 -2
  13. package/dist/{chunk-p8wq37hd.js → chunk-1rvgv1fr.js} +5 -5
  14. package/dist/{chunk-n761hp6d.js → chunk-1tzqqr0p.js} +2 -2
  15. package/dist/chunk-2k3ga51z.js +2 -0
  16. package/dist/{chunk-n9av365c.js → chunk-3dg2zg8d.js} +1 -1
  17. package/dist/{chunk-5efv1fhk.js → chunk-4fbg7gq8.js} +2 -2
  18. package/dist/{chunk-agxjwnz0.js → chunk-4gg9594a.js} +8 -8
  19. package/dist/{chunk-y3p6w1e0.js → chunk-4jaet63w.js} +5 -5
  20. package/dist/chunk-54kn2jtw.js +2 -0
  21. package/dist/chunk-54mc7876.js +2 -0
  22. package/dist/{chunk-2p3eaj16.js → chunk-6a0ekt1n.js} +3 -3
  23. package/dist/chunk-6e76tz09.js +2 -0
  24. package/dist/{chunk-bphwhfbd.js → chunk-6n11z33h.js} +5 -5
  25. package/dist/{chunk-7rk7wfm6.js → chunk-72jt897s.js} +13 -13
  26. package/dist/chunk-72w08sh9.js +2 -0
  27. package/dist/{chunk-dy7yccxm.js → chunk-7c5b0th8.js} +7 -7
  28. package/dist/chunk-7p7hdn42.js +2 -0
  29. package/dist/chunk-88mhhbqj.js +2 -0
  30. package/dist/{chunk-a0r4dpzs.js → chunk-8dmey36n.js} +2 -2
  31. package/dist/{chunk-gtfs96f2.js → chunk-93f6kwht.js} +2 -2
  32. package/dist/chunk-9736003n.js +2 -0
  33. package/dist/chunk-9b52cnzm.js +2 -0
  34. package/dist/chunk-9bhvh2dc.js +2 -0
  35. package/dist/{chunk-17wb2x3z.js → chunk-9egd7tx3.js} +2 -2
  36. package/dist/{chunk-2ws2qe1k.js → chunk-9gwhs0gk.js} +2 -2
  37. package/dist/chunk-9y1dm510.js +2 -0
  38. package/dist/chunk-a4yzet7p.js +2 -0
  39. package/dist/chunk-abzrvxct.js +2 -0
  40. package/dist/chunk-avbvedyx.js +2 -0
  41. package/dist/{chunk-cm5cp3m0.js → chunk-ax16vnn5.js} +4 -4
  42. package/dist/{chunk-3vpgr6nk.js → chunk-b9d70mgr.js} +3 -3
  43. package/dist/{chunk-pdnyhs63.js → chunk-bnewgd23.js} +1 -1
  44. package/dist/{chunk-4ws3yz5q.js → chunk-brbqz5he.js} +8 -8
  45. package/dist/{chunk-5hxvhmg3.js → chunk-cbt1dchd.js} +4 -4
  46. package/dist/chunk-cvq4bz8y.js +2 -0
  47. package/dist/chunk-d7p5jr31.js +2 -0
  48. package/dist/chunk-dh1f8ga0.js +2 -0
  49. package/dist/{chunk-6cw072n5.js → chunk-dq9djbgq.js} +4 -4
  50. package/dist/chunk-dzp2a775.js +2 -0
  51. package/dist/{chunk-tb4wmzzd.js → chunk-e3t2bqyf.js} +5 -5
  52. package/dist/{chunk-fcvyk047.js → chunk-e4d0jgcw.js} +7 -7
  53. package/dist/{chunk-rxt4jj9b.js → chunk-e758jz81.js} +6 -6
  54. package/dist/{chunk-1fc6rax4.js → chunk-ek5ynvqh.js} +2 -2
  55. package/dist/{chunk-jg9f5nqf.js → chunk-em2yy1te.js} +6 -6
  56. package/dist/{chunk-m0x96g8e.js → chunk-f6nk205v.js} +1 -1
  57. package/dist/chunk-f86ehf7n.js +2 -0
  58. package/dist/{chunk-f54t0qar.js → chunk-fmawgk87.js} +1 -1
  59. package/dist/chunk-fn2cqvb1.js +2 -0
  60. package/dist/chunk-fzj3e3zk.js +2 -0
  61. package/dist/{chunk-gqjb1y7c.js → chunk-g7mjv276.js} +2 -2
  62. package/dist/{chunk-p5ez40kf.js → chunk-gahpv8ce.js} +2 -2
  63. package/dist/{chunk-r6dtrd7y.js → chunk-gcje06er.js} +30 -30
  64. package/dist/chunk-gsc617cx.js +2 -0
  65. package/dist/{chunk-1bgv727x.js → chunk-gtd6qs1r.js} +2 -2
  66. package/dist/chunk-h8kbcz9t.js +2 -0
  67. package/dist/{chunk-rc424p1c.js → chunk-he8rmsdq.js} +24 -24
  68. package/dist/chunk-hx575xy8.js +2 -0
  69. package/dist/{chunk-0jcady6w.js → chunk-j476jghg.js} +1 -1
  70. package/dist/chunk-j58z3y2g.js +2 -0
  71. package/dist/chunk-j5t40n2g.js +2 -0
  72. package/dist/{chunk-kvhsdyfg.js → chunk-j8r0am39.js} +1 -1
  73. package/dist/chunk-jcz6rd9n.js +2 -0
  74. package/dist/{chunk-yvqe0pzk.js → chunk-jdddw8en.js} +2 -2
  75. package/dist/{chunk-kjjvs3sc.js → chunk-jgj16jmg.js} +2 -2
  76. package/dist/{chunk-nmkkfpmh.js → chunk-jw7cakxt.js} +6 -6
  77. package/dist/{chunk-0h99mrb0.js → chunk-k3t72x38.js} +2 -2
  78. package/dist/{chunk-0svj1nfa.js → chunk-k3zcadcc.js} +2 -2
  79. package/dist/chunk-k5nd8zqh.js +2 -0
  80. package/dist/{chunk-df60fpgx.js → chunk-kz6qw9fm.js} +3 -3
  81. package/dist/{chunk-crmxg1c0.js → chunk-m7kct2sg.js} +4 -4
  82. package/dist/{chunk-jtx9x3as.js → chunk-m9dyqae7.js} +6 -6
  83. package/dist/{chunk-r5nt1bcx.js → chunk-mbhvf0sv.js} +2 -2
  84. package/dist/chunk-mcgqgheq.js +2 -0
  85. package/dist/{chunk-fn3q1gtr.js → chunk-mjg9cx5a.js} +3 -3
  86. package/dist/{chunk-xrd1md4j.js → chunk-mr2ke5km.js} +6 -6
  87. package/dist/chunk-mz1mgfq3.js +3 -0
  88. package/dist/chunk-n1tbc7da.js +2 -0
  89. package/dist/chunk-n7dm6prj.js +2 -0
  90. package/dist/{chunk-sa0nkpx9.js → chunk-ngh1aeff.js} +2 -2
  91. package/dist/chunk-nknpr8cy.js +2 -0
  92. package/dist/{chunk-jham85mf.js → chunk-nqdh7z2d.js} +1 -1
  93. package/dist/chunk-nqn4dvqd.js +2 -0
  94. package/dist/chunk-nt5dh56c.js +2 -0
  95. package/dist/chunk-p04dabqm.js +2 -0
  96. package/dist/{chunk-b5ckg7zq.js → chunk-p3dc6rg2.js} +5 -5
  97. package/dist/{chunk-cj1p3qdh.js → chunk-p7hy0seh.js} +1 -1
  98. package/dist/chunk-pe89ztq6.js +2 -0
  99. package/dist/chunk-pe9npaby.js +2 -0
  100. package/dist/chunk-pmq2pdr9.js +2 -0
  101. package/dist/chunk-r2v042ym.js +2 -0
  102. package/dist/chunk-r3zmbpv2.js +2 -0
  103. package/dist/chunk-r57s8jqs.js +2 -0
  104. package/dist/{chunk-133vw0ae.js → chunk-rccv14mn.js} +4 -4
  105. package/dist/chunk-rjzp7za8.js +2 -0
  106. package/dist/{chunk-yts2b9d8.js → chunk-s6mte5vy.js} +11 -6
  107. package/dist/{chunk-vkn133cs.js → chunk-s9b6abkb.js} +2 -2
  108. package/dist/chunk-sata7rh2.js +2 -0
  109. package/dist/{chunk-8h3jv8dd.js → chunk-sh1hbhhb.js} +2 -2
  110. package/dist/{chunk-5gxneecs.js → chunk-sjd6rt97.js} +3 -3
  111. package/dist/{chunk-ntn6bnjv.js → chunk-skht06a2.js} +1 -1
  112. package/dist/{chunk-s90m43sm.js → chunk-sxad7x2s.js} +4 -4
  113. package/dist/{chunk-w6n4y2xg.js → chunk-tj6zvs8f.js} +2 -2
  114. package/dist/chunk-tsb5h4e2.js +2 -0
  115. package/dist/{chunk-hg67a15h.js → chunk-v041eh5f.js} +3 -3
  116. package/dist/chunk-v7h8vd9n.js +2 -0
  117. package/dist/chunk-v8h2kns0.js +2 -0
  118. package/dist/chunk-vhzngsmd.js +709 -0
  119. package/dist/{chunk-ncyjaxyz.js → chunk-vmxzktdr.js} +1 -1
  120. package/dist/{chunk-1wdv3zj2.js → chunk-vvcfrsjg.js} +1 -1
  121. package/dist/chunk-vyw40ym7.js +2 -0
  122. package/dist/chunk-whq40bdm.js +2 -0
  123. package/dist/{chunk-vbrn4w81.js → chunk-x46hqa74.js} +3 -3
  124. package/dist/{chunk-0ekdbagy.js → chunk-xc7nynb9.js} +2 -2
  125. package/dist/{chunk-gc7pykfq.js → chunk-xka9fdye.js} +2 -2
  126. package/dist/chunk-xsck49x5.js +2 -0
  127. package/dist/chunk-z0c35c5c.js +2 -0
  128. package/dist/{chunk-e39nkbt4.js → chunk-zhvmcj78.js} +4 -4
  129. package/dist/{chunk-sphc7xzx.js → chunk-znx5m1jv.js} +1 -1
  130. package/dist/chunk-zwp7n01x.js +2 -0
  131. package/dist/cli.js +12 -12
  132. package/dist/client/signals-expression-runtime.js +6 -2
  133. package/dist/client/signals-public-api-runtime.js +1 -0
  134. package/dist/craft-entry.js +2 -2
  135. package/dist/craft.js +2 -2
  136. package/dist/process.js +2 -2
  137. package/dist/pwa.js +3 -3
  138. package/dist/reactive.d.ts +12 -2
  139. package/dist/reactive.js +69 -32
  140. package/dist/ssg.js +10 -10
  141. package/dist/utils.js +6 -1
  142. package/package.json +5 -5
  143. package/dist/chunk-0yjm4j26.js +0 -2
  144. package/dist/chunk-1kz70290.js +0 -2
  145. package/dist/chunk-1rwfgmmk.js +0 -2
  146. package/dist/chunk-2k3qtmn8.js +0 -2
  147. package/dist/chunk-2vget8rh.js +0 -2
  148. package/dist/chunk-3e85etrf.js +0 -2
  149. package/dist/chunk-3eqs0rpv.js +0 -2
  150. package/dist/chunk-3ftaegqg.js +0 -2
  151. package/dist/chunk-3jd5ak8h.js +0 -2
  152. package/dist/chunk-4ypwqrj2.js +0 -2
  153. package/dist/chunk-5eqna31h.js +0 -2
  154. package/dist/chunk-6a97a9wk.js +0 -2
  155. package/dist/chunk-7agp0wj2.js +0 -2
  156. package/dist/chunk-7hch54b2.js +0 -2
  157. package/dist/chunk-7pb9fepg.js +0 -2
  158. package/dist/chunk-8g8h2xwz.js +0 -2
  159. package/dist/chunk-9mtw71xy.js +0 -2
  160. package/dist/chunk-9ttf7k5e.js +0 -2
  161. package/dist/chunk-9wmjmas8.js +0 -2
  162. package/dist/chunk-a350jjd3.js +0 -2
  163. package/dist/chunk-aqydav9y.js +0 -2
  164. package/dist/chunk-ar7w1kx0.js +0 -2
  165. package/dist/chunk-aya8nv31.js +0 -2
  166. package/dist/chunk-b9ntt41z.js +0 -2
  167. package/dist/chunk-bj6ax0he.js +0 -2
  168. package/dist/chunk-cxpnkgvw.js +0 -2
  169. package/dist/chunk-d3gncxq1.js +0 -2
  170. package/dist/chunk-da886asf.js +0 -2
  171. package/dist/chunk-dnemxdvy.js +0 -2
  172. package/dist/chunk-dnqt6y8v.js +0 -3
  173. package/dist/chunk-f0bwetnx.js +0 -421
  174. package/dist/chunk-gzhrtymg.js +0 -1592
  175. package/dist/chunk-h9yvb9qn.js +0 -2
  176. package/dist/chunk-hsmwzzy2.js +0 -2
  177. package/dist/chunk-jsvc264s.js +0 -2
  178. package/dist/chunk-k98nt4pk.js +0 -2
  179. package/dist/chunk-ka1hrt56.js +0 -2
  180. package/dist/chunk-m477m5dp.js +0 -2
  181. package/dist/chunk-mkr46mzz.js +0 -2
  182. package/dist/chunk-mmyrdbxx.js +0 -2
  183. package/dist/chunk-p4f1hrvn.js +0 -2
  184. package/dist/chunk-py244ymg.js +0 -2
  185. package/dist/chunk-rp6b7awz.js +0 -2
  186. package/dist/chunk-rqfg21xk.js +0 -2
  187. package/dist/chunk-rxc1076r.js +0 -2
  188. package/dist/chunk-rzwyaqgg.js +0 -2
  189. package/dist/chunk-s5pegavh.js +0 -2
  190. package/dist/chunk-sj4vw93g.js +0 -2
  191. package/dist/chunk-snfjvd94.js +0 -2
  192. package/dist/chunk-syvsj91a.js +0 -2
  193. package/dist/chunk-tzb0n60s.js +0 -2
  194. package/dist/chunk-w8xvkbt9.js +0 -2
  195. package/dist/chunk-x5rt4kpx.js +0 -2
  196. package/dist/chunk-xbknqp19.js +0 -2
  197. package/dist/chunk-xgqyzkt2.js +0 -2
  198. package/dist/chunk-yd0074ks.js +0 -2
  199. package/dist/chunk-yd1zsy7t.js +0 -2
  200. package/dist/chunk-yjezsy4p.js +0 -2
  201. package/dist/chunk-yjvwp1s6.js +0 -2
package/dist/craft.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{So,wa,va}from"./chunk-0ekdbagy.js";import"./chunk-r6dtrd7y.js";import"./chunk-7rk7wfm6.js";import"./chunk-n761hp6d.js";import"./chunk-r9e0r6jx.js";import"./chunk-f0bwetnx.js";import"./chunk-m7hfcxt3.js";import"./chunk-pdnyhs63.js";import"./chunk-2ws2qe1k.js";import"./chunk-1bgv727x.js";import"./chunk-nmkkfpmh.js";import"./chunk-jg9f5nqf.js";import"./chunk-t2sg2tp2.js";import"./chunk-gc7pykfq.js";import"./chunk-rxt4jj9b.js";import"./chunk-gzhrtymg.js";import"./chunk-df60fpgx.js";import"./chunk-agxjwnz0.js";import"./chunk-fcvyk047.js";import"./chunk-y3p6w1e0.js";import"./chunk-c84pxd2k.js";import"./chunk-baj6w8ja.js";import{pu,xa,yh,bh,Sa,ko,Zr,ka,_a,wh,vh,Ca,Ea,Ta,$a}from"./chunk-rc424p1c.js";import"./chunk-ccxphr19.js";import"./chunk-dnqt6y8v.js";import"./chunk-m0x96g8e.js";import"./chunk-133vw0ae.js";import"./chunk-f54t0qar.js";import"./chunk-n9av365c.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{So,wa,va}from"./chunk-xc7nynb9.js";import"./chunk-gcje06er.js";import"./chunk-72jt897s.js";import"./chunk-1tzqqr0p.js";import"./chunk-r9e0r6jx.js";import"./chunk-vhzngsmd.js";import"./chunk-m7hfcxt3.js";import"./chunk-bnewgd23.js";import"./chunk-9gwhs0gk.js";import"./chunk-gtd6qs1r.js";import"./chunk-jw7cakxt.js";import"./chunk-em2yy1te.js";import"./chunk-t2sg2tp2.js";import"./chunk-xka9fdye.js";import"./chunk-e758jz81.js";import"./chunk-12sd0ep5.js";import"./chunk-kz6qw9fm.js";import"./chunk-4gg9594a.js";import"./chunk-e4d0jgcw.js";import"./chunk-4jaet63w.js";import"./chunk-c84pxd2k.js";import"./chunk-baj6w8ja.js";import{fu,xa,bh,wh,Sa,ko,Zr,ka,_a,vh,xh,Ca,Ea,Ta,$a}from"./chunk-he8rmsdq.js";import"./chunk-1p3vmy65.js";import"./chunk-mz1mgfq3.js";import"./chunk-f6nk205v.js";import"./chunk-rccv14mn.js";import"./chunk-fmawgk87.js";import"./chunk-3dg2zg8d.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(`
6
6
  `),hydrationData:i,metadata:{renderTime:s,cacheHit:!1,totalSize:a.length,componentCount:t.metadata.componentCount}}}function V(t,e){let n=[],r=[],a=[],i=new Map,s=[];return y(t.tree,(o,c)=>{if(o.type==="component"&&o.componentName){if(T(o.componentName))n.push(o.componentName)}if(o.type==="element"&&o.tag){let p=J(o);if(p)s.push(p);if(o.props){for(let[l,f]of Object.entries(o.props))if(l.startsWith("on")&&typeof f==="string"){let g=`handler_${i.size}`;i.set(g,f)}}}if(o.isStatic&&o.type==="element")r.push(b(o));else if(!o.isStatic&&o.type!=="text")a.push(o.tag||o.componentName||"unknown")}),{nativeComponents:n,staticHTML:r,dynamicParts:a,eventHandlers:i,nativeWidgets:s}}function Y(t,e={}){let n=R(t),r=P(n,e),a=new Map,i=[];return y(n.tree,(s)=>{if(s.type==="component"&&s.componentName){if(T(s.componentName)){i.push(s.componentName);let o=`<!--craft:${s.componentName}:${s.hydrationKey||"default"}-->`;a.set(s.hydrationKey||s.componentName,o)}}}),{staticHTML:r,dynamicPlaceholders:a,craftComponents:i}}function M(t){let e={type:"fragment",children:[]},n=e,r=[e],a=t,i=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);while(a.length>0){let s=a.match(/^<(@?[\w-]+)([^>]*)>/);if(s){let[p,l,f]=s,g=z(f),u=l.startsWith("@craft-"),C=u?l:l.toLowerCase(),S={type:u?"component":"element",tag:C,props:g,children:[],componentName:u?C.slice(1):void 0,isStatic:!v(f),hydrationKey:F()};if(n.children=n.children||[],n.children.push(S),!i.has(C)&&!f.endsWith("/"))r.push(S),n=S;a=a.slice(p.length);continue}let o=a.match(/^<\/(@?[\w-]+)>/);if(o){let[p,l]=o,g=l.startsWith("@craft-")?l:l.toLowerCase();while(r.length>1){let u=r.pop();if(n=r[r.length-1],u.tag===g)break}a=a.slice(p.length);continue}let c=a.match(/^[^<]+/);if(c){let p=c[0];if(p.trim()){let l={type:"text",text:p,isStatic:!v(p)};n.children=n.children||[],n.children.push(l)}a=a.slice(p.length);continue}a=a.slice(1)}return e}function z(t){let e={},n=/([\w-:@]+)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,r;while((r=n.exec(t))!==null){let[,a,i,s,o]=r,c=i??s??o??!0;e[a]=c}return e}function y(t,e,n=[]){if(e(t,n),t.children)t.children.forEach((r,a)=>{y(r,e,[...n,`${a}`])})}function h(t,e){switch(t.type){case"text":return x(t.text||"",e);case"element":case"component":{let n=t.tag||"div",r=N(t.props||{},e),a=(t.children||[]).map((i)=>h(i,e)).join("");if(!t.children||t.children.length===0){if(["input","br","hr","img","meta","link"].includes(n))return`<${n}${r} />`}return`<${n}${r}>${a}</${n}>`}case"fragment":return(t.children||[]).map((n)=>h(n,e)).join("");case"slot":return`<!--slot:${t.slotName||"default"}-->`;default:return""}}function b(t){if(t.type==="text")return t.text||"";let e=t.tag||"div",n=N(t.props||{},{});return`<${e}${n}></${e}>`}function N(t,e){let n=[];for(let[r,a]of Object.entries(t))if(a===!0)n.push(` ${r}`);else if(a!==!1&&a!==null&&a!==void 0){let i=x(String(a),e);n.push(` ${r}="${k(i)}"`)}return n.join("")}async function H(t,e){return h(t,e)}function P(t,e){let n=[];return y(t.tree,(r)=>{if(r.isStatic)n.push(h(r,e))}),n.join("")}function j(t,e,n){let r={templateId:e.id,context:n,dynamicParts:Array.from(e.dynamicParts.entries())},a=`
7
7
  <script data-craft-hydration>
8
8
  window.__CRAFT_HYDRATION__ = ${JSON.stringify(r)};
9
- </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{pu as CRAFT_BRIDGE_SCRIPT,ko as CRAFT_COMPONENTS,ka as CRAFT_COMPONENT_RUNTIME,Zr as CRAFT_COMPONENT_STYLES,So as NATIVE_COMPONENTS,Ca as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,wa as compileToNative,va as createHotReloadServer,Ea as findCraftBinary,xa as generateCraftBridgeScript,V as generateCraftOptimizations,$a as getAvailableFormats,Ta as getAvailableTargets,vh as getCraftComponents,G as getSSRCacheStats,Sa as injectCraftBridge,yh as isCraftEnvironment,Y as prerenderForCraft,_a as processCraftComponents,bh as processCraftDirective,wh as registerCraftComponent,Q as renderSSR};
9
+ </script>`;return{html:t+a,data:r}}function O(t){let e=!1,n=!1,r=!1,a=!1,i=0,s=0;function o(c,p){if(s=Math.max(s,p),c.type==="slot")e=!0;if(c.type==="component")i++;if(!c.isStatic)n=!0;if(c.props)for(let l of Object.keys(c.props)){if(l.startsWith("on"))r=!0;if(l==="@async"||l==="data-async")a=!0}if(c.children)c.children.forEach((l)=>o(l,p+1))}return o(t,0),{hasSlots:e,hasDynamicContent:n,hasEventHandlers:r,hasAsyncContent:a,componentCount:i,maxDepth:s,estimatedSize:JSON.stringify(t).length}}function A(t){let e=new Map,n=new Map;return y(t,(r,a)=>{let i=a.join(".");if(r.isStatic)e.set(i,b(r));else n.set(i,r.tag||r.componentName||"dynamic")}),{staticParts:e,dynamicParts:n}}function L(t){let e=[],n=/<script[^>]*>([\s\S]*?)<\/script>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function W(t){let e=[],n=/<style[^>]*>([\s\S]*?)<\/style>/gi,r;while((r=n.exec(t))!==null)e.push(r[1]);return e}function _(t){let e=[],n=/@include\s*\(\s*['"]([^'"]+)['"]/g,r;while((r=n.exec(t))!==null)e.push(r[1]);let a=/@component\s*\(\s*['"]([^'"]+)['"]/g;while((r=a.exec(t))!==null)e.push(r[1]);let i=/<@craft-[\w-]+/g;while((r=i.exec(t))!==null)e.push(r[0].slice(2));return[...new Set(e)]}function v(t){return/\{\{.*?\}\}|\{\!\!.*?\!\!\}/.test(t)}function x(t,e){let n=t.replace(/\{\{\s*(.+?)\s*\}\}/g,(r,a)=>{try{let i=w(a.trim(),e);return k(String(i??""))}catch{return""}});return n=n.replace(/\{!!\s*(.+?)\s*!!\}/g,(r,a)=>{try{let i=w(a.trim(),e);return String(i??"")}catch{return""}}),n}function w(t,e){if(/^[\w.]+$/.test(t)){let n=t.split("."),r=e;for(let a of n)if(r&&typeof r==="object"&&a in r)r=r[a];else return;return r}try{return Function(...Object.keys(e),`return ${t}`)(...Object.values(e))}catch{return}}function k(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function D(t){return t.replace(/\s+/g," ").replace(/>\s+</g,"><").replace(/\s+>/g,">").replace(/<\s+/g,"<").trim()}function E(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return`tpl_${Math.abs(e).toString(36)}`}function I(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36)}var K=0;function F(){return`h_${++K}`}function T(t){return["craft-button","craft-text-input","craft-textarea","craft-checkbox","craft-radio","craft-select","craft-slider","craft-toggle","craft-date-picker","craft-time-picker","craft-color-picker","craft-file-input","craft-modal","craft-alert","craft-toast","craft-progress","craft-spinner","craft-avatar","craft-badge","craft-card","craft-accordion","craft-tabs","craft-tooltip","craft-popover","craft-dropdown","craft-context-menu","craft-data-table","craft-virtual-list","craft-tree-view","craft-map","craft-chart","craft-video","craft-audio","craft-webview","craft-canvas","craft-image-viewer","craft-pdf-viewer","craft-code-editor","craft-rich-editor"].includes(t)}function J(t){let e=t.tag?.toLowerCase(),n=t.props?.type,r={button:{component:"craft-button",confidence:0.95,reason:"Native button provides better touch feedback"},"input:text":{component:"craft-text-input",confidence:0.9,reason:"Native text input has better keyboard handling"},"input:checkbox":{component:"craft-checkbox",confidence:0.95,reason:"Native checkbox follows platform conventions"},"input:range":{component:"craft-slider",confidence:0.9,reason:"Native slider provides smooth interaction"},"input:date":{component:"craft-date-picker",confidence:0.95,reason:"Native date picker provides platform-specific UI"},"input:time":{component:"craft-time-picker",confidence:0.95,reason:"Native time picker provides platform-specific UI"},"input:color":{component:"craft-color-picker",confidence:0.9,reason:"Native color picker provides platform-specific UI"},textarea:{component:"craft-textarea",confidence:0.85,reason:"Native textarea handles multiline input better"},select:{component:"craft-select",confidence:0.9,reason:"Native select provides platform dropdown UI"},progress:{component:"craft-progress",confidence:0.95,reason:"Native progress bar matches platform style"},video:{component:"craft-video",confidence:0.95,reason:"Native video provides hardware acceleration"},audio:{component:"craft-audio",confidence:0.95,reason:"Native audio provides system integration"},dialog:{component:"craft-modal",confidence:0.9,reason:"Native modal provides proper layering and focus"}},a=n?`${e}:${n}`:e,i=r[a||""]||r[e||""];if(i)return{htmlSelector:a||e||"",nativeComponent:i.component,confidence:i.confidence,reason:i.reason};return null}function U(){m.clear()}function q(){d.clear()}function B(){U(),q()}function G(){return{templateCacheSize:m.size,renderCacheSize:d.size,totalEntries:m.size+d.size}}export{fu as CRAFT_BRIDGE_SCRIPT,ko as CRAFT_COMPONENTS,ka as CRAFT_COMPONENT_RUNTIME,Zr as CRAFT_COMPONENT_STYLES,So as NATIVE_COMPONENTS,Ca as buildNative,B as clearAllCaches,q as clearRenderCache,U as clearTemplateCache,R as compileTemplate,wa as compileToNative,va as createHotReloadServer,Ea as findCraftBinary,xa as generateCraftBridgeScript,V as generateCraftOptimizations,$a as getAvailableFormats,Ta as getAvailableTargets,xh as getCraftComponents,G as getSSRCacheStats,Sa as injectCraftBridge,bh as isCraftEnvironment,Y as prerenderForCraft,_a as processCraftComponents,wh as processCraftDirective,vh as registerCraftComponent,Q as renderSSR};
package/dist/process.js CHANGED
@@ -903,7 +903,7 @@ async function processOtherDirectives(template, context, filePath, options, depe
903
903
  output = processMemoDirective(output);
904
904
  if (!opts.skipEventDirectives)
905
905
  output = processEventDirectives(output, context, filePath);
906
- output = processReactiveDirectives(output, context, filePath);
906
+ output = processReactiveDirectives(output, context, filePath, options.skipSignalsRuntime === !0 && Number(context.__stxProcessingDepth) > 0);
907
907
  if (opts.debug) {
908
908
  const hasXData = /\bx-data\s*=/.test(output), hasSignals = hasSignalsSyntax(template);
909
909
  if (hasXData && hasSignals)
@@ -1048,7 +1048,7 @@ ${runtimeScript}`);
1048
1048
  context.__stx_event_bindings = [];
1049
1049
  }
1050
1050
  }
1051
- if (!pageShipsSignalsRuntime(output) && outputNeedsSignalsRuntime(output))
1051
+ if (!opts.skipSignalsRuntime && !pageShipsSignalsRuntime(output) && outputNeedsSignalsRuntime(output))
1052
1052
  output = await injectSignalsRuntime(output, opts);
1053
1053
  output = injectTooltipRuntime(output);
1054
1054
  if (opts.csp?.enabled && opts.csp.useNonce && typeof context.cspNonce === "string")
package/dist/pwa.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{eo,Ht,xl,Cg}from"./chunk-0svj1nfa.js";import{Qs,Pi,Sg,kg,_g}from"./chunk-e39nkbt4.js";import{bl,wl,vl,vg,xg}from"./chunk-d47m4qat.js";import{Ue,Tn,Ii}from"./chunk-7xs45trj.js";import{Eg,Tg,$g,Rg,to,dy}from"./chunk-gqjb1y7c.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-xbknqp19.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>
2
+ import{eo,Ht,Sl,Eg}from"./chunk-k3zcadcc.js";import{Qs,Pi,kg,_g,Cg}from"./chunk-zhvmcj78.js";import{wl,vl,xl,xg,Sg}from"./chunk-1a8qtvs1.js";import{Ue,Tn,Ii}from"./chunk-7xs45trj.js";import{Tg,$g,Rg,Ag,to,py}from"./chunk-g7mjv276.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-2k3ga51z.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">
@@ -233,4 +233,4 @@ Icon generation requires the sharp package for image processing.`),e.success=!1,
233
233
  }, 5000);
234
234
  </script>
235
235
  </body>
236
- </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=eo(n,t);if(a){let s=Ht(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Pi(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,wl as auditBuildOutput,bl as auditConfig,re as buildPwaAssets,vl as calculateAuditResult,xg as formatAuditResult,Ii as formatSize,j as generateManifest,_ as generateManifestJson,kg as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Qs as generatePwaTags,eo as generateServiceWorker,Cg as generateServiceWorkerAuto,Sg as generateSwRegistrationScript,_g as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Pi as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,xl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,to as pwaDirectives,Eg as pwaInstallDirective,$g as pwaOfflineDirective,Rg as pwaPushDirective,Tg as pwaUpdateDirective,dy as registerPwaDirectives,vg as runPwaAudit,D as validateManifest};
236
+ </html>`}function b(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function re(n,t){let e={success:!0,files:{icons:[]},errors:[],warnings:[]},r=n.pwa;if(!r?.enabled)return e;try{B.mkdirSync(t,{recursive:!0})}catch{return e.errors.push(`Failed to create output directory: ${t}`),e.success=!1,e}try{let a=_(n);if(a){let s=w.join(t,"manifest.json");await Bun.write(s,a),e.files.manifest=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate manifest.json: ${s}`),e.success=!1}if(r.icons?.src)if(await I()){let s=await M(n,t);if(e.files.icons=s.generatedFiles,e.warnings.push(...s.warnings),!s.success)e.errors.push(...s.errors),e.success=!1}else e.warnings.push("sharp is not installed. Skipping icon generation. Install with: bun add sharp");if(r.offline?.enabled)try{let a=await F(n);if(a){let s=w.join(t,"offline.html");await Bun.write(s,a),e.files.offlinePage=s}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate offline page: ${s}`),e.success=!1}let o;if(r.precache?.enabled){let a=Ue(t,n);o={fileCount:a.fileCount,totalSize:a.totalSize},e.precacheStats=o}try{let a=eo(n,t);if(a){let s=Ht(n),l=w.join(t,s);await Bun.write(l,a),e.files.serviceWorker=l}}catch(a){let s=a instanceof Error?a.message:String(a);e.errors.push(`Failed to generate service worker: ${s}`),e.success=!1}return e}function ae(n,t){return Pi(n,t)}function se(n){return n.pwa?.enabled===!0}export{S as APPLE_TOUCH_ICON_SIZES,v as DEFAULT_ICON_SIZES,P as FAVICON_SIZES,vl as auditBuildOutput,wl as auditConfig,re as buildPwaAssets,xl as calculateAuditResult,Sg as formatAuditResult,Ii as formatSize,j as generateManifest,_ as generateManifestJson,_g as generateManifestLink,F as generateOfflinePage,Ue as generatePrecacheManifest,Tn as generatePrecacheManifestJs,M as generatePwaIcons,Qs as generatePwaTags,eo as generateServiceWorker,Eg as generateServiceWorkerAuto,kg as generateSwRegistrationScript,Cg as generateThemeColorMeta,N as getExpectedIconPaths,Ht as getServiceWorkerFileName,Pi as injectPwaTags,se as isPwaEnabled,I as isSharpAvailable,Sl as isWorkboxEnabled,q as mergeManifestConfig,ae as processPwaHtml,to as pwaDirectives,Tg as pwaInstallDirective,Rg as pwaOfflineDirective,Ag as pwaPushDirective,$g as pwaUpdateDirective,py as registerPwaDirectives,xg as runPwaAudit,D as validateManifest};
@@ -6,9 +6,10 @@
6
6
  * @param template - The HTML template string
7
7
  * @param context - Template context
8
8
  * @param filePath - Source file path for error messages
9
+ * @param deferInit - Wait for component helper registration before initialization
9
10
  * @returns Processed template with reactive runtime script
10
11
  */
11
- export declare function processReactiveDirectives(template: string, context: Record<string, unknown>, _filePath: string): string;
12
+ export declare function processReactiveDirectives(template: string, context: Record<string, unknown>, _filePath: string, deferInit?: boolean): string;
12
13
  /**
13
14
  * Check if a template contains reactive directives
14
15
  */
@@ -64,9 +65,18 @@ export declare function hasReactiveDirectives(template: string): boolean;
64
65
  *
65
66
  * ### x-init - Run code on mount
66
67
  * ```html
67
- * <div x-data="{ items: [] }" x-init="items = await fetchItems()">
68
+ * <div x-data="{ items: [] }" x-init="fetchItems().then(next => { items = next })">
68
69
  * ```
69
70
  *
71
+ * ### x-destroy - Dispose a scope's resources
72
+ * ```html
73
+ * <div x-data="{ handle: null }" x-init="handle = follow()" x-destroy="handle?.stop()">
74
+ * ```
75
+ *
76
+ * Component initializers run after their own client helpers and props are ready.
77
+ * Bare assignments write through the scope's signals, including in callbacks.
78
+ * Standalone x-data initializes synchronously. Teardown belongs to the scope.
79
+ *
70
80
  * @module reactive
71
81
  */
72
82
  // =============================================================================
package/dist/reactive.js CHANGED
@@ -1,22 +1,32 @@
1
1
  import { evaluateExpression } from "./expressions.js";
2
+ import { scanAtElementPosition } from "./html-masking.js";
2
3
  let scopeCounter = 0, elementCounter = 0;
3
4
  function escapeRegex(str) {
4
5
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
6
  }
6
7
  function extractAttributeValue(attributesStr, attrName) {
7
- const doubleMatch = attributesStr.match(new RegExp(`${attrName}\\s*=\\s*"([^"]*)"`, "i"));
8
- if (doubleMatch)
9
- return doubleMatch[1];
10
- const singleMatch = attributesStr.match(new RegExp(`${attrName}\\s*=\\s*'([^']*)'`, "i"));
11
- if (singleMatch)
12
- return singleMatch[1];
8
+ const attributes = /(?:^|\s)([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
9
+ for (const match of attributesStr.matchAll(attributes))
10
+ if (match[1].toLowerCase() === attrName.toLowerCase())
11
+ return match[2] ?? match[3] ?? match[4] ?? null;
13
12
  return null;
14
13
  }
14
+ function reactiveOpeningTags(template) {
15
+ const tags = [], opening = /<([a-z][a-z0-9-]*)\b((?:"[^"]*"|'[^']*'|[^>"'])*)>/iy;
16
+ scanAtElementPosition(template, (html, index) => {
17
+ opening.lastIndex = index;
18
+ const match = opening.exec(html);
19
+ if (!match || !extractAttributeValue(match[2], "x-data"))
20
+ return -1;
21
+ tags.push({ fullMatch: match[0], tagName: match[1], attributes: match[2], startIndex: index, endIndex: opening.lastIndex });
22
+ return opening.lastIndex;
23
+ });
24
+ return tags;
25
+ }
15
26
  function findReactiveScopes(template) {
16
- const scopes = [], xDataRegex = /<([a-z][a-z0-9-]*)\s+([^>]*x-data\s*=\s*(?:"[^"]*"|'[^']*')[^>]*)>/gi;
17
- let match;
18
- while ((match = xDataRegex.exec(template)) !== null) {
19
- const [fullMatch, tagName, attributesStr] = match, startIndex = match.index, stateExpr = extractAttributeValue(attributesStr, "x-data");
27
+ const scopes = [];
28
+ for (const { fullMatch, tagName, attributes: attributesStr, startIndex } of reactiveOpeningTags(template)) {
29
+ const stateExpr = extractAttributeValue(attributesStr, "x-data");
20
30
  if (!stateExpr)
21
31
  continue;
22
32
  const scopeId = `__stx_scope_${scopeCounter++}`, initExpr = extractAttributeValue(attributesStr, "x-init"), closingTag = findClosingTag(template, tagName, startIndex + fullMatch.length), scopeContent = template.slice(startIndex, closingTag.endIndex), refs = findRefsInScope(scopeContent);
@@ -228,7 +238,7 @@ window.__stx_reactive = (function() {
228
238
 
229
239
  // Initialize an x-data scope: parse state, run init(), register into window.stx._scopes,
230
240
  // then let the signals runtime handle all directive processing (x-for, x-text, :bind, etc.)
231
- function initScope(scopeEl, initialState, bindings, refs, initExpr) {
241
+ function initScope(scopeEl, initialState, bindings, refs, initExpr, deferInit) {
232
242
  // Parse initial state (may contain methods including async init())
233
243
  var state;
234
244
  try {
@@ -298,6 +308,11 @@ window.__stx_reactive = (function() {
298
308
  if (prop === '$refs') return $refs;
299
309
  if (prop === '$el') return scopeEl;
300
310
  if (prop === '$nextTick') return function(fn) { requestAnimationFrame(fn); };
311
+ if (prop === Symbol.unscopables) return undefined;
312
+ if (!(prop in signalState)) {
313
+ var owner = stx._scopeForBinding(scopeEl, prop);
314
+ return owner ? owner[prop] : undefined;
315
+ }
301
316
  var s = signalState[prop];
302
317
  if (!s) return undefined;
303
318
  if (rawState[prop] && s && typeof s === 'function' && typeof s.value !== 'undefined') {
@@ -331,7 +346,7 @@ window.__stx_reactive = (function() {
331
346
  return true;
332
347
  },
333
348
  has: function(target, prop) {
334
- return prop in signalState || prop === '$refs' || prop === '$el' || prop === '$nextTick';
349
+ return prop in signalState || prop === '$refs' || prop === '$el' || prop === '$nextTick' || !!stx._scopeForBinding(scopeEl, prop);
335
350
  },
336
351
  ownKeys: function() {
337
352
  return Object.keys(signalState).concat(['$refs', '$el', '$nextTick']);
@@ -383,7 +398,8 @@ window.__stx_reactive = (function() {
383
398
 
384
399
  // Register scope \u2014 merge with any existing vars from partial signal scripts
385
400
  if (!stx._scopes) stx._scopes = {};
386
- stx._scopes[scopeId] = Object.assign(stx._scopes[scopeId] || {}, scopeVars);
401
+ var registered = stx._scopes[scopeId] = Object.assign(stx._scopes[scopeId] || {}, scopeVars);
402
+ registered.__el = scopeEl;
387
403
 
388
404
  // Store on element for findElementScope
389
405
  scopeEl.__stx_scope = scopeVars;
@@ -396,10 +412,8 @@ window.__stx_reactive = (function() {
396
412
  }
397
413
  if (initExpr) {
398
414
  try {
399
- var keys = Object.keys(scopeVars);
400
- var vals = keys.map(function(k) { return scopeVars[k]; });
401
- var fn = new Function(keys.join(','), initExpr);
402
- var result = fn.apply(ctxProxy, vals);
415
+ var fn = new Function('with(this){' + initExpr + ';}');
416
+ var result = fn.call(ctxProxy);
403
417
  if (result && typeof result.then === 'function') maybePromise = result;
404
418
  } catch (e) {
405
419
  console.warn('[stx-reactive] init expression error:', e);
@@ -414,8 +428,23 @@ window.__stx_reactive = (function() {
414
428
  }
415
429
  }
416
430
 
417
- // Run init before the signals runtime processes this scope
418
- runInit();
431
+ // A component's helper setup follows its markup. Its own mount queue
432
+ // starts the initializer after all component factories have registered.
433
+ // Standalone x-data retains synchronous initialization.
434
+ if (deferInit) {
435
+ registered.__mountCallbacks = registered.__mountCallbacks || [];
436
+ registered.__mountCallbacks.push(runInit);
437
+ } else {
438
+ runInit();
439
+ }
440
+ var destroyExpr = scopeEl.getAttribute('data-stx-xdestroy') || scopeEl.getAttribute('x-destroy');
441
+ if (destroyExpr) {
442
+ registered.__destroyCallbacks = registered.__destroyCallbacks || [];
443
+ var teardown = function() { scopeEl.__stx_execute(destroyExpr); };
444
+ registered.__destroyCallbacks.push(teardown);
445
+ registered.__destroyHooks = registered.__destroyHooks || [];
446
+ registered.__destroyHooks.push(teardown);
447
+ }
419
448
 
420
449
  // Expose for debugging
421
450
  scopeEl.__stx_state = ctxProxy;
@@ -499,7 +528,7 @@ function substituteExpressionsInExpr(expr, context) {
499
528
  return JSON.stringify(value);
500
529
  }
501
530
  }
502
- function generateScopeInitializers(scopes, context) {
531
+ function generateScopeInitializers(scopes, context, deferInit) {
503
532
  if (scopes.length === 0)
504
533
  return "";
505
534
  const initializers = scopes.map((scope) => {
@@ -509,7 +538,7 @@ function generateScopeInitializers(scopes, context) {
509
538
  var scopeEl = document.querySelector('${scope.selector}');
510
539
  if (!scopeEl) return;
511
540
  var refs = ${refsJson};
512
- __stx_reactive.initScope(scopeEl, ${stateExprJson}, [], refs, ${initExprJson});
541
+ window.__stx_reactive.initScope(scopeEl, ${stateExprJson}, [], refs, ${initExprJson}${deferInit ? ", true" : ""});
513
542
  })();`;
514
543
  }).join(`
515
544
  `);
@@ -574,14 +603,14 @@ function removeReactiveAttributes(template) {
574
603
  output = output.replace(regex, "");
575
604
  return output;
576
605
  }
577
- export function processReactiveDirectives(template, context, _filePath) {
606
+ export function processReactiveDirectives(template, context, _filePath, deferInit = !1) {
578
607
  if (!hasReactiveDirectives(template))
579
608
  return template;
580
609
  const scopes = findReactiveScopes(template);
581
610
  if (scopes.length === 0)
582
611
  return template;
583
612
  let output = finalizeTemplate(template, scopes);
584
- const script = generateScopeInitializers(scopes, context), bodyCloseIdx = output.lastIndexOf("</body>");
613
+ const script = generateScopeInitializers(scopes, context, deferInit), bodyCloseIdx = output.lastIndexOf("</body>");
585
614
  if (bodyCloseIdx !== -1)
586
615
  output = output.slice(0, bodyCloseIdx) + script + `
587
616
  ` + output.slice(bodyCloseIdx);
@@ -616,22 +645,30 @@ function addAllReactiveIds(template) {
616
645
  return output;
617
646
  }
618
647
  function finalizeTemplate(template, scopes) {
619
- let index = 0, output = template.replace(/<([a-z][a-z0-9-]*)(\s+[^>]*x-data\s*=\s*(?:"[^"]*"|'[^']*')[^>]*)>/gi, (match, tagName, attributes) => {
620
- const scope = scopes[index++];
648
+ const parts = [];
649
+ let end = 0;
650
+ for (const [index, tag] of reactiveOpeningTags(template).entries()) {
651
+ const scope = scopes[index];
621
652
  if (!scope)
622
- return match;
623
- const existing = /data-stx-scope="([^"]*)"/.exec(attributes);
653
+ break;
654
+ parts.push(template.slice(end, tag.startIndex));
655
+ const existing = extractAttributeValue(tag.attributes, "data-stx-scope");
624
656
  if (existing) {
625
- scope.id = existing[1];
657
+ scope.id = existing;
626
658
  scope.selector = `[data-stx-scope="${scope.id}"]`;
627
- return match;
628
- }
629
- return `<${tagName} data-stx-scope="${scope.id}"${attributes}>`;
630
- });
659
+ parts.push(tag.fullMatch);
660
+ } else
661
+ parts.push(`<${tag.tagName} data-stx-scope="${scope.id}"${tag.attributes}>`);
662
+ end = tag.endIndex;
663
+ }
664
+ parts.push(template.slice(end));
665
+ let output = parts.join("");
631
666
  output = output.replace(/\s*x-data\s*=\s*"([^"]*)"/g, ' data-stx-xdata="$1"');
632
667
  output = output.replace(/\s*x-data\s*=\s*'([^']*)'/g, " data-stx-xdata='$1'");
633
668
  output = output.replace(/\s*x-init\s*=\s*"([^"]*)"/g, ' data-stx-xinit="$1"');
634
669
  output = output.replace(/\s*x-init\s*=\s*'([^']*)'/g, " data-stx-xinit='$1'");
670
+ output = output.replace(/\s*x-destroy\s*=\s*"([^"]*)"/g, ' data-stx-xdestroy="$1"');
671
+ output = output.replace(/\s*x-destroy\s*=\s*'([^']*)'/g, " data-stx-xdestroy='$1'");
635
672
  return output;
636
673
  }
637
674
  export function hasReactiveDirectives(template) {
package/dist/ssg.js CHANGED
@@ -1,13 +1,13 @@
1
1
  // @bun
2
- import"./chunk-7sh9fa3q.js";import{w,nl}from"./chunk-7rk7wfm6.js";import"./chunk-n761hp6d.js";import"./chunk-r9e0r6jx.js";import{Rt,S}from"./chunk-f0bwetnx.js";import"./chunk-m7hfcxt3.js";import"./chunk-pdnyhs63.js";import"./chunk-2ws2qe1k.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-1bgv727x.js";import{a}from"./chunk-nmkkfpmh.js";import{Es}from"./chunk-jg9f5nqf.js";import"./chunk-t2sg2tp2.js";import"./chunk-vbrn4w81.js";import{he,en,tn}from"./chunk-5gxneecs.js";import"./chunk-gc7pykfq.js";import{y}from"./chunk-rxt4jj9b.js";import{yt,i}from"./chunk-gzhrtymg.js";import"./chunk-df60fpgx.js";import"./chunk-agxjwnz0.js";import{ps}from"./chunk-fcvyk047.js";import"./chunk-y3p6w1e0.js";import"./chunk-c84pxd2k.js";import{Ya,Za,Qa}from"./chunk-hwcfgs3e.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-0jcady6w.js";import"./chunk-dnqt6y8v.js";import"./chunk-m0x96g8e.js";import{X,we}from"./chunk-133vw0ae.js";import"./chunk-f54t0qar.js";import"./chunk-n9av365c.js";import{c}from"./chunk-0rjcbqk3.js";import{r,ge}from"./chunk-3vpgr6nk.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let x=v.trim();if(!x)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)x=Pt(x);let p=It(x);if(!s.has(p))s.set(p,x);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(x).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.add(u[2]);let g=/<\/head\s*>/iy,v=S(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(l.size===0||v===-1)return t;let x=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!x)return t;return t.slice(0,v)+x+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=K(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?K(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=K(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
- `)}function q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let n=r(t),{depths:s}=ge(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,l;while((l=o.exec(n))!==null){if(s[l.index]!==0)continue;let u=w(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),v=w(n,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(l.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((l=e.exec(n))!==null){if(s[l.index]!==0)continue;let u=nl(n,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let n="read";try{let s=await Bun.file(t).text();n="parse";let o=Qt(s),l=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(r(e.attrs))).sort((e,u)=>s.indexOf(e.fullTag)-s.indexOf(u.fullTag));for(let e of l){if(!/\bgetStaticPaths\b/.test(r(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(r(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(r(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let x=await v();n="result";let p=Array.isArray(x)?{paths:x}:x;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,n=""){this.cacheDir=t,this.salt=n}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let n=JSON.parse(await Bun.file(t).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(t,JSON.stringify(n))}getHash(t,n){let s=D.statSync(t),o=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of n)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let l=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);l=(l<<5)-l+u,l=l&l}return Math.abs(l).toString(36)}get(t,n){let s=this.cache.get(t);if(!s)return null;let o=ft(n).some((u)=>D.existsSync(u)),l=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&ps(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||l)return this.cache.delete(t),null;let e=this.getHash(n,s.dependencies??[]);if(s.hash!==e)return this.cache.delete(t),null;return s.html}set(t,n,s,o){let l=this.getHash(n,s);this.cache.set(t,{hash:l,html:o,generatedAt:Date.now(),dependencies:s})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let n=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",n)}async get(t){let n=this.getFilePath(t);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(t,n){let s=this.getFilePath(t);await D.promises.mkdir(f.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(t){let n=this.getFilePath(t);if(await Bun.file(n).exists())await D.promises.unlink(n)}async invalidatePattern(t){let n=f.join(this.cacheDir,"isr");if(!D.existsSync(n))return;let s=await D.promises.readdir(n);for(let o of s){let l=o.replace(/_/g,"/").replace(".json","");if(t.test(l))await D.promises.unlink(f.join(n,o))}}async needsRevalidation(t){let n=await this.get(t);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(t){let n=[];if(!t.isDynamic)n.push({url:t.pattern,params:{}});else{let s=await gt(t.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${t.pattern} (${t.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),n;for(let l of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(l.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:e,params:l.params,props:l.props,revalidate:l.revalidate})}}return n}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let n of ft(t))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...l}=s;return l}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(t,n,s){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let l=o[1];if(!l.includes("getStaticProps"))return null;try{let e=l.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
2
+ import"./chunk-7sh9fa3q.js";import{x,rl}from"./chunk-72jt897s.js";import"./chunk-1tzqqr0p.js";import"./chunk-r9e0r6jx.js";import{Rt,w}from"./chunk-vhzngsmd.js";import"./chunk-m7hfcxt3.js";import"./chunk-bnewgd23.js";import"./chunk-9gwhs0gk.js";import{kt,_t,Ct,Et,Tt,$t}from"./chunk-gtd6qs1r.js";import{a}from"./chunk-jw7cakxt.js";import{Es}from"./chunk-em2yy1te.js";import"./chunk-t2sg2tp2.js";import"./chunk-x46hqa74.js";import{he,en,tn}from"./chunk-sjd6rt97.js";import"./chunk-xka9fdye.js";import{y}from"./chunk-e758jz81.js";import{yt,i}from"./chunk-12sd0ep5.js";import"./chunk-kz6qw9fm.js";import"./chunk-4gg9594a.js";import{ps}from"./chunk-e4d0jgcw.js";import"./chunk-4jaet63w.js";import"./chunk-c84pxd2k.js";import{Ya,Za,Qa}from"./chunk-hwcfgs3e.js";import{Zt,Yn,Zn}from"./chunk-ndjmt3vg.js";import{Qt}from"./chunk-j476jghg.js";import"./chunk-mz1mgfq3.js";import"./chunk-f6nk205v.js";import{X,we}from"./chunk-rccv14mn.js";import"./chunk-fmawgk87.js";import"./chunk-3dg2zg8d.js";import{c}from"./chunk-0rjcbqk3.js";import{r,ge}from"./chunk-b9d70mgr.js";import D from"fs";import f from"path";import{createHash as vt}from"crypto";function Pt(t){try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(t).replace(/\}(var |let |const |function )/g,"};$1").trim()}catch{return t}}var Dt=/<script\s+type="stx\/island"\s+data-stx-island="([^"]+)"([^>]*)>([\s\S]*?)<\/script>/g;function It(t){return Bun.hash(t).toString(16)}function ot(t,n={}){if(!t.includes('type="stx/island"'))return{html:t,chunks:[]};let s=new Map,o=t.replace(Dt,(e,u,g,v)=>{let S=v.trim();if(!S)return e;if(/\bdata-stx-src=/.test(g))return e;if(n.minify)S=Pt(S);let p=It(S);if(!s.has(p))s.set(p,S);let P=n.integrity?` data-stx-integrity="sha384-${vt("sha384").update(S).digest("base64")}"`:"";return`<script type="stx/island" data-stx-island="${u}" data-stx-src="/_stx/islands/${p}.js"${P}${g}></script>`}),l=Array.from(s,([e,u])=>({hash:e,code:u}));return{html:o,chunks:l}}var Bt=new Set(["visible","idle"]);function ct(t){if(!t.includes("data-stx-src="))return t;let n=new Map,s=/data-stx-scope="([^"]+)"[^>]*?stx-hydrate="([^"]+)"/g,o;while((o=s.exec(t))!==null)n.set(o[1],o[2]);let l=new Set,e=/data-stx-island="([^"]+)"[^>]*?data-stx-src="([^"]+)"/g,u;while((u=e.exec(t))!==null)if(Bt.has(n.get(u[1])||""))l.add(u[2]);let g=/<\/head\s*>/iy,v=w(t,(p,P)=>(g.lastIndex=P,g.exec(p)?g.lastIndex:-1))[0]?.start??-1;if(l.size===0||v===-1)return t;let S=Array.from(l).filter((p)=>!t.includes(`rel="prefetch" href="${p}"`)).map((p)=>`<link rel="prefetch" href="${p}" as="script">`).join("");if(!S)return t;return t.slice(0,v)+S+t.slice(v)}var jt=["STX_SITE_URL","SITE_URL","URL","VERCEL_URL","CF_PAGES_URL"];function K(t){let n=t.trim();if(!n)return null;let s=/^https?:\/\//i.test(n)?n:`https://${n}`;try{return new URL(s).origin+new URL(s).pathname.replace(/\/$/,"")}catch{return null}}function Ft(t){for(let n of jt){let s=t[n];if(!s)continue;let o=K(s);if(o)return{url:o,source:"env",via:n}}return null}function lt(t){if(!t||typeof t!=="object")return null;let n=t,s=n.site?.url??n.url??n.app?.url;return typeof s==="string"?K(s):null}async function At(t){let{existsSync:n}=await import("fs"),s=await import("path");for(let o of["site.config.ts","site.config.js",".config/site.config.ts"]){let l=s.resolve(t,o);if(!n(l))continue;try{let e=await import(l),u=lt(e.default??e);if(u)return u}catch{}}return null}async function ut(t={}){let n=t.cwd??process.cwd(),s=t.env??process.env;if(t.explicit){let u=K(t.explicit);if(u)return{url:u,source:"option"}}let o=lt(t.stxConfig);if(o)return{url:o,source:"stx.config",via:"site.url"};let l=await At(n);if(l)return{url:l,source:"site.config",via:"url"};let e=Ft(s);if(e)return e;return{url:"http://localhost",source:"fallback"}}function dt(){return["No site URL configured \u2014 sitemap.xml and robots.txt will point at http://localhost."," Set one in stx.config.ts (site: { url: 'https://example.com' }), in site.config.ts,"," via --domain, or with SITE_URL in the build environment."].join(`
3
+ `)}function q(t){return async()=>({paths:await t(),fallback:!1})}var Ot;function Lt(t){let n=r(t),{depths:s}=ge(n),o=/\b(?:async\s+)?function\s+getStaticPaths\s*\(/g,l;while((l=o.exec(n))!==null){if(s[l.index]!==0)continue;let u=x(n,"(",")",o.lastIndex-1),g=n.indexOf("{",u+1),v=x(n,"{","}",g);if(u<0||g<0||v<0)break;return t.slice(l.index,v+1)}let e=/\b(?:const|let|var)\s+getStaticPaths\s*=/g;while((l=e.exec(n))!==null){if(s[l.index]!==0)continue;let u=rl(n,e.lastIndex).endPos;return t.slice(e.lastIndex,u).trim()}throw SyntaxError("Could not extract getStaticPaths; use a top-level function or const declaration")}async function gt(t){let n="read";try{let s=await Bun.file(t).text();n="parse";let o=Qt(s),l=[...o.server,...o.client,...o.signals].filter((e)=>/(?:^|\s)server(?:\s|=|$)/i.test(r(e.attrs))).sort((e,u)=>s.indexOf(e.fullTag)-s.indexOf(u.fullTag));for(let e of l){if(!/\bgetStaticPaths\b/.test(r(e.content)))continue;let u=(Ot??=new Bun.Transpiler({loader:"ts",target:"bun"})).transformSync(e.content);if(!/\bgetStaticPaths\b/.test(r(u)))continue;let g=Lt(u);if(/\bdefineStaticPaths\b/.test(r(g))&&Rt(u,"defineStaticPaths"))throw SyntaxError("Cannot evaluate a module-local defineStaticPaths binding during isolated hook extraction");n="execute";let v=Function("defineStaticPaths",`return (${g})`)(q);if(typeof v!=="function")throw TypeError("getStaticPaths must be a function");let S=await v();n="result";let p=Array.isArray(S)?{paths:S}:S;if(!p||typeof p!=="object"||!("paths"in p)||!Array.isArray(p.paths))throw TypeError("getStaticPaths must return { paths: [...] } or an array of paths");for(let P of p.paths)if(!P||typeof P!=="object"||!P.params||typeof P.params!=="object"||Array.isArray(P.params))throw TypeError("Each getStaticPaths path must contain a params object");return{kind:"ok",value:p}}return{kind:"absent"}}catch(s){return{kind:"error",phase:n,error:s instanceof Error?s:Error(String(s))}}}class pt{cacheDir;cache=new Map;loaded=!1;salt;constructor(t,n=""){this.cacheDir=t,this.salt=n}async load(){if(this.loaded)return;let t=f.join(this.cacheDir,"build-cache.json");if(await Bun.file(t).exists())try{let n=JSON.parse(await Bun.file(t).text());for(let[s,o]of Object.entries(n))this.cache.set(s,o)}catch{}this.loaded=!0}async save(){await D.promises.mkdir(this.cacheDir,{recursive:!0});let t=f.join(this.cacheDir,"build-cache.json"),n={};for(let[s,o]of this.cache)n[s]=o;await Bun.write(t,JSON.stringify(n))}getHash(t,n){let s=D.statSync(t),o=`${this.salt}|${t}:${s.mtimeMs}`;for(let e of n)if(D.existsSync(e)){let u=D.statSync(e);o+=`:${e}:${u.mtimeMs}`}let l=0;for(let e=0;e<o.length;e++){let u=o.charCodeAt(e);l=(l<<5)-l+u,l=l&l}return Math.abs(l).toString(36)}get(t,n){let s=this.cache.get(t);if(!s)return null;let o=ft(n).some((u)=>D.existsSync(u)),l=[n,...s.dependencies??[]].some((u)=>u.endsWith(".stx")&&D.existsSync(u)&&ps(D.readFileSync(u,"utf8")).some((g)=>/\bserver\b/.test(g.attrs)));if(o||l)return this.cache.delete(t),null;let e=this.getHash(n,s.dependencies??[]);if(s.hash!==e)return this.cache.delete(t),null;return s.html}set(t,n,s,o){let l=this.getHash(n,s);this.cache.set(t,{hash:l,html:o,generatedAt:Date.now(),dependencies:s})}}class ht{cacheDir;constructor(t){this.cacheDir=t}getFilePath(t){let n=t.replace(/[^a-zA-Z0-9]/g,"_")+".json";return f.join(this.cacheDir,"isr",n)}async get(t){let n=this.getFilePath(t);if(!await Bun.file(n).exists())return null;try{return JSON.parse(await Bun.file(n).text())}catch{return null}}async set(t,n){let s=this.getFilePath(t);await D.promises.mkdir(f.dirname(s),{recursive:!0}),await Bun.write(s,JSON.stringify(n))}async invalidate(t){let n=this.getFilePath(t);if(await Bun.file(n).exists())await D.promises.unlink(n)}async invalidatePattern(t){let n=f.join(this.cacheDir,"isr");if(!D.existsSync(n))return;let s=await D.promises.readdir(n);for(let o of s){let l=o.replace(/_/g,"/").replace(".json","");if(t.test(l))await D.promises.unlink(f.join(n,o))}}async needsRevalidation(t){let n=await this.get(t);if(!n)return!0;return Date.now()>n.revalidateAfter}}async function Ut(t){let n=[];if(!t.isDynamic)n.push({url:t.pattern,params:{}});else{let s=await gt(t.filePath);if(s.kind==="error")throw Error(`getStaticPaths ${s.phase} failed for ${t.pattern} (${t.filePath}): ${s.error.message}`,{cause:s.error});if(s.kind==="absent")return console.warn(`Warning: Dynamic route ${t.pattern} (${t.filePath}) has no getStaticPaths`),n;let o=s.value;if(o.paths.length===0)return console.info(`getStaticPaths returned no paths for dynamic route ${t.pattern} (${t.filePath})`),n;for(let l of o.paths){let e=t.pattern;for(let[u,g]of Object.entries(l.params))e=e.replace(`:${u}`,g).replace(`:${u}*`,g);n.push({url:e,params:l.params,props:l.props,revalidate:l.revalidate})}}return n}function ft(t){return[t.replace(/\.stx$/,".data.ts"),t.replace(/\.stx$/,".data.js"),t+".data.ts",t+".data.js"]}async function Mt(t){for(let n of ft(t))if(await Bun.file(n).exists())try{let s=await import(n);if(typeof s.default==="function")return await s.default();else if(typeof s.default==="object")return s.default;else if(typeof s.getData==="function")return await s.getData();else{let{default:o,...l}=s;return l}}catch(s){console.error(`Error loading data file ${n}:`,s)}return null}async function Gt(t,n,s){let o=t.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return null;let l=o[1];if(!l.includes("getStaticProps"))return null;try{let e=l.match(/(?:export\s+)?(?:async\s+)?function\s+getStaticProps\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/);if(!e)return null;return await Function("params",`
4
4
  return (async function getStaticProps() {
5
5
  ${e[1]}
6
6
  })()
7
- `)(n)}catch(e){return console.error(`Error executing getStaticProps in ${s}:`,e),null}}function Nt(t){return/(?:^|[^\w$.])(?:export\s+)?(?:async\s+)?function\s+action\s*\(/.test(t)||/(?:^|[^\w$.])(?:export\s+)?(?:const|let|var)\s+action\s*=/.test(t)}async function mt(t,n,s={},o,l){let e=await Bun.file(t.filePath).text(),u=await Mt(t.filePath),g=await Gt(e,n,t.filePath),v={...u||{},...g||{},...s,params:n,$route:{path:t.pattern,params:n}},x=new Set,p=[],P=[],E={...l,minifyClient:!0,...o.partialsDir?{partialsDir:o.partialsDir}:{},...o.componentsDir?{componentsDir:o.componentsDir}:{},debug:!1,cache:!1,autoShell:!0,onIncludeError:(R)=>{p.push(`${f.relative(process.cwd(),R.templatePath)}: ${R.message}
8
- resolved against partialsDir: ${R.partialsDir}`)},onServerScriptError:(R)=>{P.push(`${f.relative(process.cwd(),R.sourcePath)} (${R.kind}): ${R.message}`)}};if(Nt(e))console.warn(`Warning: ${t.pattern} exports a page action, which cannot run in a static build. Its form will submit to a file. Serve this route with the production server, or point the form's action at a route handler.`);let b=await i(e,v,t.filePath,E,x);for(let R of[t.filePath,...x])for(let T of he(R))x.add(T);if(Object.keys(n).length>0){let R=`<script>if(window.stx)window.stx._rp=${JSON.stringify(n)};else window.__stx_rp=${JSON.stringify(n)};</script>`;if(b.includes("</head>"))b=b.replace("</head>",`${R}
7
+ `)(n)}catch(e){return console.error(`Error executing getStaticProps in ${s}:`,e),null}}function Nt(t){return/(?:^|[^\w$.])(?:export\s+)?(?:async\s+)?function\s+action\s*\(/.test(t)||/(?:^|[^\w$.])(?:export\s+)?(?:const|let|var)\s+action\s*=/.test(t)}async function mt(t,n,s={},o,l){let e=await Bun.file(t.filePath).text(),u=await Mt(t.filePath),g=await Gt(e,n,t.filePath),v={...u||{},...g||{},...s,params:n,$route:{path:t.pattern,params:n}},S=new Set,p=[],P=[],E={...l,minifyClient:!0,...o.partialsDir?{partialsDir:o.partialsDir}:{},...o.componentsDir?{componentsDir:o.componentsDir}:{},debug:!1,cache:!1,autoShell:!0,onIncludeError:(R)=>{p.push(`${f.relative(process.cwd(),R.templatePath)}: ${R.message}
8
+ resolved against partialsDir: ${R.partialsDir}`)},onServerScriptError:(R)=>{P.push(`${f.relative(process.cwd(),R.sourcePath)} (${R.kind}): ${R.message}`)}};if(Nt(e))console.warn(`Warning: ${t.pattern} exports a page action, which cannot run in a static build. Its form will submit to a file. Serve this route with the production server, or point the form's action at a route handler.`);let b=await i(e,v,t.filePath,E,S);for(let R of[t.filePath,...S])for(let T of he(R))S.add(T);if(Object.keys(n).length>0){let R=`<script>if(window.stx)window.stx._rp=${JSON.stringify(n)};else window.__stx_rp=${JSON.stringify(n)};</script>`;if(b.includes("</head>"))b=b.replace("</head>",`${R}
9
9
  </head>`);else b=`${R}
10
- ${b}`}if(b=await we(b,{router:o.router}),b=await y(b),o.minify!==!1)return{html:Ht(b),dependencies:Array.from(x),includeFailures:p,serverScriptFailures:P};return{html:b,dependencies:Array.from(x),includeFailures:p,serverScriptFailures:P}}function Ht(t){let n=[],s=0,o=/(<script[^>]*>)([\s\S]*?)(<\/script>)/gi,l;while((l=o.exec(t))!==null){let u=t.slice(s,l.index);n.push(u.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><"));let g=l[1],v=l[2],x=l[3];v=v.replace(/([^:"\\'`])\/\/(?!\/)(?![*!])([^\n]*)/g,"$1"),n.push(g+v+x),s=l.index+l[0].length}let e=t.slice(s);return n.push(e.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><")),n.join("").trim()}function zt(t){let n=0;for(let s=0;s<t.length;s++){let o=t.charCodeAt(s);n=(n<<5)-n+o,n=n&n}return`"${Math.abs(n).toString(36)}"`}function Wt(t,n,s,o){if(s?.sitemap===!1)return!0;if(/<meta[^>]+name=["']robots["'][^>]+content=["'][^"']*noindex/i.test(n))return!0;return o.some((l)=>{if(l instanceof RegExp)return l.test(t);return l.endsWith("/")?t===l.slice(0,-1)||t.startsWith(l):t===l})}function qt(t,n){return`<?xml version="1.0" encoding="UTF-8"?>
10
+ ${b}`}if(b=await we(b,{router:o.router}),b=await y(b),o.minify!==!1)return{html:Ht(b),dependencies:Array.from(S),includeFailures:p,serverScriptFailures:P};return{html:b,dependencies:Array.from(S),includeFailures:p,serverScriptFailures:P}}function Ht(t){let n=[],s=0,o=/(<script[^>]*>)([\s\S]*?)(<\/script>)/gi,l;while((l=o.exec(t))!==null){let u=t.slice(s,l.index);n.push(u.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><"));let g=l[1],v=l[2],S=l[3];v=v.replace(/([^:"\\'`])\/\/(?!\/)(?![*!])([^\n]*)/g,"$1"),n.push(g+v+S),s=l.index+l[0].length}let e=t.slice(s);return n.push(e.replace(/<!--(?!\[if)[\s\S]*?-->/g,"").replace(/\s+/g," ").replace(/>\s+</g,"><")),n.join("").trim()}function zt(t){let n=0;for(let s=0;s<t.length;s++){let o=t.charCodeAt(s);n=(n<<5)-n+o,n=n&n}return`"${Math.abs(n).toString(36)}"`}function Wt(t,n,s,o){if(s?.sitemap===!1)return!0;if(/<meta[^>]+name=["']robots["'][^>]+content=["'][^"']*noindex/i.test(n))return!0;return o.some((l)=>{if(l instanceof RegExp)return l.test(t);return l.endsWith("/")?t===l.slice(0,-1)||t.startsWith(l):t===l})}function qt(t,n){return`<?xml version="1.0" encoding="UTF-8"?>
11
11
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
12
12
  ${t.map((o)=>{let l=new URL(o.loc,n).href,e=` <url>
13
13
  <loc>${F(l)}</loc>`;if(o.lastmod)e+=`
@@ -37,7 +37,7 @@ ${t.map((o)=>{let l=new URL(o.loc,n).href,e=` <url>
37
37
  ${s.join(`
38
38
  `)}
39
39
  </channel>
40
- </rss>`}async function Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||c(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,x={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-rzwyaqgg.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-yd1zsy7t.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-rzwyaqgg.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];Qa(s?.layoutsDir,c(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
40
+ </rss>`}async function Vt(t={}){let n=Date.now();tn();let s=await a(process.cwd()),o=s.build||{},l=await ut({explicit:t.domain||o.domain,stxConfig:s});if(l.source==="fallback"&&(t.sitemap??o.sitemap??!0))console.warn(dt());let e={router:t.router??s?.router??{},pagesDir:t.pagesDir||o.pagesDir||"pages",outputDir:t.outputDir||o.outputDir||"dist",baseUrl:t.baseUrl||o.baseUrl||"/",domain:l.url,revalidate:t.revalidate??o.revalidate??!1,sitemap:t.sitemap??o.sitemap??!0,sitemapExclude:t.sitemapExclude||o.sitemapExclude||[],robots:t.robots??o.robots??!0,rss:t.rss??o.rss??!1,concurrency:t.concurrency||o.concurrency||10,cache:t.cache??o.cache??!0,cacheDir:t.cacheDir||o.cacheDir||c(process.cwd(),"ssg-cache"),contentLoaders:t.contentLoaders||[],hooks:t.hooks||{},minify:t.minify??o.minify??!0,generate404:t.generate404??o.generate404??!0,publicDir:t.publicDir||o.publicDir||"public",trailingSlash:t.trailingSlash??o.trailingSlash??!1,cleanOutput:t.cleanOutput??o.cleanOutput??!0,cacheSalt:t.cacheSalt??"",partialsDir:t.partialsDir||s?.partialsDir||"",componentsDir:t.componentsDir||s?.componentsDir||"",failOnIncludeError:t.failOnIncludeError??!0,failOnServerScriptError:t.failOnServerScriptError??!0,chunkIslands:t.chunkIslands===!0,prefetchIslands:t.prefetchIslands===!0,integrityIslands:t.integrityIslands===!0},u={totalPages:0,successCount:0,failedCount:0,cachedCount:0,buildTime:0,pages:[],errors:[]},g=new Set,v=0,S={},p={};await e.hooks.onBuildStart?.();try{if(e.cleanOutput&&D.existsSync(e.outputDir))await D.promises.rm(e.outputDir,{recursive:!0});await D.promises.mkdir(e.outputDir,{recursive:!0});let E=e.cacheSalt;if(!E){let{resolveUserCssConfig:d,fingerprintConfig:m}=await import("./chunk-p04dabqm.js");try{E=m(await d(process.cwd()))}catch{}}let{prepareImageDelivery:b}=await import("./chunk-k5nd8zqh.js"),R=await b(e.publicDir,e.outputDir);if(R.count>0)console.log(`Optimized ${R.count} image(s) for responsive delivery`),E=[E,R.fingerprint].filter(Boolean).join(":");let T=new pt(e.cacheDir,E);if(e.cache)await T.load();try{let{generateCss:d}=await import("./chunk-p04dabqm.js");await d('<div class="bg-black"></div>')}catch{}kt();let wt=s?.routeMiddleware?.dir||"middleware";await Ct(process.cwd(),wt);let J=_t();if(J.length>0)console.log(`Loaded ${J.length} middleware: ${J.join(", ")}`);let St=s?.routeMiddleware?.global||[];Qa(s?.layoutsDir,c(process.cwd()));let Z=X(".",{pagesDir:e.pagesDir,pagesDirs:s?._layerPageDirs});console.log(`Found ${Z.length} routes`);let M=[];for(let d of Z)try{let m=await Ut(d);for(let k of m)M.push({route:d,url:k.url,params:k.params,props:k.props,revalidate:k.revalidate??e.revalidate})}catch(m){let k=m instanceof Error?m:Error(String(m));u.failedCount++,u.errors.push({route:d.pattern,error:k}),await e.hooks.onError?.(k,d.pattern),console.error(`Error discovering paths for ${d.pattern}:`,k)}u.totalPages=M.length+u.failedCount,console.log(`Generating ${M.length} pages...`);let _=[],Q=[];for(let d=0;d<M.length;d+=e.concurrency)Q.push(M.slice(d,d+e.concurrency));for(let d of Q)await Promise.all(d.map(async(m)=>{let{route:k,url:h,params:G,props:xt,revalidate:rt}=m;try{await e.hooks.onPageStart?.(h);let A=await Bun.file(k.filePath).text(),O=Yt(A),bt=O?.middleware?Array.isArray(O.middleware)?O.middleware:[O.middleware]:[],nt=[...St,...bt];if(nt.length>0){let B=Et(h,G,O||{}),L=Tt(B,null,void 0,{isServer:!0}),j=await $t(nt,L);if(j.redirect){let C=typeof j.redirect==="string"?j.redirect:j.redirect.path||j.redirect,H=te(String(C),h),U=ee(h,e);await D.promises.mkdir(f.dirname(U),{recursive:!0}),await Bun.write(U,H),u.successCount++,u.pages.push({route:h,outputPath:U,size:Buffer.byteLength(H),cached:!1}),_.push({loc:h,lastmod:new Date().toISOString()}),console.log(` \u21B3 ${h} \u2192 redirect to ${C}`);return}if(j.abort){let C=typeof j.abort==="string"?j.abort:j.abort?.error?.message||"aborted";console.warn(` \u21B3 ${h} \u2014 middleware aborted: ${C}`);return}}let it=A.match(/definePageMeta\s*\(\s*\{[\s\S]*?validate\s*:\s*((?:\([^)]*\)|[^,}])*(?:\{[\s\S]*?\})?)/m);if(it)try{if(!await Function("route",`
41
41
  const validate = ${it[1]};
42
42
  return validate(route);
43
43
  `)({params:G})){console.warn(`Validation failed for ${h}, skipping...`);return}}catch{}let I=null,st=!1;if(e.cache){if(I=T.get(h,k.filePath),I)st=!0,u.cachedCount++}if(!I){let B=await mt(k,G,xt,e,s);if(I=B.html,e.failOnIncludeError&&B.includeFailures.length>0)throw Error(`${B.includeFailures.length} include(s) failed to resolve, so this page would have shipped with an error banner where the markup should be:
@@ -46,7 +46,7 @@ ${s.join(`
46
46
  Set ssg.failOnIncludeError to false to build anyway.`);if(e.failOnServerScriptError&&B.serverScriptFailures.length>0)throw Error(`${B.serverScriptFailures.length} <script server> block(s) failed, so this page would have shipped with the content they produce missing:
47
47
  ${B.serverScriptFailures.join(`
48
48
  `)}
49
- Set ssg.failOnServerScriptError to false to build anyway.`);if(e.cache)T.set(h,k.filePath,B.dependencies,I)}let N;if(e.trailingSlash)N=f.join(e.outputDir,h,"index.html");else N=h==="/"?f.join(e.outputDir,"index.html"):f.join(e.outputDir,`${h}.html`);if(e.chunkIslands){let{html:B,chunks:L}=ot(I,{integrity:e.integrityIslands,minify:e.minify});if(L.length>0){let j=f.join(e.outputDir,"_stx","islands");await D.promises.mkdir(j,{recursive:!0});for(let C of L){let H=f.join(j,`${C.hash}.js`);if(!await Bun.file(H).exists())await Bun.write(H,C.code);if(!g.has(C.hash)){g.add(C.hash);let U=Buffer.byteLength(C.code,"utf8");v+=U,x[C.hash]={bytes:U,file:`/_stx/islands/${C.hash}.js`}}}if(p[h]=L.map((C)=>C.hash),I=B,e.prefetchIslands)I=ct(I)}}if(await D.promises.mkdir(f.dirname(N),{recursive:!0}),await Bun.write(N,I),!Wt(h,I,O,e.sitemapExclude))_.push({loc:h,lastmod:new Date().toISOString().split("T")[0],priority:h==="/"?1:0.8});let at={route:h,outputPath:N,size:Buffer.byteLength(I,"utf8"),cached:st};if(rt!==!1)at.revalidateAt=Date.now()+rt*1000;u.pages.push(at),u.successCount++,await e.hooks.onPageEnd?.(h,I)}catch(A){u.failedCount++,u.errors.push({route:h,error:A}),await e.hooks.onError?.(A,h),console.error(`Error generating ${h}:`,A)}}));let tt=en();if(tt.length>0){let d=tt.map((m)=>`${m.filePath}: ${m.message}`).join(`
49
+ Set ssg.failOnServerScriptError to false to build anyway.`);if(e.cache)T.set(h,k.filePath,B.dependencies,I)}let N;if(e.trailingSlash)N=f.join(e.outputDir,h,"index.html");else N=h==="/"?f.join(e.outputDir,"index.html"):f.join(e.outputDir,`${h}.html`);if(e.chunkIslands){let{html:B,chunks:L}=ot(I,{integrity:e.integrityIslands,minify:e.minify});if(L.length>0){let j=f.join(e.outputDir,"_stx","islands");await D.promises.mkdir(j,{recursive:!0});for(let C of L){let H=f.join(j,`${C.hash}.js`);if(!await Bun.file(H).exists())await Bun.write(H,C.code);if(!g.has(C.hash)){g.add(C.hash);let U=Buffer.byteLength(C.code,"utf8");v+=U,S[C.hash]={bytes:U,file:`/_stx/islands/${C.hash}.js`}}}if(p[h]=L.map((C)=>C.hash),I=B,e.prefetchIslands)I=ct(I)}}if(await D.promises.mkdir(f.dirname(N),{recursive:!0}),await Bun.write(N,I),!Wt(h,I,O,e.sitemapExclude))_.push({loc:h,lastmod:new Date().toISOString().split("T")[0],priority:h==="/"?1:0.8});let at={route:h,outputPath:N,size:Buffer.byteLength(I,"utf8"),cached:st};if(rt!==!1)at.revalidateAt=Date.now()+rt*1000;u.pages.push(at),u.successCount++,await e.hooks.onPageEnd?.(h,I)}catch(A){u.failedCount++,u.errors.push({route:h,error:A}),await e.hooks.onError?.(A,h),console.error(`Error generating ${h}:`,A)}}));let tt=en();if(tt.length>0){let d=tt.map((m)=>`${m.filePath}: ${m.message}`).join(`
50
50
  `);throw Error(`Client script bundling failed:
51
51
  ${d}`)}if(e.cache)await T.save();if(e.generate404){let d=f.join(e.pagesDir,"404.stx");if(await Bun.file(d).exists()){let m=new Set,k={...s,minifyClient:!0,debug:!1,cache:!1},h=await i(await Bun.file(d).text(),{},d,k,m);await Bun.write(f.join(e.outputDir,"404.html"),h)}else await Bun.write(f.join(e.outputDir,"404.html"),`<!DOCTYPE html>
52
52
  <html lang="en">
@@ -69,7 +69,7 @@ ${d}`)}if(e.cache)await T.save();if(e.generate404){let d=f.join(e.pagesDir,"404.
69
69
  <a href="/">Go home</a>
70
70
  </div>
71
71
  </body>
72
- </html>`)}for(let d of[500]){let m=f.join(e.pagesDir,`${d}.stx`);if(await Bun.file(m).exists()){let k=new Set,h={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),G)}}let V=f.join(e.pagesDir,"error.stx");if(await Bun.file(V).exists()){let d=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(V).text(),{},V,m,d);await Bun.write(f.join(e.outputDir,"error.html"),k)}if(e.sitemap&&_.length>0){let d=qt(_,e.domain),m=f.join(e.outputDir,"sitemap.xml");await Bun.write(m,d),u.sitemapPath=m,console.log(`Generated sitemap.xml with ${_.length} URLs`)}if(e.robots!==!1){let d=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((h)=>typeof h==="string"),...d.disallow||[]],k=Es({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...m.length>0?{disallow:m}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(f.join(e.outputDir,"robots.txt"),k),console.log("Generated robots.txt")}if(e.rss){let d=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(d.getItems)m=await d.getItems();let k=Jt(d,m),h=f.join(e.outputDir,"rss.xml");await Bun.write(h,k),u.rssPath=h,console.log(`Generated rss.xml with ${m.length} items`)}let z=Ya(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let W=Za(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} repeated asset(s) from ${W.pages} page(s) (${(W.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&D.existsSync(e.publicDir))await Y(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let et=Zn();if(et)await Y(et,f.join(e.outputDir,Yn)),console.log(`Copied assets from ${Zt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:x,pages:p};await Bun.write(f.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(E,null,2))}await e.hooks.onBuildEnd?.(u);let P=u.islandChunks?`
72
+ </html>`)}for(let d of[500]){let m=f.join(e.pagesDir,`${d}.stx`);if(await Bun.file(m).exists()){let k=new Set,h={...s,minifyClient:!0,debug:!1,cache:!1},G=await i(await Bun.file(m).text(),{},m,h,k);await Bun.write(f.join(e.outputDir,`${d}.html`),G)}}let V=f.join(e.pagesDir,"error.stx");if(await Bun.file(V).exists()){let d=new Set,m={...s,minifyClient:!0,debug:!1,cache:!1},k=await i(await Bun.file(V).text(),{},V,m,d);await Bun.write(f.join(e.outputDir,"error.html"),k)}if(e.sitemap&&_.length>0){let d=qt(_,e.domain),m=f.join(e.outputDir,"sitemap.xml");await Bun.write(m,d),u.sitemapPath=m,console.log(`Generated sitemap.xml with ${_.length} URLs`)}if(e.robots!==!1){let d=typeof e.robots==="object"?e.robots:{},m=[...e.sitemapExclude.filter((h)=>typeof h==="string"),...d.disallow||[]],k=Es({rules:[{userAgent:d.userAgent||"*",allow:d.allow||["/"],...m.length>0?{disallow:m}:{}}],...d.sitemap!==!1&&u.sitemapPath?{sitemap:new URL("/sitemap.xml",e.domain).href}:{}});await Bun.write(f.join(e.outputDir,"robots.txt"),k),console.log("Generated robots.txt")}if(e.rss){let d=typeof e.rss==="object"?e.rss:{title:"Site Feed",description:"Latest updates",link:e.domain},m=[];if(d.getItems)m=await d.getItems();let k=Jt(d,m),h=f.join(e.outputDir,"rss.xml");await Bun.write(h,k),u.rssPath=h,console.log(`Generated rss.xml with ${m.length} items`)}let z=Ya(e.outputDir);if(z.assets>0)console.log(`Externalized ${z.assets} asset(s) from ${z.pages} page(s) (${(z.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);let W=Za(e.outputDir);if(W.assets>0)console.log(`Externalized ${W.assets} repeated asset(s) from ${W.pages} page(s) (${(W.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(e.publicDir&&D.existsSync(e.publicDir))await Y(e.publicDir,e.outputDir),console.log(`Copied public assets from ${e.publicDir}`);let et=Zn();if(et)await Y(et,f.join(e.outputDir,Yn)),console.log(`Copied assets from ${Zt}`)}catch(E){throw await e.hooks.onError?.(E),E}if(u.buildTime=Date.now()-n,g.size>0){u.islandChunks={count:g.size,totalBytes:v};let E={generatedChunks:g.size,totalBytes:v,chunks:S,pages:p};await Bun.write(f.join(e.outputDir,"_stx","islands-manifest.json"),JSON.stringify(E,null,2))}await e.hooks.onBuildEnd?.(u);let P=u.islandChunks?`
73
73
  Island chunks: ${u.islandChunks.count} (${(u.islandChunks.totalBytes/1024).toFixed(1)} KB lifted out of inline HTML)`:"";return console.log(`
74
74
  Build complete!
75
75
  Total: ${u.totalPages} pages
@@ -77,8 +77,8 @@ Build complete!
77
77
  Cached: ${u.cachedCount}
78
78
  Failed: ${u.failedCount}
79
79
  Time: ${u.buildTime}ms${P}
80
- `),u}async function Y(t,n){await D.promises.mkdir(n,{recursive:!0});let s=await D.promises.readdir(t,{withFileTypes:!0});for(let o of s){let l=f.join(t,o.name),e=f.join(n,o.name);if(o.isDirectory())await D.promises.mkdir(e,{recursive:!0}),await Y(l,e);else await D.promises.copyFile(l,e)}}function Kt(t={}){let n=t.cacheDir||c(process.cwd(),"ssg-cache"),s=new ht(n),o=t.revalidate||3600;return{async get(l){let e=await s.get(l);if(!e)return null;if(Date.now()>e.revalidateAfter)this.revalidate(l).catch(console.error);return{html:e.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:e.etag,"X-ISR-Generated":new Date(e.generatedAt).toISOString(),...e.headers}}},async revalidate(l){let u=X(".",{pagesDir:t.pagesDir||"pages"}).find((P)=>l.match(P.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${l}`);return}let g=l.match(u.regex),v={};if(g)u.params.forEach((P,E)=>{v[P]=g[E+1]});let x=await a(),{html:p}=await mt(u,v,{},t,x);await s.set(l,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:zt(p)}),console.log(`Revalidated: ${l}`)},async invalidate(l){if(typeof l==="string")await s.invalidate(l);else await s.invalidatePattern(l)}}}function Xt(){return{name:"markdown",extensions:[".md",".mdx"],async load(t){let n=await Bun.file(t).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},l=n;if(s){let x=s[1];l=n.slice(s[0].length).trim();for(let p of x.split(`
81
- `)){let P=p.indexOf(":");if(P>0){let E=p.slice(0,P).trim(),b=p.slice(P+1).trim();if(b==="true")b=!0;else if(b==="false")b=!1;else if(/^\d+$/.test(b))b=parseInt(b,10);else if(/^\d+\.\d+$/.test(b))b=parseFloat(b);else if(b.startsWith("[")&&b.endsWith("]"))b=b.slice(1,-1).split(",").map((R)=>R.trim().replace(/^['"]|['"]$/g,""));o[E]=b}}}let e=l.replace(/^### (.*$)/gim,"<h3>$1</h3>").replace(/^## (.*$)/gim,"<h2>$1</h2>").replace(/^# (.*$)/gim,"<h1>$1</h1>").replace(/\*\*(.*)\*\*/gim,"<strong>$1</strong>").replace(/\*(.*)\*/gim,"<em>$1</em>").replace(/`([^`]+)`/gim,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/gim,'<a href="$2">$1</a>').replace(/\n/gim,"<br>"),u=[],g=/<h([1-6])>([^<]+)<\/h[1-6]>/gi,v;while((v=g.exec(e))!==null){let x=parseInt(v[1],10),p=v[2],P=p.toLowerCase().replace(/[^a-z0-9]+/g,"-");u.push({id:P,text:p,level:x})}return{content:e,data:o,toc:u}}}}function Yt(t){return yt(t)}function te(t,n){return`<!DOCTYPE html>
80
+ `),u}async function Y(t,n){await D.promises.mkdir(n,{recursive:!0});let s=await D.promises.readdir(t,{withFileTypes:!0});for(let o of s){let l=f.join(t,o.name),e=f.join(n,o.name);if(o.isDirectory())await D.promises.mkdir(e,{recursive:!0}),await Y(l,e);else await D.promises.copyFile(l,e)}}function Kt(t={}){let n=t.cacheDir||c(process.cwd(),"ssg-cache"),s=new ht(n),o=t.revalidate||3600;return{async get(l){let e=await s.get(l);if(!e)return null;if(Date.now()>e.revalidateAfter)this.revalidate(l).catch(console.error);return{html:e.html,headers:{"Cache-Control":`public, max-age=${o}, stale-while-revalidate=${o*2}`,ETag:e.etag,"X-ISR-Generated":new Date(e.generatedAt).toISOString(),...e.headers}}},async revalidate(l){let u=X(".",{pagesDir:t.pagesDir||"pages"}).find((P)=>l.match(P.regex)!==null);if(!u){console.warn(`Route not found for revalidation: ${l}`);return}let g=l.match(u.regex),v={};if(g)u.params.forEach((P,E)=>{v[P]=g[E+1]});let S=await a(),{html:p}=await mt(u,v,{},t,S);await s.set(l,{html:p,generatedAt:Date.now(),revalidateAfter:Date.now()+o*1000,etag:zt(p)}),console.log(`Revalidated: ${l}`)},async invalidate(l){if(typeof l==="string")await s.invalidate(l);else await s.invalidatePattern(l)}}}function Xt(){return{name:"markdown",extensions:[".md",".mdx"],async load(t){let n=await Bun.file(t).text(),s=n.match(/^---\n([\s\S]*?)\n---/),o={},l=n;if(s){let S=s[1];l=n.slice(s[0].length).trim();for(let p of S.split(`
81
+ `)){let P=p.indexOf(":");if(P>0){let E=p.slice(0,P).trim(),b=p.slice(P+1).trim();if(b==="true")b=!0;else if(b==="false")b=!1;else if(/^\d+$/.test(b))b=parseInt(b,10);else if(/^\d+\.\d+$/.test(b))b=parseFloat(b);else if(b.startsWith("[")&&b.endsWith("]"))b=b.slice(1,-1).split(",").map((R)=>R.trim().replace(/^['"]|['"]$/g,""));o[E]=b}}}let e=l.replace(/^### (.*$)/gim,"<h3>$1</h3>").replace(/^## (.*$)/gim,"<h2>$1</h2>").replace(/^# (.*$)/gim,"<h1>$1</h1>").replace(/\*\*(.*)\*\*/gim,"<strong>$1</strong>").replace(/\*(.*)\*/gim,"<em>$1</em>").replace(/`([^`]+)`/gim,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/gim,'<a href="$2">$1</a>').replace(/\n/gim,"<br>"),u=[],g=/<h([1-6])>([^<]+)<\/h[1-6]>/gi,v;while((v=g.exec(e))!==null){let S=parseInt(v[1],10),p=v[2],P=p.toLowerCase().replace(/[^a-z0-9]+/g,"-");u.push({id:P,text:p,level:S})}return{content:e,data:o,toc:u}}}}function Yt(t){return yt(t)}function te(t,n){return`<!DOCTYPE html>
82
82
  <html>
83
83
  <head>
84
84
  <meta charset="utf-8">
package/dist/utils.js CHANGED
@@ -22,6 +22,7 @@ import { processScopedStyles } from "./style-scoping.js";
22
22
  import { findSfcTemplateBlock } from "./sfc-template.js";
23
23
  import { importOnce } from "./lazy-module.js";
24
24
  import { scanAtElementPosition, stashScriptElements } from "./html-masking.js";
25
+ import { hasReactiveDirectives } from "./reactive.js";
25
26
  import { markProjectedRefs } from "./misc-directives.js";
26
27
  import { collectBlockDeclarations } from "./stx-virtual-ts.js";
27
28
  import { CLIENT_LOOP_NAMES_KEY, inheritedClientLoopNames } from "./loop-binding.js";
@@ -1058,7 +1059,7 @@ export async function renderComponentWithSlot(componentPath, props, slotContent,
1058
1059
  }
1059
1060
  if (slotContent && templateContent.includes("{{ text || slot }}"))
1060
1061
  templateContent = templateContent.replace(/\{\{\s*text\s*\|\|\s*slot\s*\}\}/g, () => slotContent);
1061
- const { applySlots } = await importOnce("stx/slots", () => import("./slots.js")), { defaultSlot, namedSlots } = parsedSlotContent, callerEvents = parentContext.__stx_signals_gate === !0 && /\s(?:@[\w:.-]+|x-on:[\w:.-]+)\s*=/.test(componentSlotContent), hasSignalScripts = options._nativeHostAttrs === !0 && clientScripts.length > 0 || callerEvents && clientScripts.length > 0 || clientScripts.some((s) => /\b(?:state|derived|effect|ref|useRef|reactive|computed|watch|watchEffect|useModel|useReactiveProp|onMount|onDestroy|defineProps|withDefaults|defineEmits|defineExpose|defineSlots)\s*(?:<[^<>()]*>)?\s*\(/.test(s)), projectRefs = (content) => hasSignalScripts ? markProjectedRefs(content, componentUid) : content, projectedSlots = new Map([...namedSlots].map(([name, slot]) => [name, {
1062
+ const { applySlots } = await importOnce("stx/slots", () => import("./slots.js")), { defaultSlot, namedSlots } = parsedSlotContent, callerEvents = parentContext.__stx_signals_gate === !0 && /\s(?:@[\w:.-]+|x-on:[\w:.-]+)\s*=/.test(componentSlotContent), hasSignalScripts = clientScripts.length > 0 && hasReactiveDirectives(templateContent) || options._nativeHostAttrs === !0 && clientScripts.length > 0 || callerEvents && clientScripts.length > 0 || clientScripts.some((s) => /\b(?:state|derived|effect|ref|useRef|reactive|computed|watch|watchEffect|useModel|useReactiveProp|onMount|onDestroy|defineProps|withDefaults|defineEmits|defineExpose|defineSlots)\s*(?:<[^<>()]*>)?\s*\(/.test(s)), projectRefs = (content) => hasSignalScripts ? markProjectedRefs(content, componentUid) : content, projectedSlots = new Map([...namedSlots].map(([name, slot]) => [name, {
1062
1063
  ...slot,
1063
1064
  content: projectRefs(slot.content)
1064
1065
  }]));
@@ -1511,6 +1512,10 @@ async function buildComponentIsland(rawContent, componentFilePath, minify) {
1511
1512
  catch { __componentProps = {}; }
1512
1513
  }
1513
1514
  window.__STX_CURRENT_PROPS__ = __componentProps && typeof __componentProps === 'object' && !Array.isArray(__componentProps) ? __componentProps : {};
1515
+ const __scopeProps = window.__STX_CURRENT_PROPS__;
1516
+ Object.defineProperty(__scopeVars, '$props', { configurable: true, enumerable: true, get: function() {
1517
+ return (__componentElement && __componentElement.__stx_props) || __scopeProps;
1518
+ } });
1514
1519
 
1515
1520
  // Scope-specific lifecycle callbacks. The queues drain as they run; the
1516
1521
  // hook lists keep what setup registered, because a component behind an :if
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/stx",
3
3
  "type": "module",
4
- "version": "0.2.817",
4
+ "version": "0.2.819",
5
5
  "description": "A performant UI Framework. Powered by Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -128,12 +128,12 @@
128
128
  "dependencies": {
129
129
  "@stacksjs/ts-css": "^0.3.21",
130
130
  "@stacksjs/clapp": "^0.2.16",
131
- "@stacksjs/desktop": "0.2.817",
132
- "@stacksjs/sanitizer": "0.2.817",
131
+ "@stacksjs/desktop": "0.2.819",
132
+ "@stacksjs/sanitizer": "0.2.819",
133
133
  "@stacksjs/ts-i18n": "^0.1.11",
134
- "bun-plugin-stx": "0.2.817",
134
+ "bun-plugin-stx": "0.2.819",
135
135
  "bunfig": "^0.15.21",
136
- "stx-router": "0.2.817",
136
+ "stx-router": "0.2.819",
137
137
  "ts-broadcasting": "^0.0.11",
138
138
  "ts-images": "^0.2.22",
139
139
  "ts-syntax-highlighter": "^0.2.1"
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ht,Hn,uh}from"./chunk-yts2b9d8.js";import{le,Vn,dh,Un,vo,Gr,Jr,ph,fh,gh,Wn,qn,xo,Yr,mh}from"./chunk-17wb2x3z.js";import"./chunk-n761hp6d.js";export{vo as batch,uh as default,Vn as derived,Un as effect,ht as generateSignalsRuntime,Hn as generateSignalsRuntimeDev,qn as isDerived,Wn as isSignal,dh as memo,Jr as onDestroy,Gr as onMount,Yr as peek,gh as pendingLifecycleCounts,fh as runDestroyCallbacks,ph as runMountCallbacks,le as state,xo as untrack,mh as useOptimistic};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Df,Oh,Nh,Mh,Dh,Lf,jf,Lh,jh,Xo,Bh,lr,ur,ws}from"./chunk-gc7pykfq.js";import{nt}from"./chunk-5emrarpf.js";import"./chunk-f0bwetnx.js";import"./chunk-pdnyhs63.js";import"./chunk-m7hfcxt3.js";import"./chunk-7rk7wfm6.js";import"./chunk-r9e0r6jx.js";import"./chunk-n761hp6d.js";export{Dh as __setSignalsGeneratorsForTest,nt as cacheEngineFingerprint,ur as cacheTemplate,lr as checkCache,Bh as clearDevCaches,jf as getCachedRouterScript,Lf as getCachedSignalsRuntime,Lh as getServeClientAsset,Xo as getServeModuleBundle,ws as hashFilePath,Nh as invalidateFileCache,Mh as invalidateFileCacheByDir,Oh as readFileCached,jh as registerServeModuleBundle,Df as templateCache};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Zm,Qm,eh,th,nh}from"./chunk-tb4wmzzd.js";export{Qm as createSSRSuspense,th as generateSuspenseCSS,nh as generateSuspenseRuntime,Zm as processSuspenseDirectives,eh as renderSSRSuspense};