@fluixi/compiler 1.0.0-alpha.83 → 1.0.0-alpha.85

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 (241) hide show
  1. package/dist/analyze/expr-shape.cjs +62 -1
  2. package/dist/analyze/expr-shape.d.cts +14 -0
  3. package/dist/analyze/expr-shape.d.ts +2 -2
  4. package/dist/analyze/expr-shape.js +1 -1
  5. package/dist/analyze/expr-shape.mjs +41 -1
  6. package/dist/analyze/intrinsics.cjs +80 -1
  7. package/dist/analyze/intrinsics.d.cts +66 -0
  8. package/dist/analyze/intrinsics.d.ts +7 -7
  9. package/dist/analyze/intrinsics.d.ts.map +1 -1
  10. package/dist/analyze/intrinsics.js +3 -3
  11. package/dist/analyze/intrinsics.mjs +59 -1
  12. package/dist/analyze/paren.cjs +134 -0
  13. package/dist/analyze/paren.d.cts +23 -0
  14. package/dist/analyze/paren.d.ts +24 -0
  15. package/dist/analyze/paren.d.ts.map +1 -0
  16. package/dist/analyze/paren.js +168 -0
  17. package/dist/analyze/paren.mjs +113 -0
  18. package/dist/analyze/props-destructure.cjs +226 -1
  19. package/dist/analyze/props-destructure.d.cts +83 -0
  20. package/dist/analyze/props-destructure.d.ts +3 -3
  21. package/dist/analyze/props-destructure.d.ts.map +1 -1
  22. package/dist/analyze/props-destructure.js +4 -4
  23. package/dist/analyze/props-destructure.mjs +205 -1
  24. package/dist/analyze/reactive-bindings.cjs +190 -1
  25. package/dist/analyze/reactive-bindings.d.cts +42 -0
  26. package/dist/analyze/reactive-bindings.d.ts +1 -1
  27. package/dist/analyze/reactive-bindings.js +2 -2
  28. package/dist/analyze/reactive-bindings.mjs +167 -1
  29. package/dist/analyze/reactive-expr.cjs +38 -1
  30. package/dist/analyze/reactive-expr.d.cts +38 -0
  31. package/dist/analyze/reactive-expr.d.ts +4 -4
  32. package/dist/analyze/reactive-expr.d.ts.map +1 -1
  33. package/dist/analyze/reactive-expr.js +2 -2
  34. package/dist/analyze/reactive-expr.mjs +17 -1
  35. package/dist/analyze/static-graph.cjs +811 -1
  36. package/dist/analyze/static-graph.d.cts +102 -0
  37. package/dist/analyze/static-graph.d.ts +1 -1
  38. package/dist/analyze/static-graph.d.ts.map +1 -1
  39. package/dist/analyze/static-graph.js +11 -11
  40. package/dist/analyze/static-graph.mjs +793 -1
  41. package/dist/babel-TGY76XJ7.mjs +636 -0
  42. package/dist/chunk-4PLHS2FP.mjs +158 -0
  43. package/dist/chunk-6DB5FXS4.mjs +1718 -0
  44. package/dist/chunk-F74GFKSL.mjs +16 -0
  45. package/dist/chunk-G6QC2WRJ.mjs +11 -0
  46. package/dist/chunk-RUDJDZAA.mjs +1078 -0
  47. package/dist/codegen/backend.cjs +18 -1
  48. package/dist/codegen/backend.d.cts +35 -0
  49. package/dist/codegen/backends/imperative.cjs +542 -1
  50. package/dist/codegen/backends/imperative.d.cts +11 -0
  51. package/dist/codegen/backends/imperative.d.ts +1 -1
  52. package/dist/codegen/backends/imperative.d.ts.map +1 -1
  53. package/dist/codegen/backends/imperative.js +24 -20
  54. package/dist/codegen/backends/imperative.mjs +519 -1
  55. package/dist/codegen/contract.cjs +52 -1
  56. package/dist/codegen/contract.d.cts +24 -0
  57. package/dist/codegen/contract.d.ts +2 -2
  58. package/dist/codegen/contract.js +2 -2
  59. package/dist/codegen/contract.mjs +31 -1
  60. package/dist/codegen/partial-template.cjs +176 -1
  61. package/dist/codegen/partial-template.d.cts +61 -0
  62. package/dist/codegen/partial-template.d.ts +4 -4
  63. package/dist/codegen/partial-template.js +0 -0
  64. package/dist/codegen/partial-template.mjs +153 -1
  65. package/dist/codegen/serialize-static.cjs +125 -1
  66. package/dist/codegen/serialize-static.d.cts +38 -0
  67. package/dist/codegen/serialize-static.d.ts +3 -3
  68. package/dist/codegen/serialize-static.js +6 -6
  69. package/dist/codegen/serialize-static.mjs +104 -1
  70. package/dist/frontend/babel/build-ir-lit.cjs +1509 -1
  71. package/dist/frontend/babel/build-ir-lit.d.cts +26 -0
  72. package/dist/frontend/babel/build-ir-lit.d.ts +2 -2
  73. package/dist/frontend/babel/build-ir-lit.mjs +1478 -1
  74. package/dist/frontend/babel/build-ir.cjs +1524 -1
  75. package/dist/frontend/babel/build-ir.d.cts +35 -0
  76. package/dist/frontend/babel/build-ir.d.ts +2 -2
  77. package/dist/frontend/babel/build-ir.js +2 -2
  78. package/dist/frontend/babel/build-ir.mjs +1495 -1
  79. package/dist/frontend/babel/index.cjs +2186 -1
  80. package/dist/frontend/babel/index.d.cts +33 -0
  81. package/dist/frontend/babel/index.d.ts +1 -1
  82. package/dist/frontend/babel/index.js +1 -1
  83. package/dist/frontend/babel/index.mjs +2156 -1
  84. package/dist/frontend/babel/lower-template.cjs +1507 -1
  85. package/dist/frontend/babel/lower-template.d.cts +23 -0
  86. package/dist/frontend/babel/lower-template.d.ts +1 -1
  87. package/dist/frontend/babel/lower-template.js +2 -2
  88. package/dist/frontend/babel/lower-template.mjs +1478 -1
  89. package/dist/frontend/babel/plugin.cjs +2132 -1
  90. package/dist/frontend/babel/plugin.d.cts +95 -0
  91. package/dist/frontend/babel/plugin.d.ts +5 -5
  92. package/dist/frontend/babel/plugin.d.ts.map +1 -1
  93. package/dist/frontend/babel/plugin.js +14 -14
  94. package/dist/frontend/babel/plugin.mjs +2103 -1
  95. package/dist/frontend/babel/server-functions.cjs +110 -1
  96. package/dist/frontend/babel/server-functions.d.cts +10 -0
  97. package/dist/frontend/babel/server-functions.mjs +89 -1
  98. package/dist/frontend/babel/types.cjs +18 -1
  99. package/dist/frontend/babel/types.d.cts +33 -0
  100. package/dist/frontend/types.cjs +18 -1
  101. package/dist/frontend/types.d.cts +25 -0
  102. package/dist/frontend/vocabulary.cjs +98 -0
  103. package/dist/frontend/vocabulary.d.cts +79 -0
  104. package/dist/frontend/vocabulary.d.ts +80 -0
  105. package/dist/frontend/vocabulary.d.ts.map +1 -0
  106. package/dist/frontend/vocabulary.js +124 -0
  107. package/dist/frontend/vocabulary.mjs +77 -0
  108. package/dist/index.cjs +1595 -14
  109. package/dist/index.d.cts +27 -0
  110. package/dist/index.d.ts +1 -1
  111. package/dist/index.js +4 -4
  112. package/dist/index.mjs +1575 -14
  113. package/dist/integrations.cjs +4312 -26
  114. package/dist/integrations.d.cts +215 -0
  115. package/dist/integrations.d.ts +9 -9
  116. package/dist/integrations.d.ts.map +1 -1
  117. package/dist/integrations.js +29 -8
  118. package/dist/integrations.mjs +536 -18
  119. package/dist/ir/nodes.cjs +18 -1
  120. package/dist/ir/nodes.d.cts +168 -0
  121. package/dist/ir/nodes.d.ts +6 -6
  122. package/dist/lower/compile-template.cjs +1356 -1
  123. package/dist/lower/compile-template.d.cts +69 -0
  124. package/dist/lower/compile-template.d.ts +3 -3
  125. package/dist/lower/compile-template.js +1 -1
  126. package/dist/lower/compile-template.mjs +1336 -1
  127. package/dist/lower/jsx.cjs +529 -1
  128. package/dist/lower/jsx.d.cts +25 -0
  129. package/dist/lower/jsx.d.ts +1 -1
  130. package/dist/lower/jsx.d.ts.map +1 -1
  131. package/dist/lower/jsx.js +6 -5
  132. package/dist/lower/jsx.mjs +506 -1
  133. package/dist/lower/template.cjs +1061 -1
  134. package/dist/lower/template.d.cts +53 -0
  135. package/dist/lower/template.d.ts +3 -3
  136. package/dist/lower/template.d.ts.map +1 -1
  137. package/dist/lower/template.js +12 -11
  138. package/dist/lower/template.mjs +1042 -1
  139. package/dist/lower/text.cjs +42 -1
  140. package/dist/lower/text.d.cts +10 -0
  141. package/dist/lower/text.d.ts +2 -2
  142. package/dist/lower/text.d.ts.map +1 -1
  143. package/dist/lower/text.js +2 -2
  144. package/dist/lower/text.mjs +21 -1
  145. package/dist/optimize/analyze-static.cjs +112 -1
  146. package/dist/optimize/analyze-static.d.cts +39 -0
  147. package/dist/optimize/analyze-static.d.ts +2 -2
  148. package/dist/optimize/analyze-static.js +2 -2
  149. package/dist/optimize/analyze-static.mjs +91 -1
  150. package/dist/optimize/collapse-strategies.cjs +90 -1
  151. package/dist/optimize/collapse-strategies.d.cts +30 -0
  152. package/dist/optimize/collapse-strategies.d.ts +3 -3
  153. package/dist/optimize/collapse-strategies.mjs +67 -1
  154. package/dist/options.cjs +33 -1
  155. package/dist/options.d.cts +39 -0
  156. package/dist/options.d.ts +2 -2
  157. package/dist/options.mjs +12 -1
  158. package/dist/resolve/builtins.cjs +73 -1
  159. package/dist/resolve/builtins.d.cts +68 -0
  160. package/dist/resolve/builtins.d.ts +8 -8
  161. package/dist/resolve/builtins.d.ts.map +1 -1
  162. package/dist/resolve/builtins.js +4 -4
  163. package/dist/resolve/builtins.mjs +53 -1
  164. package/dist/resolve/component-globals.cjs +234 -14
  165. package/dist/resolve/component-globals.d.cts +80 -0
  166. package/dist/resolve/component-globals.d.ts +5 -5
  167. package/dist/resolve/component-globals.js +10 -10
  168. package/dist/resolve/component-globals.mjs +211 -14
  169. package/dist/resolve/component-resolver.cjs +80 -1
  170. package/dist/resolve/component-resolver.d.cts +68 -0
  171. package/dist/resolve/component-resolver.d.ts +3 -3
  172. package/dist/resolve/component-resolver.d.ts.map +1 -1
  173. package/dist/resolve/component-resolver.js +3 -3
  174. package/dist/resolve/component-resolver.mjs +59 -1
  175. package/dist/resolve/load-directive.cjs +93 -1
  176. package/dist/resolve/load-directive.d.cts +53 -0
  177. package/dist/resolve/load-directive.d.ts +5 -5
  178. package/dist/resolve/load-directive.js +6 -6
  179. package/dist/resolve/load-directive.mjs +72 -1
  180. package/dist/resolve/resolve-ir.cjs +108 -1
  181. package/dist/resolve/resolve-ir.d.cts +53 -0
  182. package/dist/resolve/resolve-ir.d.ts +6 -6
  183. package/dist/resolve/resolve-ir.d.ts.map +1 -1
  184. package/dist/resolve/resolve-ir.js +1 -1
  185. package/dist/resolve/resolve-ir.mjs +85 -1
  186. package/dist/resolve/write-globals.cjs +319 -14
  187. package/dist/resolve/write-globals.d.cts +30 -0
  188. package/dist/resolve/write-globals.js +2 -2
  189. package/dist/resolve/write-globals.mjs +298 -14
  190. package/dist/server-fns-ZYWQTSZU.mjs +78 -0
  191. package/dist/server-functions-PCERFA7A.mjs +82 -0
  192. package/dist/transform/bindings.cjs +71 -1
  193. package/dist/transform/bindings.d.cts +16 -0
  194. package/dist/transform/bindings.d.ts +1 -1
  195. package/dist/transform/bindings.js +1 -1
  196. package/dist/transform/bindings.mjs +50 -1
  197. package/dist/transform/index.cjs +2732 -8
  198. package/dist/transform/index.d.cts +15 -0
  199. package/dist/transform/index.mjs +3773 -17
  200. package/dist/transform/intrinsics.cjs +216 -3
  201. package/dist/transform/intrinsics.d.cts +21 -0
  202. package/dist/transform/intrinsics.js +1 -1
  203. package/dist/transform/intrinsics.mjs +193 -3
  204. package/dist/transform/props.cjs +441 -3
  205. package/dist/transform/props.d.cts +45 -0
  206. package/dist/transform/props.d.ts +1 -1
  207. package/dist/transform/props.d.ts.map +1 -1
  208. package/dist/transform/props.js +4 -4
  209. package/dist/transform/props.mjs +1482 -12
  210. package/dist/transform/server-fn-id.cjs +35 -1
  211. package/dist/transform/server-fn-id.d.cts +9 -0
  212. package/dist/transform/server-fn-id.d.ts +1 -1
  213. package/dist/transform/server-fn-id.js +2 -2
  214. package/dist/transform/server-fn-id.mjs +14 -1
  215. package/dist/transform/server-fns.cjs +114 -2
  216. package/dist/transform/server-fns.d.cts +12 -0
  217. package/dist/transform/server-fns.js +3 -3
  218. package/dist/transform/server-fns.mjs +1155 -11
  219. package/dist/transform/source-locations.cjs +330 -1
  220. package/dist/transform/source-locations.d.cts +43 -0
  221. package/dist/transform/source-locations.d.ts +1 -1
  222. package/dist/transform/source-locations.js +5 -5
  223. package/dist/transform/source-locations.mjs +307 -1
  224. package/dist/transform/templates.cjs +2701 -7
  225. package/dist/transform/templates.d.cts +69 -0
  226. package/dist/transform/templates.d.ts +2 -2
  227. package/dist/transform/templates.d.ts.map +1 -1
  228. package/dist/transform/templates.js +7 -7
  229. package/dist/transform/templates.mjs +3743 -16
  230. package/dist/transform-RWDTQUF5.mjs +893 -0
  231. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  232. package/package.json +6 -5
  233. package/dist/babel-VXKH6MRQ.mjs +0 -1
  234. package/dist/chunk-3SAEGOMQ.mjs +0 -1
  235. package/dist/chunk-5KMMN5QP.mjs +0 -1
  236. package/dist/chunk-IBRM4W7I.mjs +0 -10
  237. package/dist/chunk-OHHZCYIQ.mjs +0 -1
  238. package/dist/chunk-YKZ54NVE.mjs +0 -1
  239. package/dist/server-fns-6QM243HC.mjs +0 -2
  240. package/dist/server-functions-E3LKCZ4R.mjs +0 -1
  241. package/dist/transform-C4ZXRVGP.mjs +0 -8
