@fluixi/compiler 1.0.0-alpha.82 → 1.0.0-alpha.84

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 (188) 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.mjs +41 -1
  4. package/dist/analyze/intrinsics.cjs +80 -1
  5. package/dist/analyze/intrinsics.d.cts +66 -0
  6. package/dist/analyze/intrinsics.mjs +59 -1
  7. package/dist/analyze/paren.cjs +134 -0
  8. package/dist/analyze/paren.d.cts +23 -0
  9. package/dist/analyze/paren.d.ts +24 -0
  10. package/dist/analyze/paren.d.ts.map +1 -0
  11. package/dist/analyze/paren.js +168 -0
  12. package/dist/analyze/paren.mjs +113 -0
  13. package/dist/analyze/props-destructure.cjs +226 -1
  14. package/dist/analyze/props-destructure.d.cts +83 -0
  15. package/dist/analyze/props-destructure.mjs +205 -1
  16. package/dist/analyze/reactive-bindings.cjs +190 -1
  17. package/dist/analyze/reactive-bindings.d.cts +42 -0
  18. package/dist/analyze/reactive-bindings.mjs +167 -1
  19. package/dist/analyze/reactive-expr.cjs +38 -1
  20. package/dist/analyze/reactive-expr.d.cts +38 -0
  21. package/dist/analyze/reactive-expr.mjs +17 -1
  22. package/dist/analyze/static-graph.cjs +811 -0
  23. package/dist/analyze/static-graph.d.cts +102 -0
  24. package/dist/analyze/static-graph.d.ts +103 -0
  25. package/dist/analyze/static-graph.d.ts.map +1 -0
  26. package/dist/analyze/static-graph.js +869 -0
  27. package/dist/analyze/static-graph.mjs +793 -0
  28. package/dist/babel-NRW4EFTG.mjs +636 -0
  29. package/dist/chunk-3YKZ4GNH.mjs +11 -0
  30. package/dist/chunk-EZR7NZOY.mjs +1718 -0
  31. package/dist/chunk-FSSWUXUR.mjs +16 -0
  32. package/dist/chunk-MJV3UXIL.mjs +158 -0
  33. package/dist/chunk-R2VHAZAX.mjs +1078 -0
  34. package/dist/codegen/backend.cjs +18 -1
  35. package/dist/codegen/backend.d.cts +35 -0
  36. package/dist/codegen/backends/imperative.cjs +542 -1
  37. package/dist/codegen/backends/imperative.d.cts +11 -0
  38. package/dist/codegen/backends/imperative.d.ts.map +1 -1
  39. package/dist/codegen/backends/imperative.js +68 -13
  40. package/dist/codegen/backends/imperative.mjs +519 -1
  41. package/dist/codegen/contract.cjs +52 -1
  42. package/dist/codegen/contract.d.cts +24 -0
  43. package/dist/codegen/contract.mjs +31 -1
  44. package/dist/codegen/partial-template.cjs +176 -1
  45. package/dist/codegen/partial-template.d.cts +61 -0
  46. package/dist/codegen/partial-template.mjs +153 -1
  47. package/dist/codegen/serialize-static.cjs +125 -1
  48. package/dist/codegen/serialize-static.d.cts +38 -0
  49. package/dist/codegen/serialize-static.d.ts +16 -0
  50. package/dist/codegen/serialize-static.d.ts.map +1 -1
  51. package/dist/codegen/serialize-static.js +25 -0
  52. package/dist/codegen/serialize-static.mjs +104 -1
  53. package/dist/frontend/babel/build-ir-lit.cjs +1509 -1
  54. package/dist/frontend/babel/build-ir-lit.d.cts +26 -0
  55. package/dist/frontend/babel/build-ir-lit.mjs +1478 -1
  56. package/dist/frontend/babel/build-ir.cjs +1524 -1
  57. package/dist/frontend/babel/build-ir.d.cts +35 -0
  58. package/dist/frontend/babel/build-ir.mjs +1495 -1
  59. package/dist/frontend/babel/index.cjs +2186 -1
  60. package/dist/frontend/babel/index.d.cts +33 -0
  61. package/dist/frontend/babel/index.mjs +2156 -1
  62. package/dist/frontend/babel/lower-template.cjs +1507 -1
  63. package/dist/frontend/babel/lower-template.d.cts +23 -0
  64. package/dist/frontend/babel/lower-template.mjs +1478 -1
  65. package/dist/frontend/babel/plugin.cjs +2132 -1
  66. package/dist/frontend/babel/plugin.d.cts +95 -0
  67. package/dist/frontend/babel/plugin.mjs +2103 -1
  68. package/dist/frontend/babel/server-functions.cjs +110 -1
  69. package/dist/frontend/babel/server-functions.d.cts +10 -0
  70. package/dist/frontend/babel/server-functions.mjs +89 -1
  71. package/dist/frontend/babel/types.cjs +18 -1
  72. package/dist/frontend/babel/types.d.cts +33 -0
  73. package/dist/frontend/types.cjs +18 -1
  74. package/dist/frontend/types.d.cts +25 -0
  75. package/dist/frontend/vocabulary.cjs +98 -0
  76. package/dist/frontend/vocabulary.d.cts +79 -0
  77. package/dist/frontend/vocabulary.d.ts +80 -0
  78. package/dist/frontend/vocabulary.d.ts.map +1 -0
  79. package/dist/frontend/vocabulary.js +124 -0
  80. package/dist/frontend/vocabulary.mjs +77 -0
  81. package/dist/index.cjs +1594 -13
  82. package/dist/index.d.cts +27 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +3 -0
  85. package/dist/index.mjs +1574 -13
  86. package/dist/integrations.cjs +4307 -25
  87. package/dist/integrations.d.cts +215 -0
  88. package/dist/integrations.d.ts +16 -0
  89. package/dist/integrations.d.ts.map +1 -1
  90. package/dist/integrations.js +21 -2
  91. package/dist/integrations.mjs +531 -17
  92. package/dist/ir/nodes.cjs +18 -1
  93. package/dist/ir/nodes.d.cts +168 -0
  94. package/dist/ir/nodes.d.ts +46 -0
  95. package/dist/ir/nodes.d.ts.map +1 -1
  96. package/dist/lower/compile-template.cjs +1356 -1
  97. package/dist/lower/compile-template.d.cts +69 -0
  98. package/dist/lower/compile-template.d.ts +12 -0
  99. package/dist/lower/compile-template.d.ts.map +1 -1
  100. package/dist/lower/compile-template.js +5 -1
  101. package/dist/lower/compile-template.mjs +1336 -1
  102. package/dist/lower/jsx.cjs +529 -1
  103. package/dist/lower/jsx.d.cts +25 -0
  104. package/dist/lower/jsx.d.ts +2 -0
  105. package/dist/lower/jsx.d.ts.map +1 -1
  106. package/dist/lower/jsx.js +27 -4
  107. package/dist/lower/jsx.mjs +506 -1
  108. package/dist/lower/template.cjs +1061 -1
  109. package/dist/lower/template.d.cts +53 -0
  110. package/dist/lower/template.d.ts +14 -1
  111. package/dist/lower/template.d.ts.map +1 -1
  112. package/dist/lower/template.js +106 -19
  113. package/dist/lower/template.mjs +1042 -1
  114. package/dist/lower/text.cjs +42 -1
  115. package/dist/lower/text.d.cts +10 -0
  116. package/dist/lower/text.mjs +21 -1
  117. package/dist/optimize/analyze-static.cjs +112 -1
  118. package/dist/optimize/analyze-static.d.cts +39 -0
  119. package/dist/optimize/analyze-static.mjs +91 -1
  120. package/dist/optimize/collapse-strategies.cjs +90 -1
  121. package/dist/optimize/collapse-strategies.d.cts +30 -0
  122. package/dist/optimize/collapse-strategies.mjs +67 -1
  123. package/dist/options.cjs +33 -1
  124. package/dist/options.d.cts +39 -0
  125. package/dist/options.mjs +12 -1
  126. package/dist/resolve/builtins.cjs +73 -1
  127. package/dist/resolve/builtins.d.cts +68 -0
  128. package/dist/resolve/builtins.mjs +53 -1
  129. package/dist/resolve/component-globals.cjs +233 -13
  130. package/dist/resolve/component-globals.d.cts +80 -0
  131. package/dist/resolve/component-globals.mjs +210 -13
  132. package/dist/resolve/component-resolver.cjs +80 -1
  133. package/dist/resolve/component-resolver.d.cts +68 -0
  134. package/dist/resolve/component-resolver.mjs +59 -1
  135. package/dist/resolve/load-directive.cjs +93 -1
  136. package/dist/resolve/load-directive.d.cts +53 -0
  137. package/dist/resolve/load-directive.mjs +72 -1
  138. package/dist/resolve/resolve-ir.cjs +108 -1
  139. package/dist/resolve/resolve-ir.d.cts +53 -0
  140. package/dist/resolve/resolve-ir.mjs +85 -1
  141. package/dist/resolve/write-globals.cjs +318 -13
  142. package/dist/resolve/write-globals.d.cts +30 -0
  143. package/dist/resolve/write-globals.mjs +297 -13
  144. package/dist/server-fns-4ZXN6DYU.mjs +78 -0
  145. package/dist/server-functions-V6D6DRIA.mjs +82 -0
  146. package/dist/transform/bindings.cjs +71 -1
  147. package/dist/transform/bindings.d.cts +16 -0
  148. package/dist/transform/bindings.mjs +50 -1
  149. package/dist/transform/index.cjs +2732 -8
  150. package/dist/transform/index.d.cts +15 -0
  151. package/dist/transform/index.mjs +3773 -17
  152. package/dist/transform/intrinsics.cjs +216 -3
  153. package/dist/transform/intrinsics.d.cts +21 -0
  154. package/dist/transform/intrinsics.mjs +193 -3
  155. package/dist/transform/props.cjs +441 -3
  156. package/dist/transform/props.d.cts +45 -0
  157. package/dist/transform/props.mjs +1482 -12
  158. package/dist/transform/server-fn-id.cjs +35 -1
  159. package/dist/transform/server-fn-id.d.cts +9 -0
  160. package/dist/transform/server-fn-id.mjs +14 -1
  161. package/dist/transform/server-fns.cjs +114 -2
  162. package/dist/transform/server-fns.d.cts +12 -0
  163. package/dist/transform/server-fns.mjs +1155 -11
  164. package/dist/transform/source-locations.cjs +330 -0
  165. package/dist/transform/source-locations.d.cts +43 -0
  166. package/dist/transform/source-locations.d.ts +44 -0
  167. package/dist/transform/source-locations.d.ts.map +1 -0
  168. package/dist/transform/source-locations.js +238 -0
  169. package/dist/transform/source-locations.mjs +307 -0
  170. package/dist/transform/templates.cjs +2701 -7
  171. package/dist/transform/templates.d.cts +69 -0
  172. package/dist/transform/templates.d.ts +12 -4
  173. package/dist/transform/templates.d.ts.map +1 -1
  174. package/dist/transform/templates.js +72 -7
  175. package/dist/transform/templates.mjs +3743 -16
  176. package/dist/transform-BT4MMASR.mjs +893 -0
  177. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  178. package/package.json +6 -5
  179. package/dist/babel-4JUDAR2G.mjs +0 -1
  180. package/dist/chunk-3SAEGOMQ.mjs +0 -1
  181. package/dist/chunk-IBRM4W7I.mjs +0 -10
  182. package/dist/chunk-OHHZCYIQ.mjs +0 -1
  183. package/dist/chunk-PVR2SN3B.mjs +0 -1
  184. package/dist/chunk-QUIYULS2.mjs +0 -1
  185. package/dist/chunk-YR3SAEO7.mjs +0 -1
  186. package/dist/server-fns-6QM243HC.mjs +0 -2
  187. package/dist/server-functions-E3LKCZ4R.mjs +0 -1
  188. package/dist/transform-5WC4FWJE.mjs +0 -8
@@ -1 +1,1478 @@
1
- import{types as M}from"@babel/core";import ue from"@babel/generator";import{parseTemplate as Je}from"@fluixi/template-parser";var me={kind:"eager"},fe=["pointerdown","focusin","keydown"],B=new Set(["eager","idle","visible","interaction","media","never"]),m=class extends Error{};function P(e){return e.startsWith("load:")}function I(e,t){let n=e.slice(5);if(!B.has(n))throw new m(`Unknown load strategy 'load:${n}'. Expected one of ${[...B].join(", ")}.`);switch(n){case"eager":return me;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return t?{kind:"visible",rootMargin:t}:{kind:"visible"};case"interaction":return{kind:"interaction",events:t?he(t):[...fe]};case"media":if(!t)throw new m(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:t};default:throw new m(`Unhandled load strategy '${n}'.`)}}function he(e){let t=e.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new m("'load:interaction' was given no event names.");return t}var ge=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),F={className:"class",htmlFor:"for"},ve=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),ke=new Set(["script","style","textarea","title"]);function A(e){return ke.has(e)}function z(e){return F[e]??e}function f(e){return e.kind!=="attr"||e.expr!==void 0||e.name.includes(":")?!1:!ve.has(e.name)}function J(e){if(!e.static||A(e.tag))return!1;for(let t of e.props)if(!f(t))return!1;for(let t of e.children)if(t.kind!=="text"&&!(t.kind==="element"&&J(t)))return!1;return!0}function h(e){let t=e.props.map(ye).filter(Boolean).join(""),n=`<${e.tag}${t}>`;return ge.has(e.tag)?n:`${n}${e.children.map(xe).join("")}</${e.tag}>`}function xe(e){if(e.kind==="text")return Ee(e.value);if(e.kind!=="element")throw new Error(`serializeStatic: unexpected ${e.kind}`);return h(e)}function ye(e){let t=F[e.name]??e.name,n=e.literal;return n===!0||n===void 0?` ${t}`:n===!1||n===null?"":` ${t}="${Ne(String(n))}"`}function Ne(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ee(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var Re="<!--fx-->",be="<!--fx/-->";function w(e){return e.kind==="expr"||e.kind==="component"||e.kind==="control"}function Se(e){return e.kind==="text"||e.kind==="element"&&V(e)}function V(e){return e.svg||A(e.tag)||!e.props.every(t=>f(t))?!1:e.children.every(t=>Se(t)||w(t))}function $(e){if(w(e))return!0;let t=e.children;return t?t.some($):!1}function G(e){for(let t=0;t<e.children.length;t++){let n=e.children[t];if(n.kind==="text"&&(n.value===""||e.children[t+1]?.kind==="text"))return!1}return e.children.every(t=>t.kind!=="element"||G(t))}function W(e){if(!V(e)||!G(e)||!e.children.some($))return null;let t=[],n=[],r=0,i=l=>{let s=`_n$${r++}`;return t.push({ref:s,expr:l}),s};return o(e,"_el$"),{html:Ie(e),tag:e.tag,steps:t,holes:n};function o(l,s){let a=-1;l.children.forEach((p,d)=>{$(p)&&(a=d)});let c=null;for(let p=0;p<=a;p++){let d=l.children[p],u=c?`${c}.nextSibling`:`${s}.firstChild`;if(w(d)){let H=i(u),_=i(`holeEnd(${H})`);n.push({parentRef:s,startRef:H,endRef:_,node:d}),c=_;continue}let S=i(u);d.kind==="element"&&$(d)&&o(d,S),c=S}}}function Ie(e){return h(q(e)).split(U).join(Re+be)}function q(e){return{...e,children:e.children.map(t=>w(t)?{kind:"text",value:U}:t.kind==="element"?q(t):t)}}var U="\0fx-hole\0";var L={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},st={version:2,module:"@fluixi/dom",symbols:[...L.symbols,"template","cloneTemplate","walk"]};var $e={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function we(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function Z(e){return we(e)?e:JSON.stringify(e)}function Te(e){return e.expr!==void 0?e.reactive?`() => (${e.expr})`:`(${e.expr})`:JSON.stringify(e.literal??!0)}function Ce(e){return e.expr!==void 0?`(${e.expr})`:JSON.stringify(e.literal??!0)}function Pe(e,t,n){let r=e.filter(s=>s.kind==="spread"),o=e.filter(s=>s.kind!=="spread").map(s=>`${Z(s.name)}: ${Te(s)}`);t!=null&&o.push(`children: ${t}`);let l=`{ ${o.join(", ")} }`;return r.length>0?(n.add("mergeProps"),`mergeProps(${r.map(s=>s.expr).join(", ")}, ${l})`):l}function Y(e,t,n){return e.length===1?g(e[0],t,n):`[${e.map(r=>g(r,t,n)).join(", ")}]`}function K(e,t,n,r,i){r.add("createMemo"),r.add("createComponent");let o=t.filter(c=>c.kind==="spread"),s=t.filter(c=>c.kind!=="spread").map(c=>`get ${Z(c.name)}() { return ${Ce(c)}; }`);n.length>0&&s.push(`get children() { return ${Y(n,r,i)}; }`);let a=`{ ${s.join(", ")} }`;return o.length>0&&(r.add("mergeProps"),a=`mergeProps(${o.map(c=>c.expr).join(", ")}, ${a})`),`createMemo(() => createComponent(${e}, ${a}))`}function Ae(e,t){let n=z(t.name),r=t.literal;return r===!0||r===void 0?`${e}.setAttribute(${JSON.stringify(n)}, "");`:r===!1||r===null?"":`${e}.setAttribute(${JSON.stringify(n)}, ${JSON.stringify(String(r))});`}var Q=!1;function g(e,t,n){switch(e.kind){case"text":return JSON.stringify(e.value);case"expr":return e.reactive?`() => (${e.code})`:`(${e.code})`;case"fragment":return e.children.length===0?"null":Y(e.children,t,n);case"component":return K(e.name,e.props,e.children,t,n);case"control":{let r=$e[e.control]??e.control;return t.add(r),K(r,e.props,e.children,t,n)}case"element":{if(n&&e.static&&!e.svg&&J(e)){t.add("templateNode");let s=`_tmpl$${n.length}`;return n.push({id:s,html:h(e),tag:e.tag,svg:!1}),`templateNode(${s}, ${JSON.stringify(e.tag)})`}if(n&&Q){let s=W(e);if(s){t.add("templateNode"),t.add("insert"),t.add("holeEnd"),t.add("holeContent"),t.add("holeScope");let a=`_tmpl$${n.length}`;n.push({id:a,html:s.html,tag:s.tag,svg:!1});let c=[`const _el$ = templateNode(${a}, ${JSON.stringify(s.tag)}, true);`];for(let p of s.steps)c.push(`const ${p.ref} = ${p.expr};`);for(let p of s.holes)c.push(`insert(${p.parentRef}, holeScope(${p.startRef}, () => (${g(p.node,t,n)})), ${p.endRef}, holeContent(${p.startRef}, ${p.endRef}));`);return c.push("return _el$;"),`(() => { ${c.join(" ")} })()`}}t.add("createNativeElement");let r=JSON.stringify(e.tag),i="_el$",o=[],l=e.svg?`${r}, true`:r;if(o.push(`const ${i} = createNativeElement(${l});`),e.props.length>0)if(!e.svg&&e.props.every(f))for(let s of e.props)o.push(Ae(i,s));else{t.add("spread");let s=e.svg?", isSVG: true":"";o.push(`spread({ element: ${i}, props: ${Pe(e.props,null,t)}${s} });`)}for(let s of e.children){t.add("insert");let a=g(s,t,n),c=s.kind==="expr"&&s.reactive||s.kind==="component"||s.kind==="control";o.push(c?`insert(${i}, ${a}, null);`:`insert(${i}, ${a});`)}return o.push(`return ${i};`),`(() => { ${o.join(" ")} })()`}}}function v(e,t){if(!t||t.length===0)return e;let n=new Map(t.map(r=>[r.id,JSON.stringify(r.html)]));return e.replace(/_tmpl\$\d+/g,r=>n.get(r)??r)}var k={name:"imperative",contract:L,emit(e,t){let n=new Set,r=t?.templateClone!==!1?[]:void 0;return Q=t?.partialTemplates===!0,{code:g(e,n,r),imports:Array.from(n),templates:r}}};function x(e){let t=e.split(/\r\n|\n|\r/),n=0;for(let i=0;i<t.length;i++)/[^ \t]/.test(t[i])&&(n=i);let r="";for(let i=0;i<t.length;i++){let o=t[i].replace(/\t/g," ");i!==0&&(o=o.replace(/^ +/,"")),i!==t.length-1&&(o=o.replace(/ +$/,"")),o&&(i!==n&&(o+=" "),r+=o)}return r}var ee=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Le(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function te(e){return e.charAt(0).toUpperCase()+e.slice(1)}var D=class{constructor(t,n){this.holes=t;this.used=n}hole(t){return this.holes[t]??{code:"undefined",reactive:!1}}emit(t){let{code:n,imports:r,templates:i}=k.emit(t,{});for(let o of r)this.used.add(o);return v(n,i)}lowerRoot(t){let n=this.lowerChildren(t);return n.length===1?n[0]:{kind:"fragment",children:n}}lowerChildren(t){let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(i.kind==="Element"||i.kind==="Component"){let l=i.attributes.find(s=>s.kind==="IfDirective");if(l&&l.kind==="IfDirective"){let s=r+1;s<t.length&&this.isBlankText(t[s])&&s++;let a=t[s],c=a&&(a.kind==="Element"||a.kind==="Component")&&a.attributes.some(p=>p.kind==="ElseDirective");n.push(this.lowerIf(i,l.hole,c?a:null)),c&&(r=s);continue}if(i.attributes.some(s=>s.kind==="EachDirective")){n.push(this.lowerEach(i));continue}}let o=this.lowerNode(i);o&&n.push(o)}return n}isBlankText(t){return t.kind==="Text"&&!t.raw&&x(t.value)===""}lowerNode(t){switch(t.kind){case"Text":{if(t.raw)return{kind:"text",value:t.value};let n=x(t.value);return n?{kind:"text",value:n}:null}case"Comment":return null;case"Expression":{let n=this.hole(t.hole);return{kind:"expr",code:n.code,reactive:n.reactive}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(t.children)};case"Element":return this.lowerElement(t);case"Component":return this.lowerComponent(t);default:return null}}lowerElement(t){let n=t.attributes.find(r=>r.kind==="Attribute"&&r.name==="is");if(t.tag==="component"&&n&&n.value&&n.value.kind==="hole"){let r=t.attributes.filter(o=>o!==n),i=this.lowerComponent({...t,kind:"Component",tag:"Dynamic",tagHole:null,attributes:r});return i.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(n.value.hole).code})`}),i}return{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:this.lowerAttributes(t.attributes),children:this.lowerChildren(t.children),static:!1}}lowerComponent(t){let n=t.tagHole!=null?this.hole(t.tagHole).code:t.tag,r=this.lowerAttributes(t.attributes),{slots:i,rest:o}=this.partitionSlots(t.children);for(let[a,c]of i){let p=c.length===1?c[0]:{kind:"fragment",children:c},d={name:a,kind:"attr",expr:this.emit(p),jsxElement:!0},u=r.findIndex(S=>S.name===a);u>=0?r[u]=d:r.push(d)}let l=t.attributes.find(a=>a.kind==="LoadDirective"),s=l?I(`load:${l.strategy}`,l.modifier):void 0;return{kind:"component",name:n,props:r,children:this.lowerChildren(o),...s?{load:s}:{}}}partitionSlots(t){let n=new Map,r=[];for(let i of t){if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(l=>l.kind==="Attribute"&&l.name==="slot");if(o&&o.value&&o.value.kind==="static"){let l={...i,attributes:i.attributes.filter(c=>c!==o)},s=l.kind==="Element"?this.lowerElement(l):this.lowerComponent(l),a=n.get(o.value.value)??[];a.push(s),n.set(o.value.value,a);continue}}r.push(i)}return{slots:n,rest:r}}lowerIf(t,n,r){let i=this.hole(n),o=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive}];if(r){let s=this.stripAndLower(r,a=>a.kind==="ElseDirective");o.push({name:"fallback",kind:"attr",expr:this.emit(s),jsxElement:!0})}let l=this.stripAndLower(t,s=>s.kind==="IfDirective");return{kind:"component",name:"Show",props:o,children:[l]}}lowerEach(t){let n=t.attributes.find(a=>a.kind==="EachDirective");if(!n||n.kind!=="EachDirective")return this.lowerNode(t);let r=this.hole(n.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive}];if(n.key){let a="static"in n.key?`(item) => item[${JSON.stringify(n.key.static)}]`:this.hole(n.key.hole).code;i.push({name:"by",kind:"attr",expr:a})}let o=this.itemArrow(t),l;if(o){let a={kind:"expr",code:o.body,reactive:o.bodyReactive},c=this.rebuildWithChildren(t,[a]);l=`(${o.params.join(", ")}) => (${this.emit(c)})`}else{let a=this.stripAndLower(t,c=>c.kind==="EachDirective");l=`() => (${this.emit(a)})`}return{kind:"component",name:"For",props:i,children:[{kind:"expr",code:l,reactive:!1}]}}itemArrow(t){let n=t.children.filter(r=>!this.isBlankText(r));return n.length!==1||n[0].kind!=="Expression"?null:this.hole(n[0].hole).arrow??null}stripAndLower(t,n){let r={...t,attributes:t.attributes.filter(i=>!n(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(t,n){let r=this.lowerAttributes(t.attributes.filter(i=>i.kind!=="EachDirective"));return t.kind==="Element"?{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:r,children:n,static:!1}:{kind:"component",name:t.tag,props:r,children:n}}lowerAttributes(t){let n=[],r=[],i=!1,o=[],l=!1,s=[];for(let a of t)switch(a.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":n.push(this.plainAttr(a));break;case"PropertyBinding":n.push({name:a.name,kind:"prop",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"EventBinding":n.push(this.eventProp(a));break;case"RefBinding":n.push({name:"ref",kind:"ref",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"Spread":n.push({name:"",kind:"spread",expr:this.hole(a.hole).code});break;case"ClassDirective":{let c=this.hole(a.hole);r.push(`${JSON.stringify(a.name)}: ${c.code}`),i=i||c.reactive;break}case"StyleDirective":{let c=this.hole(a.hole);o.push(`${JSON.stringify(a.name)}: ${c.code}`),l=l||c.reactive;break}case"BindDirective":n.push(...this.bindProps(a.name,this.hole(a.hole).code));break;case"UseDirective":{let c=a.name??(a.hole!=null?this.hole(a.hole).code:null);if(!c)break;s.push(a.name!=null&&a.hole!=null?`[${c}, () => (${this.hole(a.hole).code})]`:`[${c}]`);break}}return r.length>0&&n.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i}),o.length>0&&n.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:l}),s.length>0&&n.push({name:"use",kind:"attr",expr:`[${s.join(", ")}]`}),n}eventProp(t){let n=t.name.toLowerCase(),r=this.hole(t.hole).code;if(!(t.syntax==="colon"||t.modifiers.length>0))return{name:"on"+te(t.name),kind:"event",event:{name:n,delegated:ee.has(n)},expr:r};let o=this.wrapHandler(r,t.modifiers),l=this.eventOptions(t.modifiers),s=l?`[${o}, ${l}]`:o;return{name:"on:"+n,kind:"attr",expr:s}}wrapHandler(t,n){let r=n.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return n.includes("prevent")&&i.push("e.preventDefault();"),n.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?t:`(e) => { ${r}${i.join(" ")} return (${t})(e); }`}eventOptions(t){let n=[];return t.includes("capture")&&n.push("capture: true"),t.includes("once")&&n.push("once: true"),t.includes("passive")&&n.push("passive: true"),n.length?`{ ${n.join(", ")} }`:null}bindProps(t,n){let r=t==="checked",i=r?"change":"input",o=r?"checked":"value";this.used.add("bindPair");let l=`bindPair(${n})`;return[{name:t,kind:"attr",expr:`${l}[0]()`,reactive:!0},{name:"on"+te(i),kind:"event",event:{name:i,delegated:ee.has(i)},expr:`(e) => ${l}[1](e.target.${o})`}]}plainAttr(t){let n=t.value,r=t.name;t.name==="class"?r=n&&n.kind==="hole"&&this.hole(n.hole).object?"classList":"className":t.name==="html"&&(r="innerHTML");let o={name:r,kind:"attr"};if(n==null)return o.literal=!0,o;if(n.kind==="static")return o.literal=n.value,o;if(n.kind==="hole"){let a=this.hole(n.hole);return o.expr=a.code,o.reactive=a.reactive,o}let l=!1,s=n.parts.map(a=>{if("text"in a)return Le(a.text);let c=this.hole(a.hole);return l=l||c.reactive,"${"+c.code+"}"}).join("");return o.expr="`"+s+"`",o.reactive=l,o}};function ne(e,t,n,r={}){let{root:i}=Je(e,{svg:r.svg});return new D(t,n).lowerRoot(i.children)}import{types as b,traverse as We,template as qe}from"@babel/core";import pe from"@babel/generator";function De(e){switch(e.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 e.reactive?"reactive-prop":e.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function T(e){let t=[],n=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let o of i.children)r(o);return!1;case"fragment":for(let o of i.children)r(o);return!1;case"element":{let o=!0;for(let s of i.children)r(s)||(o=!1);let l;for(let s of i.props)if(l=De(s),l)break;return!l&&!o&&(l=je(i)),i.static=!l,l?n.set(i,l):t.push(i),i.static}default:return!1}};for(let i of Array.isArray(e)?e:[e])r(i);return{staticElements:t,reasons:n}}function je(e){for(let t of e.children){if(t.kind==="expr")return"expression-child";if(t.kind==="component")return"component-child";if(t.kind==="control")return"control-child";if(t.kind==="element"&&!t.static||t.kind==="fragment")return"expression-child"}return"expression-child"}function re(e,t=new Set,n={}){let r=ie(e,t,n);return T(r),r}var Oe="children";function y(e){switch(e.kind){case"call":return!0;case"member":return e.property!==Oe;case"compound":return e.parts.some(y);case"opaque":return!1}}var Xe=new Set(["CallExpression","OptionalCallExpression"]),Me=new Set(["MemberExpression","OptionalMemberExpression"]);function E(e){if(!e)return{kind:"opaque"};if(Xe.has(e.type))return{kind:"call"};if(Me.has(e.type)){let t=e.property;return{kind:"member",property:!(e.computed===!0)&&t?.type==="Identifier"?t.name:null}}return e.type==="ConditionalExpression"?{kind:"compound",parts:[e.test,e.consequent,e.alternate].map(N)}:e.type==="LogicalExpression"||e.type==="BinaryExpression"?{kind:"compound",parts:[e.left,e.right].map(N)}:e.type==="TemplateLiteral"?{kind:"compound",parts:e.expressions.map(N)}:e.type==="ObjectExpression"?{kind:"compound",parts:e.properties.filter(n=>(n.type==="ObjectProperty"||n.type==="Property")&&n.computed!==!0).map(n=>N(n.value))}:e.type==="ArrayExpression"?{kind:"compound",parts:e.elements.filter(n=>n!=null&&n.type!=="SpreadElement").map(N)}:{kind:"opaque"}}var N=e=>E(e);var He=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),_e=/^on[A-Z]/,Be=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]),ae=e=>y(E(e));function R(e){if(e.type==="StringLiteral"||e.type==="NumericLiteral"||e.type==="BooleanLiteral"||e.type==="Literal"&&(typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"))return e.value}var j=e=>!!e&&typeof R(e)=="string";function Fe(e,t){return e.type==="JSXIdentifier"?{tag:e.name,component:e.name[0]!==e.name[0].toLowerCase()}:e.type==="JSXMemberExpression"?{tag:t.code(e),component:!0}:e.type==="JSXNamespacedName"?{tag:`${e.namespace.name}:${e.name.name}`,component:!1}:{tag:"div",component:!1}}function O(e){return e.type==="JSXIdentifier"?e.name==="class"?"className":e.name:e.type==="JSXNamespacedName"?`${e.namespace.name}:${e.name.name}`:"unknown"}function ze(e,t){let n=O(e.name),r=_e.test(n),i=r||n.startsWith("on:")||n==="ref",l={name:n,kind:r?"event":"attr"};if(r){let a=n.slice(2).toLowerCase();l.event={name:a,delegated:Be.has(a)}}let s=e.value;if(s==null)return l.literal=!0,l;if(j(s))return l.literal=R(s),l;if(s.type==="JSXExpressionContainer"&&s.expression?.type!=="JSXEmptyExpression"){let a=s.expression,c=R(a);return c!==void 0?(l.literal=c,l):(l.expr=t.code(a),l.reactive=i?!1:ae(a),(a.type==="JSXElement"||a.type==="JSXFragment")&&(l.jsxElement=!0),l)}return l.literal=!0,l}function oe(e,t){let n=e.value;return n==null?null:j(n)?JSON.stringify(R(n)):n.type==="JSXExpressionContainer"&&n.expression?.type!=="JSXEmptyExpression"?t.code(n.expression):null}function Ve(e,t){let n=[],r=[];for(let i of e){if(i.type==="JSXSpreadAttribute"){n.push({name:"",kind:"spread",expr:t.code(i.argument)});continue}if(i.type!=="JSXAttribute"||P(O(i.name)))continue;let o=i.name.type==="JSXNamespacedName"?i.name.namespace.name:null;if(o==="use"){let l=i.name.name.name;t.used.add(l);let s=oe(i,t);r.push(s!=null?`[${l}, () => (${s})]`:`[${l}]`);continue}if(o==="oncapture"){let l=i.name.name.name.toLowerCase(),s=oe(i,t)??"undefined";n.push({name:"on:"+l,kind:"attr",expr:`[${s}, { capture: true }]`});continue}n.push(ze(i,t))}return r.length>0&&n.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),n}function se(e,t){let n=[];for(let r of e)if(r.type==="JSXText"){let i=x(r.value);i&&n.push({kind:"text",value:i})}else if(r.type==="JSXExpressionContainer"){if(r.expression?.type!=="JSXEmptyExpression"){let i=r.expression;n.push({kind:"expr",code:t.code(i),reactive:ae(i)})}}else r.type==="JSXElement"||r.type==="JSXFragment"?n.push(le(r,t)):r.type==="JSXSpreadChild"&&n.push({kind:"expr",code:t.code(r.expression),reactive:!1});return n}function Ge(e){for(let t of e){if(t.type!=="JSXAttribute")continue;let n=O(t.name);if(P(n)){if(t.value&&!j(t.value))throw new m(`'${n}' needs a literal value, not an expression — the strategy is compile-time.`);return I(n,t.value?R(t.value):null)}}}function le(e,t){if(e.type==="JSXFragment")return{kind:"fragment",children:se(e.children,t)};let{tag:n,component:r}=Fe(e.openingElement.name,t),i=Ve(e.openingElement.attributes,t),o=se(e.children,t);if(r){let l=Ge(e.openingElement.attributes);return{kind:"component",name:n,props:i,children:o,...l?{load:l}:{}}}return{kind:"element",tag:n,svg:He.has(n),props:i,children:o,static:!1}}function ce(e,t){let n=le(e,t);return T(n),n}var Ue=pe.default??pe;function de(e){return Ue(e,{concise:!0}).code}function Ke(e,t,n){let r=b.cloneNode(e,!0),i=b.file(b.program([b.expressionStatement(r)])),o=!1,l=(s,a,c)=>{for(let p of c)t.add(p);s.replaceWith(qe.expression(a,{placeholderPattern:!1,plugins:["typescript"]})()),s.skip(),o=!0};return We(i,{"JSXElement|JSXFragment"(s){let a=s.node,c=Ze(a,t,n);n?.(c);let{code:p,imports:d,templates:u}=k.emit(c,{});l(s,v(p,u),d)},TaggedTemplateExpression(s){let a=s.node.tag;if(!b.isIdentifier(a)||a.name!=="html"&&a.name!=="svg")return;let c=re(s.node,t,{svg:a.name==="svg",onNested:n});n?.(c);let{code:p,imports:d,templates:u}=k.emit(c,{});l(s,v(p,u),d)}}),o?i.program.body[0].expression:e}function C(e,t,n){return de(Ke(e,t,n))}function X(e){return y(E(e))}function Ze(e,t=new Set,n){return ce(e,{code:i=>i.type==="JSXMemberExpression"?de(i):C(i,t,n),used:t})}var Ye=ue.default??ue;function Qe(e){return Ye(e,{concise:!0}).code}function et(e,t,n){let r={code:C(e,t,n),reactive:X(e)};if(M.isArrowFunctionExpression(e)&&!M.isBlockStatement(e.body)){let i=e.body;r.arrow={params:e.params.map(o=>Qe(o)),body:C(i,t,n),bodyReactive:X(i)}}return M.isObjectExpression(e)&&(r.object=!0),r}function ie(e,t,n={}){let r=e.quasi,i=r.expressions.map(o=>et(o,t,n.onNested));return ne(tt(r),i,t,n)}function tt(e){let t=[];return e.quasis.forEach((n,r)=>{let i=n.value.cooked??n.value.raw;if(t.push({kind:"static",text:i,start:n.start??0}),r<e.expressions.length){let o=e.expressions[r];t.push({kind:"hole",index:r,start:o.start??0,end:o.end??0})}}),t}export{ie as lowerLitTemplate};
1
+ // src/frontend/babel/lower-template.ts
2
+ import { types as t2 } from "@babel/core";
3
+ import _generate2 from "@babel/generator";
4
+
5
+ // src/lower/template.ts
6
+ import {
7
+ parseTemplate
8
+ } from "@fluixi/template-parser";
9
+
10
+ // src/resolve/load-directive.ts
11
+ var EAGER = { kind: "eager" };
12
+ var DEFAULT_INTERACTION_EVENTS = ["pointerdown", "focusin", "keydown"];
13
+ var STRATEGIES = /* @__PURE__ */ new Set(["eager", "idle", "visible", "interaction", "media", "never"]);
14
+ var LoadDirectiveError = class extends Error {
15
+ };
16
+ function isLoadDirective(name) {
17
+ return name.startsWith("load:");
18
+ }
19
+ function parseLoadDirective(name, value) {
20
+ const strategy = name.slice("load:".length);
21
+ if (!STRATEGIES.has(strategy)) {
22
+ throw new LoadDirectiveError(
23
+ `Unknown load strategy 'load:${strategy}'. Expected one of ${[...STRATEGIES].join(", ")}.`
24
+ );
25
+ }
26
+ switch (strategy) {
27
+ case "eager":
28
+ return EAGER;
29
+ case "idle":
30
+ return { kind: "idle" };
31
+ case "never":
32
+ return { kind: "never" };
33
+ case "visible":
34
+ return value ? { kind: "visible", rootMargin: value } : { kind: "visible" };
35
+ case "interaction":
36
+ return {
37
+ kind: "interaction",
38
+ events: value ? splitEvents(value) : [...DEFAULT_INTERACTION_EVENTS]
39
+ };
40
+ case "media":
41
+ if (!value) {
42
+ throw new LoadDirectiveError(
43
+ `'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`
44
+ );
45
+ }
46
+ return { kind: "media", query: value };
47
+ default:
48
+ throw new LoadDirectiveError(`Unhandled load strategy '${strategy}'.`);
49
+ }
50
+ }
51
+ function splitEvents(value) {
52
+ const events = value.split(/[\s,]+/).map((e) => e.trim()).filter(Boolean);
53
+ if (events.length === 0) {
54
+ throw new LoadDirectiveError(`'load:interaction' was given no event names.`);
55
+ }
56
+ return events;
57
+ }
58
+
59
+ // src/codegen/serialize-static.ts
60
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
61
+ "area",
62
+ "base",
63
+ "br",
64
+ "col",
65
+ "embed",
66
+ "hr",
67
+ "img",
68
+ "input",
69
+ "link",
70
+ "meta",
71
+ "param",
72
+ "source",
73
+ "track",
74
+ "wbr"
75
+ ]);
76
+ var HTML_NAME = {
77
+ className: "class",
78
+ htmlFor: "for"
79
+ };
80
+ var PROPERTY_ONLY = /* @__PURE__ */ new Set([
81
+ "innerHTML",
82
+ "outerHTML",
83
+ "innerText",
84
+ "textContent",
85
+ "value",
86
+ "checked",
87
+ "selected",
88
+ "muted",
89
+ "defaultValue",
90
+ "defaultChecked",
91
+ "children",
92
+ "ref"
93
+ ]);
94
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
95
+ function isRawTextElement(tag) {
96
+ return RAW_TEXT_ELEMENTS.has(tag);
97
+ }
98
+ function htmlAttrName(name) {
99
+ return HTML_NAME[name] ?? name;
100
+ }
101
+ function isPlainLiteralAttr(prop) {
102
+ if (prop.kind !== "attr") return false;
103
+ if (prop.expr !== void 0) return false;
104
+ if (prop.name.includes(":")) return false;
105
+ return !PROPERTY_ONLY.has(prop.name);
106
+ }
107
+ function isSerializable(node) {
108
+ if (!node.static) return false;
109
+ if (isRawTextElement(node.tag)) return false;
110
+ for (const prop of node.props) {
111
+ if (!isPlainLiteralAttr(prop)) return false;
112
+ }
113
+ for (const child of node.children) {
114
+ if (child.kind === "text") continue;
115
+ if (child.kind === "element" && isSerializable(child)) continue;
116
+ return false;
117
+ }
118
+ return true;
119
+ }
120
+ function serializeStatic(node) {
121
+ const attrs = node.props.map(serializeProp).filter(Boolean).join("");
122
+ const open = `<${node.tag}${attrs}>`;
123
+ if (VOID_ELEMENTS.has(node.tag)) return open;
124
+ return `${open}${node.children.map(serializeChild).join("")}</${node.tag}>`;
125
+ }
126
+ function serializeChild(child) {
127
+ if (child.kind === "text") return escapeText(child.value);
128
+ if (child.kind !== "element") throw new Error(`serializeStatic: unexpected ${child.kind}`);
129
+ return serializeStatic(child);
130
+ }
131
+ function serializeProp(prop) {
132
+ const name = HTML_NAME[prop.name] ?? prop.name;
133
+ const value = prop.literal;
134
+ if (value === true || value === void 0) return ` ${name}`;
135
+ if (value === false || value === null) return "";
136
+ return ` ${name}="${escapeAttr(String(value))}"`;
137
+ }
138
+ function escapeAttr(value) {
139
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
140
+ }
141
+ function escapeText(value) {
142
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
143
+ }
144
+ function templatePositions(root) {
145
+ const pos = [];
146
+ let file;
147
+ const walk = (el) => {
148
+ file ??= el.at?.file;
149
+ pos.push(el.at?.line ?? 0, el.at?.column ?? 0);
150
+ for (const child of el.children) if (child.kind === "element") walk(child);
151
+ };
152
+ walk(root);
153
+ return file && pos.some((n) => n !== 0) ? { file, pos } : void 0;
154
+ }
155
+
156
+ // src/codegen/partial-template.ts
157
+ var HOLE_START = "<!--fx-->";
158
+ var HOLE_END = "<!--fx/-->";
159
+ function isHole(node) {
160
+ return node.kind === "expr" || node.kind === "component" || node.kind === "control";
161
+ }
162
+ function isTemplateChild(node) {
163
+ return node.kind === "text" || node.kind === "element" && isTemplateElement(node);
164
+ }
165
+ function isTemplateElement(node) {
166
+ if (node.svg) return false;
167
+ if (isRawTextElement(node.tag)) return false;
168
+ if (!node.props.every((p) => isPlainLiteralAttr(p))) return false;
169
+ return node.children.every((c) => isTemplateChild(c) || isHole(c));
170
+ }
171
+ function containsHole(node) {
172
+ if (isHole(node)) return true;
173
+ const children = node.children;
174
+ return children ? children.some(containsHole) : false;
175
+ }
176
+ function addressable(el) {
177
+ for (let i = 0; i < el.children.length; i++) {
178
+ const child = el.children[i];
179
+ if (child.kind === "text") {
180
+ if (child.value === "") return false;
181
+ if (el.children[i + 1]?.kind === "text") return false;
182
+ }
183
+ }
184
+ return el.children.every((c) => c.kind !== "element" || addressable(c));
185
+ }
186
+ function planPartialTemplate(root) {
187
+ if (!isTemplateElement(root)) return null;
188
+ if (!addressable(root)) return null;
189
+ if (!root.children.some(containsHole)) return null;
190
+ const steps = [];
191
+ const holes = [];
192
+ let refCount = 0;
193
+ const declare = (expr) => {
194
+ const ref = `_n$${refCount++}`;
195
+ steps.push({ ref, expr });
196
+ return ref;
197
+ };
198
+ walk(root, "_el$");
199
+ return { html: serializeWithMarkers(root), tag: root.tag, steps, holes };
200
+ function walk(el, elementRef) {
201
+ let last = -1;
202
+ el.children.forEach((child, i) => {
203
+ if (containsHole(child)) last = i;
204
+ });
205
+ let previous = null;
206
+ for (let i = 0; i <= last; i++) {
207
+ const child = el.children[i];
208
+ const expr = previous ? `${previous}.nextSibling` : `${elementRef}.firstChild`;
209
+ if (isHole(child)) {
210
+ const startRef = declare(expr);
211
+ const endRef = declare(`holeEnd(${startRef})`);
212
+ holes.push({ parentRef: elementRef, startRef, endRef, node: child });
213
+ previous = endRef;
214
+ continue;
215
+ }
216
+ const ref = declare(expr);
217
+ if (child.kind === "element" && containsHole(child)) walk(child, ref);
218
+ previous = ref;
219
+ }
220
+ }
221
+ }
222
+ function serializeWithMarkers(el) {
223
+ return serializeStatic(withSentinels(el)).split(SENTINEL).join(HOLE_START + HOLE_END);
224
+ }
225
+ function withSentinels(el) {
226
+ return {
227
+ ...el,
228
+ children: el.children.map(
229
+ (child) => isHole(child) ? { kind: "text", value: SENTINEL } : child.kind === "element" ? withSentinels(child) : child
230
+ )
231
+ };
232
+ }
233
+ var SENTINEL = "\0fx-hole\0";
234
+
235
+ // src/codegen/contract.ts
236
+ var RUNTIME_CONTRACT_V1 = {
237
+ version: 1,
238
+ module: "@fluixi/dom",
239
+ symbols: [
240
+ "createNativeElement",
241
+ "insert",
242
+ "spread",
243
+ "setAttribute",
244
+ "delegateEvents",
245
+ "createComponent",
246
+ "createMemo",
247
+ "untrack",
248
+ "Show",
249
+ "For",
250
+ "Index",
251
+ "Switch",
252
+ "Match",
253
+ "Dynamic",
254
+ "ErrorBoundary"
255
+ ]
256
+ };
257
+ var RUNTIME_CONTRACT_V2 = {
258
+ version: 2,
259
+ module: "@fluixi/dom",
260
+ symbols: [...RUNTIME_CONTRACT_V1.symbols, "template", "cloneTemplate", "walk"]
261
+ };
262
+
263
+ // src/analyze/intrinsics.ts
264
+ var REACTIVE_MODULE = "@fluixi/reactive/signal";
265
+ var INTRINSICS = {
266
+ $signal: { export: "signal", module: REACTIVE_MODULE, returns: "signal-handle" },
267
+ $memo: { export: "memo", module: REACTIVE_MODULE, returns: "memo-handle" },
268
+ $effect: { export: "effect", module: REACTIVE_MODULE, returns: "effect" },
269
+ $store: { export: "store", module: "@fluixi/reactive/store", returns: "store-handle" },
270
+ $resource: { export: "resource", module: REACTIVE_MODULE, returns: "resource-handle" },
271
+ // No short runtime form for these yet, so the intrinsic stands for the `create*`
272
+ // name. Still worth having — no import to write — and when a shorter form is
273
+ // designed, the change is this line rather than a compiler pass.
274
+ $selector: { export: "createSelector", module: REACTIVE_MODULE, returns: "memo-accessor" },
275
+ $deferred: { export: "createDeferred", module: REACTIVE_MODULE, returns: "memo-accessor" },
276
+ // Not value constructors, but the compiler has to know them: they change what a read
277
+ // does. `untrack` suppresses dependency collection, which is exactly the kind of thing
278
+ // dependency analysis must not guess at.
279
+ $untrack: { export: "untrack", module: REACTIVE_MODULE, returns: "plain" },
280
+ $untrackStore: { export: "untrackStore", module: "@fluixi/reactive/store", returns: "plain" }
281
+ };
282
+ var INTRINSIC_CALL = new RegExp(`\\$(?:${Object.keys(INTRINSICS).map((n) => n.slice(1)).join("|")})\\s*\\(`);
283
+
284
+ // src/transform/source-locations.ts
285
+ var SOURCE_MARKER = "__fx_source";
286
+ var HOLE_MARKER = "__fx_hole";
287
+ var markHole = (accessor, line, column, name) => `(globalThis.${HOLE_MARKER} ?? ((f) => f))(${accessor},${line},${column}${name === void 0 ? "" : `,${JSON.stringify(name)}`})`;
288
+ var PROPS_MARKER = "__fx_props";
289
+ var markProps = (object, at) => `(globalThis.${PROPS_MARKER} ?? ((p) => p))(${object},${JSON.stringify(at)})`;
290
+
291
+ // src/analyze/paren.ts
292
+ function skipQuoted(src, start) {
293
+ const quote = src[start];
294
+ for (let i = start + 1; i < src.length; i++) {
295
+ const c = src[i];
296
+ if (c === "\\") i++;
297
+ else if (c === quote) return i + 1;
298
+ else if (c === "\n") return -1;
299
+ }
300
+ return -1;
301
+ }
302
+ function skipTemplate(src, start) {
303
+ let i = start + 1;
304
+ while (i < src.length) {
305
+ const c = src[i];
306
+ if (c === "\\") {
307
+ i += 2;
308
+ } else if (c === "`") {
309
+ return i + 1;
310
+ } else if (c === "$" && src[i + 1] === "{") {
311
+ let depth = 1;
312
+ i += 2;
313
+ while (i < src.length && depth > 0) {
314
+ const k = src[i];
315
+ if (k === "\\") i += 2;
316
+ else if (k === "`") {
317
+ const end = skipTemplate(src, i);
318
+ if (end < 0) return -1;
319
+ i = end;
320
+ } else if (k === '"' || k === "'") {
321
+ const end = skipQuoted(src, i);
322
+ if (end < 0) return -1;
323
+ i = end;
324
+ } else {
325
+ if (k === "{") depth++;
326
+ else if (k === "}") depth--;
327
+ i++;
328
+ }
329
+ }
330
+ } else {
331
+ i++;
332
+ }
333
+ }
334
+ return -1;
335
+ }
336
+ function skipRegex(src, start) {
337
+ let inClass = false;
338
+ for (let i = start + 1; i < src.length; i++) {
339
+ const c = src[i];
340
+ if (c === "\\") i++;
341
+ else if (c === "[") inClass = true;
342
+ else if (c === "]") inClass = false;
343
+ else if (c === "\n") return -1;
344
+ else if (c === "/" && !inClass) {
345
+ let end = i + 1;
346
+ while (end < src.length && /[a-z]/i.test(src[end])) end++;
347
+ return end;
348
+ }
349
+ }
350
+ return -1;
351
+ }
352
+ function divides(prev) {
353
+ return prev !== "" && /[A-Za-z0-9_$)\]]/.test(prev);
354
+ }
355
+ function topLevelComma(src) {
356
+ let depth = 0;
357
+ let prev = "";
358
+ let i = 0;
359
+ while (i < src.length) {
360
+ const c = src[i];
361
+ if (c === '"' || c === "'") {
362
+ const end = skipQuoted(src, i);
363
+ if (end < 0) return null;
364
+ i = end;
365
+ prev = c;
366
+ } else if (c === "`") {
367
+ const end = skipTemplate(src, i);
368
+ if (end < 0) return null;
369
+ i = end;
370
+ prev = c;
371
+ } else if (c === "/" && src[i + 1] === "/") {
372
+ return null;
373
+ } else if (c === "/" && src[i + 1] === "*") {
374
+ const end = src.indexOf("*/", i + 2);
375
+ if (end < 0) return null;
376
+ i = end + 2;
377
+ } else if (c === "/" && !divides(prev)) {
378
+ const end = skipRegex(src, i);
379
+ if (end < 0) return null;
380
+ i = end;
381
+ prev = "/";
382
+ } else {
383
+ if (c === "(" || c === "[" || c === "{") depth++;
384
+ else if (c === ")" || c === "]" || c === "}") {
385
+ depth--;
386
+ if (depth < 0) return null;
387
+ } else if (c === "," && depth === 0) return true;
388
+ if (!/\s/.test(c)) prev = c;
389
+ i++;
390
+ }
391
+ }
392
+ return depth === 0 ? false : null;
393
+ }
394
+ function paren(code, position) {
395
+ const src = code.trim();
396
+ if (src === "") return `(${code})`;
397
+ if (position === "arrowBody" && src[0] === "{") return `(${code})`;
398
+ return topLevelComma(src) === false ? code : `(${code})`;
399
+ }
400
+
401
+ // src/codegen/backends/imperative.ts
402
+ var CONTROL_COMPONENT = {
403
+ show: "Show",
404
+ for: "For",
405
+ index: "Index",
406
+ switch: "Switch",
407
+ match: "Match",
408
+ dynamic: "Dynamic",
409
+ errorBoundary: "ErrorBoundary",
410
+ suspense: "Suspense"
411
+ };
412
+ function isIdent(name) {
413
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
414
+ }
415
+ function propKey(name) {
416
+ return isIdent(name) ? name : JSON.stringify(name);
417
+ }
418
+ function propValue(p) {
419
+ if (p.expr !== void 0) {
420
+ if (p.name === "ref" && p.at)
421
+ return markHole(paren(p.expr, "value"), p.at.line, p.at.column, p.expr);
422
+ if (!p.reactive) return paren(p.expr, "value");
423
+ const accessor = `() => ${paren(p.expr, "arrowBody")}`;
424
+ return p.at ? markHole(accessor, p.at.line, p.at.column, p.directive) : accessor;
425
+ }
426
+ return JSON.stringify(p.literal ?? true);
427
+ }
428
+ function componentPropValue(p) {
429
+ if (p.expr !== void 0) return paren(p.expr, "value");
430
+ return JSON.stringify(p.literal ?? true);
431
+ }
432
+ function emitProps(props, childrenExpr, used) {
433
+ const spreads = props.filter((p) => p.kind === "spread");
434
+ const normal = props.filter((p) => p.kind !== "spread");
435
+ const entries = normal.map((p) => `${propKey(p.name)}: ${propValue(p)}`);
436
+ if (childrenExpr != null) entries.push(`children: ${childrenExpr}`);
437
+ const obj = `{ ${entries.join(", ")} }`;
438
+ if (spreads.length > 0) {
439
+ used.add("mergeProps");
440
+ return `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
441
+ }
442
+ return obj;
443
+ }
444
+ function markBind(code, at) {
445
+ return at ? markHole(code, at.line, at.column) : code;
446
+ }
447
+ function emitChildren(children, used, templates) {
448
+ if (children.length === 1) return emitNode(children[0], used, templates);
449
+ return `[${children.map((c) => emitNode(c, used, templates)).join(", ")}]`;
450
+ }
451
+ function emitComponent(name, props, children, used, templates, at) {
452
+ used.add("createMemo");
453
+ used.add("createComponent");
454
+ const spreads = props.filter((p) => p.kind === "spread");
455
+ const normal = props.filter((p) => p.kind !== "spread");
456
+ const entries = normal.map(
457
+ (p) => `get ${propKey(p.name)}() { return ${componentPropValue(p)}; }`
458
+ );
459
+ if (children.length > 0) {
460
+ entries.push(`get children() { return ${emitChildren(children, used, templates)}; }`);
461
+ }
462
+ let obj = `{ ${entries.join(", ")} }`;
463
+ if (spreads.length > 0) {
464
+ used.add("mergeProps");
465
+ obj = `mergeProps(${spreads.map((s) => s.expr).join(", ")}, ${obj})`;
466
+ }
467
+ const propAt = {};
468
+ for (const p of normal) if (p.at) propAt[p.name] = [p.at.line, p.at.column];
469
+ if (Object.keys(propAt).length) obj = markProps(obj, propAt);
470
+ const mark = at ? `globalThis.${SOURCE_MARKER}?.(${JSON.stringify(at.file)},${at.line},${at.column},${JSON.stringify(name)}), ` : "";
471
+ return `createMemo(${paren(`${mark}() => createComponent(${name}, ${obj})`, "value")})`;
472
+ }
473
+ function staticAttrAssignment(el, prop) {
474
+ const name = htmlAttrName(prop.name);
475
+ const value = prop.literal;
476
+ if (value === true || value === void 0) return `${el}.setAttribute(${JSON.stringify(name)}, "");`;
477
+ if (value === false || value === null) return "";
478
+ return `${el}.setAttribute(${JSON.stringify(name)}, ${JSON.stringify(String(value))});`;
479
+ }
480
+ var partial = false;
481
+ function emitNode(node, used, templates) {
482
+ switch (node.kind) {
483
+ case "text":
484
+ return JSON.stringify(node.value);
485
+ case "expr": {
486
+ if (!node.reactive) return paren(node.code, "value");
487
+ const accessor = `() => ${paren(node.code, "arrowBody")}`;
488
+ return node.at ? markHole(accessor, node.at.line, node.at.column) : accessor;
489
+ }
490
+ case "fragment":
491
+ if (node.children.length === 0) return "null";
492
+ return emitChildren(node.children, used, templates);
493
+ case "component":
494
+ return markBind(emitComponent(node.name, node.props, node.children, used, templates, node.at), node.bindAt ?? node.at);
495
+ case "control": {
496
+ const name = CONTROL_COMPONENT[node.control] ?? node.control;
497
+ used.add(name);
498
+ return markBind(emitComponent(name, node.props, node.children, used, templates), node.bindAt);
499
+ }
500
+ case "element": {
501
+ if (templates && node.static && !node.svg && isSerializable(node)) {
502
+ used.add("templateNode");
503
+ const id = `_tmpl$${templates.length}`;
504
+ templates.push({ id, html: serializeStatic(node), tag: node.tag, svg: false });
505
+ const at = templatePositions(node);
506
+ return at ? `templateNode(${id}, ${JSON.stringify(node.tag)}, false, false, ${JSON.stringify(at)})` : `templateNode(${id}, ${JSON.stringify(node.tag)})`;
507
+ }
508
+ if (templates && partial) {
509
+ const plan = planPartialTemplate(node);
510
+ if (plan) {
511
+ used.add("templateNode");
512
+ used.add("insert");
513
+ used.add("holeEnd");
514
+ used.add("holeContent");
515
+ used.add("holeScope");
516
+ const id = `_tmpl$${templates.length}`;
517
+ templates.push({ id, html: plan.html, tag: plan.tag, svg: false });
518
+ const at = templatePositions(node);
519
+ const lines = [
520
+ `const _el$ = templateNode(${id}, ${JSON.stringify(plan.tag)}, true${at ? `, false, ${JSON.stringify(at)}` : ""});`
521
+ ];
522
+ for (const step of plan.steps) lines.push(`const ${step.ref} = ${step.expr};`);
523
+ for (const hole of plan.holes) {
524
+ lines.push(
525
+ `insert(${hole.parentRef}, holeScope(${hole.startRef}, () => ${paren(emitNode(hole.node, used, templates), "arrowBody")}), ${hole.endRef}, holeContent(${hole.startRef}, ${hole.endRef}));`
526
+ );
527
+ }
528
+ lines.push("return _el$;");
529
+ return `(() => { ${lines.join(" ")} })()`;
530
+ }
531
+ }
532
+ used.add("createNativeElement");
533
+ const tag = JSON.stringify(node.tag);
534
+ const el = "_el$";
535
+ const parts = [];
536
+ const createArgs = node.at ? `${tag}, ${node.svg}, ${JSON.stringify(node.at)}` : node.svg ? `${tag}, true` : tag;
537
+ parts.push(`const ${el} = createNativeElement(${createArgs});`);
538
+ if (node.props.length > 0) {
539
+ if (!node.svg && node.props.every(isPlainLiteralAttr)) {
540
+ for (const p of node.props) parts.push(staticAttrAssignment(el, p));
541
+ } else {
542
+ used.add("spread");
543
+ const svgFlag = node.svg ? ", isSVG: true" : "";
544
+ parts.push(`spread({ element: ${el}, props: ${emitProps(node.props, null, used)}${svgFlag} });`);
545
+ }
546
+ }
547
+ for (const child of node.children) {
548
+ used.add("insert");
549
+ const childCode = emitNode(child, used, templates);
550
+ const isFn = child.kind === "expr" && child.reactive || child.kind === "component" || child.kind === "control";
551
+ parts.push(isFn ? `insert(${el}, ${childCode}, null);` : `insert(${el}, ${childCode});`);
552
+ }
553
+ parts.push(`return ${el};`);
554
+ return `(() => { ${parts.join(" ")} })()`;
555
+ }
556
+ }
557
+ }
558
+ function inlineTemplates(code, templates) {
559
+ if (!templates || templates.length === 0) return code;
560
+ const byId = new Map(templates.map((t3) => [t3.id, JSON.stringify(t3.html)]));
561
+ return code.replace(/_tmpl\$\d+/g, (id) => byId.get(id) ?? id);
562
+ }
563
+ var imperativeBackend = {
564
+ name: "imperative",
565
+ contract: RUNTIME_CONTRACT_V1,
566
+ emit(node, options) {
567
+ const used = /* @__PURE__ */ new Set();
568
+ const templates = options?.templateClone !== false ? [] : void 0;
569
+ partial = options?.partialTemplates === true;
570
+ const code = emitNode(node, used, templates);
571
+ return { code, imports: Array.from(used), templates };
572
+ }
573
+ };
574
+
575
+ // src/lower/text.ts
576
+ function cleanTemplateText(value) {
577
+ const lines = value.split(/\r\n|\n|\r/);
578
+ let lastNonEmpty = 0;
579
+ for (let i = 0; i < lines.length; i++) {
580
+ if (/[^ \t]/.test(lines[i])) lastNonEmpty = i;
581
+ }
582
+ let out = "";
583
+ for (let i = 0; i < lines.length; i++) {
584
+ let line = lines[i].replace(/\t/g, " ");
585
+ if (i !== 0) line = line.replace(/^ +/, "");
586
+ if (i !== lines.length - 1) line = line.replace(/ +$/, "");
587
+ if (!line) continue;
588
+ if (i !== lastNonEmpty) line += " ";
589
+ out += line;
590
+ }
591
+ return out;
592
+ }
593
+
594
+ // src/lower/template.ts
595
+ var DELEGATED = /* @__PURE__ */ new Set([
596
+ "click",
597
+ "dblclick",
598
+ "input",
599
+ "change",
600
+ "submit",
601
+ "focus",
602
+ "blur",
603
+ "keydown",
604
+ "keyup",
605
+ "keypress",
606
+ "mousedown",
607
+ "mouseup"
608
+ ]);
609
+ function escapeTemplate(s) {
610
+ return s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
611
+ }
612
+ function capitalize(s) {
613
+ return s.charAt(0).toUpperCase() + s.slice(1);
614
+ }
615
+ var Lowerer = class {
616
+ constructor(holes, used, sourceFile, positionAt) {
617
+ this.holes = holes;
618
+ this.used = used;
619
+ this.sourceFile = sourceFile;
620
+ this.positionAt = positionAt;
621
+ }
622
+ /**
623
+ * Where a tag is written, for the mark a component node carries.
624
+ *
625
+ * The parser reports offsets, and they are offsets into the file: the pieces it was given
626
+ * carry the positions the front-end recorded. Only built when the host asked for source
627
+ * locations, which is the only time either of these is set.
628
+ */
629
+ tagAt(node) {
630
+ const start = node.loc?.start;
631
+ if (!this.sourceFile || !this.positionAt || start == null) return void 0;
632
+ const { line, column } = this.positionAt(start);
633
+ return { file: this.sourceFile, line, column };
634
+ }
635
+ hole(i) {
636
+ return this.holes[i] ?? { code: "undefined", reactive: false };
637
+ }
638
+ /** Emit a nested IR subtree to code (for `Show` fallback / `For` children). */
639
+ emit(node) {
640
+ const { code, imports, templates } = imperativeBackend.emit(node, {});
641
+ for (const s of imports) this.used.add(s);
642
+ return inlineTemplates(code, templates);
643
+ }
644
+ // --- content ------------------------------------------------------------
645
+ lowerRoot(children) {
646
+ const nodes = this.lowerChildren(children);
647
+ if (nodes.length === 1) return nodes[0];
648
+ return { kind: "fragment", children: nodes };
649
+ }
650
+ /** Lower a sibling list, handling text-drop and if/else/each restructuring. */
651
+ lowerChildren(children) {
652
+ const out = [];
653
+ for (let i = 0; i < children.length; i++) {
654
+ const child = children[i];
655
+ if (child.kind === "Element" || child.kind === "Component") {
656
+ const ifDir = child.attributes.find((a) => a.kind === "IfDirective");
657
+ if (ifDir && ifDir.kind === "IfDirective") {
658
+ let elseIdx = i + 1;
659
+ if (elseIdx < children.length && this.isBlankText(children[elseIdx])) elseIdx++;
660
+ const elseNode = children[elseIdx];
661
+ const hasElse = elseNode && (elseNode.kind === "Element" || elseNode.kind === "Component") && elseNode.attributes.some((a) => a.kind === "ElseDirective");
662
+ out.push(this.lowerIf(child, ifDir.hole, hasElse ? elseNode : null));
663
+ if (hasElse) i = elseIdx;
664
+ continue;
665
+ }
666
+ if (child.attributes.some((a) => a.kind === "EachDirective")) {
667
+ out.push(this.lowerEach(child));
668
+ continue;
669
+ }
670
+ }
671
+ const node = this.lowerNode(child);
672
+ if (node) out.push(node);
673
+ }
674
+ return out;
675
+ }
676
+ isBlankText(n) {
677
+ return n.kind === "Text" && !n.raw && cleanTemplateText(n.value) === "";
678
+ }
679
+ lowerNode(node) {
680
+ switch (node.kind) {
681
+ case "Text": {
682
+ if (node.raw) return { kind: "text", value: node.value };
683
+ const cleaned = cleanTemplateText(node.value);
684
+ return cleaned ? { kind: "text", value: cleaned } : null;
685
+ }
686
+ case "Comment":
687
+ return null;
688
+ // dropped, like JSX comments
689
+ case "Expression": {
690
+ const h = this.hole(node.hole);
691
+ return { kind: "expr", code: h.code, reactive: h.reactive, ...h.at ? { at: h.at } : {} };
692
+ }
693
+ case "Fragment":
694
+ return { kind: "fragment", children: this.lowerChildren(node.children) };
695
+ case "Element":
696
+ return this.lowerElement(node);
697
+ case "Component":
698
+ return this.lowerComponent(node);
699
+ default:
700
+ return null;
701
+ }
702
+ }
703
+ lowerElement(el) {
704
+ const isAttr = el.attributes.find((a) => a.kind === "Attribute" && a.name === "is");
705
+ if (el.tag === "component" && isAttr && isAttr.value && isAttr.value.kind === "hole") {
706
+ const rest = el.attributes.filter((a) => a !== isAttr);
707
+ const node = this.lowerComponent({ ...el, kind: "Component", tag: "Dynamic", tagHole: null, attributes: rest });
708
+ node.props.unshift({ name: "component", kind: "attr", expr: `() => ${paren(this.hole(isAttr.value.hole).code, "arrowBody")}` });
709
+ return node;
710
+ }
711
+ const at = this.tagAt(el);
712
+ return {
713
+ kind: "element",
714
+ tag: el.tag,
715
+ svg: el.namespace === "svg",
716
+ props: this.lowerAttributes(el.attributes),
717
+ children: this.lowerChildren(el.children),
718
+ static: false,
719
+ ...at ? { at } : {}
720
+ };
721
+ }
722
+ lowerComponent(el) {
723
+ const name = el.tagHole != null ? this.hole(el.tagHole).code : el.tag;
724
+ const props = this.lowerAttributes(el.attributes);
725
+ const { slots, rest } = this.partitionSlots(el.children);
726
+ for (const [slotName, nodes] of slots) {
727
+ const ir = nodes.length === 1 ? nodes[0] : { kind: "fragment", children: nodes };
728
+ const slotProp = {
729
+ name: slotName,
730
+ kind: "attr",
731
+ expr: this.emit(ir),
732
+ jsxElement: true
733
+ };
734
+ const clash = props.findIndex((p) => p.name === slotName);
735
+ if (clash >= 0) props[clash] = slotProp;
736
+ else props.push(slotProp);
737
+ }
738
+ const loadAttr = el.attributes.find((a) => a.kind === "LoadDirective");
739
+ const load = loadAttr ? parseLoadDirective(`load:${loadAttr.strategy}`, loadAttr.modifier) : void 0;
740
+ const bindAt = props.find((p) => p.at && p.reactive)?.at;
741
+ const at = this.tagAt(el);
742
+ return {
743
+ kind: "component",
744
+ name,
745
+ props,
746
+ children: this.lowerChildren(rest),
747
+ ...at ? { at } : {},
748
+ ...bindAt ? { bindAt } : {},
749
+ ...load ? { load } : {}
750
+ };
751
+ }
752
+ /** Split a component's children into named slots (`slot="x"`) and the rest. */
753
+ partitionSlots(children) {
754
+ const slots = /* @__PURE__ */ new Map();
755
+ const rest = [];
756
+ for (const child of children) {
757
+ if (child.kind === "Element" || child.kind === "Component") {
758
+ const slot = child.attributes.find(
759
+ (a) => a.kind === "Attribute" && a.name === "slot"
760
+ );
761
+ if (slot && slot.value && slot.value.kind === "static") {
762
+ const stripped = { ...child, attributes: child.attributes.filter((a) => a !== slot) };
763
+ const ir = stripped.kind === "Element" ? this.lowerElement(stripped) : this.lowerComponent(stripped);
764
+ const bucket = slots.get(slot.value.value) ?? [];
765
+ bucket.push(ir);
766
+ slots.set(slot.value.value, bucket);
767
+ continue;
768
+ }
769
+ }
770
+ rest.push(child);
771
+ }
772
+ return { slots, rest };
773
+ }
774
+ // --- control-flow sugar -------------------------------------------------
775
+ /** `<el if=${cond}>…</el>` (+ optional `<el else>`) → `<Show when fallback>`. */
776
+ lowerIf(el, condHole, elseEl) {
777
+ const cond = this.hole(condHole);
778
+ const props = [
779
+ { name: "when", kind: "attr", expr: cond.code, reactive: cond.reactive, ...cond.at ? { at: cond.at } : {} }
780
+ ];
781
+ if (elseEl) {
782
+ const elseIR = this.stripAndLower(elseEl, (a) => a.kind === "ElseDirective");
783
+ props.push({ name: "fallback", kind: "attr", expr: this.emit(elseIR), jsxElement: true });
784
+ }
785
+ const child = this.stripAndLower(el, (a) => a.kind === "IfDirective");
786
+ const at = this.tagAt(el);
787
+ return { kind: "component", name: "Show", props, children: [child], ...at ? { at } : {}, ...cond.at ? { bindAt: cond.at } : {} };
788
+ }
789
+ /** `<el each=${items} key?>${item => …}</el>` → `<For each>{item => <el>…</el>}</For>`. */
790
+ lowerEach(el) {
791
+ const eachDir = el.attributes.find((a) => a.kind === "EachDirective");
792
+ if (!eachDir || eachDir.kind !== "EachDirective") return this.lowerNode(el);
793
+ const each = this.hole(eachDir.hole);
794
+ const props = [{ name: "each", kind: "attr", expr: each.code, reactive: each.reactive, ...each.at ? { at: each.at } : {} }];
795
+ if (eachDir.key) {
796
+ const by = "static" in eachDir.key ? `(item) => item[${JSON.stringify(eachDir.key.static)}]` : this.hole(eachDir.key.hole).code;
797
+ props.push({ name: "by", kind: "attr", expr: by });
798
+ }
799
+ const arrow = this.itemArrow(el);
800
+ let childrenCode;
801
+ if (arrow) {
802
+ const bodyIR = { kind: "expr", code: arrow.body, reactive: arrow.bodyReactive };
803
+ const repeated = this.rebuildWithChildren(el, [bodyIR]);
804
+ childrenCode = `(${arrow.params.join(", ")}) => ${paren(this.emit(repeated), "arrowBody")}`;
805
+ } else {
806
+ const repeated = this.stripAndLower(el, (a) => a.kind === "EachDirective");
807
+ childrenCode = `() => ${paren(this.emit(repeated), "arrowBody")}`;
808
+ }
809
+ const children = [{ kind: "expr", code: childrenCode, reactive: false }];
810
+ const at = this.tagAt(el);
811
+ return { kind: "component", name: "For", props, children, ...at ? { at } : {}, ...each.at ? { bindAt: each.at } : {} };
812
+ }
813
+ /** The single `${item => expr}` child arrow, if that's the element's content. */
814
+ itemArrow(el) {
815
+ const kids = el.children.filter((c) => !this.isBlankText(c));
816
+ if (kids.length !== 1 || kids[0].kind !== "Expression") return null;
817
+ return this.hole(kids[0].hole).arrow ?? null;
818
+ }
819
+ /** Lower an element to IR, dropping the directive attribute matched by `drop`. */
820
+ stripAndLower(el, drop) {
821
+ const clone = { ...el, attributes: el.attributes.filter((a) => !drop(a)) };
822
+ return clone.kind === "Element" ? this.lowerElement(clone) : this.lowerComponent(clone);
823
+ }
824
+ /** Same element (minus each/key) but with explicit IR children. */
825
+ rebuildWithChildren(el, children) {
826
+ const props = this.lowerAttributes(
827
+ el.attributes.filter((a) => a.kind !== "EachDirective")
828
+ );
829
+ if (el.kind === "Element") {
830
+ const at = this.tagAt(el);
831
+ return {
832
+ kind: "element",
833
+ tag: el.tag,
834
+ svg: el.namespace === "svg",
835
+ props,
836
+ children,
837
+ static: false,
838
+ ...at ? { at } : {}
839
+ };
840
+ }
841
+ return { kind: "component", name: el.tag, props, children };
842
+ }
843
+ // --- attributes ---------------------------------------------------------
844
+ lowerAttributes(attrs) {
845
+ const props = [];
846
+ const classEntries = [];
847
+ let classReactive = false;
848
+ let classAt;
849
+ const styleEntries = [];
850
+ let styleReactive = false;
851
+ let styleAt;
852
+ const usePairs = [];
853
+ for (const a of attrs) {
854
+ switch (a.kind) {
855
+ case "IfDirective":
856
+ case "EachDirective":
857
+ case "ElseDirective":
858
+ break;
859
+ // handled as control-flow at the parent level
860
+ case "Attribute":
861
+ props.push(this.plainAttr(a));
862
+ break;
863
+ case "PropertyBinding":
864
+ props.push({
865
+ name: a.name,
866
+ kind: "prop",
867
+ expr: this.hole(a.hole).code,
868
+ reactive: this.hole(a.hole).reactive,
869
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
870
+ });
871
+ break;
872
+ case "EventBinding":
873
+ props.push(this.eventProp(a));
874
+ break;
875
+ case "RefBinding":
876
+ props.push({
877
+ name: "ref",
878
+ kind: "ref",
879
+ expr: this.hole(a.hole).code,
880
+ reactive: this.hole(a.hole).reactive,
881
+ // Which variable ends up holding the element, and where it was written.
882
+ ...this.hole(a.hole).at ? { at: this.hole(a.hole).at } : {}
883
+ });
884
+ break;
885
+ case "Spread":
886
+ props.push({ name: "", kind: "spread", expr: this.hole(a.hole).code });
887
+ break;
888
+ case "ClassDirective": {
889
+ const h = this.hole(a.hole);
890
+ classEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
891
+ classReactive = classReactive || h.reactive;
892
+ classAt ??= h.at;
893
+ break;
894
+ }
895
+ case "StyleDirective": {
896
+ const h = this.hole(a.hole);
897
+ styleEntries.push(`${JSON.stringify(a.name)}: ${h.code}`);
898
+ styleReactive = styleReactive || h.reactive;
899
+ styleAt ??= h.at;
900
+ break;
901
+ }
902
+ case "BindDirective":
903
+ props.push(...this.bindProps(a.name, this.hole(a.hole)));
904
+ break;
905
+ case "UseDirective": {
906
+ const dir = a.name ?? (a.hole != null ? this.hole(a.hole).code : null);
907
+ if (!dir) break;
908
+ usePairs.push(a.name != null && a.hole != null ? `[${dir}, () => ${paren(this.hole(a.hole).code, "arrowBody")}]` : `[${dir}]`);
909
+ break;
910
+ }
911
+ }
912
+ }
913
+ if (classEntries.length > 0) {
914
+ props.push({
915
+ name: "classList",
916
+ kind: "attr",
917
+ expr: `{ ${classEntries.join(", ")} }`,
918
+ reactive: classReactive,
919
+ ...classAt ? { at: classAt } : {}
920
+ });
921
+ }
922
+ if (styleEntries.length > 0) {
923
+ props.push({
924
+ name: "style",
925
+ kind: "attr",
926
+ expr: `{ ${styleEntries.join(", ")} }`,
927
+ reactive: styleReactive,
928
+ ...styleAt ? { at: styleAt } : {}
929
+ });
930
+ }
931
+ if (usePairs.length > 0) {
932
+ props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
933
+ }
934
+ return props;
935
+ }
936
+ /**
937
+ * Lower an event binding. Plain `@click`/`onClick` (no modifiers) stays a
938
+ * DELEGATED handler (unchanged, byte-identical with JSX). `on:click` or any
939
+ * modifier (`.capture`/`.once`/`.passive`/`.prevent`/`.stop`/`.self`) emits a
940
+ * NATIVE `on:name` prop the runtime attaches via addEventListener.
941
+ */
942
+ eventProp(a) {
943
+ const dom = a.name.toLowerCase();
944
+ const handler = this.hole(a.hole).code;
945
+ const native = a.syntax === "colon" || a.modifiers.length > 0;
946
+ if (!native) {
947
+ return {
948
+ name: "on" + capitalize(a.name),
949
+ kind: "event",
950
+ event: { name: dom, delegated: DELEGATED.has(dom) },
951
+ expr: handler
952
+ };
953
+ }
954
+ const wrapped = this.wrapHandler(handler, a.modifiers);
955
+ const options = this.eventOptions(a.modifiers);
956
+ const value = options ? `[${wrapped}, ${options}]` : wrapped;
957
+ return { name: "on:" + dom, kind: "attr", expr: value };
958
+ }
959
+ /** Wrap a handler for `.prevent`/`.stop`/`.self` (no wrap when none apply). */
960
+ wrapHandler(handler, mods) {
961
+ const guard = mods.includes("self") ? "if (e.target !== e.currentTarget) return; " : "";
962
+ const pre = [];
963
+ if (mods.includes("prevent")) pre.push("e.preventDefault();");
964
+ if (mods.includes("stop")) pre.push("e.stopPropagation();");
965
+ if (!guard && pre.length === 0) return handler;
966
+ return `(e) => { ${guard}${pre.join(" ")} return (${handler})(e); }`;
967
+ }
968
+ /** addEventListener options object from `.capture`/`.once`/`.passive`, or null. */
969
+ eventOptions(mods) {
970
+ const opts = [];
971
+ if (mods.includes("capture")) opts.push("capture: true");
972
+ if (mods.includes("once")) opts.push("once: true");
973
+ if (mods.includes("passive")) opts.push("passive: true");
974
+ return opts.length ? `{ ${opts.join(", ")} }` : null;
975
+ }
976
+ /** `bind:value=${sig}` → `value={read()}` + `onInput={e => write(e…value)}`. */
977
+ bindProps(prop, h) {
978
+ const sigCode = h.code;
979
+ const checked = prop === "checked";
980
+ const evt = checked ? "change" : "input";
981
+ const accessor = checked ? "checked" : "value";
982
+ this.used.add("bindPair");
983
+ const sig = `bindPair(${sigCode})`;
984
+ return [
985
+ {
986
+ name: prop,
987
+ kind: "attr",
988
+ expr: `${sig}[0]()`,
989
+ reactive: true,
990
+ directive: `bind:${prop}`,
991
+ ...h.at ? { at: h.at } : {}
992
+ },
993
+ {
994
+ name: "on" + capitalize(evt),
995
+ kind: "event",
996
+ event: { name: evt, delegated: DELEGATED.has(evt) },
997
+ // delegated handler: `target` is the bound element (currentTarget is the root)
998
+ expr: `(e) => ${sig}[1](e.target.${accessor})`
999
+ }
1000
+ ];
1001
+ }
1002
+ /** A plain attribute (incl. lit `?bool`, mixed values) — old `mkProp` behavior. */
1003
+ plainAttr(a) {
1004
+ const v = a.value;
1005
+ let name = a.name;
1006
+ if (a.name === "class") {
1007
+ name = v && v.kind === "hole" && this.hole(v.hole).object ? "classList" : "className";
1008
+ } else if (a.name === "html") {
1009
+ name = "innerHTML";
1010
+ }
1011
+ const kind = "attr";
1012
+ const base = { name, kind };
1013
+ if (v == null) {
1014
+ base.literal = true;
1015
+ return base;
1016
+ }
1017
+ if (v.kind === "static") {
1018
+ base.literal = v.value;
1019
+ return base;
1020
+ }
1021
+ if (v.kind === "hole") {
1022
+ const h = this.hole(v.hole);
1023
+ base.expr = h.code;
1024
+ base.reactive = h.reactive;
1025
+ if (h.at) base.at = h.at;
1026
+ return base;
1027
+ }
1028
+ let reactive = false;
1029
+ let at;
1030
+ const body = v.parts.map((p) => {
1031
+ if ("text" in p) return escapeTemplate(p.text);
1032
+ const h = this.hole(p.hole);
1033
+ reactive = reactive || h.reactive;
1034
+ at ??= h.at;
1035
+ return "${" + h.code + "}";
1036
+ }).join("");
1037
+ base.expr = "`" + body + "`";
1038
+ base.reactive = reactive;
1039
+ if (at) base.at = at;
1040
+ return base;
1041
+ }
1042
+ };
1043
+ function lowerTemplate(pieces, holes, used, opts = {}) {
1044
+ const { root } = parseTemplate(pieces, { svg: opts.svg });
1045
+ return new Lowerer(holes, used, opts.sourceFile, opts.positionAt).lowerRoot(root.children);
1046
+ }
1047
+
1048
+ // src/frontend/babel/build-ir.ts
1049
+ import { types as t, traverse, template } from "@babel/core";
1050
+ import _generate from "@babel/generator";
1051
+
1052
+ // src/optimize/analyze-static.ts
1053
+ function propReason(prop) {
1054
+ switch (prop.kind) {
1055
+ case "event":
1056
+ return "event";
1057
+ case "ref":
1058
+ return "ref";
1059
+ case "spread":
1060
+ return "spread";
1061
+ case "class":
1062
+ case "style":
1063
+ return "class-or-style-directive";
1064
+ case "attr":
1065
+ case "prop":
1066
+ if (prop.reactive) return "reactive-prop";
1067
+ if (prop.expr !== void 0) return "expression-prop";
1068
+ return void 0;
1069
+ /* c8 ignore next 2 */
1070
+ default:
1071
+ return "expression-prop";
1072
+ }
1073
+ }
1074
+ function analyzeStatic(root) {
1075
+ const staticElements = [];
1076
+ const reasons = /* @__PURE__ */ new Map();
1077
+ const visit = (node) => {
1078
+ switch (node.kind) {
1079
+ case "text":
1080
+ return true;
1081
+ case "expr":
1082
+ return false;
1083
+ case "component":
1084
+ case "control":
1085
+ for (const child of node.children) visit(child);
1086
+ return false;
1087
+ case "fragment":
1088
+ for (const child of node.children) visit(child);
1089
+ return false;
1090
+ case "element": {
1091
+ let childrenStatic = true;
1092
+ for (const child of node.children) {
1093
+ if (!visit(child)) childrenStatic = false;
1094
+ }
1095
+ let reason;
1096
+ for (const prop of node.props) {
1097
+ reason = propReason(prop);
1098
+ if (reason) break;
1099
+ }
1100
+ if (!reason && !childrenStatic) {
1101
+ reason = childReason(node);
1102
+ }
1103
+ node.static = !reason;
1104
+ if (reason) reasons.set(node, reason);
1105
+ else staticElements.push(node);
1106
+ return node.static;
1107
+ }
1108
+ /* c8 ignore next 2 */
1109
+ default:
1110
+ return false;
1111
+ }
1112
+ };
1113
+ for (const node of Array.isArray(root) ? root : [root]) visit(node);
1114
+ return { staticElements, reasons };
1115
+ }
1116
+ function childReason(node) {
1117
+ for (const child of node.children) {
1118
+ if (child.kind === "expr") return "expression-child";
1119
+ if (child.kind === "component") return "component-child";
1120
+ if (child.kind === "control") return "control-child";
1121
+ if (child.kind === "element" && !child.static) return "expression-child";
1122
+ if (child.kind === "fragment") return "expression-child";
1123
+ }
1124
+ return "expression-child";
1125
+ }
1126
+
1127
+ // src/frontend/babel/build-ir-lit.ts
1128
+ function buildIRFromLit(node, used = /* @__PURE__ */ new Set(), opts = {}) {
1129
+ const ir = lowerLitTemplate(node, used, opts);
1130
+ analyzeStatic(ir);
1131
+ return ir;
1132
+ }
1133
+
1134
+ // src/analyze/reactive-expr.ts
1135
+ var STABLE_MEMBER = "children";
1136
+ function isReactiveShape(shape) {
1137
+ switch (shape.kind) {
1138
+ case "call":
1139
+ return true;
1140
+ case "member":
1141
+ return shape.property !== STABLE_MEMBER;
1142
+ case "compound":
1143
+ return shape.parts.some(isReactiveShape);
1144
+ case "opaque":
1145
+ return false;
1146
+ }
1147
+ }
1148
+
1149
+ // src/analyze/expr-shape.ts
1150
+ var CALL = /* @__PURE__ */ new Set(["CallExpression", "OptionalCallExpression"]);
1151
+ var MEMBER = /* @__PURE__ */ new Set(["MemberExpression", "OptionalMemberExpression"]);
1152
+ function shapeOf(node) {
1153
+ if (!node) return { kind: "opaque" };
1154
+ if (CALL.has(node.type)) return { kind: "call" };
1155
+ if (MEMBER.has(node.type)) {
1156
+ const property = node.property;
1157
+ const computed = node.computed === true;
1158
+ return {
1159
+ kind: "member",
1160
+ property: !computed && property?.type === "Identifier" ? property.name : null
1161
+ };
1162
+ }
1163
+ if (node.type === "ConditionalExpression") {
1164
+ return { kind: "compound", parts: [node.test, node.consequent, node.alternate].map(part) };
1165
+ }
1166
+ if (node.type === "LogicalExpression" || node.type === "BinaryExpression") {
1167
+ return { kind: "compound", parts: [node.left, node.right].map(part) };
1168
+ }
1169
+ if (node.type === "TemplateLiteral") {
1170
+ return { kind: "compound", parts: node.expressions.map(part) };
1171
+ }
1172
+ if (node.type === "ObjectExpression") {
1173
+ const props = node.properties.filter(
1174
+ (p) => (p.type === "ObjectProperty" || p.type === "Property") && p.computed !== true
1175
+ );
1176
+ return { kind: "compound", parts: props.map((p) => part(p.value)) };
1177
+ }
1178
+ if (node.type === "ArrayExpression") {
1179
+ const items = node.elements.filter(
1180
+ (e) => e != null && e.type !== "SpreadElement"
1181
+ );
1182
+ return { kind: "compound", parts: items.map(part) };
1183
+ }
1184
+ return { kind: "opaque" };
1185
+ }
1186
+ var part = (n) => shapeOf(n);
1187
+
1188
+ // src/lower/jsx.ts
1189
+ var SVG_TAGS = /* @__PURE__ */ new Set([
1190
+ "svg",
1191
+ "path",
1192
+ "circle",
1193
+ "rect",
1194
+ "line",
1195
+ "polygon",
1196
+ "polyline",
1197
+ "ellipse",
1198
+ "g",
1199
+ "defs",
1200
+ "clipPath",
1201
+ "text"
1202
+ ]);
1203
+ var EVENT_RE = /^on[A-Z]/;
1204
+ var DELEGATED2 = /* @__PURE__ */ new Set([
1205
+ "click",
1206
+ "dblclick",
1207
+ "input",
1208
+ "change",
1209
+ "submit",
1210
+ "focus",
1211
+ "blur",
1212
+ "keydown",
1213
+ "keyup",
1214
+ "keypress",
1215
+ "mousedown",
1216
+ "mouseup"
1217
+ ]);
1218
+ var isReactive = (node) => isReactiveShape(shapeOf(node));
1219
+ var posOf = (node, ctx) => {
1220
+ if (!ctx.sourceFile) return void 0;
1221
+ const at = node.loc?.start;
1222
+ return at ? { line: at.line, column: at.column } : void 0;
1223
+ };
1224
+ function literalOf(node) {
1225
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") {
1226
+ return node.value;
1227
+ }
1228
+ if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number" || typeof node.value === "boolean")) {
1229
+ return node.value;
1230
+ }
1231
+ return void 0;
1232
+ }
1233
+ var isString = (node) => !!node && typeof literalOf(node) === "string";
1234
+ function tagInfo(name, ctx) {
1235
+ if (name.type === "JSXIdentifier") {
1236
+ return { tag: name.name, component: name.name[0] !== name.name[0].toLowerCase() };
1237
+ }
1238
+ if (name.type === "JSXMemberExpression") return { tag: ctx.code(name), component: true };
1239
+ if (name.type === "JSXNamespacedName") {
1240
+ return { tag: `${name.namespace.name}:${name.name.name}`, component: false };
1241
+ }
1242
+ return { tag: "div", component: false };
1243
+ }
1244
+ function attrName(name) {
1245
+ if (name.type === "JSXIdentifier") return name.name === "class" ? "className" : name.name;
1246
+ if (name.type === "JSXNamespacedName") return `${name.namespace.name}:${name.name.name}`;
1247
+ return "unknown";
1248
+ }
1249
+ function buildAttr(attr, ctx) {
1250
+ const name = attrName(attr.name);
1251
+ const isEvent = EVENT_RE.test(name);
1252
+ const isHandler = isEvent || name.startsWith("on:") || name === "ref";
1253
+ const kind = isEvent ? "event" : "attr";
1254
+ const base = { name, kind };
1255
+ if (isEvent) {
1256
+ const evt = name.slice(2).toLowerCase();
1257
+ base.event = { name: evt, delegated: DELEGATED2.has(evt) };
1258
+ }
1259
+ const v = attr.value;
1260
+ if (v == null) {
1261
+ base.literal = true;
1262
+ base.at = posOf(attr, ctx);
1263
+ return base;
1264
+ }
1265
+ if (isString(v)) {
1266
+ base.literal = literalOf(v);
1267
+ base.at = posOf(v, ctx);
1268
+ return base;
1269
+ }
1270
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
1271
+ const expr = v.expression;
1272
+ const literal = literalOf(expr);
1273
+ if (literal !== void 0) {
1274
+ base.literal = literal;
1275
+ base.at = posOf(expr, ctx);
1276
+ return base;
1277
+ }
1278
+ base.expr = ctx.code(expr);
1279
+ base.reactive = isHandler ? false : isReactive(expr);
1280
+ base.at = posOf(expr, ctx);
1281
+ if (expr.type === "JSXElement" || expr.type === "JSXFragment") base.jsxElement = true;
1282
+ return base;
1283
+ }
1284
+ base.literal = true;
1285
+ return base;
1286
+ }
1287
+ function attrExprCode(attr, ctx) {
1288
+ const v = attr.value;
1289
+ if (v == null) return null;
1290
+ if (isString(v)) return JSON.stringify(literalOf(v));
1291
+ if (v.type === "JSXExpressionContainer" && v.expression?.type !== "JSXEmptyExpression") {
1292
+ return ctx.code(v.expression);
1293
+ }
1294
+ return null;
1295
+ }
1296
+ function buildProps(attrs, ctx) {
1297
+ const props = [];
1298
+ const usePairs = [];
1299
+ for (const a of attrs) {
1300
+ if (a.type === "JSXSpreadAttribute") {
1301
+ props.push({ name: "", kind: "spread", expr: ctx.code(a.argument) });
1302
+ continue;
1303
+ }
1304
+ if (a.type !== "JSXAttribute") continue;
1305
+ if (isLoadDirective(attrName(a.name))) continue;
1306
+ const ns = a.name.type === "JSXNamespacedName" ? a.name.namespace.name : null;
1307
+ if (ns === "use") {
1308
+ const dir = a.name.name.name;
1309
+ ctx.used.add(dir);
1310
+ const opts = attrExprCode(a, ctx);
1311
+ usePairs.push(opts != null ? `[${dir}, () => ${paren(opts, "arrowBody")}]` : `[${dir}]`);
1312
+ continue;
1313
+ }
1314
+ if (ns === "oncapture") {
1315
+ const evt = a.name.name.name.toLowerCase();
1316
+ const h = attrExprCode(a, ctx) ?? "undefined";
1317
+ props.push({ name: "on:" + evt, kind: "attr", expr: `[${h}, { capture: true }]` });
1318
+ continue;
1319
+ }
1320
+ props.push(buildAttr(a, ctx));
1321
+ }
1322
+ if (usePairs.length > 0) props.push({ name: "use", kind: "attr", expr: `[${usePairs.join(", ")}]` });
1323
+ return props;
1324
+ }
1325
+ function buildChildren(children, ctx) {
1326
+ const out = [];
1327
+ for (const child of children) {
1328
+ if (child.type === "JSXText") {
1329
+ const text = cleanTemplateText(child.value);
1330
+ if (text) out.push({ kind: "text", value: text });
1331
+ } else if (child.type === "JSXExpressionContainer") {
1332
+ if (child.expression?.type !== "JSXEmptyExpression") {
1333
+ const expr = child.expression;
1334
+ const reactive = isReactive(expr);
1335
+ out.push({
1336
+ kind: "expr",
1337
+ code: ctx.code(expr),
1338
+ reactive,
1339
+ ...reactive ? { at: posOf(expr, ctx) } : {}
1340
+ });
1341
+ }
1342
+ } else if (child.type === "JSXElement" || child.type === "JSXFragment") {
1343
+ out.push(buildNode(child, ctx));
1344
+ } else if (child.type === "JSXSpreadChild") {
1345
+ out.push({ kind: "expr", code: ctx.code(child.expression), reactive: false });
1346
+ }
1347
+ }
1348
+ return out;
1349
+ }
1350
+ function readLoad(attrs) {
1351
+ for (const a of attrs) {
1352
+ if (a.type !== "JSXAttribute") continue;
1353
+ const name = attrName(a.name);
1354
+ if (!isLoadDirective(name)) continue;
1355
+ if (a.value && !isString(a.value)) {
1356
+ throw new LoadDirectiveError(
1357
+ `'${name}' needs a literal value, not an expression — the strategy is compile-time.`
1358
+ );
1359
+ }
1360
+ return parseLoadDirective(name, a.value ? literalOf(a.value) : null);
1361
+ }
1362
+ return void 0;
1363
+ }
1364
+ function buildNode(node, ctx) {
1365
+ if (node.type === "JSXFragment") {
1366
+ return { kind: "fragment", children: buildChildren(node.children, ctx) };
1367
+ }
1368
+ const { tag, component } = tagInfo(node.openingElement.name, ctx);
1369
+ const props = buildProps(node.openingElement.attributes, ctx);
1370
+ const children = buildChildren(node.children, ctx);
1371
+ const at = ctx.sourceFile && node.loc?.start ? { file: ctx.sourceFile, line: node.loc.start.line, column: node.loc.start.column } : void 0;
1372
+ if (component) {
1373
+ const load = readLoad(node.openingElement.attributes);
1374
+ return { kind: "component", name: tag, props, children, ...load ? { load } : {}, ...at ? { at } : {} };
1375
+ }
1376
+ return { kind: "element", tag, svg: SVG_TAGS.has(tag), props, children, static: false, ...at ? { at } : {} };
1377
+ }
1378
+ function buildJsxIR(node, ctx) {
1379
+ const ir = buildNode(node, ctx);
1380
+ analyzeStatic(ir);
1381
+ return ir;
1382
+ }
1383
+
1384
+ // src/frontend/babel/build-ir.ts
1385
+ var generate = _generate.default ?? _generate;
1386
+ function gen(node) {
1387
+ return generate(node, { concise: true }).code;
1388
+ }
1389
+ function transformNestedJSX(node, used, onNested) {
1390
+ const clone = t.cloneNode(node, true);
1391
+ const file = t.file(t.program([t.expressionStatement(clone)]));
1392
+ let changed = false;
1393
+ const emitInto = (path, code, imports) => {
1394
+ for (const s of imports) used.add(s);
1395
+ path.replaceWith(template.expression(code, { placeholderPattern: false, plugins: ["typescript"] })());
1396
+ path.skip();
1397
+ changed = true;
1398
+ };
1399
+ traverse(file, {
1400
+ "JSXElement|JSXFragment"(path) {
1401
+ const jsx = path.node;
1402
+ const nestedIR = buildIR(jsx, used, onNested);
1403
+ onNested?.(nestedIR);
1404
+ const { code, imports, templates } = imperativeBackend.emit(nestedIR, {});
1405
+ emitInto(path, inlineTemplates(code, templates), imports);
1406
+ },
1407
+ // Nested lit templates compose: ${cond ? html`…` : html`…`},
1408
+ // ${list.map(x => html`<li>${x}</li>`)}. Compile them the same way.
1409
+ TaggedTemplateExpression(path) {
1410
+ const tag = path.node.tag;
1411
+ if (!t.isIdentifier(tag) || tag.name !== "html" && tag.name !== "svg") return;
1412
+ const ir = buildIRFromLit(path.node, used, { svg: tag.name === "svg", onNested });
1413
+ onNested?.(ir);
1414
+ const { code, imports, templates } = imperativeBackend.emit(ir, {});
1415
+ emitInto(path, inlineTemplates(code, templates), imports);
1416
+ }
1417
+ });
1418
+ return changed ? file.program.body[0].expression : node;
1419
+ }
1420
+ function genExpr(node, used, onNested) {
1421
+ return gen(transformNestedJSX(node, used, onNested));
1422
+ }
1423
+ function isReactiveExpr(node) {
1424
+ return isReactiveShape(shapeOf(node));
1425
+ }
1426
+ function buildIR(node, used = /* @__PURE__ */ new Set(), onNested) {
1427
+ const ir = buildJsxIR(node, {
1428
+ code: (n) => (
1429
+ // A member-expression tag (`<ns.Foo/>`) is not an Expression, so it cannot go
1430
+ // through the nested-JSX compile — it only ever needs printing.
1431
+ n.type === "JSXMemberExpression" ? gen(n) : genExpr(n, used, onNested)
1432
+ ),
1433
+ used
1434
+ });
1435
+ return ir;
1436
+ }
1437
+
1438
+ // src/frontend/babel/lower-template.ts
1439
+ var generate2 = _generate2.default ?? _generate2;
1440
+ function gen2(node) {
1441
+ return generate2(node, { concise: true }).code;
1442
+ }
1443
+ function bindHole(expr, used, onNested) {
1444
+ const hole = {
1445
+ code: genExpr(expr, used, onNested),
1446
+ reactive: isReactiveExpr(expr)
1447
+ };
1448
+ if (t2.isArrowFunctionExpression(expr) && !t2.isBlockStatement(expr.body)) {
1449
+ const body = expr.body;
1450
+ hole.arrow = {
1451
+ params: expr.params.map((p) => gen2(p)),
1452
+ body: genExpr(body, used, onNested),
1453
+ bodyReactive: isReactiveExpr(body)
1454
+ };
1455
+ }
1456
+ if (t2.isObjectExpression(expr)) hole.object = true;
1457
+ return hole;
1458
+ }
1459
+ function lowerLitTemplate(node, used, opts = {}) {
1460
+ const quasi = node.quasi;
1461
+ const holes = quasi.expressions.map((e) => bindHole(e, used, opts.onNested));
1462
+ return lowerTemplate(buildPieces(quasi), holes, used, opts);
1463
+ }
1464
+ function buildPieces(quasi) {
1465
+ const pieces = [];
1466
+ quasi.quasis.forEach((q, i) => {
1467
+ const text = q.value.cooked ?? q.value.raw;
1468
+ pieces.push({ kind: "static", text, start: q.start ?? 0 });
1469
+ if (i < quasi.expressions.length) {
1470
+ const e = quasi.expressions[i];
1471
+ pieces.push({ kind: "hole", index: i, start: e.start ?? 0, end: e.end ?? 0 });
1472
+ }
1473
+ });
1474
+ return pieces;
1475
+ }
1476
+ export {
1477
+ lowerLitTemplate
1478
+ };