@@ -1,16 +1,3743 @@
1
- import{parse as Kn}from"@babel/parser";var _t=44,Jt=59,He="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xe=new Uint8Array(64),Ft=new Uint8Array(128);for(let n=0;n<He.length;n++){let e=He.charCodeAt(n);Xe[n]=e,Ft[e]=n}function U(n,e,t){let r=e-t;r=r<0?-r<<1|1:r<<1;do{let i=r&31;r>>>=5,r>0&&(i|=32),n.write(Xe[i])}while(r>0);return e}var Ue=1024*16,qe=typeof TextDecoder<"u"?new TextDecoder:typeof Buffer<"u"?{decode(n){return Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString()}}:{decode(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e}},Bt=class{constructor(){this.pos=0,this.out="",this.buffer=new Uint8Array(Ue)}write(n){let{buffer:e}=this;e[this.pos++]=n,this.pos===Ue&&(this.out+=qe.decode(e),this.pos=0)}flush(){let{buffer:n,out:e,pos:t}=this;return t>0?e+qe.decode(n.subarray(0,t)):e}};function Ve(n){let e=new Bt,t=0,r=0,i=0,s=0;for(let o=0;o<n.length;o++){let a=n[o];if(o>0&&e.write(Jt),a.length===0)continue;let l=0;for(let c=0;c<a.length;c++){let u=a[c];c>0&&e.write(_t),l=U(e,u[0],l),u.length!==1&&(t=U(e,u[1],t),r=U(e,u[2],r),i=U(e,u[3],i),u.length!==4&&(s=U(e,u[4],s)))}}return e.flush()}var se=class n{constructor(e){this.bits=e instanceof n?e.bits.slice():[]}add(e){this.bits[e>>5]|=1<<(e&31)}has(e){return!!(this.bits[e>>5]&1<<(e&31))}},oe=class n{constructor(e,t,r){this.start=e,this.end=t,this.original=r,this.intro="",this.outro="",this.content=r,this.storeName=!1,this.edited=!1,this.previous=null,this.next=null}appendLeft(e){this.outro+=e}appendRight(e){this.intro=this.intro+e}clone(){let e=new n(this.start,this.end,this.original);return e.intro=this.intro,e.outro=this.outro,e.content=this.content,e.storeName=this.storeName,e.edited=this.edited,e}contains(e){return this.start<e&&e<this.end}eachNext(e){let t=this;for(;t;)e(t),t=t.next}eachPrevious(e){let t=this;for(;t;)e(t),t=t.previous}edit(e,t,r){return this.content=e,r||(this.intro="",this.outro=""),this.storeName=t,this.edited=!0,this}prependLeft(e){this.outro=e+this.outro}prependRight(e){this.intro=e+this.intro}reset(){this.intro="",this.outro="",this.edited&&(this.content=this.original,this.storeName=!1,this.edited=!1)}split(e){let t=e-this.start,r=this.original.slice(0,t),i=this.original.slice(t);this.original=r;let s=new n(e,this.end,i);return s.outro=this.outro,this.outro="",this.end=e,this.edited?(s.edit("",!1),this.content=""):this.content=r,s.next=this.next,s.next&&(s.next.previous=s),s.previous=this,this.next=s,s}toString(){return this.intro+this.content+this.outro}trimEnd(e){if(this.outro=this.outro.replace(e,""),this.outro.length)return!0;let t=this.content.replace(e,"");if(t.length)return t!==this.content&&(this.split(this.start+t.length).edit("",void 0,!0),this.edited&&this.edit(t,this.storeName,!0)),!0;if(this.edit("",void 0,!0),this.intro=this.intro.replace(e,""),this.intro.length)return!0}trimStart(e){if(this.intro=this.intro.replace(e,""),this.intro.length)return!0;let t=this.content.replace(e,"");if(t.length){if(t!==this.content){let r=this.split(this.end-t.length);this.edited&&r.edit(t,this.storeName,!0),this.edit("",void 0,!0)}return!0}else if(this.edit("",void 0,!0),this.outro=this.outro.replace(e,""),this.outro.length)return!0}};function Ht(){return typeof globalThis<"u"&&typeof globalThis.btoa=="function"?n=>globalThis.btoa(unescape(encodeURIComponent(n))):typeof Buffer=="function"?n=>Buffer.from(n,"utf-8").toString("base64"):()=>{throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.")}}var Ut=Ht(),Se=class{constructor(e){this.version=3,this.file=e.file,this.sources=e.sources,this.sourcesContent=e.sourcesContent,this.names=e.names,this.mappings=Ve(e.mappings),typeof e.x_google_ignoreList<"u"&&(this.x_google_ignoreList=e.x_google_ignoreList),typeof e.debugId<"u"&&(this.debugId=e.debugId)}toString(){return JSON.stringify(this)}toUrl(){return"data:application/json;charset=utf-8;base64,"+Ut(this.toString())}};function qt(n){let e=n.split(`
2
- `),t=e.filter(s=>/^\t+/.test(s)),r=e.filter(s=>/^ {2,}/.test(s));if(t.length===0&&r.length===0)return null;if(t.length>=r.length)return" ";let i=r.reduce((s,o)=>{let a=/^ +/.exec(o)[0].length;return Math.min(a,s)},1/0);return new Array(i+1).join(" ")}function Xt(n,e){let t=n.split(/[/\\]/),r=e.split(/[/\\]/);for(t.pop();t[0]===r[0];)t.shift(),r.shift();if(t.length){let i=t.length;for(;i--;)t[i]=".."}return t.concat(r).join("/")}var Vt=Object.prototype.toString;function Wt(n){return Vt.call(n)==="[object Object]"}function We(n){let e=n.split(`
3
- `),t=[];for(let r=0,i=0;r<e.length;r++)t.push(i),i+=e[r].length+1;return function(i){let s=0,o=t.length;for(;s<o;){let c=s+o>>1;i<t[c]?o=c:s=c+1}let a=s-1,l=i-t[a];return{line:a,column:l}}}var zt=/\w/,we=class{constructor(e){this.hires=e,this.generatedCodeLine=0,this.generatedCodeColumn=0,this.raw=[],this.rawSegments=this.raw[this.generatedCodeLine]=[],this.pending=null}addEdit(e,t,r,i){if(t.length){let s=t.length-1,o=t.indexOf(`
4
- `,0),a=-1;for(;o>=0&&s>o;){let c=[this.generatedCodeColumn,e,r.line,r.column];i>=0&&c.push(i),this.rawSegments.push(c),this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,a=o,o=t.indexOf(`
5
- `,o+1)}let l=[this.generatedCodeColumn,e,r.line,r.column];i>=0&&l.push(i),this.rawSegments.push(l),this.advance(t.slice(a+1))}else this.pending&&(this.rawSegments.push(this.pending),this.advance(t));this.pending=null}addUneditedChunk(e,t,r,i,s){let o=t.start,a=!0,l=!1;for(;o<t.end;){if(r[o]===`
6
- `)i.line+=1,i.column=0,this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,a=!0,l=!1;else{if(this.hires||a||s.has(o)){let c=[this.generatedCodeColumn,e,i.line,i.column];this.hires==="boundary"?zt.test(r[o])?l||(this.rawSegments.push(c),l=!0):(this.rawSegments.push(c),l=!1):this.rawSegments.push(c)}i.column+=1,this.generatedCodeColumn+=1,a=!1}o+=1}this.pending=null}advance(e){if(!e)return;let t=e.split(`
7
- `);if(t.length>1){for(let r=0;r<t.length-1;r++)this.generatedCodeLine++,this.raw[this.generatedCodeLine]=this.rawSegments=[];this.generatedCodeColumn=0}this.generatedCodeColumn+=t[t.length-1].length}},q=`
8
- `,j={insertLeft:!1,insertRight:!1,storeName:!1},ae=class n{constructor(e,t={}){let r=new oe(0,e.length,e);Object.defineProperties(this,{original:{writable:!0,value:e},outro:{writable:!0,value:""},intro:{writable:!0,value:""},firstChunk:{writable:!0,value:r},lastChunk:{writable:!0,value:r},lastSearchedChunk:{writable:!0,value:r},byStart:{writable:!0,value:{}},byEnd:{writable:!0,value:{}},filename:{writable:!0,value:t.filename},indentExclusionRanges:{writable:!0,value:t.indentExclusionRanges},sourcemapLocations:{writable:!0,value:new se},storedNames:{writable:!0,value:{}},indentStr:{writable:!0,value:void 0},ignoreList:{writable:!0,value:t.ignoreList},offset:{writable:!0,value:t.offset||0}}),this.byStart[0]=r,this.byEnd[e.length]=r}addSourcemapLocation(e){this.sourcemapLocations.add(e)}append(e){if(typeof e!="string")throw new TypeError("outro content must be a string");return this.outro+=e,this}appendLeft(e,t){if(e=e+this.offset,typeof t!="string")throw new TypeError("inserted content must be a string");this._split(e);let r=this.byEnd[e];return r?r.appendLeft(t):this.intro+=t,this}appendRight(e,t){if(e=e+this.offset,typeof t!="string")throw new TypeError("inserted content must be a string");this._split(e);let r=this.byStart[e];return r?r.appendRight(t):this.outro+=t,this}clone(){let e=new n(this.original,{filename:this.filename,offset:this.offset}),t=this.firstChunk,r=e.firstChunk=e.lastSearchedChunk=t.clone();for(;t;){e.byStart[r.start]=r,e.byEnd[r.end]=r;let i=t.next,s=i&&i.clone();s&&(r.next=s,s.previous=r,r=s),t=i}return e.lastChunk=r,this.indentExclusionRanges&&(e.indentExclusionRanges=this.indentExclusionRanges.slice()),e.sourcemapLocations=new se(this.sourcemapLocations),e.intro=this.intro,e.outro=this.outro,e}generateDecodedMap(e){e=e||{};let t=0,r=Object.keys(this.storedNames),i=new we(e.hires),s=We(this.original);return this.intro&&i.advance(this.intro),this.firstChunk.eachNext(o=>{let a=s(o.start);o.intro.length&&i.advance(o.intro),o.edited?i.addEdit(t,o.content,a,o.storeName?r.indexOf(o.original):-1):i.addUneditedChunk(t,o,this.original,a,this.sourcemapLocations),o.outro.length&&i.advance(o.outro)}),this.outro&&i.advance(this.outro),{file:e.file?e.file.split(/[/\\]/).pop():void 0,sources:[e.source?Xt(e.file||"",e.source):e.file||""],sourcesContent:e.includeContent?[this.original]:void 0,names:r,mappings:i.raw,x_google_ignoreList:this.ignoreList?[t]:void 0}}generateMap(e){return new Se(this.generateDecodedMap(e))}_ensureindentStr(){this.indentStr===void 0&&(this.indentStr=qt(this.original))}_getRawIndentString(){return this._ensureindentStr(),this.indentStr}getIndentString(){return this._ensureindentStr(),this.indentStr===null?" ":this.indentStr}indent(e,t){let r=/^[^\r\n]/gm;if(Wt(e)&&(t=e,e=void 0),e===void 0&&(this._ensureindentStr(),e=this.indentStr||" "),e==="")return this;t=t||{};let i={};t.exclude&&(typeof t.exclude[0]=="number"?[t.exclude]:t.exclude).forEach(u=>{for(let f=u[0];f<u[1];f+=1)i[f]=!0});let s=t.indentStart!==!1,o=c=>s?`${e}${c}`:(s=!0,c);this.intro=this.intro.replace(r,o);let a=0,l=this.firstChunk;for(;l;){let c=l.end;if(l.edited)i[a]||(l.content=l.content.replace(r,o),l.content.length&&(s=l.content[l.content.length-1]===`
9
- `));else for(a=l.start;a<c;){if(!i[a]){let u=this.original[a];u===`
10
- `?s=!0:u!=="\r"&&s&&(s=!1,a===l.start||(this._splitChunk(l,a),l=l.next),l.prependRight(e))}a+=1}a=l.end,l=l.next}return this.outro=this.outro.replace(r,o),this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(e,t){return j.insertLeft||(console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"),j.insertLeft=!0),this.appendLeft(e,t)}insertRight(e,t){return j.insertRight||(console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"),j.insertRight=!0),this.prependRight(e,t)}move(e,t,r){if(e=e+this.offset,t=t+this.offset,r=r+this.offset,r>=e&&r<=t)throw new Error("Cannot move a selection inside itself");this._split(e),this._split(t),this._split(r);let i=this.byStart[e],s=this.byEnd[t],o=i.previous,a=s.next,l=this.byStart[r];if(!l&&s===this.lastChunk)return this;let c=l?l.previous:this.lastChunk;return o&&(o.next=a),a&&(a.previous=o),c&&(c.next=i),l&&(l.previous=s),i.previous||(this.firstChunk=s.next),s.next||(this.lastChunk=i.previous,this.lastChunk.next=null),i.previous=c,s.next=l||null,c||(this.firstChunk=i),l||(this.lastChunk=s),this}overwrite(e,t,r,i){return i=i||{},this.update(e,t,r,{...i,overwrite:!i.contentOnly})}update(e,t,r,i){if(e=e+this.offset,t=t+this.offset,typeof r!="string")throw new TypeError("replacement content must be a string");if(this.original.length!==0){for(;e<0;)e+=this.original.length;for(;t<0;)t+=this.original.length}if(t>this.original.length)throw new Error("end is out of bounds");if(e===t)throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");this._split(e),this._split(t),i===!0&&(j.storeName||(console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"),j.storeName=!0),i={storeName:!0});let s=i!==void 0?i.storeName:!1,o=i!==void 0?i.overwrite:!1;if(s){let c=this.original.slice(e,t);Object.defineProperty(this.storedNames,c,{writable:!0,value:!0,enumerable:!0})}let a=this.byStart[e],l=this.byEnd[t];if(a){let c=a;for(;c!==l;){if(c.next!==this.byStart[c.end])throw new Error("Cannot overwrite across a split point");c=c.next,c.edit("",!1)}a.edit(r,s,!o)}else{let c=new oe(e,t,"").edit(r,s);l.next=c,c.previous=l}return this}prepend(e){if(typeof e!="string")throw new TypeError("outro content must be a string");return this.intro=e+this.intro,this}prependLeft(e,t){if(e=e+this.offset,typeof t!="string")throw new TypeError("inserted content must be a string");this._split(e);let r=this.byEnd[e];return r?r.prependLeft(t):this.intro=t+this.intro,this}prependRight(e,t){if(e=e+this.offset,typeof t!="string")throw new TypeError("inserted content must be a string");this._split(e);let r=this.byStart[e];return r?r.prependRight(t):this.outro=t+this.outro,this}remove(e,t){if(e=e+this.offset,t=t+this.offset,this.original.length!==0){for(;e<0;)e+=this.original.length;for(;t<0;)t+=this.original.length}if(e===t)return this;if(e<0||t>this.original.length)throw new Error("Character is out of bounds");if(e>t)throw new Error("end must be greater than start");this._split(e),this._split(t);let r=this.byStart[e];for(;r;)r.intro="",r.outro="",r.edit(""),r=t>r.end?this.byStart[r.end]:null;return this}reset(e,t){if(e=e+this.offset,t=t+this.offset,this.original.length!==0){for(;e<0;)e+=this.original.length;for(;t<0;)t+=this.original.length}if(e===t)return this;if(e<0||t>this.original.length)throw new Error("Character is out of bounds");if(e>t)throw new Error("end must be greater than start");this._split(e),this._split(t);let r=this.byStart[e];for(;r;)r.reset(),r=t>r.end?this.byStart[r.end]:null;return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let e=this.lastChunk;do{if(e.outro.length)return e.outro[e.outro.length-1];if(e.content.length)return e.content[e.content.length-1];if(e.intro.length)return e.intro[e.intro.length-1]}while(e=e.previous);return this.intro.length?this.intro[this.intro.length-1]:""}lastLine(){let e=this.outro.lastIndexOf(q);if(e!==-1)return this.outro.substr(e+1);let t=this.outro,r=this.lastChunk;do{if(r.outro.length>0){if(e=r.outro.lastIndexOf(q),e!==-1)return r.outro.substr(e+1)+t;t=r.outro+t}if(r.content.length>0){if(e=r.content.lastIndexOf(q),e!==-1)return r.content.substr(e+1)+t;t=r.content+t}if(r.intro.length>0){if(e=r.intro.lastIndexOf(q),e!==-1)return r.intro.substr(e+1)+t;t=r.intro+t}}while(r=r.previous);return e=this.intro.lastIndexOf(q),e!==-1?this.intro.substr(e+1)+t:this.intro+t}slice(e=0,t=this.original.length-this.offset){if(e=e+this.offset,t=t+this.offset,this.original.length!==0){for(;e<0;)e+=this.original.length;for(;t<0;)t+=this.original.length}let r="",i=this.firstChunk;for(;i&&(i.start>e||i.end<=e);){if(i.start<t&&i.end>=t)return r;i=i.next}if(i&&i.edited&&i.start!==e)throw new Error(`Cannot use replaced character ${e} as slice start anchor.`);let s=i;for(;i;){i.intro&&(s!==i||i.start===e)&&(r+=i.intro);let o=i.start<t&&i.end>=t;if(o&&i.edited&&i.end!==t)throw new Error(`Cannot use replaced character ${t} as slice end anchor.`);let a=s===i?e-i.start:0,l=o?i.content.length+t-i.end:i.content.length;if(r+=i.content.slice(a,l),i.outro&&(!o||i.end===t)&&(r+=i.outro),o)break;i=i.next}return r}snip(e,t){let r=this.clone();return r.remove(0,e),r.remove(t,r.original.length),r}_split(e){if(this.byStart[e]||this.byEnd[e])return;let t=this.lastSearchedChunk,r=t,i=e>t.end;for(;t;){if(t.contains(e))return this._splitChunk(t,e);if(t=i?this.byStart[t.end]:this.byEnd[t.start],t===r)return;r=t}}_splitChunk(e,t){if(e.edited&&e.content.length){let i=We(this.original)(t);throw new Error(`Cannot split a chunk that has already been edited (${i.line}:${i.column} – "${e.original}")`)}let r=e.split(t);return this.byEnd[t]=e,this.byStart[t]=r,this.byEnd[r.end]=r,e===this.lastChunk&&(this.lastChunk=r),this.lastSearchedChunk=e,!0}toString(){let e=this.intro,t=this.firstChunk;for(;t;)e+=t.toString(),t=t.next;return e+this.outro}isEmpty(){let e=this.firstChunk;do if(e.intro.length&&e.intro.trim()||e.content.length&&e.content.trim()||e.outro.length&&e.outro.trim())return!1;while(e=e.next);return!0}length(){let e=this.firstChunk,t=0;do t+=e.intro.length+e.content.length+e.outro.length;while(e=e.next);return t}trimLines(){return this.trim("[\\r\\n]")}trim(e){return this.trimStart(e).trimEnd(e)}trimEndAborted(e){let t=new RegExp((e||"\\s")+"+$");if(this.outro=this.outro.replace(t,""),this.outro.length)return!0;let r=this.lastChunk;do{let i=r.end,s=r.trimEnd(t);if(r.end!==i&&(this.lastChunk===r&&(this.lastChunk=r.next),this.byEnd[r.end]=r,this.byStart[r.next.start]=r.next,this.byEnd[r.next.end]=r.next),s)return!0;r=r.previous}while(r);return!1}trimEnd(e){return this.trimEndAborted(e),this}trimStartAborted(e){let t=new RegExp("^"+(e||"\\s")+"+");if(this.intro=this.intro.replace(t,""),this.intro.length)return!0;let r=this.firstChunk;do{let i=r.end,s=r.trimStart(t);if(r.end!==i&&(r===this.lastChunk&&(this.lastChunk=r.next),this.byEnd[r.end]=r,this.byStart[r.next.start]=r.next,this.byEnd[r.next.end]=r.next),s)return!0;r=r.next}while(r);return!1}trimStart(e){return this.trimStartAborted(e),this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(e,t){function r(s,o){return typeof t=="string"?t.replace(/\$(\$|&|\d+)/g,(a,l)=>l==="$"?"$":l==="&"?s[0]:+l<s.length?s[+l]:`$${l}`):t(...s,s.index,o,s.groups)}function i(s,o){let a,l=[];for(;a=s.exec(o);)l.push(a);return l}if(e.global)i(e,this.original).forEach(o=>{if(o.index!=null){let a=r(o,this.original);a!==o[0]&&this.overwrite(o.index,o.index+o[0].length,a)}});else{let s=this.original.match(e);if(s&&s.index!=null){let o=r(s,this.original);o!==s[0]&&this.overwrite(s.index,s.index+s[0].length,o)}}return this}_replaceString(e,t){let{original:r}=this,i=r.indexOf(e);return i!==-1&&(typeof t=="function"&&(t=t(e,i,r)),e!==t&&this.overwrite(i,i+e.length,t)),this}replace(e,t){return typeof e=="string"?this._replaceString(e,t):this._replaceRegexp(e,t)}_replaceAllString(e,t){let{original:r}=this,i=e.length;for(let s=r.indexOf(e);s!==-1;s=r.indexOf(e,s+i)){let o=r.slice(s,s+i),a=t;typeof t=="function"&&(a=t(o,s,r)),o!==a&&this.overwrite(s,s+i,a)}return this}replaceAll(e,t){if(typeof e=="string")return this._replaceAllString(e,t);if(!e.global)throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");return this._replaceRegexp(e,t)}};function Kt(n){switch(n.kind){case"event":return"event";case"ref":return"ref";case"spread":return"spread";case"class":case"style":return"class-or-style-directive";case"attr":case"prop":return n.reactive?"reactive-prop":n.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function _(n){let e=[],t=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let s of i.children)r(s);return!1;case"fragment":for(let s of i.children)r(s);return!1;case"element":{let s=!0;for(let a of i.children)r(a)||(s=!1);let o;for(let a of i.props)if(o=Kt(a),o)break;return!o&&!s&&(o=Gt(i)),i.static=!o,o?t.set(i,o):e.push(i),i.static}default:return!1}};for(let i of Array.isArray(n)?n:[n])r(i);return{staticElements:e,reasons:t}}function Gt(n){for(let e of n.children){if(e.kind==="expr")return"expression-child";if(e.kind==="component")return"component-child";if(e.kind==="control")return"control-child";if(e.kind==="element"&&!e.static||e.kind==="fragment")return"expression-child"}return"expression-child"}var le={kind:"eager"},Yt=["pointerdown","focusin","keydown"],ze=new Set(["eager","idle","visible","interaction","media","never"]),O=class extends Error{};function Re(n){return n.startsWith("load:")}function ce(n,e){let t=n.slice(5);if(!ze.has(t))throw new O(`Unknown load strategy 'load:${t}'. Expected one of ${[...ze].join(", ")}.`);switch(t){case"eager":return le;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return e?{kind:"visible",rootMargin:e}:{kind:"visible"};case"interaction":return{kind:"interaction",events:e?Zt(e):[...Yt]};case"media":if(!e)throw new O(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:e};default:throw new O(`Unhandled load strategy '${t}'.`)}}function Zt(n){let e=n.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean);if(e.length===0)throw new O("'load:interaction' was given no event names.");return e}function X(n){return n.kind!=="eager"&&n.kind!=="never"}var V=["Show","For","Index","Switch","Match","Portal","Dynamic","ErrorBoundary"],W=["Suspense","SuspenseList","Await"],J=["Router","Outlet","Redirect","Link"],vr=[...V,...W,...J],Ee=new Set([...V,...W]);function Ke(n={}){let{controlFlowModule:e="@fluixi/dom",coreModule:t="@fluixi/core",routerModule:r="@fluixi/core/router"}=n,i={};for(let s of V)i[s]=e;for(let s of W)i[s]=t;for(let s of J)i[s]=r;return i}function ue(n,e={}){let{resolver:t,isBound:r,modules:i,strategyFor:s}=e,o=Ke(i),a=new Map,l=new Set,c=f=>{let{name:d}=f;if(!d||d.includes(".")||r?.(d))return;let h=u(d);if(!h){l.add(d);return}let m=h.origin==="builtin"&&Ee.has(d)?le:s?.(f)??le;f.source={...h,loading:m},a.set(d,f.source)},u=f=>{if(Ee.has(f))return{module:o[f],export:f,origin:"builtin"};let d=t?.resolve(f);if(d)return{module:d.module,export:d.export,origin:"rule"};if(J.includes(f))return{module:o[f],export:f,origin:"builtin"}};return de(n,f=>{f.kind==="component"&&c(f)}),{resolved:a,unresolved:[...l]}}function de(n,e){let t=Array.isArray(n)?n:[n];for(let r of t){e(r);let i=r.children;i&&de(i,e)}}function fe(n){let e=[];de(n,s=>{s.kind==="component"&&s.source&&e.push(s)});let t=new Set,r=new Set;for(let s of e){let{module:o,loading:a}=s.source;a.kind==="eager"&&t.add(o),a.kind==="never"&&r.add(o)}let i=new Map;for(let s of e){let o=s.source;X(o.loading)&&t.has(o.module)&&(o.loading={kind:"eager"},i.set(o.module,(i.get(o.module)??0)+1))}return{collapsed:i,conflicted:[...r].filter(s=>t.has(s))}}var Qt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Ge={className:"class",htmlFor:"for"},en=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),tn=new Set(["script","style","textarea","title"]);function ke(n){return tn.has(n)}function Ye(n){return Ge[n]??n}function z(n){return n.kind!=="attr"||n.expr!==void 0||n.name.includes(":")?!1:!en.has(n.name)}function Ce(n){if(!n.static||ke(n.tag))return!1;for(let e of n.props)if(!z(e))return!1;for(let e of n.children)if(e.kind!=="text"&&!(e.kind==="element"&&Ce(e)))return!1;return!0}function K(n){let e=n.props.map(rn).filter(Boolean).join(""),t=`<${n.tag}${e}>`;return Qt.has(n.tag)?t:`${t}${n.children.map(nn).join("")}</${n.tag}>`}function nn(n){if(n.kind==="text")return on(n.value);if(n.kind!=="element")throw new Error(`serializeStatic: unexpected ${n.kind}`);return K(n)}function rn(n){let e=Ge[n.name]??n.name,t=n.literal;return t===!0||t===void 0?` ${e}`:t===!1||t===null?"":` ${e}="${sn(String(t))}"`}function sn(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function on(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ie(n){let e=[],t,r=i=>{t??=i.at?.file,e.push(i.at?.line??0,i.at?.column??0);for(let s of i.children)s.kind==="element"&&r(s)};return r(n),t&&e.some(i=>i!==0)?{file:t,pos:e}:void 0}var an="<!--fx-->",ln="<!--fx/-->";function me(n){return n.kind==="expr"||n.kind==="component"||n.kind==="control"}function cn(n){return n.kind==="text"||n.kind==="element"&&Ze(n)}function Ze(n){return n.svg||ke(n.tag)||!n.props.every(e=>z(e))?!1:n.children.every(e=>cn(e)||me(e))}function pe(n){if(me(n))return!0;let e=n.children;return e?e.some(pe):!1}function Qe(n){for(let e=0;e<n.children.length;e++){let t=n.children[e];if(t.kind==="text"&&(t.value===""||n.children[e+1]?.kind==="text"))return!1}return n.children.every(e=>e.kind!=="element"||Qe(e))}function et(n){if(!Ze(n)||!Qe(n)||!n.children.some(pe))return null;let e=[],t=[],r=0,i=o=>{let a=`_n$${r++}`;return e.push({ref:a,expr:o}),a};return s(n,"_el$"),{html:un(n),tag:n.tag,steps:e,holes:t};function s(o,a){let l=-1;o.children.forEach((u,f)=>{pe(u)&&(l=f)});let c=null;for(let u=0;u<=l;u++){let f=o.children[u],d=c?`${c}.nextSibling`:`${a}.firstChild`;if(me(f)){let m=i(d),y=i(`holeEnd(${m})`);t.push({parentRef:a,startRef:m,endRef:y,node:f}),c=y;continue}let h=i(d);f.kind==="element"&&pe(f)&&s(f,h),c=h}}}function un(n){return K(tt(n)).split(nt).join(an+ln)}function tt(n){return{...n,children:n.children.map(e=>me(e)?{kind:"text",value:nt}:e.kind==="element"?tt(e):e)}}var nt="\0fx-hole\0";var $e={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},$r={version:2,module:"@fluixi/dom",symbols:[...$e.symbols,"template","cloneTemplate","walk"]};var A="@fluixi/reactive/signal",C={$signal:{export:"signal",module:A,returns:"signal-handle"},$memo:{export:"memo",module:A,returns:"memo-handle"},$effect:{export:"effect",module:A,returns:"effect"},$store:{export:"store",module:"@fluixi/reactive/store",returns:"store-handle"},$resource:{export:"resource",module:A,returns:"resource-handle"},$selector:{export:"createSelector",module:A,returns:"memo-accessor"},$deferred:{export:"createDeferred",module:A,returns:"memo-accessor"},$untrack:{export:"untrack",module:A,returns:"plain"},$untrackStore:{export:"untrackStore",module:"@fluixi/reactive/store",returns:"plain"}},rt={signal:"signal-handle",memo:"memo-handle",effect:"effect",store:"store-handle",createSignal:["signal-accessor","signal-setter"],createMemo:"memo-accessor",createEffect:"effect",createRenderEffect:"effect",createStore:"reactive-object",resource:"resource-handle",createResource:"reactive-object",createSelector:"memo-accessor",createDeferred:"memo-accessor"},dn=["@fluixi/reactive","@fluixi/reactive/signal","@fluixi/reactive/store","@fluixi/core"],fn=new RegExp(`\\$(?:${Object.keys(C).map(n=>n.slice(1)).join("|")})\\s*\\(`);function it(n){return fn.test(n)}function he(n){return Object.prototype.hasOwnProperty.call(C,n)}function st(n){return dn.includes(n)}function b(n,e){if(n)switch(n.type){case"Identifier":e.add(n.name);return;case"ObjectPattern":for(let t of n.properties??[])t.type==="RestElement"?b(t.argument,e):b(t.value,e);return;case"ArrayPattern":for(let t of n.elements??[])b(t,e);return;case"AssignmentPattern":b(n.left,e);return;case"RestElement":b(n.argument,e);return}}function G(n,e){if(!(!n||typeof n!="object"||typeof n.type!="string")){e(n);for(let t of Object.keys(n)){if(t==="loc"||t==="leadingComments"||t==="trailingComments")continue;let r=n[t];if(Array.isArray(r))for(let i of r)G(i,e);else r&&typeof r=="object"&&G(r,e)}}}function pn(n,e){if(n.type!=="CallExpression")return;let t=n.callee;if(t?.type!=="Identifier")return;let r=t.name,i=e.primitives.get(r);if(i)return i;let s=C[r];if(s&&!e.shadowed.has(r))return s.returns}function mn(n,e,t){if(Array.isArray(e)){n.type==="ArrayPattern"&&n.elements.forEach((r,i)=>{let s=e[i];r?.type==="Identifier"&&s&&t.set(r.name,s)});return}n.type==="Identifier"&&t.set(n.name,e)}function ot(n){let e=new Set;return G(n,t=>{switch(t.type){case"VariableDeclarator":b(t.id,e);return;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":b(t.id,e);for(let r of t.params??[])b(r,e);return;case"ClassDeclaration":case"ClassExpression":b(t.id,e);return;case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":b(t.local,e);return;case"CatchClause":b(t.param,e);return}}),e}function ge(n){let e={kinds:new Map,primitives:new Map,shadowed:new Set},t=n;G(t,r=>{let i=new Set;if(r.type==="VariableDeclarator")b(r.id,i);else if(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration")b(r.id,i);else if(r.type==="ImportDefaultSpecifier"||r.type==="ImportNamespaceSpecifier")b(r.local,i);else if(r.type==="ImportSpecifier")b(r.local,i);else if(r.type==="FunctionExpression"||r.type==="ArrowFunctionExpression"||r.type==="FunctionDeclaration")for(let s of r.params??[])b(s,i);for(let s of i)C[s]&&e.shadowed.add(s)});for(let r of t.body??[])if(r.type==="ImportDeclaration"&&st(r.source?.value))for(let i of r.specifiers??[]){if(i.type!=="ImportSpecifier")continue;let s=i.imported,o=s.type==="Identifier"?s.name:s.value,a=rt[o];a&&e.primitives.set(i.local.name,a)}return G(t,r=>{if(r.type!=="VariableDeclarator"||!r.init)return;let i=pn(r.init,e);i&&mn(r.id,i,e.kinds)}),e}var Oe="__fx_source",hn="__fx_component",gn="__fx_hole",Y=(n,e,t,r)=>`(globalThis.${gn} ?? ((f) => f))(${n},${e},${t}${r===void 0?"":`,${JSON.stringify(r)}`})`,yn="__fx_props",lt=(n,e)=>`(globalThis.${yn} ?? ((p) => p))(${n},${JSON.stringify(e)})`,ct=new Set(["signal","memo","effect","store","resource","watch","createSignal","createMemo","createEffect","createStore","createResource"]);function ut(n){for(let e of ct)if(n.includes(e))return!0;return n.includes("$signal")||n.includes("$memo")||n.includes("$effect")||n.includes("$store")}var vn=new Set(["IfStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","LabeledStatement","WithStatement"]);function bn(n,e){return!e||n.type==="BlockStatement"?!1:vn.has(e.type)}function at(n){return n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration"}function Nn(n){return n.type.endsWith("Statement")||n.type==="VariableDeclaration"}function Te(n,e,t=[]){if(!(!n||typeof n.type!="string")){e(n,t),t.push(n);for(let r of Object.keys(n)){if(r==="loc"||r==="parent")continue;let i=n[r];if(Array.isArray(i))for(let s of i)Te(s,e,t);else i&&typeof i.type=="string"&&Te(i,e,t)}t.pop()}}function xn(n){let e=n[n.length-1];if(e?.type!=="VariableDeclarator")return;let t=e.id;if(t?.type==="Identifier")return t.name;if(t?.type==="ArrayPattern"){let r=t.elements?.[0];if(r?.type==="Identifier")return r.name}}function Sn(n){if(n.type==="FunctionDeclaration"){let e=n.id?.name;return e&&e[0]===e[0]?.toUpperCase()?e:void 0}if(n.type==="VariableDeclarator"){let e=n.id,t=n.init;if(e?.type!=="Identifier"||!t||t.type!=="ArrowFunctionExpression"&&t.type!=="FunctionExpression")return;let r=e.name;return r[0]===r[0]?.toUpperCase()?r:void 0}}function dt(n,e){let t=[],r=new Set,{primitives:i,shadowed:s}=ge(n);return Te(n,(o,a)=>{let l=Sn(o);if(l){let g=o.loc?.start,$=o.end;for(let D=a.length-1;D>=0;D--){let M=a[D];if(M.type!=="VariableDeclaration"&&M.type!=="ExportNamedDeclaration"&&M.type!=="ExportDefaultDeclaration")break;$=M.end}g&&t.push({start:$,end:$,code:`;globalThis.${hn}?.(${JSON.stringify(l)},${JSON.stringify(e)},${g.line},${g.column});`})}if(o.type!=="CallExpression")return;let c=o.callee;if(c?.type!=="Identifier")return;let u=c.name,f=he(u)&&!s.has(u)?C[u]:void 0,d=i.has(u)||ct.has(u);if(!f&&!d)return;let h=o.loc?.start;if(!h)return;let m,y,S=-1;for(let g=a.length-1;g>=0;g--)if(Nn(a[g])||at(a[g])){m=a[g],y=a[g-1],S=g;break}if(!m)return;let x=m.start,v=m.end;for(let g=S-1;g>=0&&at(a[g]);g--)x=a[g].start,v=a[g].end,y=a[g-1];if(r.has(x))return;r.add(x);let I=xn(a),P=[JSON.stringify(e),String(h.line),String(h.column),I?JSON.stringify(I):void 0].filter(g=>g!==void 0).join(","),k=`globalThis.${Oe}?.(${P});`;if(bn(m,y)){t.push({start:x,end:x,code:`{${k}`}),t.push({start:v,end:v,code:"}"});return}t.push({start:x,end:x,code:k})}),{edits:t,marked:t.length}}var wn={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function Rn(n){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)}function mt(n){return Rn(n)?n:JSON.stringify(n)}function En(n){if(n.expr!==void 0){if(n.name==="ref"&&n.at)return Y(`(${n.expr})`,n.at.line,n.at.column,n.expr);if(!n.reactive)return`(${n.expr})`;let e=`() => (${n.expr})`;return n.at?Y(e,n.at.line,n.at.column,n.directive):e}return JSON.stringify(n.literal??!0)}function kn(n){return n.expr!==void 0?`(${n.expr})`:JSON.stringify(n.literal??!0)}function Cn(n,e,t){let r=n.filter(a=>a.kind==="spread"),s=n.filter(a=>a.kind!=="spread").map(a=>`${mt(a.name)}: ${En(a)}`);e!=null&&s.push(`children: ${e}`);let o=`{ ${s.join(", ")} }`;return r.length>0?(t.add("mergeProps"),`mergeProps(${r.map(a=>a.expr).join(", ")}, ${o})`):o}function ft(n,e){return e?Y(n,e.line,e.column):n}function ht(n,e,t){return n.length===1?Z(n[0],e,t):`[${n.map(r=>Z(r,e,t)).join(", ")}]`}function pt(n,e,t,r,i,s){r.add("createMemo"),r.add("createComponent");let o=e.filter(d=>d.kind==="spread"),a=e.filter(d=>d.kind!=="spread"),l=a.map(d=>`get ${mt(d.name)}() { return ${kn(d)}; }`);t.length>0&&l.push(`get children() { return ${ht(t,r,i)}; }`);let c=`{ ${l.join(", ")} }`;o.length>0&&(r.add("mergeProps"),c=`mergeProps(${o.map(d=>d.expr).join(", ")}, ${c})`);let u={};for(let d of a)d.at&&(u[d.name]=[d.at.line,d.at.column]);return Object.keys(u).length&&(c=lt(c,u)),`createMemo((${s?`globalThis.${Oe}?.(${JSON.stringify(s.file)},${s.line},${s.column},${JSON.stringify(n)}), `:""}() => createComponent(${n}, ${c})))`}function In(n,e){let t=Ye(e.name),r=e.literal;return r===!0||r===void 0?`${n}.setAttribute(${JSON.stringify(t)}, "");`:r===!1||r===null?"":`${n}.setAttribute(${JSON.stringify(t)}, ${JSON.stringify(String(r))});`}var gt=!1;function Z(n,e,t){switch(n.kind){case"text":return JSON.stringify(n.value);case"expr":{if(!n.reactive)return`(${n.code})`;let r=`() => (${n.code})`;return n.at?Y(r,n.at.line,n.at.column):r}case"fragment":return n.children.length===0?"null":ht(n.children,e,t);case"component":return ft(pt(n.name,n.props,n.children,e,t,n.at),n.bindAt??n.at);case"control":{let r=wn[n.control]??n.control;return e.add(r),ft(pt(r,n.props,n.children,e,t),n.bindAt)}case"element":{if(t&&n.static&&!n.svg&&Ce(n)){e.add("templateNode");let a=`_tmpl$${t.length}`;t.push({id:a,html:K(n),tag:n.tag,svg:!1});let l=Ie(n);return l?`templateNode(${a}, ${JSON.stringify(n.tag)}, false, false, ${JSON.stringify(l)})`:`templateNode(${a}, ${JSON.stringify(n.tag)})`}if(t&&gt){let a=et(n);if(a){e.add("templateNode"),e.add("insert"),e.add("holeEnd"),e.add("holeContent"),e.add("holeScope");let l=`_tmpl$${t.length}`;t.push({id:l,html:a.html,tag:a.tag,svg:!1});let c=Ie(n),u=[`const _el$ = templateNode(${l}, ${JSON.stringify(a.tag)}, true${c?`, false, ${JSON.stringify(c)}`:""});`];for(let f of a.steps)u.push(`const ${f.ref} = ${f.expr};`);for(let f of a.holes)u.push(`insert(${f.parentRef}, holeScope(${f.startRef}, () => (${Z(f.node,e,t)})), ${f.endRef}, holeContent(${f.startRef}, ${f.endRef}));`);return u.push("return _el$;"),`(() => { ${u.join(" ")} })()`}}e.add("createNativeElement");let r=JSON.stringify(n.tag),i="_el$",s=[],o=n.at?`${r}, ${n.svg}, ${JSON.stringify(n.at)}`:n.svg?`${r}, true`:r;if(s.push(`const ${i} = createNativeElement(${o});`),n.props.length>0)if(!n.svg&&n.props.every(z))for(let a of n.props)s.push(In(i,a));else{e.add("spread");let a=n.svg?", isSVG: true":"";s.push(`spread({ element: ${i}, props: ${Cn(n.props,null,e)}${a} });`)}for(let a of n.children){e.add("insert");let l=Z(a,e,t),c=a.kind==="expr"&&a.reactive||a.kind==="component"||a.kind==="control";s.push(c?`insert(${i}, ${l}, null);`:`insert(${i}, ${l});`)}return s.push(`return ${i};`),`(() => { ${s.join(" ")} })()`}}}function ye(n,e){if(!e||e.length===0)return n;let t=new Map(e.map(r=>[r.id,JSON.stringify(r.html)]));return n.replace(/_tmpl\$\d+/g,r=>t.get(r)??r)}var F={name:"imperative",contract:$e,emit(n,e){let t=new Set,r=e?.templateClone!==!1?[]:void 0;return gt=e?.partialTemplates===!0,{code:Z(n,t,r),imports:Array.from(t),templates:r}}};var $n=n=>"components"in n;function yt(n,e){return n.replace(/\$(\d+)/g,(t,r)=>e[Number(r)]??t)}function Tn(n,e){return typeof e=="string"?{module:e,export:n}:e}function ve(n=[]){let e=new Map,t=[],r=[];for(let o of n){if(!$n(o)){r.push(o);continue}for(let[a,l]of Object.entries(o.components)){let c=Tn(a,l),u=e.get(a);if(u&&u.module!==c.module){let f=t.find(d=>d.name===a);f?f.modules.push(c.module):t.push({name:a,modules:[u.module,c.module]});continue}e.set(a,c)}}let i=new Map;return{resolve:o=>{if(i.has(o))return i.get(o);let a=e.get(o);if(!a)for(let l of r){let c=o.match(new RegExp(l.match.source,l.match.flags.replace("g","")));if(c){a={module:yt(l.module,c),export:l.export?yt(l.export,c):o};break}}return i.set(o,a),a},names:()=>[...e.keys()],conflicts:()=>t}}import{parseTemplate as On}from"@fluixi/template-parser";function Q(n){let e=n.split(/\r\n|\n|\r/),t=0;for(let i=0;i<e.length;i++)/[^ \t]/.test(e[i])&&(t=i);let r="";for(let i=0;i<e.length;i++){let s=e[i].replace(/\t/g," ");i!==0&&(s=s.replace(/^ +/,"")),i!==e.length-1&&(s=s.replace(/ +$/,"")),s&&(i!==t&&(s+=" "),r+=s)}return r}var vt=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Ln(n){return n.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function bt(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Le=class{constructor(e,t,r,i){this.holes=e;this.used=t;this.sourceFile=r;this.positionAt=i}tagAt(e){let t=e.loc?.start;if(!this.sourceFile||!this.positionAt||t==null)return;let{line:r,column:i}=this.positionAt(t);return{file:this.sourceFile,line:r,column:i}}hole(e){return this.holes[e]??{code:"undefined",reactive:!1}}emit(e){let{code:t,imports:r,templates:i}=F.emit(e,{});for(let s of r)this.used.add(s);return ye(t,i)}lowerRoot(e){let t=this.lowerChildren(e);return t.length===1?t[0]:{kind:"fragment",children:t}}lowerChildren(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(a=>a.kind==="IfDirective");if(o&&o.kind==="IfDirective"){let a=r+1;a<e.length&&this.isBlankText(e[a])&&a++;let l=e[a],c=l&&(l.kind==="Element"||l.kind==="Component")&&l.attributes.some(u=>u.kind==="ElseDirective");t.push(this.lowerIf(i,o.hole,c?l:null)),c&&(r=a);continue}if(i.attributes.some(a=>a.kind==="EachDirective")){t.push(this.lowerEach(i));continue}}let s=this.lowerNode(i);s&&t.push(s)}return t}isBlankText(e){return e.kind==="Text"&&!e.raw&&Q(e.value)===""}lowerNode(e){switch(e.kind){case"Text":{if(e.raw)return{kind:"text",value:e.value};let t=Q(e.value);return t?{kind:"text",value:t}:null}case"Comment":return null;case"Expression":{let t=this.hole(e.hole);return{kind:"expr",code:t.code,reactive:t.reactive,...t.at?{at:t.at}:{}}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(e.children)};case"Element":return this.lowerElement(e);case"Component":return this.lowerComponent(e);default:return null}}lowerElement(e){let t=e.attributes.find(i=>i.kind==="Attribute"&&i.name==="is");if(e.tag==="component"&&t&&t.value&&t.value.kind==="hole"){let i=e.attributes.filter(o=>o!==t),s=this.lowerComponent({...e,kind:"Component",tag:"Dynamic",tagHole:null,attributes:i});return s.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(t.value.hole).code})`}),s}let r=this.tagAt(e);return{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:this.lowerAttributes(e.attributes),children:this.lowerChildren(e.children),static:!1,...r?{at:r}:{}}}lowerComponent(e){let t=e.tagHole!=null?this.hole(e.tagHole).code:e.tag,r=this.lowerAttributes(e.attributes),{slots:i,rest:s}=this.partitionSlots(e.children);for(let[u,f]of i){let d=f.length===1?f[0]:{kind:"fragment",children:f},h={name:u,kind:"attr",expr:this.emit(d),jsxElement:!0},m=r.findIndex(y=>y.name===u);m>=0?r[m]=h:r.push(h)}let o=e.attributes.find(u=>u.kind==="LoadDirective"),a=o?ce(`load:${o.strategy}`,o.modifier):void 0,l=r.find(u=>u.at&&u.reactive)?.at,c=this.tagAt(e);return{kind:"component",name:t,props:r,children:this.lowerChildren(s),...c?{at:c}:{},...l?{bindAt:l}:{},...a?{load:a}:{}}}partitionSlots(e){let t=new Map,r=[];for(let i of e){if(i.kind==="Element"||i.kind==="Component"){let s=i.attributes.find(o=>o.kind==="Attribute"&&o.name==="slot");if(s&&s.value&&s.value.kind==="static"){let o={...i,attributes:i.attributes.filter(c=>c!==s)},a=o.kind==="Element"?this.lowerElement(o):this.lowerComponent(o),l=t.get(s.value.value)??[];l.push(a),t.set(s.value.value,l);continue}}r.push(i)}return{slots:t,rest:r}}lowerIf(e,t,r){let i=this.hole(t),s=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive,...i.at?{at:i.at}:{}}];if(r){let l=this.stripAndLower(r,c=>c.kind==="ElseDirective");s.push({name:"fallback",kind:"attr",expr:this.emit(l),jsxElement:!0})}let o=this.stripAndLower(e,l=>l.kind==="IfDirective"),a=this.tagAt(e);return{kind:"component",name:"Show",props:s,children:[o],...a?{at:a}:{},...i.at?{bindAt:i.at}:{}}}lowerEach(e){let t=e.attributes.find(c=>c.kind==="EachDirective");if(!t||t.kind!=="EachDirective")return this.lowerNode(e);let r=this.hole(t.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive,...r.at?{at:r.at}:{}}];if(t.key){let c="static"in t.key?`(item) => item[${JSON.stringify(t.key.static)}]`:this.hole(t.key.hole).code;i.push({name:"by",kind:"attr",expr:c})}let s=this.itemArrow(e),o;if(s){let c={kind:"expr",code:s.body,reactive:s.bodyReactive},u=this.rebuildWithChildren(e,[c]);o=`(${s.params.join(", ")}) => (${this.emit(u)})`}else{let c=this.stripAndLower(e,u=>u.kind==="EachDirective");o=`() => (${this.emit(c)})`}let a=[{kind:"expr",code:o,reactive:!1}],l=this.tagAt(e);return{kind:"component",name:"For",props:i,children:a,...l?{at:l}:{},...r.at?{bindAt:r.at}:{}}}itemArrow(e){let t=e.children.filter(r=>!this.isBlankText(r));return t.length!==1||t[0].kind!=="Expression"?null:this.hole(t[0].hole).arrow??null}stripAndLower(e,t){let r={...e,attributes:e.attributes.filter(i=>!t(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(e,t){let r=this.lowerAttributes(e.attributes.filter(i=>i.kind!=="EachDirective"));if(e.kind==="Element"){let i=this.tagAt(e);return{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:r,children:t,static:!1,...i?{at:i}:{}}}return{kind:"component",name:e.tag,props:r,children:t}}lowerAttributes(e){let t=[],r=[],i=!1,s,o=[],a=!1,l,c=[];for(let u of e)switch(u.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":t.push(this.plainAttr(u));break;case"PropertyBinding":t.push({name:u.name,kind:"prop",expr:this.hole(u.hole).code,reactive:this.hole(u.hole).reactive,...this.hole(u.hole).at?{at:this.hole(u.hole).at}:{}});break;case"EventBinding":t.push(this.eventProp(u));break;case"RefBinding":t.push({name:"ref",kind:"ref",expr:this.hole(u.hole).code,reactive:this.hole(u.hole).reactive,...this.hole(u.hole).at?{at:this.hole(u.hole).at}:{}});break;case"Spread":t.push({name:"",kind:"spread",expr:this.hole(u.hole).code});break;case"ClassDirective":{let f=this.hole(u.hole);r.push(`${JSON.stringify(u.name)}: ${f.code}`),i=i||f.reactive,s??=f.at;break}case"StyleDirective":{let f=this.hole(u.hole);o.push(`${JSON.stringify(u.name)}: ${f.code}`),a=a||f.reactive,l??=f.at;break}case"BindDirective":t.push(...this.bindProps(u.name,this.hole(u.hole)));break;case"UseDirective":{let f=u.name??(u.hole!=null?this.hole(u.hole).code:null);if(!f)break;c.push(u.name!=null&&u.hole!=null?`[${f}, () => (${this.hole(u.hole).code})]`:`[${f}]`);break}}return r.length>0&&t.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i,...s?{at:s}:{}}),o.length>0&&t.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:a,...l?{at:l}:{}}),c.length>0&&t.push({name:"use",kind:"attr",expr:`[${c.join(", ")}]`}),t}eventProp(e){let t=e.name.toLowerCase(),r=this.hole(e.hole).code;if(!(e.syntax==="colon"||e.modifiers.length>0))return{name:"on"+bt(e.name),kind:"event",event:{name:t,delegated:vt.has(t)},expr:r};let s=this.wrapHandler(r,e.modifiers),o=this.eventOptions(e.modifiers),a=o?`[${s}, ${o}]`:s;return{name:"on:"+t,kind:"attr",expr:a}}wrapHandler(e,t){let r=t.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return t.includes("prevent")&&i.push("e.preventDefault();"),t.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?e:`(e) => { ${r}${i.join(" ")} return (${e})(e); }`}eventOptions(e){let t=[];return e.includes("capture")&&t.push("capture: true"),e.includes("once")&&t.push("once: true"),e.includes("passive")&&t.push("passive: true"),t.length?`{ ${t.join(", ")} }`:null}bindProps(e,t){let r=t.code,i=e==="checked",s=i?"change":"input",o=i?"checked":"value";this.used.add("bindPair");let a=`bindPair(${r})`;return[{name:e,kind:"attr",expr:`${a}[0]()`,reactive:!0,directive:`bind:${e}`,...t.at?{at:t.at}:{}},{name:"on"+bt(s),kind:"event",event:{name:s,delegated:vt.has(s)},expr:`(e) => ${a}[1](e.target.${o})`}]}plainAttr(e){let t=e.value,r=e.name;e.name==="class"?r=t&&t.kind==="hole"&&this.hole(t.hole).object?"classList":"className":e.name==="html"&&(r="innerHTML");let s={name:r,kind:"attr"};if(t==null)return s.literal=!0,s;if(t.kind==="static")return s.literal=t.value,s;if(t.kind==="hole"){let c=this.hole(t.hole);return s.expr=c.code,s.reactive=c.reactive,c.at&&(s.at=c.at),s}let o=!1,a,l=t.parts.map(c=>{if("text"in c)return Ln(c.text);let u=this.hole(c.hole);return o=o||u.reactive,a??=u.at,"${"+u.code+"}"}).join("");return s.expr="`"+l+"`",s.reactive=o,a&&(s.at=a),s}};function Nt(n,e,t,r={}){let{root:i}=On(n,{svg:r.svg});return new Le(e,t,r.sourceFile,r.positionAt).lowerRoot(i.children)}function xt(n,e,t={}){let r=new Set,i=Nt(n,[...e],r,{svg:t.svg,...t.sourceFile?{sourceFile:t.sourceFile}:{},...t.positionAt?{positionAt:t.positionAt}:{}});_(i),ue(i,{resolver:ve(t.resolve??[]),modules:{controlFlowModule:t.controlFlowModule??"@fluixi/dom",coreModule:t.coreModule??"@fluixi/core",routerModule:t.routerModule??"@fluixi/core/router"},strategyFor:l=>l.load}),fe(i);let{code:s,imports:o,templates:a}=F.emit(i,{templateClone:t.templateClone,partialTemplates:t.partialTemplates});for(let l of o)r.add(l);return t.hoistTemplates?{code:s,imports:[...r],ir:i,templates:a}:{code:ye(s,a),imports:[...r],ir:i}}var Pn="children";function B(n){switch(n.kind){case"call":return!0;case"member":return n.property!==Pn;case"compound":return n.parts.some(B);case"opaque":return!1}}var Mn=new Set(["CallExpression","OptionalCallExpression"]),An=new Set(["MemberExpression","OptionalMemberExpression"]);function H(n){if(!n)return{kind:"opaque"};if(Mn.has(n.type))return{kind:"call"};if(An.has(n.type)){let e=n.property;return{kind:"member",property:!(n.computed===!0)&&e?.type==="Identifier"?e.name:null}}return n.type==="ConditionalExpression"?{kind:"compound",parts:[n.test,n.consequent,n.alternate].map(ee)}:n.type==="LogicalExpression"||n.type==="BinaryExpression"?{kind:"compound",parts:[n.left,n.right].map(ee)}:n.type==="TemplateLiteral"?{kind:"compound",parts:n.expressions.map(ee)}:n.type==="ObjectExpression"?{kind:"compound",parts:n.properties.filter(t=>(t.type==="ObjectProperty"||t.type==="Property")&&t.computed!==!0).map(t=>ee(t.value))}:n.type==="ArrayExpression"?{kind:"compound",parts:n.elements.filter(t=>t!=null&&t.type!=="SpreadElement").map(ee)}:{kind:"opaque"}}var ee=n=>H(n);var Dn=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),jn=/^on[A-Z]/,_n=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]),Rt=n=>B(H(n)),te=(n,e)=>{if(!e.sourceFile)return;let t=n.loc?.start;return t?{line:t.line,column:t.column}:void 0};function ne(n){if(n.type==="StringLiteral"||n.type==="NumericLiteral"||n.type==="BooleanLiteral"||n.type==="Literal"&&(typeof n.value=="string"||typeof n.value=="number"||typeof n.value=="boolean"))return n.value}var Pe=n=>!!n&&typeof ne(n)=="string";function Jn(n,e){return n.type==="JSXIdentifier"?{tag:n.name,component:n.name[0]!==n.name[0].toLowerCase()}:n.type==="JSXMemberExpression"?{tag:e.code(n),component:!0}:n.type==="JSXNamespacedName"?{tag:`${n.namespace.name}:${n.name.name}`,component:!1}:{tag:"div",component:!1}}function Me(n){return n.type==="JSXIdentifier"?n.name==="class"?"className":n.name:n.type==="JSXNamespacedName"?`${n.namespace.name}:${n.name.name}`:"unknown"}function Fn(n,e){let t=Me(n.name),r=jn.test(t),i=r||t.startsWith("on:")||t==="ref",o={name:t,kind:r?"event":"attr"};if(r){let l=t.slice(2).toLowerCase();o.event={name:l,delegated:_n.has(l)}}let a=n.value;if(a==null)return o.literal=!0,o.at=te(n,e),o;if(Pe(a))return o.literal=ne(a),o.at=te(a,e),o;if(a.type==="JSXExpressionContainer"&&a.expression?.type!=="JSXEmptyExpression"){let l=a.expression,c=ne(l);return c!==void 0?(o.literal=c,o.at=te(l,e),o):(o.expr=e.code(l),o.reactive=i?!1:Rt(l),o.at=te(l,e),(l.type==="JSXElement"||l.type==="JSXFragment")&&(o.jsxElement=!0),o)}return o.literal=!0,o}function St(n,e){let t=n.value;return t==null?null:Pe(t)?JSON.stringify(ne(t)):t.type==="JSXExpressionContainer"&&t.expression?.type!=="JSXEmptyExpression"?e.code(t.expression):null}function Bn(n,e){let t=[],r=[];for(let i of n){if(i.type==="JSXSpreadAttribute"){t.push({name:"",kind:"spread",expr:e.code(i.argument)});continue}if(i.type!=="JSXAttribute"||Re(Me(i.name)))continue;let s=i.name.type==="JSXNamespacedName"?i.name.namespace.name:null;if(s==="use"){let o=i.name.name.name;e.used.add(o);let a=St(i,e);r.push(a!=null?`[${o}, () => (${a})]`:`[${o}]`);continue}if(s==="oncapture"){let o=i.name.name.name.toLowerCase(),a=St(i,e)??"undefined";t.push({name:"on:"+o,kind:"attr",expr:`[${a}, { capture: true }]`});continue}t.push(Fn(i,e))}return r.length>0&&t.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),t}function wt(n,e){let t=[];for(let r of n)if(r.type==="JSXText"){let i=Q(r.value);i&&t.push({kind:"text",value:i})}else if(r.type==="JSXExpressionContainer"){if(r.expression?.type!=="JSXEmptyExpression"){let i=r.expression,s=Rt(i);t.push({kind:"expr",code:e.code(i),reactive:s,...s?{at:te(i,e)}:{}})}}else r.type==="JSXElement"||r.type==="JSXFragment"?t.push(Et(r,e)):r.type==="JSXSpreadChild"&&t.push({kind:"expr",code:e.code(r.expression),reactive:!1});return t}function Hn(n){for(let e of n){if(e.type!=="JSXAttribute")continue;let t=Me(e.name);if(Re(t)){if(e.value&&!Pe(e.value))throw new O(`'${t}' needs a literal value, not an expression — the strategy is compile-time.`);return ce(t,e.value?ne(e.value):null)}}}function Et(n,e){if(n.type==="JSXFragment")return{kind:"fragment",children:wt(n.children,e)};let{tag:t,component:r}=Jn(n.openingElement.name,e),i=Bn(n.openingElement.attributes,e),s=wt(n.children,e),o=e.sourceFile&&n.loc?.start?{file:e.sourceFile,line:n.loc.start.line,column:n.loc.start.column}:void 0;if(r){let a=Hn(n.openingElement.attributes);return{kind:"component",name:t,props:i,children:s,...a?{load:a}:{},...o?{at:o}:{}}}return{kind:"element",tag:t,svg:Dn.has(t),props:i,children:s,static:!1,...o?{at:o}:{}}}function kt(n,e){let t=Et(n,e);return _(t),t}function L(n,e){if(n)switch(n.type){case"Identifier":e.add(n.name);return;case"ObjectPattern":for(let t of n.properties)t.type==="RestElement"?L(t.argument,e):L(t.value,e);return;case"ArrayPattern":for(let t of n.elements)L(t,e);return;case"AssignmentPattern":L(n.left,e);return;case"RestElement":L(n.argument,e);return}}function Ct(n,e){switch(n.type){case"ImportDeclaration":for(let t of n.specifiers)L(t.local,e);return;case"VariableDeclaration":for(let t of n.declarations)L(t.id,e);return;case"FunctionDeclaration":case"ClassDeclaration":L(n.id,e);return;case"ExportNamedDeclaration":case"ExportDefaultDeclaration":n.declaration&&Ct(n.declaration,e);return}}function Ae(n){let e=new Set;for(let t of n.body)Ct(t,e);return e}import{parse as pi}from"@babel/parser";function E(n,e){if(n)switch(n.type){case"Identifier":e.add(n.name);return;case"ObjectPattern":for(let t of n.properties)t.type==="RestElement"?E(t.argument,e):E(t.value,e);return;case"ArrayPattern":for(let t of n.elements)E(t,e);return;case"AssignmentPattern":E(n.left,e);return;case"RestElement":E(n.argument,e);return}}function De(n){switch(n.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"NullLiteral":case"BigIntLiteral":case"RegExpLiteral":case"Identifier":return!0;case"Literal":return!0;case"TemplateLiteral":return n.expressions.every(De);case"UnaryExpression":return De(n.argument);case"MemberExpression":return!1;default:return!1}}function be(n,e){if(!(!n||typeof n!="object")){e(n);for(let t of Object.keys(n)){if(t==="loc"||t==="range"||t==="leadingComments"||t==="trailingComments")continue;let r=n[t];if(Array.isArray(r))for(let i of r)i&&typeof i=="object"&&be(i,e);else r&&typeof r=="object"&&typeof r.type=="string"&&be(r,e)}}}function Un(n){let e=new Set;return be(n,t=>{if(t.type==="AssignmentExpression")E(t.left,e);else if(t.type==="UpdateExpression"){let r=t.argument;r?.type==="Identifier"&&e.add(r.name)}}),e}function qn(n,e){let t=new Set,r=i=>{let s=new Set;E(i,s);for(let o of s)e.has(o)&&t.add(o)};return be(n,i=>{switch(i.type){case"VariableDeclarator":r(i.id);return;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":r(i.id);for(let s of i.params??[])r(s);return;case"CatchClause":r(i.param);return;case"ClassDeclaration":case"ClassExpression":r(i.id);return}}),t}function It(n,e,t){for(let r of n.properties??[]){if(r.type==="RestElement"){let u=r.argument;if(u?.type!=="Identifier"||e.length>0){let f=new Set;E(u,f);for(let d of f)t.bails.push({name:d,reason:"rest"});continue}t.rest={name:u.name,keys:[]};continue}if(r.computed){let u=new Set;E(r.value,u);for(let f of u)t.bails.push({name:f,reason:"computed"});continue}let i=r.key,s=i.type==="Identifier"?i.name:i.value,o=r.value,a;o.type==="AssignmentPattern"&&(a=o.right,o=o.left);let l=[...e,s];if(o.type==="Identifier"){if(a&&!De(a)){t.bails.push({name:o.name,reason:"unsafe-default"});continue}t.reads.push({name:o.name,path:l,...a?{fallback:a}:{}});continue}if(o.type==="ObjectPattern"){if(a){let u=new Set;E(o,u);for(let f of u)t.bails.push({name:f,reason:"unsafe-default"});continue}It(o,l,t);continue}let c=new Set;E(o,c);for(let u of c)t.bails.push({name:u,reason:"computed"})}}function $t(n,e){let t={reads:[],bails:[]};if(n?.type!=="ObjectPattern"||(It(n,[],t),t.rest&&(e?.type!=="BlockStatement"?(t.bails.push({name:t.rest.name,reason:"rest"}),delete t.rest):t.rest.keys=(n.properties??[]).filter(a=>a.type!=="RestElement"&&!a.computed).map(a=>{let l=a.key;return l.type==="Identifier"?l.name:l.value})),t.reads.length===0&&!t.rest))return t;let r=new Set(t.reads.map(a=>a.name));t.rest&&r.add(t.rest.name);let i=Un(e),s=qn(e,r),o=[];for(let a of t.reads)i.has(a.name)?t.bails.push({name:a.name,reason:"reassigned"}):s.has(a.name)?t.bails.push({name:a.name,reason:"shadowed"}):o.push(a);return t.reads=o,t.rest&&i.has(t.rest.name)?(t.bails.push({name:t.rest.name,reason:"reassigned"}),delete t.rest):t.rest&&s.has(t.rest.name)&&(t.bails.push({name:t.rest.name,reason:"shadowed"}),delete t.rest),t}function Tt(n){switch(n){case"rest":return"this rest element cannot be served by splitProps, and copying the props into a plain object would lose the getters";case"computed":return"the property is not known until it runs";case"reassigned":return"the binding is assigned to, and props are read-only";case"shadowed":return"an inner scope binds the same name";case"unsafe-default":return"the default would have to run again on every read"}}function re(n,e,t=null){if(!(!n||typeof n!="object"||typeof n.type!="string")&&!n.type.startsWith("TS")&&e(n,t)!==!1)for(let r of Object.keys(n)){if(r==="loc"||r==="leadingComments"||r==="trailingComments")continue;let i=n[r];if(Array.isArray(i))for(let s of i)re(s,e,n);else i&&typeof i=="object"&&re(i,e,n)}}function Ot(n){return!!n&&n[0]>="A"&&n[0]<="Z"}function Xn(n){let e=[];return re(n,t=>{if(t.type==="FunctionDeclaration"&&Ot(t.id?.name)){e.push(t);return}if(t.type==="VariableDeclarator"&&Ot(t.id?.name)){let r=t.init;r&&(r.type==="ArrowFunctionExpression"||r.type==="FunctionExpression")&&e.push(r)}}),e}function Vn(n){let e=new Set;return re(n,t=>{t.type==="Identifier"&&e.add(t.name)}),e}function Wn(n,e){if(!e)return!0;switch(e.type){case"MemberExpression":case"OptionalMemberExpression":return!(e.property===n&&!e.computed);case"ObjectProperty":case"ObjectMethod":case"ClassProperty":case"ClassMethod":return!(e.key===n&&!e.computed);case"LabeledStatement":case"BreakStatement":case"ContinueStatement":return e.label!==n;case"ImportSpecifier":case"ExportSpecifier":return!1;default:return!0}}function Lt(n,e,t={}){let r=[],i=[],s=new Set;for(let o of Xn(n)){let a=o.params?.[0];if(a?.type!=="ObjectPattern")continue;let l=$t(a,o.body);for(let m of l.bails)i.push({name:m.name,reason:m.reason,message:Tt(m.reason),start:a.start});if(l.bails.length>0||l.reads.length===0&&!l.rest)continue;let c=Vn(o),u=t.parameterName??"props";for(;c.has(u);)u=`_${u}`;let f=new Map;for(let m of l.reads){let y=`${u}.${m.path.join(".")}`,S=m.fallback;f.set(m.name,S?`(${y} === undefined ? ${e.slice(S.start,S.end)} : ${y})`:y)}let d=a.typeAnnotation;if(r.push({start:a.start,end:d?.start??a.end,code:u}),l.rest){let m=l.rest.keys.map(S=>JSON.stringify(S)).join(", "),y=o.body;r.push({start:y.start+1,end:y.start+1,code:`
11
- const [, ${l.rest.name}] = splitProps(${u}, [${m}]);`}),s.add("splitProps")}let h=[];re(o.body,(m,y)=>{if(m.type!=="Identifier")return;let S=f.get(m.name);if(!S)return;let x=y?.type==="ObjectProperty"&&y.shorthand&&y.value===m;if(!x&&!Wn(m,y))return;let v=l.reads.find(I=>I.name===m.name).path;h.push({node:m,parent:x?y:null,text:S,property:v[v.length-1]})});for(let m of h)m.parent?r.push({start:m.parent.start,end:m.parent.end,code:`${m.node.name}: ${m.text}`}):r.push({start:m.node.start,end:m.node.end,code:m.text}),zn(m.node,u,m.property)}return{edits:r,diagnostics:i,used:s}}function zn(n,e,t){n.type="MemberExpression",n.computed=!1,n.optional=!1,n.object={type:"Identifier",name:e,start:n.start,end:n.start},n.property={type:"Identifier",name:t,start:n.end,end:n.end},delete n.name}function je(n,e){if(!(!n||typeof n!="object"||typeof n.type!="string")){e(n);for(let t of Object.keys(n)){if(t==="loc"||t==="leadingComments"||t==="trailingComments")continue;let r=n[t];if(Array.isArray(r))for(let i of r)je(i,e);else r&&typeof r=="object"&&je(r,e)}}}function Pt(n){let e=[],t=[],r=new Map,i=new Set,{shadowed:s}=ge(n);return je(n,o=>{if(o.type!=="CallExpression")return;let a=o.callee;if(a?.type!=="Identifier")return;let l=a.name;if(!he(l))return;if(s.has(l)){i.has(l)||(i.add(l),t.push({name:l,message:`${l} is reserved for the compiler, and this module binds it. The call keeps your binding's meaning; rename it to use the intrinsic.`,start:a.start}));return}let c=C[l];e.push({start:a.start,end:a.end,code:c.export});let u=r.get(c.module)??new Set;u.add(c.export),r.set(c.module,u)}),{edits:e,diagnostics:t,imports:r}}function Mt(n,e){let t=[];for(let[r,i]of[...n.imports].sort(([s],[o])=>s.localeCompare(o))){let s=[...i].filter(o=>!e.has(o)).sort();s.length&&t.push(`import { ${s.join(", ")} } from ${JSON.stringify(r)};`)}return t.length?`${t.join(`
12
- `)}
13
- `:""}var Gn=new Set(V),Yn=new Set(W),Zn=new Set(J),Qn=new Set(["createMemo","createEffect","createRenderEffect","createRoot","createSignal","onCleanup","batch","untrack"]);function xe(n,e,t=null,r=""){if(!(!n||typeof n!="object")){if(Array.isArray(n)){for(let i of n)xe(i,e,t,r);return}typeof n.type=="string"&&e(n,t,r);for(let i of Object.keys(n))i==="loc"||i==="leadingComments"||i==="trailingComments"||xe(n[i],e,typeof n.type=="string"?n:t,i)}}var _e=n=>n.type==="JSXElement"||n.type==="JSXFragment";function er(n,e,t){return _e(n)?!(e&&_e(e)&&t==="children"):!1}function tr(n,e){return n.type==="TaggedTemplateExpression"&&n.tag?.type==="Identifier"&&(n.tag.name===e||n.tag.name==="svg")}function At(n){return n.filter(e=>!n.some(t=>t!==e&&t.start<=e.start&&t.end>=e.end&&t.end-t.start>e.end-e.start&&!(e.start===e.end&&(e.start===t.start||e.start===t.end))))}function Ne(n,e,t,r){let i=At(r.filter(o=>o.start>=e&&o.end<=t)).sort((o,a)=>a.start-o.start),s=n.slice(e,t);for(let o of i)s=s.slice(0,o.start-e)+o.code+s.slice(o.end-e);return s}function nr(n,e,t,r=!1){let i=r?e.loc?.start:void 0,s={code:Ne(n,e.start,e.end,t),reactive:B(H(e)),...i?{at:{line:i.line,column:i.column}}:{}};return e.type==="ArrowFunctionExpression"&&e.body?.type!=="BlockStatement"&&(s.arrow={params:e.params.map(o=>Ne(n,o.start,o.end,t)),body:Ne(n,e.body.start,e.body.end,t),bodyReactive:B(H(e.body))}),e.type==="ObjectExpression"&&(s.object=!0),s}function Dt(n,e,t){if(!e||e.length===0)return n;let r=new Map;for(let i of e){let s=`${i.svg?"svg:":""}${i.html}`,o=t.get(s);o||(o=`_fxTmpl$${t.size}`,t.set(s,o)),r.set(i.id,o)}return n.replace(/_tmpl\$\d+/g,i=>r.get(i)??i)}function Je(n,e){if(n.kind==="component"&&n.load&&!n.source&&X(n.load)&&(e.ignoredLoad.has(n.name)||e.ignoredLoad.set(n.name,n.load)),n.kind==="component"&&n.source){let t=n.source;t.origin==="builtin"?e.builtins.add(n.name):X(t.loading)&&!e.resolved.has(n.name)?e.deferred.set(n.name,t):(e.deferred.delete(n.name),e.resolved.set(n.name,t))}if("props"in n&&n.props)for(let t of n.props)t.kind==="event"&&t.event?.delegated&&e.delegatedEvents.add(t.event.name);if("children"in n&&n.children)for(let t of n.children)Je(t,e)}function rr(n,e){for(let t of n.body??[])if(t.type==="ImportDeclaration")for(let r of t.specifiers??[]){if(r.local?.name!==e)continue;if(r.type==="ImportNamespaceSpecifier")return;let i=r.type==="ImportDefaultSpecifier"?"default":r.imported?.name??r.imported?.value;return{module:t.source.value,export:i,declaration:t,specifier:r}}}function ir(n,e){for(let t of n.body??[])if(t.type==="ImportDeclaration"){for(let r of t.specifiers??[])if(r.type==="ImportNamespaceSpecifier"&&r.local?.name===e)return!0}return!1}function sr(n,e,t){let r=!1;return xe(n,i=>{r||i.type!=="Identifier"||i.name!==e||i.start===t.local?.start&&i.end===t.local?.end||(r=!0)}),r}function or(n){let e=[`kind: ${JSON.stringify(n.kind)}`];return n.kind==="visible"&&n.rootMargin&&e.push(`rootMargin: ${JSON.stringify(n.rootMargin)}`),n.kind==="interaction"&&e.push(`events: ${JSON.stringify(n.events)}`),n.kind==="media"&&e.push(`query: ${JSON.stringify(n.query)}`),`{ ${e.join(", ")} }`}function ar(n){let e=[0];for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e.push(t+1);return t=>{let r=0,i=e.length-1;for(;r<i;){let s=r+i+1>>1;e[s]<=t?r=s:i=s-1}return{line:r+1,column:t-e[r]}}}function lr(n){let e=[];return n.quasi.quasis.forEach((t,r)=>{if(e.push({kind:"static",text:t.value.cooked??t.value.raw,start:t.start}),r<n.quasi.expressions.length){let i=n.quasi.expressions[r];e.push({kind:"hole",index:r,start:i.start,end:i.end})}}),e}function cr(n,e){if(!e)return n;let t=e.endsWith("/")?e:`${e}/`;return n.startsWith(t)?n.slice(t.length):n}function Ji(n,e,t={}){let r=t.litTag??"html",i=t.format??"both",s=i!=="jsx",o=i!=="lit",a=s&&(n.includes(`${r}\``)||n.includes("svg`")),l=t.intrinsics!==!1&&it(n),c=t.sourceLocations===!0&&ut(n),u=cr(e,t.sourceRoot);if(!a&&!(o&&n.includes("<"))&&!l&&!c)return null;let f=Kn(n,{sourceType:"module",plugins:["jsx","typescript"],errorRecovery:!0}),d=[];xe(f.program,(p,w,N)=>{(s&&tr(p,r)||o&&er(p,w,N))&&d.push(p)});let h=t.propsDestructure===!1?{edits:[],diagnostics:[],used:new Set}:Lt(f.program,n,{runtimeModule:t.runtimeModule}),m=t.intrinsics===!1?{edits:[],diagnostics:[],imports:new Map}:Pt(f.program),y=t.sourceLocations===!0?dt(f.program,u):{edits:[],marked:0};if(d.length===0&&h.edits.length===0&&y.edits.length===0&&m.edits.length===0&&m.diagnostics.length===0&&h.diagnostics.length===0)return null;d.sort((p,w)=>w.start-p.start||p.end-w.end);let x=new Set(h.used),v={builtins:new Set,resolved:new Map,deferred:new Map,delegatedEvents:new Set,ignoredLoad:new Map,unresolved:new Set,declared:ot(f.program)},I=new Map,P=[...h.edits,...m.edits,...y.edits];for(let p of d){let w=d.some(R=>R!==p&&R.start<=p.start&&R.end>=p.end&&R.end-R.start>p.end-p.start);if(_e(p)){P.push({start:p.start,end:p.end,code:ur(n,p,P,w,x,v,I,t,u)});continue}let N=p.quasi.expressions.map(R=>nr(n,R,P,t.sourceLocations===!0)),T=xt(lr(p),N,{...t,hoistTemplates:!0,...t.sourceLocations===!0?{sourceFile:u,positionAt:ar(n)}:{},templateClone:t.templateClone??!0,partialTemplates:w?!1:t.partialTemplates??!0,svg:p.tag.name==="svg"});for(let R of T.imports)x.add(R);Je(T.ir,v),P.push({start:p.start,end:p.end,code:Dt(T.code,T.templates,I)})}let k=new ae(n);for(let p of At(P))p.start===p.end?k.appendLeft(p.start,p.code):k.overwrite(p.start,p.end,p.code);let g=Ae(f.program),$=new Map;for(let[p]of v.ignoredLoad)g.has(p)||$.set(p,"unsupplied");for(let[p,w]of[...v.ignoredLoad]){if(!g.has(p))continue;let N=rr(f.program,p);if(!N){$.set(p,ir(f.program,p)?"namespace":"local");continue}if(sr(f.program,p,N.specifier)){$.set(p,"value");continue}let T=N.declaration.specifiers.filter(ie=>ie!==N.specifier),R=T.length===0&&n[N.declaration.end]===`
14
- `?N.declaration.end+1:N.declaration.end;k.overwrite(N.declaration.start,R,T.length===0?"":`import { ${T.map(ie=>n.slice(ie.start,ie.end)).join(", ")} } from ${JSON.stringify(N.declaration.source.value)};`),v.deferred.set(p,{module:N.module,export:N.export,origin:"rule",loading:w}),g.delete(p),v.ignoredLoad.delete(p)}let D=dr(x,v,I,g,t);D&&k.prepend(D);let M=Mt(m,g);M&&k.prepend(M);let jt={value:p=>`${p} is used as a value here, not only as a tag, so its import has to stay — deferring would hand those references a lazy wrapper instead of the component. Defer it at the point it is rendered, or keep it eager.`,namespace:p=>`${p} came in through a namespace import, which has no single export to defer. Import ${p} by name.`,local:p=>`${p} is declared in this file, so there is no module to load separately. Move it to its own file and import it.`,unsupplied:p=>`nothing supplies ${p}, so there is no import to defer. Import it, or add a \`resolve\` rule for it.`},Fe=[...v.ignoredLoad].map(([p,w])=>({name:p,strategy:w,message:`load:${w.kind} has no effect on <${p}>: ${jt[$.get(p)??"unsupplied"](p)}`})),Be=[...v.unresolved].map(p=>({name:p,message:`<${p}> is not defined: nothing imports it and no \`resolve\` rule supplies it. This compiles to a reference to a name that does not exist, so the component renders nothing. Import ${p}, or add a \`resolve\` rule for it.`}));return{code:k.toString(),map:k.generateMap({source:e,includeContent:!0,hires:!0}),...Fe.length?{loadDiagnostics:Fe}:{},...Be.length?{unresolvedDiagnostics:Be}:{},...h.diagnostics.length?{propsDiagnostics:h.diagnostics}:{},...m.diagnostics.length?{intrinsicDiagnostics:m.diagnostics}:{}}}function ur(n,e,t,r,i,s,o,a,l){let c=kt(e,{code:d=>Ne(n,d.start,d.end,t),used:i,...a.sourceLocations===!0&&l?{sourceFile:l}:{}});_(c);let u=ue(c,{resolver:ve(a.resolve??[]),isBound:d=>s.declared.has(d),modules:{controlFlowModule:a.controlFlowModule??a.runtimeModule??"@fluixi/dom",coreModule:a.coreModule??"@fluixi/core",routerModule:a.routerModule??"@fluixi/core/router"},strategyFor:d=>d.load});for(let d of u.unresolved)s.unresolved.add(d);fe(c);let f=F.emit(c,{templateClone:a.templateClone??!0,partialTemplates:r?!1:a.partialTemplates??!0});for(let d of f.imports)i.add(d);return Je(c,s),Dt(f.code,f.templates,o)}function dr(n,e,t,r,i){let s=i.runtimeModule??"@fluixi/dom",o=i.coreModule??"@fluixi/core",a=new Map,l=(d,h)=>a.set(d,[...a.get(d)??[],h]),c=new Set(n);for(let d of e.builtins)c.add(d);e.delegatedEvents.size>0&&c.add("delegateEvents");for(let d of[...c].sort())r.has(d)||(Qn.has(d)?l(i.reactiveModule??"@fluixi/reactive/signal",d):Zn.has(d)?l(i.routerModule??"@fluixi/core/router",d):Yn.has(d)?l(o,d):Gn.has(d)?l(i.controlFlowModule??s,d):l(s,d));for(let[d,h]of e.resolved)r.has(d)||l(h.module,h.export==="default"?`default as ${d}`:d===h.export?d:`${h.export} as ${d}`);let u=[];for(let[d,h]of a)u.push(`import { ${h.join(", ")} } from ${JSON.stringify(d)};`);let f=[...e.deferred].filter(([d])=>!r.has(d));if(f.length>0){r.has("deferred")||u.push(`import { deferred } from ${JSON.stringify(o)};`);for(let[d,h]of f)u.push(`const ${d} = deferred(() => import(${JSON.stringify(h.module)}), { strategy: ${or(h.loading)}, export: ${JSON.stringify(h.export)} });`)}for(let[d,h]of t)u.push(`const ${h} = ${JSON.stringify(d.startsWith("svg:")?d.slice(4):d)};`);return e.delegatedEvents.size>0&&u.push(`delegateEvents(${JSON.stringify([...e.delegatedEvents])});`),u.length>0?u.join(`
15
- `)+`
16
- `:null}export{Ji as transformTemplates};
1
+ // src/transform/templates.ts
2
+ import { parse as parse2 } from "@babel/parser";
3
+
4
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
5
+ var comma = ",".charCodeAt(0);
6
+ var semicolon = ";".charCodeAt(0);
7
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
8
+ var intToChar = new Uint8Array(64);
9
+ var charToInt = new Uint8Array(128);
10
+ for (let i = 0; i < chars.length; i++) {
11
+ const c = chars.charCodeAt(i);
12
+ intToChar[i] = c;
13
+ charToInt[c] = i;
14
+ }
15
+ function encodeInteger(builder, num, relative) {
16
+ let delta = num - relative;
17
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
18
+ do {
19
+ let clamped = delta & 31;
20
+ delta >>>= 5;
21
+ if (delta > 0) clamped |= 32;
22
+ builder.write(intToChar[clamped]);
23
+ } while (delta > 0);
24
+ return num;
25
+ }
26
+ var bufLength = 1024 * 16;
27
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
28
+ decode(buf) {
29
+ const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
30
+ return out.toString();
31
+ }
32
+ } : {
33
+ decode(buf) {
34
+ let out = "";
35
+ for (let i = 0; i < buf.length; i++) {
36
+ out += String.fromCharCode(buf[i]);
37
+ }
38
+ return out;
39
+ }
40
+ };
41
+ var StringWriter = class {
42
+ constructor() {
43
+ this.pos = 0;
44
+ this.out = "";
45
+ this.buffer = new Uint8Array(bufLength);
46
+ }
47
+ write(v) {
48
+ const { buffer } = this;
49
+ buffer[this.pos++] = v;
50
+ if (this.pos === bufLength) {
51
+ this.out += td.decode(buffer);
52
+ this.pos = 0;
53
+ }
54
+ }
55
+ flush() {
56
+ const { buffer, out, pos } = this;
57
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
58
+ }
59
+ };
60
+ function encode(decoded) {
61
+ const writer = new StringWriter();
62
+ let sourcesIndex = 0;
63
+ let sourceLine = 0;
64
+ let sourceColumn = 0;
65
+ let namesIndex = 0;
66
+ for (let i = 0; i < decoded.length; i++) {
67
+ const line = decoded[i];
68
+ if (i > 0) writer.write(semicolon);
69
+ if (line.length === 0) continue;
70
+ let genColumn = 0;
71
+ for (let j = 0; j < line.length; j++) {
72
+ const segment = line[j];
73
+ if (j > 0) writer.write(comma);
74
+ genColumn = encodeInteger(writer, segment[0], genColumn);
75
+ if (segment.length === 1) continue;
76
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
77
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
78
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
79
+ if (segment.length === 4) continue;
80
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
81
+ }
82
+ }
83
+ return writer.flush();
84
+ }
85
+
86
+ // ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
87
+ var BitSet = class _BitSet {
88
+ constructor(arg) {
89
+ this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
90
+ }
91
+ add(n2) {
92
+ this.bits[n2 >> 5] |= 1 << (n2 & 31);
93
+ }
94
+ has(n2) {
95
+ return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
96
+ }
97
+ };
98
+ var Chunk = class _Chunk {
99
+ constructor(start, end, content) {
100
+ this.start = start;
101
+ this.end = end;
102
+ this.original = content;
103
+ this.intro = "";
104
+ this.outro = "";
105
+ this.content = content;
106
+ this.storeName = false;
107
+ this.edited = false;
108
+ {
109
+ this.previous = null;
110
+ this.next = null;
111
+ }
112
+ }
113
+ appendLeft(content) {
114
+ this.outro += content;
115
+ }
116
+ appendRight(content) {
117
+ this.intro = this.intro + content;
118
+ }
119
+ clone() {
120
+ const chunk = new _Chunk(this.start, this.end, this.original);
121
+ chunk.intro = this.intro;
122
+ chunk.outro = this.outro;
123
+ chunk.content = this.content;
124
+ chunk.storeName = this.storeName;
125
+ chunk.edited = this.edited;
126
+ return chunk;
127
+ }
128
+ contains(index) {
129
+ return this.start < index && index < this.end;
130
+ }
131
+ eachNext(fn) {
132
+ let chunk = this;
133
+ while (chunk) {
134
+ fn(chunk);
135
+ chunk = chunk.next;
136
+ }
137
+ }
138
+ eachPrevious(fn) {
139
+ let chunk = this;
140
+ while (chunk) {
141
+ fn(chunk);
142
+ chunk = chunk.previous;
143
+ }
144
+ }
145
+ edit(content, storeName, contentOnly) {
146
+ this.content = content;
147
+ if (!contentOnly) {
148
+ this.intro = "";
149
+ this.outro = "";
150
+ }
151
+ this.storeName = storeName;
152
+ this.edited = true;
153
+ return this;
154
+ }
155
+ prependLeft(content) {
156
+ this.outro = content + this.outro;
157
+ }
158
+ prependRight(content) {
159
+ this.intro = content + this.intro;
160
+ }
161
+ reset() {
162
+ this.intro = "";
163
+ this.outro = "";
164
+ if (this.edited) {
165
+ this.content = this.original;
166
+ this.storeName = false;
167
+ this.edited = false;
168
+ }
169
+ }
170
+ split(index) {
171
+ const sliceIndex = index - this.start;
172
+ const originalBefore = this.original.slice(0, sliceIndex);
173
+ const originalAfter = this.original.slice(sliceIndex);
174
+ this.original = originalBefore;
175
+ const newChunk = new _Chunk(index, this.end, originalAfter);
176
+ newChunk.outro = this.outro;
177
+ this.outro = "";
178
+ this.end = index;
179
+ if (this.edited) {
180
+ newChunk.edit("", false);
181
+ this.content = "";
182
+ } else {
183
+ this.content = originalBefore;
184
+ }
185
+ newChunk.next = this.next;
186
+ if (newChunk.next) newChunk.next.previous = newChunk;
187
+ newChunk.previous = this;
188
+ this.next = newChunk;
189
+ return newChunk;
190
+ }
191
+ toString() {
192
+ return this.intro + this.content + this.outro;
193
+ }
194
+ trimEnd(rx) {
195
+ this.outro = this.outro.replace(rx, "");
196
+ if (this.outro.length) return true;
197
+ const trimmed = this.content.replace(rx, "");
198
+ if (trimmed.length) {
199
+ if (trimmed !== this.content) {
200
+ this.split(this.start + trimmed.length).edit("", void 0, true);
201
+ if (this.edited) {
202
+ this.edit(trimmed, this.storeName, true);
203
+ }
204
+ }
205
+ return true;
206
+ } else {
207
+ this.edit("", void 0, true);
208
+ this.intro = this.intro.replace(rx, "");
209
+ if (this.intro.length) return true;
210
+ }
211
+ }
212
+ trimStart(rx) {
213
+ this.intro = this.intro.replace(rx, "");
214
+ if (this.intro.length) return true;
215
+ const trimmed = this.content.replace(rx, "");
216
+ if (trimmed.length) {
217
+ if (trimmed !== this.content) {
218
+ const newChunk = this.split(this.end - trimmed.length);
219
+ if (this.edited) {
220
+ newChunk.edit(trimmed, this.storeName, true);
221
+ }
222
+ this.edit("", void 0, true);
223
+ }
224
+ return true;
225
+ } else {
226
+ this.edit("", void 0, true);
227
+ this.outro = this.outro.replace(rx, "");
228
+ if (this.outro.length) return true;
229
+ }
230
+ }
231
+ };
232
+ function getBtoa() {
233
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
234
+ return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
235
+ } else if (typeof Buffer === "function") {
236
+ return (str) => Buffer.from(str, "utf-8").toString("base64");
237
+ } else {
238
+ return () => {
239
+ throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
240
+ };
241
+ }
242
+ }
243
+ var btoa = /* @__PURE__ */ getBtoa();
244
+ var SourceMap = class {
245
+ constructor(properties) {
246
+ this.version = 3;
247
+ this.file = properties.file;
248
+ this.sources = properties.sources;
249
+ this.sourcesContent = properties.sourcesContent;
250
+ this.names = properties.names;
251
+ this.mappings = encode(properties.mappings);
252
+ if (typeof properties.x_google_ignoreList !== "undefined") {
253
+ this.x_google_ignoreList = properties.x_google_ignoreList;
254
+ }
255
+ if (typeof properties.debugId !== "undefined") {
256
+ this.debugId = properties.debugId;
257
+ }
258
+ }
259
+ toString() {
260
+ return JSON.stringify(this);
261
+ }
262
+ toUrl() {
263
+ return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
264
+ }
265
+ };
266
+ function guessIndent(code) {
267
+ const lines = code.split("\n");
268
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
269
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
270
+ if (tabbed.length === 0 && spaced.length === 0) {
271
+ return null;
272
+ }
273
+ if (tabbed.length >= spaced.length) {
274
+ return " ";
275
+ }
276
+ const min = spaced.reduce((previous, current) => {
277
+ const numSpaces = /^ +/.exec(current)[0].length;
278
+ return Math.min(numSpaces, previous);
279
+ }, Infinity);
280
+ return new Array(min + 1).join(" ");
281
+ }
282
+ function getRelativePath(from, to) {
283
+ const fromParts = from.split(/[/\\]/);
284
+ const toParts = to.split(/[/\\]/);
285
+ fromParts.pop();
286
+ while (fromParts[0] === toParts[0]) {
287
+ fromParts.shift();
288
+ toParts.shift();
289
+ }
290
+ if (fromParts.length) {
291
+ let i = fromParts.length;
292
+ while (i--) fromParts[i] = "..";
293
+ }
294
+ return fromParts.concat(toParts).join("/");
295
+ }
296
+ var toString = Object.prototype.toString;
297
+ function isObject(thing) {
298
+ return toString.call(thing) === "[object Object]";
299
+ }
300
+ function getLocator(source) {
301
+ const originalLines = source.split("\n");
302
+ const lineOffsets = [];
303
+ for (let i = 0, pos = 0; i < originalLines.length; i++) {
304
+ lineOffsets.push(pos);
305
+ pos += originalLines[i].length + 1;
306
+ }
307
+ return function locate(index) {
308
+ let i = 0;
309
+ let j = lineOffsets.length;
310
+ while (i < j) {
311
+ const m = i + j >> 1;
312
+ if (index < lineOffsets[m]) {
313
+ j = m;
314
+ } else {
315
+ i = m + 1;
316
+ }
317
+ }
318
+ const line = i - 1;
319
+ const column = index - lineOffsets[line];
320
+ return { line, column };
321
+ };
322
+ }
323
+ var wordRegex = /\w/;
324
+ var Mappings = class {
325
+ constructor(hires) {
326
+ this.hires = hires;
327
+ this.generatedCodeLine = 0;
328
+ this.generatedCodeColumn = 0;
329
+ this.raw = [];
330
+ this.rawSegments = this.raw[this.generatedCodeLine] = [];
331
+ this.pending = null;
332
+ }
333
+ addEdit(sourceIndex, content, loc, nameIndex) {
334
+ if (content.length) {
335
+ const contentLengthMinusOne = content.length - 1;
336
+ let contentLineEnd = content.indexOf("\n", 0);
337
+ let previousContentLineEnd = -1;
338
+ while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
339
+ const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
340
+ if (nameIndex >= 0) {
341
+ segment2.push(nameIndex);
342
+ }
343
+ this.rawSegments.push(segment2);
344
+ this.generatedCodeLine += 1;
345
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
346
+ this.generatedCodeColumn = 0;
347
+ previousContentLineEnd = contentLineEnd;
348
+ contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
349
+ }
350
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
351
+ if (nameIndex >= 0) {
352
+ segment.push(nameIndex);
353
+ }
354
+ this.rawSegments.push(segment);
355
+ this.advance(content.slice(previousContentLineEnd + 1));
356
+ } else if (this.pending) {
357
+ this.rawSegments.push(this.pending);
358
+ this.advance(content);
359
+ }
360
+ this.pending = null;
361
+ }
362
+ addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
363
+ let originalCharIndex = chunk.start;
364
+ let first = true;
365
+ let charInHiresBoundary = false;
366
+ while (originalCharIndex < chunk.end) {
367
+ if (original[originalCharIndex] === "\n") {
368
+ loc.line += 1;
369
+ loc.column = 0;
370
+ this.generatedCodeLine += 1;
371
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
372
+ this.generatedCodeColumn = 0;
373
+ first = true;
374
+ charInHiresBoundary = false;
375
+ } else {
376
+ if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
377
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
378
+ if (this.hires === "boundary") {
379
+ if (wordRegex.test(original[originalCharIndex])) {
380
+ if (!charInHiresBoundary) {
381
+ this.rawSegments.push(segment);
382
+ charInHiresBoundary = true;
383
+ }
384
+ } else {
385
+ this.rawSegments.push(segment);
386
+ charInHiresBoundary = false;
387
+ }
388
+ } else {
389
+ this.rawSegments.push(segment);
390
+ }
391
+ }
392
+ loc.column += 1;
393
+ this.generatedCodeColumn += 1;
394
+ first = false;
395
+ }
396
+ originalCharIndex += 1;
397
+ }
398
+ this.pending = null;
399
+ }
400
+ advance(str) {
401
+ if (!str) return;
402
+ const lines = str.split("\n");
403
+ if (lines.length > 1) {
404
+ for (let i = 0; i < lines.length - 1; i++) {
405
+ this.generatedCodeLine++;
406
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
407
+ }
408
+ this.generatedCodeColumn = 0;
409
+ }
410
+ this.generatedCodeColumn += lines[lines.length - 1].length;
411
+ }
412
+ };
413
+ var n = "\n";
414
+ var warned = {
415
+ insertLeft: false,
416
+ insertRight: false,
417
+ storeName: false
418
+ };
419
+ var MagicString = class _MagicString {
420
+ constructor(string, options = {}) {
421
+ const chunk = new Chunk(0, string.length, string);
422
+ Object.defineProperties(this, {
423
+ original: { writable: true, value: string },
424
+ outro: { writable: true, value: "" },
425
+ intro: { writable: true, value: "" },
426
+ firstChunk: { writable: true, value: chunk },
427
+ lastChunk: { writable: true, value: chunk },
428
+ lastSearchedChunk: { writable: true, value: chunk },
429
+ byStart: { writable: true, value: {} },
430
+ byEnd: { writable: true, value: {} },
431
+ filename: { writable: true, value: options.filename },
432
+ indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
433
+ sourcemapLocations: { writable: true, value: new BitSet() },
434
+ storedNames: { writable: true, value: {} },
435
+ indentStr: { writable: true, value: void 0 },
436
+ ignoreList: { writable: true, value: options.ignoreList },
437
+ offset: { writable: true, value: options.offset || 0 }
438
+ });
439
+ this.byStart[0] = chunk;
440
+ this.byEnd[string.length] = chunk;
441
+ }
442
+ addSourcemapLocation(char) {
443
+ this.sourcemapLocations.add(char);
444
+ }
445
+ append(content) {
446
+ if (typeof content !== "string") throw new TypeError("outro content must be a string");
447
+ this.outro += content;
448
+ return this;
449
+ }
450
+ appendLeft(index, content) {
451
+ index = index + this.offset;
452
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
453
+ this._split(index);
454
+ const chunk = this.byEnd[index];
455
+ if (chunk) {
456
+ chunk.appendLeft(content);
457
+ } else {
458
+ this.intro += content;
459
+ }
460
+ return this;
461
+ }
462
+ appendRight(index, content) {
463
+ index = index + this.offset;
464
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
465
+ this._split(index);
466
+ const chunk = this.byStart[index];
467
+ if (chunk) {
468
+ chunk.appendRight(content);
469
+ } else {
470
+ this.outro += content;
471
+ }
472
+ return this;
473
+ }
474
+ clone() {
475
+ const cloned = new _MagicString(this.original, { filename: this.filename, offset: this.offset });
476
+ let originalChunk = this.firstChunk;
477
+ let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
478
+ while (originalChunk) {
479
+ cloned.byStart[clonedChunk.start] = clonedChunk;
480
+ cloned.byEnd[clonedChunk.end] = clonedChunk;
481
+ const nextOriginalChunk = originalChunk.next;
482
+ const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
483
+ if (nextClonedChunk) {
484
+ clonedChunk.next = nextClonedChunk;
485
+ nextClonedChunk.previous = clonedChunk;
486
+ clonedChunk = nextClonedChunk;
487
+ }
488
+ originalChunk = nextOriginalChunk;
489
+ }
490
+ cloned.lastChunk = clonedChunk;
491
+ if (this.indentExclusionRanges) {
492
+ cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
493
+ }
494
+ cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
495
+ cloned.intro = this.intro;
496
+ cloned.outro = this.outro;
497
+ return cloned;
498
+ }
499
+ generateDecodedMap(options) {
500
+ options = options || {};
501
+ const sourceIndex = 0;
502
+ const names = Object.keys(this.storedNames);
503
+ const mappings = new Mappings(options.hires);
504
+ const locate = getLocator(this.original);
505
+ if (this.intro) {
506
+ mappings.advance(this.intro);
507
+ }
508
+ this.firstChunk.eachNext((chunk) => {
509
+ const loc = locate(chunk.start);
510
+ if (chunk.intro.length) mappings.advance(chunk.intro);
511
+ if (chunk.edited) {
512
+ mappings.addEdit(
513
+ sourceIndex,
514
+ chunk.content,
515
+ loc,
516
+ chunk.storeName ? names.indexOf(chunk.original) : -1
517
+ );
518
+ } else {
519
+ mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
520
+ }
521
+ if (chunk.outro.length) mappings.advance(chunk.outro);
522
+ });
523
+ if (this.outro) {
524
+ mappings.advance(this.outro);
525
+ }
526
+ return {
527
+ file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
528
+ sources: [
529
+ options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
530
+ ],
531
+ sourcesContent: options.includeContent ? [this.original] : void 0,
532
+ names,
533
+ mappings: mappings.raw,
534
+ x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
535
+ };
536
+ }
537
+ generateMap(options) {
538
+ return new SourceMap(this.generateDecodedMap(options));
539
+ }
540
+ _ensureindentStr() {
541
+ if (this.indentStr === void 0) {
542
+ this.indentStr = guessIndent(this.original);
543
+ }
544
+ }
545
+ _getRawIndentString() {
546
+ this._ensureindentStr();
547
+ return this.indentStr;
548
+ }
549
+ getIndentString() {
550
+ this._ensureindentStr();
551
+ return this.indentStr === null ? " " : this.indentStr;
552
+ }
553
+ indent(indentStr, options) {
554
+ const pattern = /^[^\r\n]/gm;
555
+ if (isObject(indentStr)) {
556
+ options = indentStr;
557
+ indentStr = void 0;
558
+ }
559
+ if (indentStr === void 0) {
560
+ this._ensureindentStr();
561
+ indentStr = this.indentStr || " ";
562
+ }
563
+ if (indentStr === "") return this;
564
+ options = options || {};
565
+ const isExcluded = {};
566
+ if (options.exclude) {
567
+ const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
568
+ exclusions.forEach((exclusion) => {
569
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
570
+ isExcluded[i] = true;
571
+ }
572
+ });
573
+ }
574
+ let shouldIndentNextCharacter = options.indentStart !== false;
575
+ const replacer = (match) => {
576
+ if (shouldIndentNextCharacter) return `${indentStr}${match}`;
577
+ shouldIndentNextCharacter = true;
578
+ return match;
579
+ };
580
+ this.intro = this.intro.replace(pattern, replacer);
581
+ let charIndex = 0;
582
+ let chunk = this.firstChunk;
583
+ while (chunk) {
584
+ const end = chunk.end;
585
+ if (chunk.edited) {
586
+ if (!isExcluded[charIndex]) {
587
+ chunk.content = chunk.content.replace(pattern, replacer);
588
+ if (chunk.content.length) {
589
+ shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
590
+ }
591
+ }
592
+ } else {
593
+ charIndex = chunk.start;
594
+ while (charIndex < end) {
595
+ if (!isExcluded[charIndex]) {
596
+ const char = this.original[charIndex];
597
+ if (char === "\n") {
598
+ shouldIndentNextCharacter = true;
599
+ } else if (char !== "\r" && shouldIndentNextCharacter) {
600
+ shouldIndentNextCharacter = false;
601
+ if (charIndex === chunk.start) {
602
+ chunk.prependRight(indentStr);
603
+ } else {
604
+ this._splitChunk(chunk, charIndex);
605
+ chunk = chunk.next;
606
+ chunk.prependRight(indentStr);
607
+ }
608
+ }
609
+ }
610
+ charIndex += 1;
611
+ }
612
+ }
613
+ charIndex = chunk.end;
614
+ chunk = chunk.next;
615
+ }
616
+ this.outro = this.outro.replace(pattern, replacer);
617
+ return this;
618
+ }
619
+ insert() {
620
+ throw new Error(
621
+ "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
622
+ );
623
+ }
624
+ insertLeft(index, content) {
625
+ if (!warned.insertLeft) {
626
+ console.warn(
627
+ "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
628
+ );
629
+ warned.insertLeft = true;
630
+ }
631
+ return this.appendLeft(index, content);
632
+ }
633
+ insertRight(index, content) {
634
+ if (!warned.insertRight) {
635
+ console.warn(
636
+ "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
637
+ );
638
+ warned.insertRight = true;
639
+ }
640
+ return this.prependRight(index, content);
641
+ }
642
+ move(start, end, index) {
643
+ start = start + this.offset;
644
+ end = end + this.offset;
645
+ index = index + this.offset;
646
+ if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
647
+ this._split(start);
648
+ this._split(end);
649
+ this._split(index);
650
+ const first = this.byStart[start];
651
+ const last = this.byEnd[end];
652
+ const oldLeft = first.previous;
653
+ const oldRight = last.next;
654
+ const newRight = this.byStart[index];
655
+ if (!newRight && last === this.lastChunk) return this;
656
+ const newLeft = newRight ? newRight.previous : this.lastChunk;
657
+ if (oldLeft) oldLeft.next = oldRight;
658
+ if (oldRight) oldRight.previous = oldLeft;
659
+ if (newLeft) newLeft.next = first;
660
+ if (newRight) newRight.previous = last;
661
+ if (!first.previous) this.firstChunk = last.next;
662
+ if (!last.next) {
663
+ this.lastChunk = first.previous;
664
+ this.lastChunk.next = null;
665
+ }
666
+ first.previous = newLeft;
667
+ last.next = newRight || null;
668
+ if (!newLeft) this.firstChunk = first;
669
+ if (!newRight) this.lastChunk = last;
670
+ return this;
671
+ }
672
+ overwrite(start, end, content, options) {
673
+ options = options || {};
674
+ return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
675
+ }
676
+ update(start, end, content, options) {
677
+ start = start + this.offset;
678
+ end = end + this.offset;
679
+ if (typeof content !== "string") throw new TypeError("replacement content must be a string");
680
+ if (this.original.length !== 0) {
681
+ while (start < 0) start += this.original.length;
682
+ while (end < 0) end += this.original.length;
683
+ }
684
+ if (end > this.original.length) throw new Error("end is out of bounds");
685
+ if (start === end)
686
+ throw new Error(
687
+ "Cannot overwrite a zero-length range – use appendLeft or prependRight instead"
688
+ );
689
+ this._split(start);
690
+ this._split(end);
691
+ if (options === true) {
692
+ if (!warned.storeName) {
693
+ console.warn(
694
+ "The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
695
+ );
696
+ warned.storeName = true;
697
+ }
698
+ options = { storeName: true };
699
+ }
700
+ const storeName = options !== void 0 ? options.storeName : false;
701
+ const overwrite = options !== void 0 ? options.overwrite : false;
702
+ if (storeName) {
703
+ const original = this.original.slice(start, end);
704
+ Object.defineProperty(this.storedNames, original, {
705
+ writable: true,
706
+ value: true,
707
+ enumerable: true
708
+ });
709
+ }
710
+ const first = this.byStart[start];
711
+ const last = this.byEnd[end];
712
+ if (first) {
713
+ let chunk = first;
714
+ while (chunk !== last) {
715
+ if (chunk.next !== this.byStart[chunk.end]) {
716
+ throw new Error("Cannot overwrite across a split point");
717
+ }
718
+ chunk = chunk.next;
719
+ chunk.edit("", false);
720
+ }
721
+ first.edit(content, storeName, !overwrite);
722
+ } else {
723
+ const newChunk = new Chunk(start, end, "").edit(content, storeName);
724
+ last.next = newChunk;
725
+ newChunk.previous = last;
726
+ }
727
+ return this;
728
+ }
729
+ prepend(content) {
730
+ if (typeof content !== "string") throw new TypeError("outro content must be a string");
731
+ this.intro = content + this.intro;
732
+ return this;
733
+ }
734
+ prependLeft(index, content) {
735
+ index = index + this.offset;
736
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
737
+ this._split(index);
738
+ const chunk = this.byEnd[index];
739
+ if (chunk) {
740
+ chunk.prependLeft(content);
741
+ } else {
742
+ this.intro = content + this.intro;
743
+ }
744
+ return this;
745
+ }
746
+ prependRight(index, content) {
747
+ index = index + this.offset;
748
+ if (typeof content !== "string") throw new TypeError("inserted content must be a string");
749
+ this._split(index);
750
+ const chunk = this.byStart[index];
751
+ if (chunk) {
752
+ chunk.prependRight(content);
753
+ } else {
754
+ this.outro = content + this.outro;
755
+ }
756
+ return this;
757
+ }
758
+ remove(start, end) {
759
+ start = start + this.offset;
760
+ end = end + this.offset;
761
+ if (this.original.length !== 0) {
762
+ while (start < 0) start += this.original.length;
763
+ while (end < 0) end += this.original.length;
764
+ }
765
+ if (start === end) return this;
766
+ if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
767
+ if (start > end) throw new Error("end must be greater than start");
768
+ this._split(start);
769
+ this._split(end);
770
+ let chunk = this.byStart[start];
771
+ while (chunk) {
772
+ chunk.intro = "";
773
+ chunk.outro = "";
774
+ chunk.edit("");
775
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
776
+ }
777
+ return this;
778
+ }
779
+ reset(start, end) {
780
+ start = start + this.offset;
781
+ end = end + this.offset;
782
+ if (this.original.length !== 0) {
783
+ while (start < 0) start += this.original.length;
784
+ while (end < 0) end += this.original.length;
785
+ }
786
+ if (start === end) return this;
787
+ if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
788
+ if (start > end) throw new Error("end must be greater than start");
789
+ this._split(start);
790
+ this._split(end);
791
+ let chunk = this.byStart[start];
792
+ while (chunk) {
793
+ chunk.reset();
794
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
795
+ }
796
+ return this;
797
+ }
798
+ lastChar() {
799
+ if (this.outro.length) return this.outro[this.outro.length - 1];
800
+ let chunk = this.lastChunk;
801
+ do {
802
+ if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
803
+ if (chunk.content.length) return chunk.content[chunk.content.length - 1];
804
+ if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
805
+ } while (chunk = chunk.previous);
806
+ if (this.intro.length) return this.intro[this.intro.length - 1];
807
+ return "";
808
+ }
809
+ lastLine() {
810
+ let lineIndex = this.outro.lastIndexOf(n);
811
+ if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
812
+ let lineStr = this.outro;
813
+ let chunk = this.lastChunk;
814
+ do {
815
+ if (chunk.outro.length > 0) {
816
+ lineIndex = chunk.outro.lastIndexOf(n);
817
+ if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
818
+ lineStr = chunk.outro + lineStr;
819
+ }
820
+ if (chunk.content.length > 0) {
821
+ lineIndex = chunk.content.lastIndexOf(n);
822
+ if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
823
+ lineStr = chunk.content + lineStr;
824
+ }
825
+ if (chunk.intro.length > 0) {
826
+ lineIndex = chunk.intro.lastIndexOf(n);
827
+ if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
828
+ lineStr = chunk.intro + lineStr;
829
+ }
830
+ } while (chunk = chunk.previous);
831
+ lineIndex = this.intro.lastIndexOf(n);
832
+ if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
833
+ return this.intro + lineStr;
834
+ }
835
+ slice(start = 0, end = this.original.length - this.offset) {
836
+ start = start + this.offset;
837
+ end = end + this.offset;
838
+ if (this.original.length !== 0) {
839
+ while (start < 0) start += this.original.length;
840
+ while (end < 0) end += this.original.length;
841
+ }
842
+ let result = "";
843
+ let chunk = this.firstChunk;
844
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
845
+ if (chunk.start < end && chunk.end >= end) {
846
+ return result;
847
+ }
848
+ chunk = chunk.next;
849
+ }
850
+ if (chunk && chunk.edited && chunk.start !== start)
851
+ throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
852
+ const startChunk = chunk;
853
+ while (chunk) {
854
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
855
+ result += chunk.intro;
856
+ }
857
+ const containsEnd = chunk.start < end && chunk.end >= end;
858
+ if (containsEnd && chunk.edited && chunk.end !== end)
859
+ throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
860
+ const sliceStart = startChunk === chunk ? start - chunk.start : 0;
861
+ const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
862
+ result += chunk.content.slice(sliceStart, sliceEnd);
863
+ if (chunk.outro && (!containsEnd || chunk.end === end)) {
864
+ result += chunk.outro;
865
+ }
866
+ if (containsEnd) {
867
+ break;
868
+ }
869
+ chunk = chunk.next;
870
+ }
871
+ return result;
872
+ }
873
+ // TODO deprecate this? not really very useful
874
+ snip(start, end) {
875
+ const clone = this.clone();
876
+ clone.remove(0, start);
877
+ clone.remove(end, clone.original.length);
878
+ return clone;
879
+ }
880
+ _split(index) {
881
+ if (this.byStart[index] || this.byEnd[index]) return;
882
+ let chunk = this.lastSearchedChunk;
883
+ let previousChunk = chunk;
884
+ const searchForward = index > chunk.end;
885
+ while (chunk) {
886
+ if (chunk.contains(index)) return this._splitChunk(chunk, index);
887
+ chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
888
+ if (chunk === previousChunk) return;
889
+ previousChunk = chunk;
890
+ }
891
+ }
892
+ _splitChunk(chunk, index) {
893
+ if (chunk.edited && chunk.content.length) {
894
+ const loc = getLocator(this.original)(index);
895
+ throw new Error(
896
+ `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
897
+ );
898
+ }
899
+ const newChunk = chunk.split(index);
900
+ this.byEnd[index] = chunk;
901
+ this.byStart[index] = newChunk;
902
+ this.byEnd[newChunk.end] = newChunk;
903
+ if (chunk === this.lastChunk) this.lastChunk = newChunk;
904
+ this.lastSearchedChunk = chunk;
905
+ return true;
906
+ }
907
+ toString() {
908
+ let str = this.intro;
909
+ let chunk = this.firstChunk;
910
+ while (chunk) {
911
+ str += chunk.toString();
912
+ chunk = chunk.next;
913
+ }
914
+ return str + this.outro;
915
+ }
916
+ isEmpty() {
917
+ let chunk = this.firstChunk;
918
+ do {
919
+ if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
920
+ return false;
921
+ } while (chunk = chunk.next);
922
+ return true;
923
+ }
924
+ length() {
925
+ let chunk = this.firstChunk;
926
+ let length = 0;
927
+ do {
928
+ length += chunk.intro.length + chunk.content.length + chunk.outro.length;
929
+ } while (chunk = chunk.next);
930
+ return length;
931
+ }
932
+ trimLines() {
933
+ return this.trim("[\\r\\n]");
934
+ }
935
+ trim(charType) {
936
+ return this.trimStart(charType).trimEnd(charType);
937
+ }
938
+ trimEndAborted(charType) {
939
+ const rx = new RegExp((charType || "\\s") + "+$");
940
+ this.outro = this.outro.replace(rx, "");
941
+ if (this.outro.length) return true;
942
+ let chunk = this.lastChunk;
943
+ do {
944
+ const end = chunk.end;
945
+ const aborted = chunk.trimEnd(rx);
946
+ if (chunk.end !== end) {
947
+ if (this.lastChunk === chunk) {
948
+ this.lastChunk = chunk.next;
949
+ }
950
+ this.byEnd[chunk.end] = chunk;
951
+ this.byStart[chunk.next.start] = chunk.next;
952
+ this.byEnd[chunk.next.end] = chunk.next;
953
+ }
954
+ if (aborted) return true;
955
+ chunk = chunk.previous;
956
+ } while (chunk);
957
+ return false;
958
+ }
959
+ trimEnd(charType) {
960
+ this.trimEndAborted(charType);
961
+ return this;
962
+ }
963
+ trimStartAborted(charType) {
964
+ const rx = new RegExp("^" + (charType || "\\s") + "+");
965
+ this.intro = this.intro.replace(rx, "");
966
+ if (this.intro.length) return true;
967
+ let chunk = this.firstChunk;
968
+ do {
969
+ const end = chunk.end;
970
+ const aborted = chunk.trimStart(rx);
971
+ if (chunk.end !== end) {
972
+ if (chunk === this.lastChunk) this.lastChunk = chunk.next;
973
+ this.byEnd[chunk.end] = chunk;
974
+ this.byStart[chunk.next.start] = chunk.next;
975
+ this.byEnd[chunk.next.end] = chunk.next;
976
+ }
977
+ if (aborted) return true;
978
+ chunk = chunk.next;
979
+ } while (chunk);
980
+ return false;
981
+ }
982
+ trimStart(charType) {
983
+ this.trimStartAborted(charType);
984
+ return this;
985
+ }
986
+ hasChanged() {
987
+ return this.original !== this.toString();
988
+ }
989
+ _replaceRegexp(searchValue, replacement) {
990
+ function getReplacement(match, str) {
991
+ if (typeof replacement === "string") {
992
+ return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
993
+ if (i === "$") return "$";
994
+ if (i === "&") return match[0];
995
+ const num = +i;
996
+ if (num < match.length) return match[+i];
997
+ return `$${i}`;
998
+ });
999
+ } else {
1000
+ return replacement(...match, match.index, str, match.groups);
1001
+ }
1002
+ }
1003
+ function matchAll(re, str) {
1004
+ let match;
1005
+ const matches = [];
1006
+ while (match = re.exec(str)) {
1007
+ matches.push(match);
1008
+ }
1009
+ return matches;
1010
+ }
1011
+ if (searchValue.global) {
1012
+ const matches = matchAll(searchValue, this.original);
1013
+ matches.forEach((match) => {
1014
+ if (match.index != null) {
1015
+ const replacement2 = getReplacement(match, this.original);
1016
+ if (replacement2 !== match[0]) {
1017
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1018
+ }
1019
+ }
1020
+ });
1021
+ } else {
1022
+ const match = this.original.match(searchValue);
1023
+ if (match && match.index != null) {
1024
+ const replacement2 = getReplacement(match, this.original);
1025
+ if (replacement2 !== match[0]) {
1026
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1027
+ }
1028
+ }
1029
+ }
1030
+ return this;
1031
+ }
1032
+ _replaceString(string, replacement) {
1033
+ const { original } = this;
1034
+ const index = original.indexOf(string);
1035
+ if (index !== -1) {
1036
+ if (typeof replacement === "function") {
1037
+ replacement = replacement(string, index, original);
1038
+ }
1039
+ if (string !== replacement) {
1040
+ this.overwrite(index, index + string.length, replacement);
1041
+ }
1042
+ }
1043
+ return this;
1044
+ }
1045
+ replace(searchValue, replacement) {
1046
+ if (typeof searchValue === "string") {
1047
+ return this._replaceString(searchValue, replacement);
1048
+ }
1049
+ return this._replaceRegexp(searchValue, replacement);
1050
+ }
1051
+ _replaceAllString(string, replacement) {
1052
+ const { original } = this;
1053
+ const stringLength = string.length;
1054
+ for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1055
+ const previous = original.slice(index, index + stringLength);
1056
+ let _replacement = replacement;
1057
+ if (typeof replacement === "function") {
1058
+ _replacement = replacement(previous, index, original);
1059
+ }
1060
+ if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
1061
+ }
1062
+ return this;
1063
+ }
1064
+ replaceAll(searchValue, replacement) {
1065
+ if (typeof searchValue === "string") {
1066
+ return this._replaceAllString(searchValue, replacement);
1067
+ }
1068
+ if (!searchValue.global) {
1069
+ throw new TypeError(
1070
+ "MagicString.prototype.replaceAll called with a non-global RegExp argument"
1071
+ );
1072
+ }
1073
+ return this._replaceRegexp(searchValue, replacement);
1074
+ }
1075
+ };
1076
+
1077
+ // src/optimize/analyze-static.ts
1078
+ function propReason(prop) {
1079
+ switch (prop.kind) {
1080
+ case "event":
1081
+ return "event";
1082
+ case "ref":
1083
+ return "ref";
1084
+ case "spread":
1085
+ return "spread";
1086
+ case "class":
1087
+ case "style":
1088
+ return "class-or-style-directive";
1089
+ case "attr":
1090
+ case "prop":
1091
+ if (prop.reactive) return "reactive-prop";
1092
+ if (prop.expr !== void 0) return "expression-prop";
1093
+ return void 0;
1094
+ /* c8 ignore next 2 */
1095
+ default:
1096
+ return "expression-prop";
1097
+ }
1098
+ }
1099
+ function analyzeStatic(root) {
1100
+ const staticElements = [];
1101
+ const reasons = /* @__PURE__ */ new Map();
1102
+ const visit = (node) => {
1103
+ switch (node.kind) {
1104
+ case "text":
1105
+ return true;
1106
+ case "expr":
1107
+ return false;
1108
+ case "component":
1109
+ case "control":
1110
+ for (const child of node.children) visit(child);
1111
+ return false;
1112
+ case "fragment":
1113
+ for (const child of node.children) visit(child);
1114
+ return false;
1115
+ case "element": {
1116
+ let childrenStatic = true;
1117
+ for (const child of node.children) {
1118
+ if (!visit(child)) childrenStatic = false;
1119
+ }
1120
+ let reason;
1121
+ for (const prop of node.props) {
1122
+ reason = propReason(prop);
1123
+ if (reason) break;
1124
+ }
1125
+ if (!reason && !childrenStatic) {
1126
+ reason = childReason(node);
1127
+ }
1128
+ node.static = !reason;
1129
+ if (reason) reasons.set(node, reason);
1130
+ else staticElements.push(node);
1131
+ return node.static;
1132
+ }
1133
+ /* c8 ignore next 2 */
1134
+ default:
1135
+ return false;
1136
+ }
1137
+ };
1138
+ for (const node of Array.isArray(root) ? root : [root]) visit(node);
1139
+ return { staticElements, reasons };
1140
+ }
1141
+ function childReason(node) {
1142
+ for (const child of node.children) {
1143
+ if (child.kind === "expr") return "expression-child";
1144
+ if (child.kind === "component") return "component-child";
1145
+ if (child.kind === "control") return "control-child";
1146
+ if (child.kind === "element" && !child.static) return "expression-child";
1147
+ if (child.kind === "fragment") return "expression-child";
1148
+ }
1149
+ return "expression-child";
1150
+ }
1151
+
1152
+ // src/resolve/load-directive.ts
1153
+ var EAGER = { kind: "eager" };
1154
+ var DEFAULT_INTERACTION_EVENTS = ["pointerdown", "focusin", "keydown"];
1155
+ var STRATEGIES = /* @__PURE__ */ new Set(["eager", "idle", "visible", "interaction", "media", "never"]);
1156
+ var LoadDirectiveError = class extends Error {
1157
+ };
1158
+ function isLoadDirective(name) {
1159
+ return name.startsWith("load:");
1160
+ }
1161
+ function parseLoadDirective(name, value) {
1162
+ const strategy = name.slice("load:".length);
1163
+ if (!STRATEGIES.has(strategy)) {
1164
+ throw new LoadDirectiveError(
1165
+ `Unknown load strategy 'load:${strategy}'. Expected one of ${[...STRATEGIES].join(", ")}.`
1166
+ );
1167
+ }
1168
+ switch (strategy) {
1169
+ case "eager":
1170
+ return EAGER;
1171
+ case "idle":
1172
+ return { kind: "idle" };
1173
+ case "never":
1174
+ return { kind: "never" };
1175
+ case "visible":
1176
+ return value ? { kind: "visible", rootMargin: value } : { kind: "visible" };
1177
+ case "interaction":
1178
+ return {
1179
+ kind: "interaction",
1180
+ events: value ? splitEvents(value) : [...DEFAULT_INTERACTION_EVENTS]
1181
+ };
1182
+ case "media":
1183
+ if (!value) {
1184
+ throw new LoadDirectiveError(
1185
+ `'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`
1186
+ );
1187
+ }
1188
+ return { kind: "media", query: value };
1189
+ default:
1190
+ throw new LoadDirectiveError(`Unhandled load strategy '${strategy}'.`);
1191
+ }
1192
+ }
1193
+ function splitEvents(value) {
1194
+ const events = value.split(/[\s,]+/).map((e) => e.trim()).filter(Boolean);
1195
+ if (events.length === 0) {
1196
+ throw new LoadDirectiveError(`'load:interaction' was given no event names.`);
1197
+ }
1198
+ return events;
1199
+ }
1200
+ function isDeferred(strategy) {
1201
+ return strategy.kind !== "eager" && strategy.kind !== "never";
1202
+ }
1203
+
1204
+ // src/resolve/builtins.ts
1205
+ var DOM_CONTROL_FLOW = [
1206
+ "Show",
1207
+ "For",
1208
+ "Index",
1209
+ "Switch",
1210
+ "Match",
1211
+ "Portal",
1212
+ "Dynamic",
1213
+ "ErrorBoundary"
1214
+ ];
1215
+ var CORE_CONTROL_FLOW = ["Suspense", "SuspenseList", "Await"];
1216
+ var ROUTER_COMPONENTS = ["Router", "Outlet", "Redirect", "Link"];
1217
+ var BUILTIN_COMPONENTS = [
1218
+ ...DOM_CONTROL_FLOW,
1219
+ ...CORE_CONTROL_FLOW,
1220
+ ...ROUTER_COMPONENTS
1221
+ ];
1222
+ var RESERVED_COMPONENTS = /* @__PURE__ */ new Set([
1223
+ ...DOM_CONTROL_FLOW,
1224
+ ...CORE_CONTROL_FLOW
1225
+ ]);
1226
+ function builtinComponentMap(modules = {}) {
1227
+ const {
1228
+ controlFlowModule = "@fluixi/dom",
1229
+ coreModule = "@fluixi/core",
1230
+ routerModule = "@fluixi/core/router"
1231
+ } = modules;
1232
+ const map = {};
1233
+ for (const name of DOM_CONTROL_FLOW) map[name] = controlFlowModule;
1234
+ for (const name of CORE_CONTROL_FLOW) map[name] = coreModule;
1235
+ for (const name of ROUTER_COMPONENTS) map[name] = routerModule;
1236
+ return map;
1237
+ }
1238
+
1239
+ // src/resolve/resolve-ir.ts
1240
+ function resolveComponentSources(root, options = {}) {
1241
+ const { resolver, isBound, modules, strategyFor } = options;
1242
+ const builtins = builtinComponentMap(modules);
1243
+ const resolved = /* @__PURE__ */ new Map();
1244
+ const unresolved = /* @__PURE__ */ new Set();
1245
+ const annotate = (node) => {
1246
+ const { name } = node;
1247
+ if (!name || name.includes(".")) return;
1248
+ if (isBound?.(name)) return;
1249
+ const source = sourceFor(name);
1250
+ if (!source) {
1251
+ unresolved.add(name);
1252
+ return;
1253
+ }
1254
+ const loading = source.origin === "builtin" && RESERVED_COMPONENTS.has(name) ? EAGER : strategyFor?.(node) ?? EAGER;
1255
+ node.source = { ...source, loading };
1256
+ resolved.set(name, node.source);
1257
+ };
1258
+ const sourceFor = (name) => {
1259
+ if (RESERVED_COMPONENTS.has(name)) {
1260
+ return { module: builtins[name], export: name, origin: "builtin" };
1261
+ }
1262
+ const rule = resolver?.resolve(name);
1263
+ if (rule) return { module: rule.module, export: rule.export, origin: "rule" };
1264
+ if (ROUTER_COMPONENTS.includes(name)) {
1265
+ return { module: builtins[name], export: name, origin: "builtin" };
1266
+ }
1267
+ return void 0;
1268
+ };
1269
+ walk(root, (node) => {
1270
+ if (node.kind === "component") annotate(node);
1271
+ });
1272
+ return { resolved, unresolved: [...unresolved] };
1273
+ }
1274
+ function walk(root, visit) {
1275
+ const nodes = Array.isArray(root) ? root : [root];
1276
+ for (const node of nodes) {
1277
+ visit(node);
1278
+ const children = node.children;
1279
+ if (children) walk(children, visit);
1280
+ }
1281
+ }
1282
+
1283
+ // src/optimize/collapse-strategies.ts
1284
+ function collapseStrategies(root) {
1285
+ const components = [];
1286
+ walk(root, (node) => {
1287
+ if (node.kind === "component" && node.source) components.push(node);
1288
+ });
1289
+ const eager = /* @__PURE__ */ new Set();
1290
+ const never = /* @__PURE__ */ new Set();
1291
+ for (const node of components) {
1292
+ const { module, loading } = node.source;
1293
+ if (loading.kind === "eager") eager.add(module);
1294
+ if (loading.kind === "never") never.add(module);
1295
+ }
1296
+ const collapsed = /* @__PURE__ */ new Map();
1297
+ for (const node of components) {
1298
+ const source = node.source;
1299
+ if (!isDeferred(source.loading)) continue;
1300
+ if (!eager.has(source.module)) continue;
1301
+ source.loading = { kind: "eager" };
1302
+ collapsed.set(source.module, (collapsed.get(source.module) ?? 0) + 1);
1303
+ }
1304
+ return {
1305
+ collapsed,
1306
+ conflicted: [...never].filter((m) => eager.has(m))
1307
+ };
1308
+ }
1309
+
1310
+ // src/codegen/serialize-static.ts
1311
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
1312
+ "area",
1313
+ "base",
1314
+ "br",
1315
+ "col",
1316
+ "embed",
1317
+ "hr",
1318
+ "img",
1319
+ "input",
1320
+ "link",
1321
+ "meta",
1322
+ "param",
1323
+ "source",
1324
+ "track",
1325
+ "wbr"
1326
+ ]);
1327
+ var HTML_NAME = {
1328
+ className: "class",
1329
+ htmlFor: "for"
1330
+ };
1331
+ var PROPERTY_ONLY = /* @__PURE__ */ new Set([
1332
+ "innerHTML",
1333
+ "outerHTML",
1334
+ "innerText",
1335
+ "textContent",
1336
+ "value",
1337
+ "checked",
1338
+ "selected",
1339
+ "muted",
1340
+ "defaultValue",
1341
+ "defaultChecked",
1342
+ "children",
1343
+ "ref"
1344
+ ]);
1345
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
1346
+ function isRawTextElement(tag) {
1347
+ return RAW_TEXT_ELEMENTS.has(tag);
1348
+ }
1349
+ function htmlAttrName(name) {
1350
+ return HTML_NAME[name] ?? name;
1351
+ }
1352
+ function isPlainLiteralAttr(prop) {
1353
+ if (prop.kind !== "attr") return false;
1354
+ if (prop.expr !== void 0) return false;
1355
+ if (prop.name.includes(":")) return false;
1356
+ return !PROPERTY_ONLY.has(prop.name);
1357
+ }
1358
+ function isSerializable(node) {
1359
+ if (!node.static) return false;
1360
+ if (isRawTextElement(node.tag)) return false;
1361
+ for (const prop of node.props) {
1362
+ if (!isPlainLiteralAttr(prop)) return false;
1363
+ }
1364
+ for (const child of node.children) {
1365
+ if (child.kind === "text") continue;
1366
+ if (child.kind === "element" && isSerializable(child)) continue;
1367
+ return false;
1368
+ }
1369
+ return true;
1370
+ }
1371
+ function serializeStatic(node) {
1372
+ const attrs = node.props.map(serializeProp).filter(Boolean).join("");
1373
+ const open = `<${node.tag}${attrs}>`;
1374
+ if (VOID_ELEMENTS.has(node.tag)) return open;
1375
+ return `${open}${node.children.map(serializeChild).join("")}</${node.tag}>`;
1376
+ }
1377
+ function serializeChild(child) {
1378
+ if (child.kind === "text") return escapeText(child.value);
1379
+ if (child.kind !== "element") throw new Error(`serializeStatic: unexpected ${child.kind}`);
1380
+ return serializeStatic(child);
1381
+ }
1382
+ function serializeProp(prop) {
1383
+ const name = HTML_NAME[prop.name] ?? prop.name;
1384
+ const value = prop.literal;
1385
+ if (value === true || value === void 0) return ` ${name}`;
1386
+ if (value === false || value === null) return "";
1387
+ return ` ${name}="${escapeAttr(String(value))}"`;
1388
+ }
1389
+ function escapeAttr(value) {
1390
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1391
+ }
1392
+ function escapeText(value) {
1393
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1394
+ }
1395
+ function templatePositions(root) {
1396
+ const pos = [];
1397
+ let file;
1398
+ const walk8 = (el) => {
1399
+ file ??= el.at?.file;
1400
+ pos.push(el.at?.line ?? 0, el.at?.column ?? 0);
1401
+ for (const child of el.children) if (child.kind === "element") walk8(child);
1402
+ };
1403
+ walk8(root);
1404
+ return file && pos.some((n2) => n2 !== 0) ? { file, pos } : void 0;
1405
+ }
1406
+
1407
+ // src/codegen/partial-template.ts
1408
+ var HOLE_START = "<!--fx-->";
1409
+ var HOLE_END = "<!--fx/-->";
1410
+ function isHole(node) {
1411
+ return node.kind === "expr" || node.kind === "component" || node.kind === "control";
1412
+ }
1413
+ function isTemplateChild(node) {
1414
+ return node.kind === "text" || node.kind === "element" && isTemplateElement(node);
1415
+ }
1416
+ function isTemplateElement(node) {
1417
+ if (node.svg) return false;
1418
+ if (isRawTextElement(node.tag)) return false;
1419
+ if (!node.props.every((p) => isPlainLiteralAttr(p))) return false;
1420
+ return node.children.every((c) => isTemplateChild(c) || isHole(c));
1421
+ }
1422
+ function containsHole(node) {
1423
+ if (isHole(node)) return true;
1424
+ const children = node.children;
1425
+ return children ? children.some(containsHole) : false;
1426
+ }
1427
+ function addressable(el) {
1428
+ for (let i = 0; i < el.children.length; i++) {
1429
+ const child = el.children[i];
1430
+ if (child.kind === "text") {
1431
+ if (child.value === "") return false;
1432
+ if (el.children[i + 1]?.kind === "text") return false;
1433
+ }
1434
+ }
1435
+ return el.children.every((c) => c.kind !== "element" || addressable(c));
1436
+ }
1437
+ function planPartialTemplate(root) {
1438
+ if (!isTemplateElement(root)) return null;
1439
+ if (!addressable(root)) return null;
1440
+ if (!root.children.some(containsHole)) return null;
1441
+ const steps = [];
1442
+ const holes = [];
1443
+ let refCount = 0;
1444
+ const declare = (expr) => {
1445
+ const ref = `_n$${refCount++}`;
1446
+ steps.push({ ref, expr });
1447
+ return ref;
1448
+ };
1449
+ walk8(root, "_el$");
1450
+ return { html: serializeWithMarkers(root), tag: root.tag, steps, holes };
1451
+ function walk8(el, elementRef) {
1452
+ let last = -1;
1453
+ el.children.forEach((child, i) => {
1454
+ if (containsHole(child)) last = i;
1455
+ });
1456
+ let previous = null;
1457
+ for (let i = 0; i <= last; i++) {
1458
+ const child = el.children[i];
1459
+ const expr = previous ? `${previous}.nextSibling` : `${elementRef}.firstChild`;
1460
+ if (isHole(child)) {
1461
+ const startRef = declare(expr);
1462
+ const endRef = declare(`holeEnd(${startRef})`);
1463
+ holes.push({ parentRef: elementRef, startRef, endRef, node: child });
1464
+ previous = endRef;
1465
+ continue;
1466
+ }
1467
+ const ref = declare(expr);
1468
+ if (child.kind === "element" && containsHole(child)) walk8(child, ref);
1469
+ previous = ref;
1470
+ }
1471
+ }
1472
+ }
1473
+ function serializeWithMarkers(el) {
1474
+ return serializeStatic(withSentinels(el)).split(SENTINEL).join(HOLE_START + HOLE_END);
1475
+ }
1476
+ function withSentinels(el) {
1477
+ return {
1478
+ ...el,
1479
+ children: el.children.map(
1480
+ (child) => isHole(child) ? { kind: "text", value: SENTINEL } : child.kind === "element" ? withSentinels(child) : child
1481
+ )
1482
+ };
1483
+ }
1484
+ var SENTINEL = "\0fx-hole\0";
1485
+
1486
+ // src/codegen/contract.ts
1487
+ var RUNTIME_CONTRACT_V1 = {
1488
+ version: 1,
1489
+ module: "@fluixi/dom",
1490
+ symbols: [
1491
+ "createNativeElement",
1492
+ "insert",
1493
+ "spread",
1494
+ "setAttribute",
1495
+ "delegateEvents",
1496
+ "createComponent",
1497
+ "createMemo",
1498
+ "untrack",
1499
+ "Show",
1500
+ "For",
1501
+ "Index",
1502
+ "Switch",
1503
+ "Match",
1504
+ "Dynamic",
1505
+ "ErrorBoundary"
1506
+ ]
1507
+ };
1508
+ var RUNTIME_CONTRACT_V2 = {
1509
+ version: 2,
1510
+ module: "@fluixi/dom",
1511
+ symbols: [...RUNTIME_CONTRACT_V1.symbols, "template", "cloneTemplate", "walk"]
1512
+ };
1513
+
1514
+ // src/analyze/intrinsics.ts
1515
+ var REACTIVE_MODULE = "@fluixi/reactive/signal";
1516
+ var INTRINSICS = {
1517
+ $signal: { export: "signal", module: REACTIVE_MODULE, returns: "signal-handle" },
1518
+ $memo: { export: "memo", module: REACTIVE_MODULE, returns: "memo-handle" },
1519
+ $effect: { export: "effect", module: REACTIVE_MODULE, returns: "effect" },
1520
+ $store: { export: "store", module: "@fluixi/reactive/store", returns: "store-handle" },
1521
+ $resource: { export: "resource", module: REACTIVE_MODULE, returns: "resource-handle" },
1522
+ // No short runtime form for these yet, so the intrinsic stands for the `create*`
1523
+ // name. Still worth having: no import to write, and when a shorter form is
1524
+ // designed, the change is this line rather than a compiler pass.
1525
+ $selector: { export: "createSelector", module: REACTIVE_MODULE, returns: "memo-accessor" },
1526
+ $deferred: { export: "createDeferred", module: REACTIVE_MODULE, returns: "memo-accessor" },
1527
+ // Not value constructors, but the compiler has to know them: they change what a read
1528
+ // does. `untrack` suppresses dependency collection, which is exactly the kind of thing
1529
+ // dependency analysis must not guess at.
1530
+ $untrack: { export: "untrack", module: REACTIVE_MODULE, returns: "plain" },
1531
+ $untrackStore: { export: "untrackStore", module: "@fluixi/reactive/store", returns: "plain" }
1532
+ };
1533
+ var RUNTIME_PRIMITIVES = {
1534
+ signal: "signal-handle",
1535
+ memo: "memo-handle",
1536
+ effect: "effect",
1537
+ store: "store-handle",
1538
+ createSignal: ["signal-accessor", "signal-setter"],
1539
+ createMemo: "memo-accessor",
1540
+ createEffect: "effect",
1541
+ createRenderEffect: "effect",
1542
+ createStore: "reactive-object",
1543
+ resource: "resource-handle",
1544
+ createResource: "reactive-object",
1545
+ createSelector: "memo-accessor",
1546
+ createDeferred: "memo-accessor"
1547
+ };
1548
+ var PRIMITIVE_MODULES = [
1549
+ "@fluixi/reactive",
1550
+ "@fluixi/reactive/signal",
1551
+ "@fluixi/reactive/store",
1552
+ "@fluixi/core"
1553
+ ];
1554
+ var INTRINSIC_CALL = new RegExp(`\\$(?:${Object.keys(INTRINSICS).map((n2) => n2.slice(1)).join("|")})\\s*\\(`);
1555
+ function mayHaveIntrinsic(code) {
1556
+ return INTRINSIC_CALL.test(code);
1557
+ }
1558
+ function isIntrinsicName(name) {
1559
+ return Object.prototype.hasOwnProperty.call(INTRINSICS, name);
1560
+ }
1561
+ function isPrimitiveModule(source) {
1562
+ return PRIMITIVE_MODULES.includes(source);
1563
+ }
1564
+
1565
+ // src/analyze/reactive-bindings.ts
1566
+ function patternNames(node, out) {
1567
+ if (!node) return;
1568
+ switch (node.type) {
1569
+ case "Identifier":
1570
+ out.add(node.name);
1571
+ return;
1572
+ case "ObjectPattern":
1573
+ for (const p of node.properties ?? []) {
1574
+ if (p.type === "RestElement") patternNames(p.argument, out);
1575
+ else patternNames(p.value, out);
1576
+ }
1577
+ return;
1578
+ case "ArrayPattern":
1579
+ for (const e of node.elements ?? []) patternNames(e, out);
1580
+ return;
1581
+ case "AssignmentPattern":
1582
+ patternNames(node.left, out);
1583
+ return;
1584
+ case "RestElement":
1585
+ patternNames(node.argument, out);
1586
+ return;
1587
+ }
1588
+ }
1589
+ function walk2(root, visit) {
1590
+ if (!root || typeof root !== "object" || typeof root.type !== "string") return;
1591
+ visit(root);
1592
+ for (const key of Object.keys(root)) {
1593
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
1594
+ const value = root[key];
1595
+ if (Array.isArray(value)) for (const item of value) walk2(item, visit);
1596
+ else if (value && typeof value === "object") walk2(value, visit);
1597
+ }
1598
+ }
1599
+ function calledPrimitive(node, bindings) {
1600
+ if (node.type !== "CallExpression") return void 0;
1601
+ const callee = node.callee;
1602
+ if (callee?.type !== "Identifier") return void 0;
1603
+ const name = callee.name;
1604
+ const imported = bindings.primitives.get(name);
1605
+ if (imported) return imported;
1606
+ const intrinsic = INTRINSICS[name];
1607
+ if (intrinsic && !bindings.shadowed.has(name)) return intrinsic.returns;
1608
+ return void 0;
1609
+ }
1610
+ function classify(id, returns, kinds) {
1611
+ if (Array.isArray(returns)) {
1612
+ if (id.type === "ArrayPattern") {
1613
+ id.elements.forEach((element, index) => {
1614
+ const kind = returns[index];
1615
+ if (element?.type === "Identifier" && kind) kinds.set(element.name, kind);
1616
+ });
1617
+ }
1618
+ return;
1619
+ }
1620
+ if (id.type === "Identifier") kinds.set(id.name, returns);
1621
+ }
1622
+ function declaredNames(program) {
1623
+ const names = /* @__PURE__ */ new Set();
1624
+ walk2(program, (node) => {
1625
+ switch (node.type) {
1626
+ case "VariableDeclarator":
1627
+ patternNames(node.id, names);
1628
+ return;
1629
+ case "FunctionDeclaration":
1630
+ case "FunctionExpression":
1631
+ case "ArrowFunctionExpression":
1632
+ patternNames(node.id, names);
1633
+ for (const p of node.params ?? []) patternNames(p, names);
1634
+ return;
1635
+ case "ClassDeclaration":
1636
+ case "ClassExpression":
1637
+ patternNames(node.id, names);
1638
+ return;
1639
+ case "ImportSpecifier":
1640
+ case "ImportDefaultSpecifier":
1641
+ case "ImportNamespaceSpecifier":
1642
+ patternNames(node.local, names);
1643
+ return;
1644
+ case "CatchClause":
1645
+ patternNames(node.param, names);
1646
+ return;
1647
+ }
1648
+ });
1649
+ return names;
1650
+ }
1651
+ function resolveReactiveBindings(program) {
1652
+ const bindings = { kinds: /* @__PURE__ */ new Map(), primitives: /* @__PURE__ */ new Map(), shadowed: /* @__PURE__ */ new Set() };
1653
+ const root = program;
1654
+ walk2(root, (node) => {
1655
+ const names = /* @__PURE__ */ new Set();
1656
+ if (node.type === "VariableDeclarator") patternNames(node.id, names);
1657
+ else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") patternNames(node.id, names);
1658
+ else if (node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") patternNames(node.local, names);
1659
+ else if (node.type === "ImportSpecifier") patternNames(node.local, names);
1660
+ else if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration") {
1661
+ for (const p of node.params ?? []) patternNames(p, names);
1662
+ }
1663
+ for (const name of names) if (INTRINSICS[name]) bindings.shadowed.add(name);
1664
+ });
1665
+ for (const statement of root.body ?? []) {
1666
+ if (statement.type !== "ImportDeclaration") continue;
1667
+ if (!isPrimitiveModule(statement.source?.value)) continue;
1668
+ for (const specifier of statement.specifiers ?? []) {
1669
+ if (specifier.type !== "ImportSpecifier") continue;
1670
+ const importedNode = specifier.imported;
1671
+ const imported = importedNode.type === "Identifier" ? importedNode.name : importedNode.value;
1672
+ const returns = RUNTIME_PRIMITIVES[imported];
1673
+ if (returns) bindings.primitives.set(specifier.local.name, returns);
1674
+ }
1675
+ }
1676
+ walk2(root, (node) => {
1677
+ if (node.type !== "VariableDeclarator" || !node.init) return;
1678
+ const returns = calledPrimitive(node.init, bindings);
1679
+ if (returns) classify(node.id, returns, bindings.kinds);
1680
+ });
1681
+ return bindings;
1682
+ }
1683
+
1684
+ // src/transform/source-locations.ts
1685
+ var SOURCE_MARKER = "__fx_source";
1686
+ var COMPONENT_MARKER = "__fx_component";
1687
+ var HOLE_MARKER = "__fx_hole";
1688
+ var markHole = (accessor, line, column, name) => `(globalThis.${HOLE_MARKER} ?? ((f) => f))(${accessor},${line},${column}${name === void 0 ? "" : `,${JSON.stringify(name)}`})`;
1689
+ var PROPS_MARKER = "__fx_props";
1690
+ var markProps = (object, at) => `(globalThis.${PROPS_MARKER} ?? ((p) => p))(${object},${JSON.stringify(at)})`;
1691
+ var RUNTIME_PRIMITIVES2 = /* @__PURE__ */ new Set([
1692
+ "signal",
1693
+ "memo",
1694
+ "effect",
1695
+ "store",
1696
+ "resource",
1697
+ "watch",
1698
+ "createSignal",
1699
+ "createMemo",
1700
+ "createEffect",
1701
+ "createStore",
1702
+ "createResource"
1703
+ ]);
1704
+ function mayHaveReactiveCall(code) {
1705
+ for (const name of RUNTIME_PRIMITIVES2) {
1706
+ if (code.includes(name)) return true;
1707
+ }
1708
+ return code.includes("$signal") || code.includes("$memo") || code.includes("$effect") || code.includes("$store");
1709
+ }
1710
+ var SINGLE_STATEMENT_PARENTS = /* @__PURE__ */ new Set([
1711
+ "IfStatement",
1712
+ "ForStatement",
1713
+ "ForInStatement",
1714
+ "ForOfStatement",
1715
+ "WhileStatement",
1716
+ "DoWhileStatement",
1717
+ "LabeledStatement",
1718
+ "WithStatement"
1719
+ ]);
1720
+ function isLoneBranch(statement, parent) {
1721
+ if (!parent || statement.type === "BlockStatement") return false;
1722
+ return SINGLE_STATEMENT_PARENTS.has(parent.type);
1723
+ }
1724
+ function isExport(node) {
1725
+ return node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration";
1726
+ }
1727
+ function isStatement(node) {
1728
+ return node.type.endsWith("Statement") || node.type === "VariableDeclaration";
1729
+ }
1730
+ function walk3(node, visit, stack = []) {
1731
+ if (!node || typeof node.type !== "string") return;
1732
+ visit(node, stack);
1733
+ stack.push(node);
1734
+ for (const key of Object.keys(node)) {
1735
+ if (key === "loc" || key === "parent") continue;
1736
+ const value = node[key];
1737
+ if (Array.isArray(value)) {
1738
+ for (const child of value) walk3(child, visit, stack);
1739
+ } else if (value && typeof value.type === "string") {
1740
+ walk3(value, visit, stack);
1741
+ }
1742
+ }
1743
+ stack.pop();
1744
+ }
1745
+ function nameFor(stack) {
1746
+ const declarator = stack[stack.length - 1];
1747
+ if (declarator?.type !== "VariableDeclarator") return void 0;
1748
+ const id = declarator.id;
1749
+ if (id?.type === "Identifier") return id.name;
1750
+ if (id?.type === "ArrayPattern") {
1751
+ const first = id.elements?.[0];
1752
+ if (first?.type === "Identifier") return first.name;
1753
+ }
1754
+ return void 0;
1755
+ }
1756
+ function componentName(node) {
1757
+ if (node.type === "FunctionDeclaration") {
1758
+ const name = node.id?.name;
1759
+ return name && name[0] === name[0]?.toUpperCase() ? name : void 0;
1760
+ }
1761
+ if (node.type === "VariableDeclarator") {
1762
+ const id = node.id;
1763
+ const init = node.init;
1764
+ if (id?.type !== "Identifier" || !init) return void 0;
1765
+ if (init.type !== "ArrowFunctionExpression" && init.type !== "FunctionExpression") return void 0;
1766
+ const name = id.name;
1767
+ return name[0] === name[0]?.toUpperCase() ? name : void 0;
1768
+ }
1769
+ return void 0;
1770
+ }
1771
+ function collectSourceEdits(program, filename) {
1772
+ const edits = [];
1773
+ const claimed = /* @__PURE__ */ new Set();
1774
+ const { primitives, shadowed } = resolveReactiveBindings(program);
1775
+ walk3(program, (node, stack) => {
1776
+ const component = componentName(node);
1777
+ if (component) {
1778
+ const at = node.loc?.start;
1779
+ let end2 = node.end;
1780
+ for (let i = stack.length - 1; i >= 0; i--) {
1781
+ const up = stack[i];
1782
+ if (up.type !== "VariableDeclaration" && up.type !== "ExportNamedDeclaration" && up.type !== "ExportDefaultDeclaration") {
1783
+ break;
1784
+ }
1785
+ end2 = up.end;
1786
+ }
1787
+ if (at) {
1788
+ edits.push({
1789
+ start: end2,
1790
+ end: end2,
1791
+ code: `;globalThis.${COMPONENT_MARKER}?.(${JSON.stringify(component)},${JSON.stringify(filename)},${at.line},${at.column});`
1792
+ });
1793
+ }
1794
+ }
1795
+ if (node.type !== "CallExpression") return;
1796
+ const callee = node.callee;
1797
+ if (callee?.type !== "Identifier") return;
1798
+ const name = callee.name;
1799
+ const intrinsic = isIntrinsicName(name) && !shadowed.has(name) ? INTRINSICS[name] : void 0;
1800
+ const imported = primitives.has(name) || RUNTIME_PRIMITIVES2.has(name);
1801
+ if (!intrinsic && !imported) return;
1802
+ const position = node.loc?.start;
1803
+ if (!position) return;
1804
+ let statement;
1805
+ let parent;
1806
+ let index = -1;
1807
+ for (let i = stack.length - 1; i >= 0; i--) {
1808
+ if (isStatement(stack[i]) || isExport(stack[i])) {
1809
+ statement = stack[i];
1810
+ parent = stack[i - 1];
1811
+ index = i;
1812
+ break;
1813
+ }
1814
+ }
1815
+ if (!statement) return;
1816
+ let start = statement.start;
1817
+ let end = statement.end;
1818
+ for (let i = index - 1; i >= 0; i--) {
1819
+ if (!isExport(stack[i])) break;
1820
+ start = stack[i].start;
1821
+ end = stack[i].end;
1822
+ parent = stack[i - 1];
1823
+ }
1824
+ if (claimed.has(start)) return;
1825
+ claimed.add(start);
1826
+ const label = nameFor(stack);
1827
+ const args = [
1828
+ JSON.stringify(filename),
1829
+ String(position.line),
1830
+ String(position.column),
1831
+ label ? JSON.stringify(label) : void 0
1832
+ ].filter((a) => a !== void 0).join(",");
1833
+ const mark = `globalThis.${SOURCE_MARKER}?.(${args});`;
1834
+ if (isLoneBranch(statement, parent)) {
1835
+ edits.push({ start, end: start, code: `{${mark}` });
1836
+ edits.push({ start: end, end, code: "}" });
1837
+ return;
1838
+ }
1839
+ edits.push({ start, end: start, code: mark });
1840
+ });
1841
+ return { edits, marked: edits.length };
1842
+ }
1843
+
1844
+ // src/analyze/paren.ts
1845
+ function skipQuoted(src, start) {
1846
+ const quote = src[start];
1847
+ for (let i = start + 1; i < src.length; i++) {
1848
+ const c = src[i];
1849
+ if (c === "\\") i++;
1850
+ else if (c === quote) return i + 1;
1851
+ else if (c === "\n") return -1;
1852
+ }
1853
+ return -1;
1854
+ }
1855
+ function skipTemplate(src, start) {
1856
+ let i = start + 1;
1857
+ while (i < src.length) {
1858
+ const c = src[i];
1859
+ if (c === "\\") {
1860
+ i += 2;
1861
+ } else if (c === "`") {
1862
+ return i + 1;
1863
+ } else if (c === "$" && src[i + 1] === "{") {
1864
+ let depth = 1;
1865
+ i += 2;
1866
+ while (i < src.length && depth > 0) {
1867
+ const k = src[i];
1868
+ if (k === "\\") i += 2;
1869
+ else if (k === "`") {
1870
+ const end = skipTemplate(src, i);
1871
+ if (end < 0) return -1;
1872
+ i = end;
1873
+ } else if (k === '"' || k === "'") {
1874
+ const end = skipQuoted(src, i);
1875
+ if (end < 0) return -1;
1876
+ i = end;
1877
+ } else {
1878
+ if (k === "{") depth++;
1879
+ else if (k === "}") depth--;
1880
+ i++;
1881
+ }
1882
+ }
1883
+ } else {
1884
+ i++;
1885
+ }
1886
+ }
1887
+ return -1;
1888
+ }
1889
+ function skipRegex(src, start) {
1890
+ let inClass = false;
1891
+ for (let i = start + 1; i < src.length; i++) {
1892
+ const c = src[i];
1893
+ if (c === "\\") i++;
1894
+ else if (c === "[") inClass = true;
1895
+ else if (c === "]") inClass = false;
1896
+ else if (c === "\n") return -1;
1897
+ else if (c === "/" && !inClass) {
1898
+ let end = i + 1;
1899
+ while (end < src.length && /[a-z]/i.test(src[end])) end++;
1900
+ return end;
1901
+ }
1902
+ }
1903
+ return -1;
1904
+ }
1905
+ function divides(prev) {
1906
+ return prev !== "" && /[A-Za-z0-9_$)\]]/.test(prev);
1907
+ }
1908
+ function topLevelComma(src) {
1909
+ let depth = 0;
1910
+ let prev = "";
1911
+ let i = 0;
1912
+ while (i < src.length) {
1913
+ const c = src[i];
1914
+ if (c === '"' || c === "'") {
1915
+ const end = skipQuoted(src, i);
1916
+ if (end < 0) return null;
1917
+ i = end;
1918
+ prev = c;
1919
+ } else if (c === "`") {
1920
+ const end = skipTemplate(src, i);
1921
+ if (end < 0) return null;
1922
+ i = end;
1923
+ prev = c;
1924
+ } else if (c === "/" && src[i + 1] === "/") {
1925
+ return null;
1926
+ } else if (c === "/" && src[i + 1] === "*") {
1927
+ const end = src.indexOf("*/", i + 2);
1928
+ if (end < 0) return null;
1929
+ i = end + 2;
1930
+ } else if (c === "/" && !divides(prev)) {
1931
+ const end = skipRegex(src, i);
1932
+ if (end < 0) return null;
1933
+ i = end;
1934
+ prev = "/";
1935
+ } else {
1936
+ if (c === "(" || c === "[" || c === "{") depth++;
1937
+ else if (c === ")" || c === "]" || c === "}") {
1938
+ depth--;
1939
+ if (depth < 0) return null;
1940
+ } else if (c === "," && depth === 0) return true;
1941
+ if (!/\s/.test(c)) prev = c;
1942
+ i++;
1943
+ }
1944
+ }
1945
+ return depth === 0 ? false : null;
1946
+ }
1947
+ function paren(code, position) {
1948
+ const src = code.trim();
1949
+ if (src === "") return `(${code})`;
1950
+ if (position === "arrowBody" && src[0] === "{") return `(${code})`;
1951
+ return topLevelComma(src) === false ? code : `(${code})`;
1952
+ }
1953
+
1954
+ // src/codegen/backends/imperative.ts
1955
+ var CONTROL_COMPONENT = {
1956
+ show: "Show",
1957
+ for: "For",
1958
+ index: "Index",
1959
+ switch: "Switch",
1960
+ match: "Match",
1961
+ dynamic: "Dynamic",
1962
+ errorBoundary: "ErrorBoundary",
1963
+ suspense: "Suspense"
1964
+ };
1965
+ function isIdent(name) {
1966
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
1967
+ }
1968
+ function propKey(name) {
1969
+ return isIdent(name) ? name : JSON.stringify(name);
1970
+ }
1971
+ function propValue(p) {
1972
+ if (p.expr !== void 0) {
1973
+ if (p.name === "ref" && p.at)
1974
+ return markHole(paren(p.expr, "value"), p.at.line, p.at.column, p.expr);
1975
+ if (!p.reactive) return paren(p.expr, "value");
1976
+ const accessor = `() => ${paren(p.expr, "arrowBody")}`;
1977
+ return p.at ? markHole(accessor, p.at.line, p.at.column, p.directive) : accessor;
1978
+ }
1979
+ return JSON.stringify(p.literal ?? true);
1980
+ }
1981
+ function componentPropValue(p) {
1982
+ if (p.expr !== void 0) return paren(p.expr, "value");
1983
+ return JSON.stringify(p.literal ?? true);
1984
+ }
1985
+ function emitProps(props, childrenExpr, used) {
1986
+ const spreads = props.filter((p) => p.kind === "spread");
1987
+ const normal = props.filter((p) => p.kind !== "spread");
1988
+ const entries = normal.map((p) => `${propKey(p.name)}: ${propValue(p)}`);
1989
+ if (childrenExpr != null) entries.push(`children: ${childrenExpr}`);
1990
+ const obj = `{ ${entries.join(", ")} }`;
1991
+ if (spreads.length > 0) {
1992
+ used.add("mergeProps");
1993
+ return `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
1994
+ }
1995
+ return obj;
1996
+ }
1997
+ function markBind(code, at) {
1998
+ return at ? markHole(code, at.line, at.column) : code;
1999
+ }
2000
+ function emitChildren(children, used, templates) {
2001
+ if (children.length === 1) return emitNode(children[0], used, templates);
2002
+ return `[${children.map((c) => emitNode(c, used, templates)).join(", ")}]`;
2003
+ }
2004
+ function emitComponent(name, props, children, used, templates, at) {
2005
+ used.add("createMemo");
2006
+ used.add("createComponent");
2007
+ const spreads = props.filter((p) => p.kind === "spread");
2008
+ const normal = props.filter((p) => p.kind !== "spread");
2009
+ const entries = normal.map(
2010
+ (p) => `get ${propKey(p.name)}() { return ${componentPropValue(p)}; }`
2011
+ );
2012
+ if (children.length > 0) {
2013
+ entries.push(`get children() { return ${emitChildren(children, used, templates)}; }`);
2014
+ }
2015
+ let obj = `{ ${entries.join(", ")} }`;
2016
+ if (spreads.length > 0) {
2017
+ used.add("mergeProps");
2018
+ obj = `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
2019
+ }
2020
+ const propAt = {};
2021
+ for (const p of normal) if (p.at) propAt[p.name] = [p.at.line, p.at.column];
2022
+ if (Object.keys(propAt).length) obj = markProps(obj, propAt);
2023
+ const mark = at ? `globalThis.${SOURCE_MARKER}?.(${JSON.stringify(at.file)},${at.line},${at.column},${JSON.stringify(name)}), ` : "";
2024
+ return `createMemo(${paren(`${mark}() => createComponent(${name}, ${obj})`, "value")})`;
2025
+ }
2026
+ function staticAttrAssignment(el, prop) {
2027
+ const name = htmlAttrName(prop.name);
2028
+ const value = prop.literal;
2029
+ if (value === true || value === void 0) return `${el}.setAttribute(${JSON.stringify(name)}, "");`;
2030
+ if (value === false || value === null) return "";
2031
+ return `${el}.setAttribute(${JSON.stringify(name)}, ${JSON.stringify(String(value))});`;
2032
+ }
2033
+ var partial = false;
2034
+ function emitNode(node, used, templates) {
2035
+ switch (node.kind) {
2036
+ case "text":
2037
+ return JSON.stringify(node.value);
2038
+ case "expr": {
2039
+ if (!node.reactive) return paren(node.code, "value");
2040
+ const accessor = `() => ${paren(node.code, "arrowBody")}`;
2041
+ return node.at ? markHole(accessor, node.at.line, node.at.column) : accessor;
2042
+ }
2043
+ case "fragment":
2044
+ if (node.children.length === 0) return "null";
2045
+ return emitChildren(node.children, used, templates);
2046
+ case "component":
2047
+ return markBind(emitComponent(node.name, node.props, node.children, used, templates, node.at), node.bindAt ?? node.at);
2048
+ case "control": {
2049
+ const name = CONTROL_COMPONENT[node.control] ?? node.control;
2050
+ used.add(name);
2051
+ return markBind(emitComponent(name, node.props, node.children, used, templates), node.bindAt);
2052
+ }
2053
+ case "element": {
2054
+ if (templates && node.static && !node.svg && isSerializable(node)) {
2055
+ used.add("templateNode");
2056
+ const id = `_tmpl$${templates.length}`;
2057
+ templates.push({ id, html: serializeStatic(node), tag: node.tag, svg: false });
2058
+ const at = templatePositions(node);
2059
+ return at ? `templateNode(${id}, ${JSON.stringify(node.tag)}, false, false, ${JSON.stringify(at)})` : `templateNode(${id}, ${JSON.stringify(node.tag)})`;
2060
+ }
2061
+ if (templates && partial) {
2062
+ const plan = planPartialTemplate(node);
2063
+ if (plan) {
2064
+ used.add("templateNode");
2065
+ used.add("insert");
2066
+ used.add("holeEnd");
2067
+ used.add("holeContent");
2068
+ used.add("holeScope");
2069
+ const id = `_tmpl$${templates.length}`;
2070
+ templates.push({ id, html: plan.html, tag: plan.tag, svg: false });
2071
+ const at = templatePositions(node);
2072
+ const lines = [
2073
+ `const _el$ = templateNode(${id}, ${JSON.stringify(plan.tag)}, true${at ? `, false, ${JSON.stringify(at)}` : ""});`
2074
+ ];
2075
+ for (const step of plan.steps) lines.push(`const ${step.ref} = ${step.expr};`);
2076
+ for (const hole of plan.holes) {
2077
+ lines.push(
2078
+ `insert(${hole.parentRef}, holeScope(${hole.startRef}, () => ${paren(emitNode(hole.node, used, templates), "arrowBody")}), ${hole.endRef}, holeContent(${hole.startRef}, ${hole.endRef}));`
2079
+ );
2080
+ }
2081
+ lines.push("return _el$;");
2082
+ return `(() => { ${lines.join(" ")} })()`;
2083
+ }
2084
+ }
2085
+ used.add("createNativeElement");
2086
+ const tag = JSON.stringify(node.tag);
2087
+ const el = "_el$";
2088
+ const parts = [];
2089
+ const createArgs = node.at ? `${tag}, ${node.svg}, ${JSON.stringify(node.at)}` : node.svg ? `${tag}, true` : tag;
2090
+ parts.push(`const ${el} = createNativeElement(${createArgs});`);
2091
+ if (node.props.length > 0) {
2092
+ if (!node.svg && node.props.every(isPlainLiteralAttr)) {
2093
+ for (const p of node.props) parts.push(staticAttrAssignment(el, p));
2094
+ } else {
2095
+ used.add("spread");
2096
+ const svgFlag = node.svg ? ", isSVG: true" : "";
2097
+ parts.push(`spread({ element: ${el}, props: ${emitProps(node.props, null, used)}${svgFlag} });`);
2098
+ }
2099
+ }
2100
+ for (const child of node.children) {
2101
+ used.add("insert");
2102
+ const childCode = emitNode(child, used, templates);
2103
+ const isFn = child.kind === "expr" && child.reactive || child.kind === "component" || child.kind === "control";
2104
+ parts.push(isFn ? `insert(${el}, ${childCode}, null);` : `insert(${el}, ${childCode});`);
2105
+ }
2106
+ parts.push(`return ${el};`);
2107
+ return `(() => { ${parts.join(" ")} })()`;
2108
+ }
2109
+ }
2110
+ }
2111
+ function inlineTemplates(code, templates) {
2112
+ if (!templates || templates.length === 0) return code;
2113
+ const byId = new Map(templates.map((t) => [t.id, JSON.stringify(t.html)]));
2114
+ return code.replace(/_tmpl\$\d+/g, (id) => byId.get(id) ?? id);
2115
+ }
2116
+ var imperativeBackend = {
2117
+ name: "imperative",
2118
+ contract: RUNTIME_CONTRACT_V1,
2119
+ emit(node, options) {
2120
+ const used = /* @__PURE__ */ new Set();
2121
+ const templates = options?.templateClone !== false ? [] : void 0;
2122
+ partial = options?.partialTemplates === true;
2123
+ const code = emitNode(node, used, templates);
2124
+ return { code, imports: Array.from(used), templates };
2125
+ }
2126
+ };
2127
+
2128
+ // src/resolve/component-resolver.ts
2129
+ var isMapRule = (rule) => "components" in rule;
2130
+ function substitute(template, match) {
2131
+ return template.replace(/\$(\d+)/g, (whole, index) => {
2132
+ const group = match[Number(index)];
2133
+ return group ?? whole;
2134
+ });
2135
+ }
2136
+ function normalise(name, entry) {
2137
+ return typeof entry === "string" ? { module: entry, export: name } : entry;
2138
+ }
2139
+ function createComponentResolver(rules = []) {
2140
+ const exact = /* @__PURE__ */ new Map();
2141
+ const conflicts = [];
2142
+ const patterns = [];
2143
+ for (const rule of rules) {
2144
+ if (!isMapRule(rule)) {
2145
+ patterns.push(rule);
2146
+ continue;
2147
+ }
2148
+ for (const [name, entry] of Object.entries(rule.components)) {
2149
+ const resolved = normalise(name, entry);
2150
+ const existing = exact.get(name);
2151
+ if (existing && existing.module !== resolved.module) {
2152
+ const conflict = conflicts.find((c) => c.name === name);
2153
+ if (conflict) conflict.modules.push(resolved.module);
2154
+ else conflicts.push({ name, modules: [existing.module, resolved.module] });
2155
+ continue;
2156
+ }
2157
+ exact.set(name, resolved);
2158
+ }
2159
+ }
2160
+ const cache = /* @__PURE__ */ new Map();
2161
+ const resolve = (name) => {
2162
+ if (cache.has(name)) return cache.get(name);
2163
+ let result = exact.get(name);
2164
+ if (!result) {
2165
+ for (const rule of patterns) {
2166
+ const match = name.match(new RegExp(rule.match.source, rule.match.flags.replace("g", "")));
2167
+ if (!match) continue;
2168
+ result = {
2169
+ module: substitute(rule.module, match),
2170
+ export: rule.export ? substitute(rule.export, match) : name
2171
+ };
2172
+ break;
2173
+ }
2174
+ }
2175
+ cache.set(name, result);
2176
+ return result;
2177
+ };
2178
+ return {
2179
+ resolve,
2180
+ names: () => [...exact.keys()],
2181
+ conflicts: () => conflicts
2182
+ };
2183
+ }
2184
+
2185
+ // src/lower/template.ts
2186
+ import {
2187
+ parseTemplate
2188
+ } from "@fluixi/template-parser";
2189
+
2190
+ // src/lower/text.ts
2191
+ function cleanTemplateText(value) {
2192
+ const lines = value.split(/\r\n|\n|\r/);
2193
+ let lastNonEmpty = 0;
2194
+ for (let i = 0; i < lines.length; i++) {
2195
+ if (/[^ \t]/.test(lines[i])) lastNonEmpty = i;
2196
+ }
2197
+ let out = "";
2198
+ for (let i = 0; i < lines.length; i++) {
2199
+ let line = lines[i].replace(/\t/g, " ");
2200
+ if (i !== 0) line = line.replace(/^ +/, "");
2201
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
2202
+ if (!line) continue;
2203
+ if (i !== lastNonEmpty) line += " ";
2204
+ out += line;
2205
+ }
2206
+ return out;
2207
+ }
2208
+
2209
+ // src/lower/template.ts
2210
+ var DELEGATED = /* @__PURE__ */ new Set([
2211
+ "click",
2212
+ "dblclick",
2213
+ "input",
2214
+ "change",
2215
+ "submit",
2216
+ "focus",
2217
+ "blur",
2218
+ "keydown",
2219
+ "keyup",
2220
+ "keypress",
2221
+ "mousedown",
2222
+ "mouseup"
2223
+ ]);
2224
+ function escapeTemplate(s) {
2225
+ return s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
2226
+ }
2227
+ function capitalize(s) {
2228
+ return s.charAt(0).toUpperCase() + s.slice(1);
2229
+ }
2230
+ var Lowerer = class {
2231
+ constructor(holes, used, sourceFile, positionAt) {
2232
+ this.holes = holes;
2233
+ this.used = used;
2234
+ this.sourceFile = sourceFile;
2235
+ this.positionAt = positionAt;
2236
+ }
2237
+ /**
2238
+ * Where a tag is written, for the mark a component node carries.
2239
+ *
2240
+ * The parser reports offsets, and they are offsets into the file: the pieces it was given
2241
+ * carry the positions the front-end recorded. Only built when the host asked for source
2242
+ * locations, which is the only time either of these is set.
2243
+ */
2244
+ tagAt(node) {
2245
+ const start = node.loc?.start;
2246
+ if (!this.sourceFile || !this.positionAt || start == null) return void 0;
2247
+ const { line, column } = this.positionAt(start);
2248
+ return { file: this.sourceFile, line, column };
2249
+ }
2250
+ hole(i) {
2251
+ return this.holes[i] ?? { code: "undefined", reactive: false };
2252
+ }
2253
+ /** Emit a nested IR subtree to code (for `Show` fallback / `For` children). */
2254
+ emit(node) {
2255
+ const { code, imports, templates } = imperativeBackend.emit(node, {});
2256
+ for (const s of imports) this.used.add(s);
2257
+ return inlineTemplates(code, templates);
2258
+ }
2259
+ // --- content ------------------------------------------------------------
2260
+ lowerRoot(children) {
2261
+ const nodes = this.lowerChildren(children);
2262
+ if (nodes.length === 1) return nodes[0];
2263
+ return { kind: "fragment", children: nodes };
2264
+ }
2265
+ /** Lower a sibling list, handling text-drop and if/else/each restructuring. */
2266
+ lowerChildren(children) {
2267
+ const out = [];
2268
+ for (let i = 0; i < children.length; i++) {
2269
+ const child = children[i];
2270
+ if (child.kind === "Element" || child.kind === "Component") {
2271
+ const ifDir = child.attributes.find((a) => a.kind === "IfDirective");
2272
+ if (ifDir && ifDir.kind === "IfDirective") {
2273
+ let elseIdx = i + 1;
2274
+ if (elseIdx < children.length && this.isBlankText(children[elseIdx])) elseIdx++;
2275
+ const elseNode = children[elseIdx];
2276
+ const hasElse = elseNode && (elseNode.kind === "Element" || elseNode.kind === "Component") && elseNode.attributes.some((a) => a.kind === "ElseDirective");
2277
+ out.push(this.lowerIf(child, ifDir.hole, hasElse ? elseNode : null));
2278
+ if (hasElse) i = elseIdx;
2279
+ continue;
2280
+ }
2281
+ if (child.attributes.some((a) => a.kind === "EachDirective")) {
2282
+ out.push(this.lowerEach(child));
2283
+ continue;
2284
+ }
2285
+ }
2286
+ const node = this.lowerNode(child);
2287
+ if (node) out.push(node);
2288
+ }
2289
+ return out;
2290
+ }
2291
+ isBlankText(n2) {
2292
+ return n2.kind === "Text" && !n2.raw && cleanTemplateText(n2.value) === "";
2293
+ }
2294
+ lowerNode(node) {
2295
+ switch (node.kind) {
2296
+ case "Text": {
2297
+ if (node.raw) return { kind: "text", value: node.value };
2298
+ const cleaned = cleanTemplateText(node.value);
2299
+ return cleaned ? { kind: "text", value: cleaned } : null;
2300
+ }
2301
+ case "Comment":
2302
+ return null;
2303
+ // dropped, like JSX comments
2304
+ case "Expression": {
2305
+ const h = this.hole(node.hole);
2306
+ return { kind: "expr", code: h.code, reactive: h.reactive, ...h.at ? { at: h.at } : {} };
2307
+ }
2308
+ case "Fragment":
2309
+ return { kind: "fragment", children: this.lowerChildren(node.children) };
2310
+ case "Element":
2311
+ return this.lowerElement(node);
2312
+ case "Component":
2313
+ return this.lowerComponent(node);
2314
+ default:
2315
+ return null;
2316
+ }
2317
+ }
2318
+ lowerElement(el) {
2319
+ const isAttr = el.attributes.find((a) => a.kind === "Attribute" && a.name === "is");
2320
+ if (el.tag === "component" && isAttr && isAttr.value && isAttr.value.kind === "hole") {
2321
+ const rest = el.attributes.filter((a) => a !== isAttr);
2322
+ const node = this.lowerComponent({ ...el, kind: "Component", tag: "Dynamic", tagHole: null, attributes: rest });
2323
+ node.props.unshift({ name: "component", kind: "attr", expr: `() => ${paren(this.hole(isAttr.value.hole).code, "arrowBody")}` });
2324
+ return node;
2325
+ }
2326
+ const at = this.tagAt(el);
2327
+ return {
2328
+ kind: "element",
2329
+ tag: el.tag,
2330
+ svg: el.namespace === "svg",
2331
+ props: this.lowerAttributes(el.attributes),
2332
+ children: this.lowerChildren(el.children),
2333
+ static: false,
2334
+ ...at ? { at } : {}
2335
+ };
2336
+ }
2337
+ lowerComponent(el) {
2338
+ const name = el.tagHole != null ? this.hole(el.tagHole).code : el.tag;
2339
+ const props = this.lowerAttributes(el.attributes);
2340
+ const { slots, rest } = this.partitionSlots(el.children);
2341
+ for (const [slotName, nodes] of slots) {
2342
+ const ir = nodes.length === 1 ? nodes[0] : { kind: "fragment", children: nodes };
2343
+ const slotProp = {
2344
+ name: slotName,
2345
+ kind: "attr",
2346
+ expr: this.emit(ir),
2347
+ jsxElement: true
2348
+ };
2349
+ const clash = props.findIndex((p) => p.name === slotName);
2350
+ if (clash >= 0) props[clash] = slotProp;
2351
+ else props.push(slotProp);
2352
+ }
2353
+ const loadAttr = el.attributes.find((a) => a.kind === "LoadDirective");
2354
+ const load = loadAttr ? parseLoadDirective(`load:${loadAttr.strategy}`, loadAttr.modifier) : void 0;
2355
+ const bindAt = props.find((p) => p.at && p.reactive)?.at;
2356
+ const at = this.tagAt(el);
2357
+ return {
2358
+ kind: "component",
2359
+ name,
2360
+ props,
2361
+ children: this.lowerChildren(rest),
2362
+ ...at ? { at } : {},
2363
+ ...bindAt ? { bindAt } : {},
2364
+ ...load ? { load } : {}
2365
+ };
2366
+ }
2367
+ /** Split a component's children into named slots (`slot="x"`) and the rest. */
2368
+ partitionSlots(children) {
2369
+ const slots = /* @__PURE__ */ new Map();
2370
+ const rest = [];
2371
+ for (const child of children) {
2372
+ if (child.kind === "Element" || child.kind === "Component") {
2373
+ const slot = child.attributes.find(
2374
+ (a) => a.kind === "Attribute" && a.name === "slot"
2375
+ );
2376
+ if (slot && slot.value && slot.value.kind === "static") {
2377
+ const stripped = { ...child, attributes: child.attributes.filter((a) => a !== slot) };
2378
+ const ir = stripped.kind === "Element" ? this.lowerElement(stripped) : this.lowerComponent(stripped);
2379
+ const bucket = slots.get(slot.value.value) ?? [];
2380
+ bucket.push(ir);
2381
+ slots.set(slot.value.value, bucket);
2382
+ continue;
2383
+ }
2384
+ }
2385
+ rest.push(child);
2386
+ }
2387
+ return { slots, rest };
2388
+ }
2389
+ // --- control-flow sugar -------------------------------------------------
2390
+ /** `<el if=${cond}>…</el>` (+ optional `<el else>`) → `<Show when fallback>`. */
2391
+ lowerIf(el, condHole, elseEl) {
2392
+ const cond = this.hole(condHole);
2393
+ const props = [
2394
+ { name: "when", kind: "attr", expr: cond.code, reactive: cond.reactive, ...cond.at ? { at: cond.at } : {} }
2395
+ ];
2396
+ if (elseEl) {
2397
+ const elseIR = this.stripAndLower(elseEl, (a) => a.kind === "ElseDirective");
2398
+ props.push({ name: "fallback", kind: "attr", expr: this.emit(elseIR), jsxElement: true });
2399
+ }
2400
+ const child = this.stripAndLower(el, (a) => a.kind === "IfDirective");
2401
+ const at = this.tagAt(el);
2402
+ return { kind: "component", name: "Show", props, children: [child], ...at ? { at } : {}, ...cond.at ? { bindAt: cond.at } : {} };
2403
+ }
2404
+ /** `<el each=${items} key?>${item => …}</el>` → `<For each>{item => <el>…</el>}</For>`. */
2405
+ lowerEach(el) {
2406
+ const eachDir = el.attributes.find((a) => a.kind === "EachDirective");
2407
+ if (!eachDir || eachDir.kind !== "EachDirective") return this.lowerNode(el);
2408
+ const each = this.hole(eachDir.hole);
2409
+ const props = [{ name: "each", kind: "attr", expr: each.code, reactive: each.reactive, ...each.at ? { at: each.at } : {} }];
2410
+ if (eachDir.key) {
2411
+ const by = "static" in eachDir.key ? `(item) => item[${JSON.stringify(eachDir.key.static)}]` : this.hole(eachDir.key.hole).code;
2412
+ props.push({ name: "by", kind: "attr", expr: by });
2413
+ }
2414
+ const arrow = this.itemArrow(el);
2415
+ let childrenCode;
2416
+ if (arrow) {
2417
+ const bodyIR = { kind: "expr", code: arrow.body, reactive: arrow.bodyReactive };
2418
+ const repeated = this.rebuildWithChildren(el, [bodyIR]);
2419
+ childrenCode = `(${arrow.params.join(", ")}) => ${paren(this.emit(repeated), "arrowBody")}`;
2420
+ } else {
2421
+ const repeated = this.stripAndLower(el, (a) => a.kind === "EachDirective");
2422
+ childrenCode = `() => ${paren(this.emit(repeated), "arrowBody")}`;
2423
+ }
2424
+ const children = [{ kind: "expr", code: childrenCode, reactive: false }];
2425
+ const at = this.tagAt(el);
2426
+ return { kind: "component", name: "For", props, children, ...at ? { at } : {}, ...each.at ? { bindAt: each.at } : {} };
2427
+ }
2428
+ /** The single `${item => expr}` child arrow, if that's the element's content. */
2429
+ itemArrow(el) {
2430
+ const kids = el.children.filter((c) => !this.isBlankText(c));
2431
+ if (kids.length !== 1 || kids[0].kind !== "Expression") return null;
2432
+ return this.hole(kids[0].hole).arrow ?? null;
2433
+ }
2434
+ /** Lower an element to IR, dropping the directive attribute matched by `drop`. */
2435
+ stripAndLower(el, drop) {
2436
+ const clone = { ...el, attributes: el.attributes.filter((a) => !drop(a)) };
2437
+ return clone.kind === "Element" ? this.lowerElement(clone) : this.lowerComponent(clone);
2438
+ }
2439
+ /** Same element (minus each/key) but with explicit IR children. */
2440
+ rebuildWithChildren(el, children) {
2441
+ const props = this.lowerAttributes(
2442
+ el.attributes.filter((a) => a.kind !== "EachDirective")
2443
+ );
2444
+ if (el.kind === "Element") {
2445
+ const at = this.tagAt(el);
2446
+ return {
2447
+ kind: "element",
2448
+ tag: el.tag,
2449
+ svg: el.namespace === "svg",
2450
+ props,
2451
+ children,
2452
+ static: false,
2453
+ ...at ? { at } : {}
2454
+ };
2455
+ }
2456
+ return { kind: "component", name: el.tag, props, children };
2457
+ }
2458
+ // --- attributes ---------------------------------------------------------
2459
+ lowerAttributes(attrs) {
2460
+ const props = [];
2461
+ const classEntries = [];
2462
+ let classReactive = false;
2463
+ let classAt;
2464
+ const styleEntries = [];
2465
+ let styleReactive = false;
2466
+ let styleAt;
2467
+ const usePairs = [];
2468
+ for (const a of attrs) {
2469
+ switch (a.kind) {
2470
+ case "IfDirective":
2471
+ case "EachDirective":
2472
+ case "ElseDirective":
2473
+ break;
2474
+ // handled as control-flow at the parent level
2475
+ case "Attribute":
2476
+ props.push(this.plainAttr(a));
2477
+ break;
2478
+ case "PropertyBinding":
2479
+ props.push({
2480
+ name: a.name,
2481
+ kind: "prop",
2482
+ expr: this.hole(a.hole).code,
2483
+ reactive: this.hole(a.hole).reactive,
2484
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
2485
+ });
2486
+ break;
2487
+ case "EventBinding":
2488
+ props.push(this.eventProp(a));
2489
+ break;
2490
+ case "RefBinding":
2491
+ props.push({
2492
+ name: "ref",
2493
+ kind: "ref",
2494
+ expr: this.hole(a.hole).code,
2495
+ reactive: this.hole(a.hole).reactive,
2496
+ // Which variable ends up holding the element, and where it was written.
2497
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
2498
+ });
2499
+ break;
2500
+ case "Spread":
2501
+ props.push({ name: "", kind: "spread", expr: this.hole(a.hole).code });
2502
+ break;
2503
+ case "ClassDirective": {
2504
+ const h = this.hole(a.hole);
2505
+ classEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
2506
+ classReactive = classReactive || h.reactive;
2507
+ classAt ??= h.at;
2508
+ break;
2509
+ }
2510
+ case "StyleDirective": {
2511
+ const h = this.hole(a.hole);
2512
+ styleEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
2513
+ styleReactive = styleReactive || h.reactive;
2514
+ styleAt ??= h.at;
2515
+ break;
2516
+ }
2517
+ case "BindDirective":
2518
+ props.push(...this.bindProps(a.name, this.hole(a.hole)));
2519
+ break;
2520
+ case "UseDirective": {
2521
+ const dir = a.name ?? (a.hole != null ? this.hole(a.hole).code : null);
2522
+ if (!dir) break;
2523
+ usePairs.push(a.name != null && a.hole != null ? `[${dir}, () => ${paren(this.hole(a.hole).code, "arrowBody")}]` : `[${dir}]`);
2524
+ break;
2525
+ }
2526
+ }
2527
+ }
2528
+ if (classEntries.length > 0) {
2529
+ props.push({
2530
+ name: "classList",
2531
+ kind: "attr",
2532
+ expr: `{ ${classEntries.join(", ")} }`,
2533
+ reactive: classReactive,
2534
+ ...classAt ? { at: classAt } : {}
2535
+ });
2536
+ }
2537
+ if (styleEntries.length > 0) {
2538
+ props.push({
2539
+ name: "style",
2540
+ kind: "attr",
2541
+ expr: `{ ${styleEntries.join(", ")} }`,
2542
+ reactive: styleReactive,
2543
+ ...styleAt ? { at: styleAt } : {}
2544
+ });
2545
+ }
2546
+ if (usePairs.length > 0) {
2547
+ props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
2548
+ }
2549
+ return props;
2550
+ }
2551
+ /**
2552
+ * Lower an event binding. Plain `@click`/`onClick` (no modifiers) stays a
2553
+ * DELEGATED handler (unchanged, byte-identical with JSX). `on:click` or any
2554
+ * modifier (`.capture`/`.once`/`.passive`/`.prevent`/`.stop`/`.self`) emits a
2555
+ * NATIVE `on:name` prop the runtime attaches via addEventListener.
2556
+ */
2557
+ eventProp(a) {
2558
+ const dom = a.name.toLowerCase();
2559
+ const handler = this.hole(a.hole).code;
2560
+ const native = a.syntax === "colon" || a.modifiers.length > 0;
2561
+ if (!native) {
2562
+ return {
2563
+ name: "on" + capitalize(a.name),
2564
+ kind: "event",
2565
+ event: { name: dom, delegated: DELEGATED.has(dom) },
2566
+ expr: handler
2567
+ };
2568
+ }
2569
+ const wrapped = this.wrapHandler(handler, a.modifiers);
2570
+ const options = this.eventOptions(a.modifiers);
2571
+ const value = options ? `[${wrapped}, ${options}]` : wrapped;
2572
+ return { name: "on:" + dom, kind: "attr", expr: value };
2573
+ }
2574
+ /** Wrap a handler for `.prevent`/`.stop`/`.self` (no wrap when none apply). */
2575
+ wrapHandler(handler, mods) {
2576
+ const guard = mods.includes("self") ? "if (e.target !== e.currentTarget) return; " : "";
2577
+ const pre = [];
2578
+ if (mods.includes("prevent")) pre.push("e.preventDefault();");
2579
+ if (mods.includes("stop")) pre.push("e.stopPropagation();");
2580
+ if (!guard && pre.length === 0) return handler;
2581
+ return `(e) => { ${guard}${pre.join(" ")} return (${handler})(e); }`;
2582
+ }
2583
+ /** addEventListener options object from `.capture`/`.once`/`.passive`, or null. */
2584
+ eventOptions(mods) {
2585
+ const opts = [];
2586
+ if (mods.includes("capture")) opts.push("capture: true");
2587
+ if (mods.includes("once")) opts.push("once: true");
2588
+ if (mods.includes("passive")) opts.push("passive: true");
2589
+ return opts.length ? `{ ${opts.join(", ")} }` : null;
2590
+ }
2591
+ /** `bind:value=${sig}` → `value={read()}` + `onInput={e => write(e…value)}`. */
2592
+ bindProps(prop, h) {
2593
+ const sigCode = h.code;
2594
+ const checked = prop === "checked";
2595
+ const evt = checked ? "change" : "input";
2596
+ const accessor = checked ? "checked" : "value";
2597
+ this.used.add("bindPair");
2598
+ const sig = `bindPair(${sigCode})`;
2599
+ return [
2600
+ {
2601
+ name: prop,
2602
+ kind: "attr",
2603
+ expr: `${sig}[0]()`,
2604
+ reactive: true,
2605
+ directive: `bind:${prop}`,
2606
+ ...h.at ? { at: h.at } : {}
2607
+ },
2608
+ {
2609
+ name: "on" + capitalize(evt),
2610
+ kind: "event",
2611
+ event: { name: evt, delegated: DELEGATED.has(evt) },
2612
+ // delegated handler: `target` is the bound element (currentTarget is the root)
2613
+ expr: `(e) => ${sig}[1](e.target.${accessor})`
2614
+ }
2615
+ ];
2616
+ }
2617
+ /** A plain attribute (incl. lit `?bool`, mixed values), old `mkProp` behavior. */
2618
+ plainAttr(a) {
2619
+ const v = a.value;
2620
+ let name = a.name;
2621
+ if (a.name === "class") {
2622
+ name = v && v.kind === "hole" && this.hole(v.hole).object ? "classList" : "className";
2623
+ } else if (a.name === "html") {
2624
+ name = "innerHTML";
2625
+ }
2626
+ const kind = "attr";
2627
+ const base = { name, kind };
2628
+ if (v == null) {
2629
+ base.literal = true;
2630
+ return base;
2631
+ }
2632
+ if (v.kind === "static") {
2633
+ base.literal = v.value;
2634
+ return base;
2635
+ }
2636
+ if (v.kind === "hole") {
2637
+ const h = this.hole(v.hole);
2638
+ base.expr = h.code;
2639
+ base.reactive = h.reactive;
2640
+ if (h.at) base.at = h.at;
2641
+ return base;
2642
+ }
2643
+ let reactive = false;
2644
+ let at;
2645
+ const body = v.parts.map((p) => {
2646
+ if ("text" in p) return escapeTemplate(p.text);
2647
+ const h = this.hole(p.hole);
2648
+ reactive = reactive || h.reactive;
2649
+ at ??= h.at;
2650
+ return "${" + h.code + "}";
2651
+ }).join("");
2652
+ base.expr = "`" + body + "`";
2653
+ base.reactive = reactive;
2654
+ if (at) base.at = at;
2655
+ return base;
2656
+ }
2657
+ };
2658
+ function lowerTemplate(pieces, holes, used, opts = {}) {
2659
+ const { root } = parseTemplate(pieces, { svg: opts.svg });
2660
+ return new Lowerer(holes, used, opts.sourceFile, opts.positionAt).lowerRoot(root.children);
2661
+ }
2662
+
2663
+ // src/lower/compile-template.ts
2664
+ function compilePieces(pieces, holes, options = {}) {
2665
+ const used = /* @__PURE__ */ new Set();
2666
+ const ir = lowerTemplate(pieces, [...holes], used, {
2667
+ svg: options.svg,
2668
+ ...options.sourceFile ? { sourceFile: options.sourceFile } : {},
2669
+ ...options.positionAt ? { positionAt: options.positionAt } : {}
2670
+ });
2671
+ analyzeStatic(ir);
2672
+ resolveComponentSources(ir, {
2673
+ resolver: createComponentResolver(options.resolve ?? []),
2674
+ modules: {
2675
+ controlFlowModule: options.controlFlowModule ?? "@fluixi/dom",
2676
+ coreModule: options.coreModule ?? "@fluixi/core",
2677
+ routerModule: options.routerModule ?? "@fluixi/core/router"
2678
+ },
2679
+ strategyFor: (node) => node.load
2680
+ });
2681
+ collapseStrategies(ir);
2682
+ const { code, imports, templates } = imperativeBackend.emit(ir, {
2683
+ templateClone: options.templateClone,
2684
+ partialTemplates: options.partialTemplates
2685
+ });
2686
+ for (const symbol of imports) used.add(symbol);
2687
+ if (options.hoistTemplates) return { code, imports: [...used], ir, templates };
2688
+ return { code: inlineTemplates(code, templates), imports: [...used], ir };
2689
+ }
2690
+
2691
+ // src/analyze/reactive-expr.ts
2692
+ var STABLE_MEMBER = "children";
2693
+ function isReactiveShape(shape) {
2694
+ switch (shape.kind) {
2695
+ case "call":
2696
+ return true;
2697
+ case "member":
2698
+ return shape.property !== STABLE_MEMBER;
2699
+ case "compound":
2700
+ return shape.parts.some(isReactiveShape);
2701
+ case "opaque":
2702
+ return false;
2703
+ }
2704
+ }
2705
+
2706
+ // src/analyze/expr-shape.ts
2707
+ var CALL = /* @__PURE__ */ new Set(["CallExpression", "OptionalCallExpression"]);
2708
+ var MEMBER = /* @__PURE__ */ new Set(["MemberExpression", "OptionalMemberExpression"]);
2709
+ function shapeOf(node) {
2710
+ if (!node) return { kind: "opaque" };
2711
+ if (CALL.has(node.type)) return { kind: "call" };
2712
+ if (MEMBER.has(node.type)) {
2713
+ const property = node.property;
2714
+ const computed = node.computed === true;
2715
+ return {
2716
+ kind: "member",
2717
+ property: !computed && property?.type === "Identifier" ? property.name : null
2718
+ };
2719
+ }
2720
+ if (node.type === "ConditionalExpression") {
2721
+ return { kind: "compound", parts: [node.test, node.consequent, node.alternate].map(part) };
2722
+ }
2723
+ if (node.type === "LogicalExpression" || node.type === "BinaryExpression") {
2724
+ return { kind: "compound", parts: [node.left, node.right].map(part) };
2725
+ }
2726
+ if (node.type === "TemplateLiteral") {
2727
+ return { kind: "compound", parts: node.expressions.map(part) };
2728
+ }
2729
+ if (node.type === "ObjectExpression") {
2730
+ const props = node.properties.filter(
2731
+ (p) => (p.type === "ObjectProperty" || p.type === "Property") && p.computed !== true
2732
+ );
2733
+ return { kind: "compound", parts: props.map((p) => part(p.value)) };
2734
+ }
2735
+ if (node.type === "ArrayExpression") {
2736
+ const items = node.elements.filter(
2737
+ (e) => e != null && e.type !== "SpreadElement"
2738
+ );
2739
+ return { kind: "compound", parts: items.map(part) };
2740
+ }
2741
+ return { kind: "opaque" };
2742
+ }
2743
+ var part = (n2) => shapeOf(n2);
2744
+
2745
+ // src/lower/jsx.ts
2746
+ var SVG_TAGS = /* @__PURE__ */ new Set([
2747
+ "svg",
2748
+ "path",
2749
+ "circle",
2750
+ "rect",
2751
+ "line",
2752
+ "polygon",
2753
+ "polyline",
2754
+ "ellipse",
2755
+ "g",
2756
+ "defs",
2757
+ "clipPath",
2758
+ "text"
2759
+ ]);
2760
+ var EVENT_RE = /^on[A-Z]/;
2761
+ var DELEGATED2 = /* @__PURE__ */ new Set([
2762
+ "click",
2763
+ "dblclick",
2764
+ "input",
2765
+ "change",
2766
+ "submit",
2767
+ "focus",
2768
+ "blur",
2769
+ "keydown",
2770
+ "keyup",
2771
+ "keypress",
2772
+ "mousedown",
2773
+ "mouseup"
2774
+ ]);
2775
+ var isReactive = (node) => isReactiveShape(shapeOf(node));
2776
+ var posOf = (node, ctx) => {
2777
+ if (!ctx.sourceFile) return void 0;
2778
+ const at = node.loc?.start;
2779
+ return at ? { line: at.line, column: at.column } : void 0;
2780
+ };
2781
+ function literalOf(node) {
2782
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") {
2783
+ return node.value;
2784
+ }
2785
+ if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number" || typeof node.value === "boolean")) {
2786
+ return node.value;
2787
+ }
2788
+ return void 0;
2789
+ }
2790
+ var isString = (node) => !!node && typeof literalOf(node) === "string";
2791
+ function tagInfo(name, ctx) {
2792
+ if (name.type === "JSXIdentifier") {
2793
+ return { tag: name.name, component: name.name[0] !== name.name[0].toLowerCase() };
2794
+ }
2795
+ if (name.type === "JSXMemberExpression") return { tag: ctx.code(name), component: true };
2796
+ if (name.type === "JSXNamespacedName") {
2797
+ return { tag: `${name.namespace.name}:${name.name.name}`, component: false };
2798
+ }
2799
+ return { tag: "div", component: false };
2800
+ }
2801
+ function attrName(name) {
2802
+ if (name.type === "JSXIdentifier") return name.name === "class" ? "className" : name.name;
2803
+ if (name.type === "JSXNamespacedName") return `${name.namespace.name}:${name.name.name}`;
2804
+ return "unknown";
2805
+ }
2806
+ function buildAttr(attr, ctx) {
2807
+ const name = attrName(attr.name);
2808
+ const isEvent = EVENT_RE.test(name);
2809
+ const isHandler = isEvent || name.startsWith("on:") || name === "ref";
2810
+ const kind = isEvent ? "event" : "attr";
2811
+ const base = { name, kind };
2812
+ if (isEvent) {
2813
+ const evt = name.slice(2).toLowerCase();
2814
+ base.event = { name: evt, delegated: DELEGATED2.has(evt) };
2815
+ }
2816
+ const v = attr.value;
2817
+ if (v == null) {
2818
+ base.literal = true;
2819
+ base.at = posOf(attr, ctx);
2820
+ return base;
2821
+ }
2822
+ if (isString(v)) {
2823
+ base.literal = literalOf(v);
2824
+ base.at = posOf(v, ctx);
2825
+ return base;
2826
+ }
2827
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
2828
+ const expr = v.expression;
2829
+ const literal = literalOf(expr);
2830
+ if (literal !== void 0) {
2831
+ base.literal = literal;
2832
+ base.at = posOf(expr, ctx);
2833
+ return base;
2834
+ }
2835
+ base.expr = ctx.code(expr);
2836
+ base.reactive = isHandler ? false : isReactive(expr);
2837
+ base.at = posOf(expr, ctx);
2838
+ if (expr.type === "JSXElement" || expr.type === "JSXFragment") base.jsxElement = true;
2839
+ return base;
2840
+ }
2841
+ base.literal = true;
2842
+ return base;
2843
+ }
2844
+ function attrExprCode(attr, ctx) {
2845
+ const v = attr.value;
2846
+ if (v == null) return null;
2847
+ if (isString(v)) return JSON.stringify(literalOf(v));
2848
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
2849
+ return ctx.code(v.expression);
2850
+ }
2851
+ return null;
2852
+ }
2853
+ function buildProps(attrs, ctx) {
2854
+ const props = [];
2855
+ const usePairs = [];
2856
+ for (const a of attrs) {
2857
+ if (a.type === "JSXSpreadAttribute") {
2858
+ props.push({ name: "", kind: "spread", expr: ctx.code(a.argument) });
2859
+ continue;
2860
+ }
2861
+ if (a.type !== "JSXAttribute") continue;
2862
+ if (isLoadDirective(attrName(a.name))) continue;
2863
+ const ns = a.name.type === "JSXNamespacedName" ? a.name.namespace.name : null;
2864
+ if (ns === "use") {
2865
+ const dir = a.name.name.name;
2866
+ ctx.used.add(dir);
2867
+ const opts = attrExprCode(a, ctx);
2868
+ usePairs.push(opts != null ? `[${dir}, () => ${paren(opts, "arrowBody")}]` : `[${dir}]`);
2869
+ continue;
2870
+ }
2871
+ if (ns === "oncapture") {
2872
+ const evt = a.name.name.name.toLowerCase();
2873
+ const h = attrExprCode(a, ctx) ?? "undefined";
2874
+ props.push({ name: "on:" + evt, kind: "attr", expr: `[${h}, { capture: true }]` });
2875
+ continue;
2876
+ }
2877
+ props.push(buildAttr(a, ctx));
2878
+ }
2879
+ if (usePairs.length > 0) props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
2880
+ return props;
2881
+ }
2882
+ function buildChildren(children, ctx) {
2883
+ const out = [];
2884
+ for (const child of children) {
2885
+ if (child.type === "JSXText") {
2886
+ const text = cleanTemplateText(child.value);
2887
+ if (text) out.push({ kind: "text", value: text });
2888
+ } else if (child.type === "JSXExpressionContainer") {
2889
+ if (child.expression?.type !== "JSXEmptyExpression") {
2890
+ const expr = child.expression;
2891
+ const reactive = isReactive(expr);
2892
+ out.push({
2893
+ kind: "expr",
2894
+ code: ctx.code(expr),
2895
+ reactive,
2896
+ ...reactive ? { at: posOf(expr, ctx) } : {}
2897
+ });
2898
+ }
2899
+ } else if (child.type === "JSXElement" || child.type === "JSXFragment") {
2900
+ out.push(buildNode(child, ctx));
2901
+ } else if (child.type === "JSXSpreadChild") {
2902
+ out.push({ kind: "expr", code: ctx.code(child.expression), reactive: false });
2903
+ }
2904
+ }
2905
+ return out;
2906
+ }
2907
+ function readLoad(attrs) {
2908
+ for (const a of attrs) {
2909
+ if (a.type !== "JSXAttribute") continue;
2910
+ const name = attrName(a.name);
2911
+ if (!isLoadDirective(name)) continue;
2912
+ if (a.value && !isString(a.value)) {
2913
+ throw new LoadDirectiveError(
2914
+ `'${name}' needs a literal value, not an expression — the strategy is compile-time.`
2915
+ );
2916
+ }
2917
+ return parseLoadDirective(name, a.value ? literalOf(a.value) : null);
2918
+ }
2919
+ return void 0;
2920
+ }
2921
+ function buildNode(node, ctx) {
2922
+ if (node.type === "JSXFragment") {
2923
+ return { kind: "fragment", children: buildChildren(node.children, ctx) };
2924
+ }
2925
+ const { tag, component } = tagInfo(node.openingElement.name, ctx);
2926
+ const props = buildProps(node.openingElement.attributes, ctx);
2927
+ const children = buildChildren(node.children, ctx);
2928
+ const at = ctx.sourceFile && node.loc?.start ? { file: ctx.sourceFile, line: node.loc.start.line, column: node.loc.start.column } : void 0;
2929
+ if (component) {
2930
+ const load = readLoad(node.openingElement.attributes);
2931
+ return { kind: "component", name: tag, props, children, ...load ? { load } : {}, ...at ? { at } : {} };
2932
+ }
2933
+ return { kind: "element", tag, svg: SVG_TAGS.has(tag), props, children, static: false, ...at ? { at } : {} };
2934
+ }
2935
+ function buildJsxIR(node, ctx) {
2936
+ const ir = buildNode(node, ctx);
2937
+ analyzeStatic(ir);
2938
+ return ir;
2939
+ }
2940
+
2941
+ // src/transform/bindings.ts
2942
+ function patternNames2(node, out) {
2943
+ if (!node) return;
2944
+ switch (node.type) {
2945
+ case "Identifier":
2946
+ out.add(node.name);
2947
+ return;
2948
+ case "ObjectPattern":
2949
+ for (const p of node.properties) {
2950
+ if (p.type === "RestElement") patternNames2(p.argument, out);
2951
+ else patternNames2(p.value, out);
2952
+ }
2953
+ return;
2954
+ case "ArrayPattern":
2955
+ for (const e of node.elements) patternNames2(e, out);
2956
+ return;
2957
+ case "AssignmentPattern":
2958
+ patternNames2(node.left, out);
2959
+ return;
2960
+ case "RestElement":
2961
+ patternNames2(node.argument, out);
2962
+ return;
2963
+ }
2964
+ }
2965
+ function declared(node, out) {
2966
+ switch (node.type) {
2967
+ case "ImportDeclaration":
2968
+ for (const s of node.specifiers) patternNames2(s.local, out);
2969
+ return;
2970
+ case "VariableDeclaration":
2971
+ for (const d of node.declarations) patternNames2(d.id, out);
2972
+ return;
2973
+ case "FunctionDeclaration":
2974
+ case "ClassDeclaration":
2975
+ patternNames2(node.id, out);
2976
+ return;
2977
+ case "ExportNamedDeclaration":
2978
+ case "ExportDefaultDeclaration":
2979
+ if (node.declaration) declared(node.declaration, out);
2980
+ return;
2981
+ }
2982
+ }
2983
+ function moduleBindings(program) {
2984
+ const names = /* @__PURE__ */ new Set();
2985
+ for (const statement of program.body) declared(statement, names);
2986
+ return names;
2987
+ }
2988
+
2989
+ // src/transform/props.ts
2990
+ import { parse } from "@babel/parser";
2991
+
2992
+ // src/analyze/props-destructure.ts
2993
+ function patternNames3(node, out) {
2994
+ if (!node) return;
2995
+ switch (node.type) {
2996
+ case "Identifier":
2997
+ out.add(node.name);
2998
+ return;
2999
+ case "ObjectPattern":
3000
+ for (const p of node.properties) {
3001
+ if (p.type === "RestElement") patternNames3(p.argument, out);
3002
+ else patternNames3(p.value, out);
3003
+ }
3004
+ return;
3005
+ case "ArrayPattern":
3006
+ for (const e of node.elements) patternNames3(e, out);
3007
+ return;
3008
+ case "AssignmentPattern":
3009
+ patternNames3(node.left, out);
3010
+ return;
3011
+ case "RestElement":
3012
+ patternNames3(node.argument, out);
3013
+ return;
3014
+ }
3015
+ }
3016
+ function isSafeDefault(node) {
3017
+ switch (node.type) {
3018
+ case "StringLiteral":
3019
+ case "NumericLiteral":
3020
+ case "BooleanLiteral":
3021
+ case "NullLiteral":
3022
+ case "BigIntLiteral":
3023
+ case "RegExpLiteral":
3024
+ case "Identifier":
3025
+ return true;
3026
+ // ESTree spells every literal as `Literal`; both shapes reach this analysis.
3027
+ case "Literal":
3028
+ return true;
3029
+ case "TemplateLiteral":
3030
+ return node.expressions.every(isSafeDefault);
3031
+ case "UnaryExpression":
3032
+ return isSafeDefault(node.argument);
3033
+ case "MemberExpression":
3034
+ return false;
3035
+ default:
3036
+ return false;
3037
+ }
3038
+ }
3039
+ function walk4(root, visit) {
3040
+ if (!root || typeof root !== "object") return;
3041
+ visit(root);
3042
+ for (const key of Object.keys(root)) {
3043
+ if (key === "loc" || key === "range" || key === "leadingComments" || key === "trailingComments") continue;
3044
+ const value = root[key];
3045
+ if (Array.isArray(value)) {
3046
+ for (const item of value) if (item && typeof item === "object") walk4(item, visit);
3047
+ } else if (value && typeof value === "object" && typeof value.type === "string") {
3048
+ walk4(value, visit);
3049
+ }
3050
+ }
3051
+ }
3052
+ function reassignedNames(body) {
3053
+ const written = /* @__PURE__ */ new Set();
3054
+ walk4(body, (node) => {
3055
+ if (node.type === "AssignmentExpression") patternNames3(node.left, written);
3056
+ else if (node.type === "UpdateExpression") {
3057
+ const arg = node.argument;
3058
+ if (arg?.type === "Identifier") written.add(arg.name);
3059
+ }
3060
+ });
3061
+ return written;
3062
+ }
3063
+ function shadowedNames(body, candidates) {
3064
+ const shadowed = /* @__PURE__ */ new Set();
3065
+ const note = (node) => {
3066
+ const names = /* @__PURE__ */ new Set();
3067
+ patternNames3(node, names);
3068
+ for (const n2 of names) if (candidates.has(n2)) shadowed.add(n2);
3069
+ };
3070
+ walk4(body, (node) => {
3071
+ switch (node.type) {
3072
+ case "VariableDeclarator":
3073
+ note(node.id);
3074
+ return;
3075
+ case "FunctionDeclaration":
3076
+ case "FunctionExpression":
3077
+ case "ArrowFunctionExpression":
3078
+ note(node.id);
3079
+ for (const p of node.params ?? []) note(p);
3080
+ return;
3081
+ case "CatchClause":
3082
+ note(node.param);
3083
+ return;
3084
+ case "ClassDeclaration":
3085
+ case "ClassExpression":
3086
+ note(node.id);
3087
+ return;
3088
+ }
3089
+ });
3090
+ return shadowed;
3091
+ }
3092
+ function collect(pattern, path, plan) {
3093
+ for (const property of pattern.properties ?? []) {
3094
+ if (property.type === "RestElement") {
3095
+ const argument = property.argument;
3096
+ if (argument?.type !== "Identifier" || path.length > 0) {
3097
+ const names2 = /* @__PURE__ */ new Set();
3098
+ patternNames3(argument, names2);
3099
+ for (const name of names2) plan.bails.push({ name, reason: "rest" });
3100
+ continue;
3101
+ }
3102
+ plan.rest = { name: argument.name, keys: [] };
3103
+ continue;
3104
+ }
3105
+ if (property.computed) {
3106
+ const names2 = /* @__PURE__ */ new Set();
3107
+ patternNames3(property.value, names2);
3108
+ for (const name of names2) plan.bails.push({ name, reason: "computed" });
3109
+ continue;
3110
+ }
3111
+ const key = property.key;
3112
+ const propertyName = key.type === "Identifier" ? key.name : key.value;
3113
+ let value = property.value;
3114
+ let fallback;
3115
+ if (value.type === "AssignmentPattern") {
3116
+ fallback = value.right;
3117
+ value = value.left;
3118
+ }
3119
+ const here = [...path, propertyName];
3120
+ if (value.type === "Identifier") {
3121
+ if (fallback && !isSafeDefault(fallback)) {
3122
+ plan.bails.push({ name: value.name, reason: "unsafe-default" });
3123
+ continue;
3124
+ }
3125
+ plan.reads.push({ name: value.name, path: here, ...fallback ? { fallback } : {} });
3126
+ continue;
3127
+ }
3128
+ if (value.type === "ObjectPattern") {
3129
+ if (fallback) {
3130
+ const names2 = /* @__PURE__ */ new Set();
3131
+ patternNames3(value, names2);
3132
+ for (const name of names2) plan.bails.push({ name, reason: "unsafe-default" });
3133
+ continue;
3134
+ }
3135
+ collect(value, here, plan);
3136
+ continue;
3137
+ }
3138
+ const names = /* @__PURE__ */ new Set();
3139
+ patternNames3(value, names);
3140
+ for (const name of names) plan.bails.push({ name, reason: "computed" });
3141
+ }
3142
+ }
3143
+ function planPropsDestructure(pattern, body) {
3144
+ const plan = { reads: [], bails: [] };
3145
+ if (pattern?.type !== "ObjectPattern") return plan;
3146
+ collect(pattern, [], plan);
3147
+ if (plan.rest) {
3148
+ if (body?.type !== "BlockStatement") {
3149
+ plan.bails.push({ name: plan.rest.name, reason: "rest" });
3150
+ delete plan.rest;
3151
+ } else {
3152
+ plan.rest.keys = (pattern.properties ?? []).filter((p) => p.type !== "RestElement" && !p.computed).map((p) => {
3153
+ const key = p.key;
3154
+ return key.type === "Identifier" ? key.name : key.value;
3155
+ });
3156
+ }
3157
+ }
3158
+ if (plan.reads.length === 0 && !plan.rest) return plan;
3159
+ const candidates = new Set(plan.reads.map((r) => r.name));
3160
+ if (plan.rest) candidates.add(plan.rest.name);
3161
+ const written = reassignedNames(body);
3162
+ const shadowed = shadowedNames(body, candidates);
3163
+ const kept = [];
3164
+ for (const read of plan.reads) {
3165
+ if (written.has(read.name)) plan.bails.push({ name: read.name, reason: "reassigned" });
3166
+ else if (shadowed.has(read.name)) plan.bails.push({ name: read.name, reason: "shadowed" });
3167
+ else kept.push(read);
3168
+ }
3169
+ plan.reads = kept;
3170
+ if (plan.rest && written.has(plan.rest.name)) {
3171
+ plan.bails.push({ name: plan.rest.name, reason: "reassigned" });
3172
+ delete plan.rest;
3173
+ } else if (plan.rest && shadowed.has(plan.rest.name)) {
3174
+ plan.bails.push({ name: plan.rest.name, reason: "shadowed" });
3175
+ delete plan.rest;
3176
+ }
3177
+ return plan;
3178
+ }
3179
+ function explainBail(reason) {
3180
+ switch (reason) {
3181
+ case "rest":
3182
+ return "this rest element cannot be served by splitProps, and copying the props into a plain object would lose the getters";
3183
+ case "computed":
3184
+ return "the property is not known until it runs";
3185
+ case "reassigned":
3186
+ return "the binding is assigned to, and props are read-only";
3187
+ case "shadowed":
3188
+ return "an inner scope binds the same name";
3189
+ case "unsafe-default":
3190
+ return "the default would have to run again on every read";
3191
+ }
3192
+ }
3193
+
3194
+ // src/transform/props.ts
3195
+ function walk5(root, visit, parent = null) {
3196
+ if (!root || typeof root !== "object" || typeof root.type !== "string") return;
3197
+ if (root.type.startsWith("TS")) return;
3198
+ if (visit(root, parent) === false) return;
3199
+ for (const key of Object.keys(root)) {
3200
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
3201
+ const value = root[key];
3202
+ if (Array.isArray(value)) {
3203
+ for (const item of value) walk5(item, visit, root);
3204
+ } else if (value && typeof value === "object") {
3205
+ walk5(value, visit, root);
3206
+ }
3207
+ }
3208
+ }
3209
+ function isComponentName(name) {
3210
+ return !!name && name[0] >= "A" && name[0] <= "Z";
3211
+ }
3212
+ function componentFunctions(program) {
3213
+ const found = [];
3214
+ walk5(program, (node) => {
3215
+ if (node.type === "FunctionDeclaration" && isComponentName(node.id?.name)) {
3216
+ found.push(node);
3217
+ return;
3218
+ }
3219
+ if (node.type === "VariableDeclarator" && isComponentName(node.id?.name)) {
3220
+ const init = node.init;
3221
+ if (init && (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression")) found.push(init);
3222
+ }
3223
+ });
3224
+ return found;
3225
+ }
3226
+ function usedNames(fn) {
3227
+ const names = /* @__PURE__ */ new Set();
3228
+ walk5(fn, (node) => {
3229
+ if (node.type === "Identifier") names.add(node.name);
3230
+ });
3231
+ return names;
3232
+ }
3233
+ function isReferencePosition(node, parent) {
3234
+ if (!parent) return true;
3235
+ switch (parent.type) {
3236
+ case "MemberExpression":
3237
+ case "OptionalMemberExpression":
3238
+ return !(parent.property === node && !parent.computed);
3239
+ case "ObjectProperty":
3240
+ case "ObjectMethod":
3241
+ case "ClassProperty":
3242
+ case "ClassMethod":
3243
+ return !(parent.key === node && !parent.computed);
3244
+ case "LabeledStatement":
3245
+ case "BreakStatement":
3246
+ case "ContinueStatement":
3247
+ return parent.label !== node;
3248
+ case "ImportSpecifier":
3249
+ case "ExportSpecifier":
3250
+ return false;
3251
+ default:
3252
+ return true;
3253
+ }
3254
+ }
3255
+ function collectPropsEdits(program, code, options = {}) {
3256
+ const edits = [];
3257
+ const diagnostics = [];
3258
+ const used = /* @__PURE__ */ new Set();
3259
+ for (const fn of componentFunctions(program)) {
3260
+ const pattern = fn.params?.[0];
3261
+ if (pattern?.type !== "ObjectPattern") continue;
3262
+ const plan = planPropsDestructure(pattern, fn.body);
3263
+ for (const b of plan.bails) {
3264
+ diagnostics.push({ name: b.name, reason: b.reason, message: explainBail(b.reason), start: pattern.start });
3265
+ }
3266
+ if (plan.bails.length > 0) continue;
3267
+ if (plan.reads.length === 0 && !plan.rest) continue;
3268
+ const taken = usedNames(fn);
3269
+ let parameter = options.parameterName ?? "props";
3270
+ while (taken.has(parameter)) parameter = `_${parameter}`;
3271
+ const replacement = /* @__PURE__ */ new Map();
3272
+ for (const read of plan.reads) {
3273
+ const access = `${parameter}.${read.path.join(".")}`;
3274
+ const fallback = read.fallback;
3275
+ replacement.set(
3276
+ read.name,
3277
+ fallback ? `(${access} === undefined ? ${code.slice(fallback.start, fallback.end)} : ${access})` : access
3278
+ );
3279
+ }
3280
+ const annotation = pattern.typeAnnotation;
3281
+ edits.push({ start: pattern.start, end: annotation?.start ?? pattern.end, code: parameter });
3282
+ if (plan.rest) {
3283
+ const keys = plan.rest.keys.map((k) => JSON.stringify(k)).join(", ");
3284
+ const body = fn.body;
3285
+ edits.push({
3286
+ start: body.start + 1,
3287
+ end: body.start + 1,
3288
+ code: `
3289
+ const [, ${plan.rest.name}] = splitProps(${parameter}, [${keys}]);`
3290
+ });
3291
+ used.add("splitProps");
3292
+ }
3293
+ const matches = [];
3294
+ walk5(fn.body, (node, parent) => {
3295
+ if (node.type !== "Identifier") return void 0;
3296
+ const text = replacement.get(node.name);
3297
+ if (!text) return void 0;
3298
+ const shorthand = parent?.type === "ObjectProperty" && parent.shorthand && parent.value === node;
3299
+ if (!shorthand && !isReferencePosition(node, parent)) return void 0;
3300
+ const path = plan.reads.find((r) => r.name === node.name).path;
3301
+ matches.push({ node, parent: shorthand ? parent : null, text, property: path[path.length - 1] });
3302
+ return void 0;
3303
+ });
3304
+ for (const match of matches) {
3305
+ if (match.parent) {
3306
+ edits.push({ start: match.parent.start, end: match.parent.end, code: `${match.node.name}: ${match.text}` });
3307
+ } else {
3308
+ edits.push({ start: match.node.start, end: match.node.end, code: match.text });
3309
+ }
3310
+ asMemberRead(match.node, parameter, match.property);
3311
+ }
3312
+ }
3313
+ return { edits, diagnostics, used };
3314
+ }
3315
+ function asMemberRead(node, parameter, property) {
3316
+ node.type = "MemberExpression";
3317
+ node.computed = false;
3318
+ node.optional = false;
3319
+ node.object = { type: "Identifier", name: parameter, start: node.start, end: node.start };
3320
+ node.property = { type: "Identifier", name: property, start: node.end, end: node.end };
3321
+ delete node["name"];
3322
+ }
3323
+
3324
+ // src/transform/intrinsics.ts
3325
+ function walk6(root, visit) {
3326
+ if (!root || typeof root !== "object" || typeof root.type !== "string") return;
3327
+ visit(root);
3328
+ for (const key of Object.keys(root)) {
3329
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
3330
+ const value = root[key];
3331
+ if (Array.isArray(value)) for (const item of value) walk6(item, visit);
3332
+ else if (value && typeof value === "object") walk6(value, visit);
3333
+ }
3334
+ }
3335
+ function collectIntrinsicEdits(program) {
3336
+ const edits = [];
3337
+ const diagnostics = [];
3338
+ const imports = /* @__PURE__ */ new Map();
3339
+ const reported = /* @__PURE__ */ new Set();
3340
+ const { shadowed } = resolveReactiveBindings(program);
3341
+ walk6(program, (node) => {
3342
+ if (node.type !== "CallExpression") return;
3343
+ const callee = node.callee;
3344
+ if (callee?.type !== "Identifier") return;
3345
+ const name = callee.name;
3346
+ if (!isIntrinsicName(name)) return;
3347
+ if (shadowed.has(name)) {
3348
+ if (!reported.has(name)) {
3349
+ reported.add(name);
3350
+ diagnostics.push({
3351
+ name,
3352
+ message: `${name} is reserved for the compiler, and this module binds it. The call keeps your binding's meaning; rename it to use the intrinsic.`,
3353
+ start: callee.start
3354
+ });
3355
+ }
3356
+ return;
3357
+ }
3358
+ const intrinsic = INTRINSICS[name];
3359
+ edits.push({ start: callee.start, end: callee.end, code: intrinsic.export });
3360
+ const forModule = imports.get(intrinsic.module) ?? /* @__PURE__ */ new Set();
3361
+ forModule.add(intrinsic.export);
3362
+ imports.set(intrinsic.module, forModule);
3363
+ });
3364
+ return { edits, diagnostics, imports };
3365
+ }
3366
+ function intrinsicImports(result, bound) {
3367
+ const lines = [];
3368
+ for (const [module, names] of [...result.imports].sort(([a], [b]) => a.localeCompare(b))) {
3369
+ const wanted = [...names].filter((name) => !bound.has(name)).sort();
3370
+ if (wanted.length) lines.push(`import { ${wanted.join(", ")} } from ${JSON.stringify(module)};`);
3371
+ }
3372
+ return lines.length ? `${lines.join("\n")}
3373
+ ` : "";
3374
+ }
3375
+
3376
+ // src/transform/templates.ts
3377
+ var CONTROL_FLOW = new Set(DOM_CONTROL_FLOW);
3378
+ var CORE_ONLY = new Set(CORE_CONTROL_FLOW);
3379
+ var ROUTER = new Set(ROUTER_COMPONENTS);
3380
+ var REACTIVE = /* @__PURE__ */ new Set([
3381
+ "createMemo",
3382
+ "createEffect",
3383
+ "createRenderEffect",
3384
+ "createRoot",
3385
+ "createSignal",
3386
+ "onCleanup",
3387
+ "batch",
3388
+ "untrack"
3389
+ ]);
3390
+ function walk7(node, visit, parent = null, key = "") {
3391
+ if (!node || typeof node !== "object") return;
3392
+ if (Array.isArray(node)) {
3393
+ for (const child of node) walk7(child, visit, parent, key);
3394
+ return;
3395
+ }
3396
+ if (typeof node.type === "string") visit(node, parent, key);
3397
+ for (const k of Object.keys(node)) {
3398
+ if (k === "loc" || k === "leadingComments" || k === "trailingComments") continue;
3399
+ walk7(node[k], visit, typeof node.type === "string" ? node : parent, k);
3400
+ }
3401
+ }
3402
+ var isJsx = (node) => node.type === "JSXElement" || node.type === "JSXFragment";
3403
+ function isJsxRoot(node, parent, key) {
3404
+ if (!isJsx(node)) return false;
3405
+ return !(parent && isJsx(parent) && key === "children");
3406
+ }
3407
+ function isTemplateTag(node, litTag) {
3408
+ return node.type === "TaggedTemplateExpression" && node.tag?.type === "Identifier" && (node.tag.name === litTag || node.tag.name === "svg");
3409
+ }
3410
+ function outermost(list) {
3411
+ return list.filter(
3412
+ (e) => !list.some(
3413
+ (o) => o !== e && o.start <= e.start && o.end >= e.end && o.end - o.start > e.end - e.start && // An insertion at either edge of the container sits beside it, not inside it, so
3414
+ // it is not something the container's code already folded in. A statement can
3415
+ // start where its callee starts (`$effect(…)`) and a declarator can end where its
3416
+ // JSX ends (`const Row = () => <b/>`).
3417
+ !(e.start === e.end && (e.start === o.start || e.start === o.end))
3418
+ )
3419
+ );
3420
+ }
3421
+ function slice(code, start, end, edits) {
3422
+ const inside = outermost(edits.filter((e) => e.start >= start && e.end <= end)).sort((a, b) => b.start - a.start);
3423
+ let out = code.slice(start, end);
3424
+ for (const e of inside) out = out.slice(0, e.start - start) + e.code + out.slice(e.end - start);
3425
+ return out;
3426
+ }
3427
+ function bindHole(code, expr, edits, keepPosition = false) {
3428
+ const at = keepPosition ? expr.loc?.start : void 0;
3429
+ const hole = {
3430
+ code: slice(code, expr.start, expr.end, edits),
3431
+ reactive: isReactiveShape(shapeOf(expr)),
3432
+ // Where the `${…}` is, so a binding made from it can say so. The source map cannot:
3433
+ // the whole template is one overwrite. Only when source locations were asked for.
3434
+ ...at ? { at: { line: at.line, column: at.column } } : {}
3435
+ };
3436
+ if (expr.type === "ArrowFunctionExpression" && expr.body?.type !== "BlockStatement") {
3437
+ hole.arrow = {
3438
+ params: expr.params.map((p) => slice(code, p.start, p.end, edits)),
3439
+ body: slice(code, expr.body.start, expr.body.end, edits),
3440
+ bodyReactive: isReactiveShape(shapeOf(expr.body))
3441
+ };
3442
+ }
3443
+ if (expr.type === "ObjectExpression") hole.object = true;
3444
+ return hole;
3445
+ }
3446
+ function adoptTemplates(code, templates, hoisted) {
3447
+ if (!templates || templates.length === 0) return code;
3448
+ const rename = /* @__PURE__ */ new Map();
3449
+ for (const tpl of templates) {
3450
+ const key = `${tpl.svg ? "svg:" : ""}${tpl.html}`;
3451
+ let name = hoisted.get(key);
3452
+ if (!name) {
3453
+ name = `_fxTmpl$${hoisted.size}`;
3454
+ hoisted.set(key, name);
3455
+ }
3456
+ rename.set(tpl.id, name);
3457
+ }
3458
+ return code.replace(/_tmpl\$\d+/g, (id) => rename.get(id) ?? id);
3459
+ }
3460
+ function collectNeeds(node, out) {
3461
+ if (node.kind === "component" && node.load && !node.source && isDeferred(node.load)) {
3462
+ if (!out.ignoredLoad.has(node.name)) out.ignoredLoad.set(node.name, node.load);
3463
+ }
3464
+ if (node.kind === "component" && node.source) {
3465
+ const src = node.source;
3466
+ if (src.origin === "builtin") out.builtins.add(node.name);
3467
+ else if (isDeferred(src.loading) && !out.resolved.has(node.name)) out.deferred.set(node.name, src);
3468
+ else {
3469
+ out.deferred.delete(node.name);
3470
+ out.resolved.set(node.name, src);
3471
+ }
3472
+ }
3473
+ if ("props" in node && node.props) {
3474
+ for (const p of node.props) {
3475
+ if (p.kind === "event" && p.event?.delegated) out.delegatedEvents.add(p.event.name);
3476
+ }
3477
+ }
3478
+ if ("children" in node && node.children) for (const c of node.children) collectNeeds(c, out);
3479
+ }
3480
+ function deferrableImport(program, name) {
3481
+ for (const statement of program.body ?? []) {
3482
+ if (statement.type !== "ImportDeclaration") continue;
3483
+ for (const specifier of statement.specifiers ?? []) {
3484
+ if (specifier.local?.name !== name) continue;
3485
+ if (specifier.type === "ImportNamespaceSpecifier") return void 0;
3486
+ const exported = specifier.type === "ImportDefaultSpecifier" ? "default" : specifier.imported?.name ?? specifier.imported?.value;
3487
+ return { module: statement.source.value, export: exported, declaration: statement, specifier };
3488
+ }
3489
+ }
3490
+ return void 0;
3491
+ }
3492
+ function hasNamespaceImport(program, name) {
3493
+ for (const statement of program.body ?? []) {
3494
+ if (statement.type !== "ImportDeclaration") continue;
3495
+ for (const specifier of statement.specifiers ?? []) {
3496
+ if (specifier.type === "ImportNamespaceSpecifier" && specifier.local?.name === name) return true;
3497
+ }
3498
+ }
3499
+ return false;
3500
+ }
3501
+ function usedAsValue(program, name, specifier) {
3502
+ let seen = false;
3503
+ walk7(program, (node) => {
3504
+ if (seen || node.type !== "Identifier" || node.name !== name) return;
3505
+ if (node.start === specifier.local?.start && node.end === specifier.local?.end) return;
3506
+ seen = true;
3507
+ });
3508
+ return seen;
3509
+ }
3510
+ function strategyLiteral(s) {
3511
+ const parts = [`kind: ${JSON.stringify(s.kind)}`];
3512
+ if (s.kind === "visible" && s.rootMargin) parts.push(`rootMargin: ${JSON.stringify(s.rootMargin)}`);
3513
+ if (s.kind === "interaction") parts.push(`events: ${JSON.stringify(s.events)}`);
3514
+ if (s.kind === "media") parts.push(`query: ${JSON.stringify(s.query)}`);
3515
+ return `{ ${parts.join(", ")} }`;
3516
+ }
3517
+ function positionsIn(code) {
3518
+ const starts = [0];
3519
+ for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
3520
+ return (offset) => {
3521
+ let low = 0;
3522
+ let high = starts.length - 1;
3523
+ while (low < high) {
3524
+ const mid = low + high + 1 >> 1;
3525
+ if (starts[mid] <= offset) low = mid;
3526
+ else high = mid - 1;
3527
+ }
3528
+ return { line: low + 1, column: offset - starts[low] };
3529
+ };
3530
+ }
3531
+ function toPieces(node) {
3532
+ const pieces = [];
3533
+ node.quasi.quasis.forEach((q, i) => {
3534
+ pieces.push({ kind: "static", text: q.value.cooked ?? q.value.raw, start: q.start });
3535
+ if (i < node.quasi.expressions.length) {
3536
+ const e = node.quasi.expressions[i];
3537
+ pieces.push({ kind: "hole", index: i, start: e.start, end: e.end });
3538
+ }
3539
+ });
3540
+ return pieces;
3541
+ }
3542
+ function relativeToRoot(id, root) {
3543
+ if (!root) return id;
3544
+ const base = root.endsWith("/") ? root : `${root}/`;
3545
+ return id.startsWith(base) ? id.slice(base.length) : id;
3546
+ }
3547
+ function transformTemplates(code, id, options = {}) {
3548
+ const litTag = options.litTag ?? "html";
3549
+ const format = options.format ?? "both";
3550
+ const wantsLit = format !== "jsx";
3551
+ const wantsJsx = format !== "lit";
3552
+ const mayHaveTemplate = wantsLit && (code.includes(`${litTag}\``) || code.includes("svg`"));
3553
+ const wantsIntrinsics = options.intrinsics !== false && mayHaveIntrinsic(code);
3554
+ const wantsSources = options.sourceLocations === true && mayHaveReactiveCall(code);
3555
+ const sourceName = relativeToRoot(id, options.sourceRoot);
3556
+ if (!mayHaveTemplate && !(wantsJsx && code.includes("<")) && !wantsIntrinsics && !wantsSources) return null;
3557
+ const ast = parse2(code, {
3558
+ sourceType: "module",
3559
+ plugins: ["jsx", "typescript"],
3560
+ errorRecovery: true
3561
+ });
3562
+ const found = [];
3563
+ walk7(ast.program, (n2, parent, key) => {
3564
+ if (wantsLit && isTemplateTag(n2, litTag)) found.push(n2);
3565
+ else if (wantsJsx && isJsxRoot(n2, parent, key)) found.push(n2);
3566
+ });
3567
+ const props = options.propsDestructure === false ? { edits: [], diagnostics: [], used: /* @__PURE__ */ new Set() } : collectPropsEdits(ast.program, code, { runtimeModule: options.runtimeModule });
3568
+ const intrinsics = options.intrinsics === false ? { edits: [], diagnostics: [], imports: /* @__PURE__ */ new Map() } : collectIntrinsicEdits(ast.program);
3569
+ const sources = options.sourceLocations === true ? collectSourceEdits(ast.program, sourceName) : { edits: [], marked: 0 };
3570
+ const silent = found.length === 0 && props.edits.length === 0 && sources.edits.length === 0 && intrinsics.edits.length === 0 && intrinsics.diagnostics.length === 0 && props.diagnostics.length === 0;
3571
+ if (silent) return null;
3572
+ found.sort((a, b) => b.start - a.start || a.end - b.end);
3573
+ const used = new Set(props.used);
3574
+ const needs = {
3575
+ builtins: /* @__PURE__ */ new Set(),
3576
+ resolved: /* @__PURE__ */ new Map(),
3577
+ deferred: /* @__PURE__ */ new Map(),
3578
+ delegatedEvents: /* @__PURE__ */ new Set(),
3579
+ ignoredLoad: /* @__PURE__ */ new Map(),
3580
+ unresolved: /* @__PURE__ */ new Set(),
3581
+ declared: declaredNames(ast.program)
3582
+ };
3583
+ const hoisted = /* @__PURE__ */ new Map();
3584
+ const edits = [...props.edits, ...intrinsics.edits, ...sources.edits];
3585
+ for (const node of found) {
3586
+ const nested = found.some(
3587
+ (o) => o !== node && o.start <= node.start && o.end >= node.end && o.end - o.start > node.end - node.start
3588
+ );
3589
+ if (isJsx(node)) {
3590
+ edits.push({ start: node.start, end: node.end, code: compileJsx(code, node, edits, nested, used, needs, hoisted, options, sourceName) });
3591
+ continue;
3592
+ }
3593
+ const holes = node.quasi.expressions.map(
3594
+ (e) => bindHole(code, e, edits, options.sourceLocations === true)
3595
+ );
3596
+ const result = compilePieces(toPieces(node), holes, {
3597
+ ...options,
3598
+ hoistTemplates: true,
3599
+ // A tag inside a template gets the same mark a JSX tag does. Without one, the nodes it
3600
+ // makes are the only ones in the module carrying no mark, and they take whichever was
3601
+ // left behind by the last declaration that did.
3602
+ ...options.sourceLocations === true ? { sourceFile: sourceName, positionAt: positionsIn(code) } : {},
3603
+ // Same defaults as the plugin, so moving a build over is not a rendering change.
3604
+ templateClone: options.templateClone ?? true,
3605
+ partialTemplates: nested ? false : options.partialTemplates ?? true,
3606
+ svg: node.tag.name === "svg"
3607
+ });
3608
+ for (const symbol of result.imports) used.add(symbol);
3609
+ collectNeeds(result.ir, needs);
3610
+ edits.push({ start: node.start, end: node.end, code: adoptTemplates(result.code, result.templates, hoisted) });
3611
+ }
3612
+ const out = new MagicString(code);
3613
+ for (const e of outermost(edits)) {
3614
+ if (e.start === e.end) out.appendLeft(e.start, e.code);
3615
+ else out.overwrite(e.start, e.end, e.code);
3616
+ }
3617
+ const bound = moduleBindings(ast.program);
3618
+ const why = /* @__PURE__ */ new Map();
3619
+ for (const [name] of needs.ignoredLoad) {
3620
+ if (!bound.has(name)) why.set(name, "unsupplied");
3621
+ }
3622
+ for (const [name, strategy] of [...needs.ignoredLoad]) {
3623
+ if (!bound.has(name)) continue;
3624
+ const found2 = deferrableImport(ast.program, name);
3625
+ if (!found2) {
3626
+ why.set(name, hasNamespaceImport(ast.program, name) ? "namespace" : "local");
3627
+ continue;
3628
+ }
3629
+ if (usedAsValue(ast.program, name, found2.specifier)) {
3630
+ why.set(name, "value");
3631
+ continue;
3632
+ }
3633
+ const rest = found2.declaration.specifiers.filter((sp) => sp !== found2.specifier);
3634
+ const end = rest.length === 0 && code[found2.declaration.end] === "\n" ? found2.declaration.end + 1 : found2.declaration.end;
3635
+ out.overwrite(
3636
+ found2.declaration.start,
3637
+ end,
3638
+ rest.length === 0 ? "" : `import { ${rest.map((sp) => code.slice(sp.start, sp.end)).join(", ")} } from ${JSON.stringify(found2.declaration.source.value)};`
3639
+ );
3640
+ needs.deferred.set(name, { module: found2.module, export: found2.export, origin: "rule", loading: strategy });
3641
+ bound.delete(name);
3642
+ needs.ignoredLoad.delete(name);
3643
+ }
3644
+ const prologue = buildPrologue(used, needs, hoisted, bound, options);
3645
+ if (prologue) out.prepend(prologue);
3646
+ const runtimeImports = intrinsicImports(intrinsics, bound);
3647
+ if (runtimeImports) out.prepend(runtimeImports);
3648
+ const reasons = {
3649
+ value: (name) => `${name} is used as a value here, not only as a tag, so its import has to stay — deferring would hand those references a lazy wrapper instead of the component. Defer it at the point it is rendered, or keep it eager.`,
3650
+ namespace: (name) => `${name} came in through a namespace import, which has no single export to defer. Import ${name} by name.`,
3651
+ local: (name) => `${name} is declared in this file, so there is no module to load separately. Move it to its own file and import it.`,
3652
+ unsupplied: (name) => `nothing supplies ${name}, so there is no import to defer. Import it, or add a \`resolve\` rule for it.`
3653
+ };
3654
+ const loadDiagnostics = [...needs.ignoredLoad].map(([name, strategy]) => ({
3655
+ name,
3656
+ strategy,
3657
+ message: `load:${strategy.kind} has no effect on <${name}>: ${reasons[why.get(name) ?? "unsupplied"](name)}`
3658
+ }));
3659
+ const unresolvedDiagnostics = [...needs.unresolved].map((name) => ({
3660
+ name,
3661
+ message: `<${name}> is not defined: nothing imports it and no \`resolve\` rule supplies it. This compiles to a reference to a name that does not exist, so the component renders nothing. Import ${name}, or add a \`resolve\` rule for it.`
3662
+ }));
3663
+ return {
3664
+ code: out.toString(),
3665
+ map: out.generateMap({ source: id, includeContent: true, hires: true }),
3666
+ ...loadDiagnostics.length ? { loadDiagnostics } : {},
3667
+ ...unresolvedDiagnostics.length ? { unresolvedDiagnostics } : {},
3668
+ ...props.diagnostics.length ? { propsDiagnostics: props.diagnostics } : {},
3669
+ ...intrinsics.diagnostics.length ? { intrinsicDiagnostics: intrinsics.diagnostics } : {}
3670
+ };
3671
+ }
3672
+ function compileJsx(code, node, edits, nested, used, needs, hoisted, options, sourceFile) {
3673
+ const ir = buildJsxIR(node, {
3674
+ code: (n2) => slice(code, n2.start, n2.end, edits),
3675
+ used,
3676
+ ...options.sourceLocations === true && sourceFile ? { sourceFile } : {}
3677
+ });
3678
+ analyzeStatic(ir);
3679
+ const report = resolveComponentSources(ir, {
3680
+ resolver: createComponentResolver(options.resolve ?? []),
3681
+ // Without this the pass calls every author-imported component unresolved, and the
3682
+ // report is unusable for diagnostics.
3683
+ isBound: (name) => needs.declared.has(name),
3684
+ modules: {
3685
+ controlFlowModule: options.controlFlowModule ?? options.runtimeModule ?? "@fluixi/dom",
3686
+ coreModule: options.coreModule ?? "@fluixi/core",
3687
+ routerModule: options.routerModule ?? "@fluixi/core/router"
3688
+ },
3689
+ strategyFor: (n2) => n2.load
3690
+ });
3691
+ for (const name of report.unresolved) needs.unresolved.add(name);
3692
+ collapseStrategies(ir);
3693
+ const emitted = imperativeBackend.emit(ir, {
3694
+ templateClone: options.templateClone ?? true,
3695
+ partialTemplates: nested ? false : options.partialTemplates ?? true
3696
+ });
3697
+ for (const symbol of emitted.imports) used.add(symbol);
3698
+ collectNeeds(ir, needs);
3699
+ return adoptTemplates(emitted.code, emitted.templates, hoisted);
3700
+ }
3701
+ function buildPrologue(used, needs, hoisted, bound, options) {
3702
+ const runtime = options.runtimeModule ?? "@fluixi/dom";
3703
+ const core = options.coreModule ?? "@fluixi/core";
3704
+ const groups = /* @__PURE__ */ new Map();
3705
+ const add = (mod, name) => groups.set(mod, [...groups.get(mod) ?? [], name]);
3706
+ const wanted = new Set(used);
3707
+ for (const name of needs.builtins) wanted.add(name);
3708
+ if (needs.delegatedEvents.size > 0) wanted.add("delegateEvents");
3709
+ for (const name of [...wanted].sort()) {
3710
+ if (bound.has(name)) continue;
3711
+ if (REACTIVE.has(name)) add(options.reactiveModule ?? "@fluixi/reactive/signal", name);
3712
+ else if (ROUTER.has(name)) add(options.routerModule ?? "@fluixi/core/router", name);
3713
+ else if (CORE_ONLY.has(name)) add(core, name);
3714
+ else if (CONTROL_FLOW.has(name)) add(options.controlFlowModule ?? runtime, name);
3715
+ else add(runtime, name);
3716
+ }
3717
+ for (const [name, src] of needs.resolved) {
3718
+ if (!bound.has(name)) add(src.module, src.export === "default" ? `default as ${name}` : name === src.export ? name : `${src.export} as ${name}`);
3719
+ }
3720
+ const lines = [];
3721
+ for (const [mod, names] of groups) {
3722
+ lines.push(`import { ${names.join(", ")} } from ${JSON.stringify(mod)};`);
3723
+ }
3724
+ const lazy = [...needs.deferred].filter(([name]) => !bound.has(name));
3725
+ if (lazy.length > 0) {
3726
+ if (!bound.has("deferred")) lines.push(`import { deferred } from ${JSON.stringify(core)};`);
3727
+ for (const [name, src] of lazy) {
3728
+ lines.push(
3729
+ `const ${name} = deferred(() => import(${JSON.stringify(src.module)}), { strategy: ${strategyLiteral(src.loading)}, export: ${JSON.stringify(src.export)} });`
3730
+ );
3731
+ }
3732
+ }
3733
+ for (const [key, name] of hoisted) {
3734
+ lines.push(`const ${name} = ${JSON.stringify(key.startsWith("svg:") ? key.slice(4) : key)};`);
3735
+ }
3736
+ if (needs.delegatedEvents.size > 0) {
3737
+ lines.push(`delegateEvents(${JSON.stringify([...needs.delegatedEvents])});`);
3738
+ }
3739
+ return lines.length > 0 ? lines.join("\n") + "\n" : null;
3740
+ }
3741
+ export {
3742
+ transformTemplates
3743
+ };