@getforma/core 0.9.1 → 1.0.1

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 (52) hide show
  1. package/README.md +24 -5
  2. package/dist/chunk-DCTOXHPF.cjs +399 -0
  3. package/dist/chunk-DCTOXHPF.cjs.map +1 -0
  4. package/dist/chunk-OUVOAYIO.js +359 -0
  5. package/dist/chunk-OUVOAYIO.js.map +1 -0
  6. package/dist/{chunk-GDULJFJO.cjs → chunk-V732ZBCU.cjs} +119 -511
  7. package/dist/chunk-V732ZBCU.cjs.map +1 -0
  8. package/dist/{chunk-CN56FSDT.js → chunk-VTPFK5TJ.js} +89 -442
  9. package/dist/chunk-VTPFK5TJ.js.map +1 -0
  10. package/dist/forma-runtime-csp.js +3400 -1
  11. package/dist/forma-runtime.js +3572 -1
  12. package/dist/formajs-runtime-hardened.global.js +3400 -1
  13. package/dist/formajs-runtime-hardened.global.js.map +1 -1
  14. package/dist/formajs-runtime.global.js +3572 -1
  15. package/dist/formajs-runtime.global.js.map +1 -1
  16. package/dist/formajs.global.js +3443 -1
  17. package/dist/formajs.global.js.map +1 -1
  18. package/dist/http.cjs +225 -0
  19. package/dist/http.cjs.map +1 -0
  20. package/dist/http.d.cts +108 -0
  21. package/dist/http.d.ts +108 -0
  22. package/dist/http.js +220 -0
  23. package/dist/http.js.map +1 -0
  24. package/dist/index.cjs +71 -607
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +2 -456
  27. package/dist/index.d.ts +2 -456
  28. package/dist/index.js +7 -523
  29. package/dist/index.js.map +1 -1
  30. package/dist/resource-Cd0cGOxS.d.ts +62 -0
  31. package/dist/resource-DK98lW5e.d.cts +62 -0
  32. package/dist/runtime-hardened.cjs.map +1 -1
  33. package/dist/runtime-hardened.js.map +1 -1
  34. package/dist/runtime.cjs +23 -22
  35. package/dist/runtime.cjs.map +1 -1
  36. package/dist/runtime.js +2 -1
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/server.cjs +179 -0
  39. package/dist/server.cjs.map +1 -0
  40. package/dist/server.d.cts +217 -0
  41. package/dist/server.d.ts +217 -0
  42. package/dist/server.js +166 -0
  43. package/dist/server.js.map +1 -0
  44. package/dist/storage.cjs +151 -0
  45. package/dist/storage.cjs.map +1 -0
  46. package/dist/storage.d.cts +77 -0
  47. package/dist/storage.d.ts +77 -0
  48. package/dist/storage.js +147 -0
  49. package/dist/storage.js.map +1 -0
  50. package/package.json +31 -1
  51. package/dist/chunk-CN56FSDT.js.map +0 -1
  52. package/dist/chunk-GDULJFJO.cjs.map +0 -1
@@ -1,2 +1,3401 @@
1
- var FormaRuntime=(function(exports){'use strict';function Je({update:e,notify:t,unwatched:n}){return {link:r,unlink:i,propagate:a,checkDirty:s,shallowPropagate:c};function r(o,l,p){let m=l.depsTail;if(m!==void 0&&m.dep===o)return;let u=m!==void 0?m.nextDep:l.deps;if(u!==void 0&&u.dep===o){u.version=p,l.depsTail=u;return}let h=o.subsTail;if(h!==void 0&&h.version===p&&h.sub===l)return;let E=l.depsTail=o.subsTail={version:p,dep:o,sub:l,prevDep:m,nextDep:u,prevSub:h,nextSub:void 0};u!==void 0&&(u.prevDep=E),m!==void 0?m.nextDep=E:l.deps=E,h!==void 0?h.nextSub=E:o.subs=E;}function i(o,l=o.sub){let p=o.dep,m=o.prevDep,u=o.nextDep,h=o.nextSub,E=o.prevSub;return u!==void 0?u.prevDep=m:l.depsTail=m,m!==void 0?m.nextDep=u:l.deps=u,h!==void 0?h.prevSub=E:p.subsTail=E,E!==void 0?E.nextSub=h:(p.subs=h)===void 0&&n(p),u}function a(o){let l=o.nextSub,p;e:do{let m=o.sub,u=m.flags;if(u&60?u&12?u&4?!(u&48)&&f(o,m)?(m.flags=u|40,u&=1):u=0:m.flags=u&-9|32:u=0:m.flags=u|32,u&2&&t(m),u&1){let h=m.subs;if(h!==void 0){let E=(o=h).nextSub;E!==void 0&&(p={value:l,prev:p},l=E);continue}}if((o=l)!==void 0){l=o.nextSub;continue}for(;p!==void 0;)if(o=p.value,p=p.prev,o!==void 0){l=o.nextSub;continue e}break}while(true)}function s(o,l){let p,m=0,u=false;e:do{let h=o.dep,E=h.flags;if(l.flags&16)u=true;else if((E&17)===17){if(e(h)){let S=h.subs;S.nextSub!==void 0&&c(S),u=true;}}else if((E&33)===33){(o.nextSub!==void 0||o.prevSub!==void 0)&&(p={value:o,prev:p}),o=h.deps,l=h,++m;continue}if(!u){let S=o.nextDep;if(S!==void 0){o=S;continue}}for(;m--;){let S=l.subs,_=S.nextSub!==void 0;if(_?(o=p.value,p=p.prev):o=S,u){if(e(l)){_&&c(S),l=o.sub;continue}u=false;}else l.flags&=-33;l=o.sub;let y=o.nextDep;if(y!==void 0){o=y;continue e}}return u}while(true)}function c(o){do{let l=o.sub,p=l.flags;(p&48)===32&&(l.flags=p|16,(p&6)===2&&t(l));}while((o=o.nextSub)!==void 0)}function f(o,l){let p=l.depsTail;for(;p!==void 0;){if(p===o)return true;p=p.prevDep;}return false}}var Ee=0,xe=0,K=0,le=0,z,W=[],{link:Ce,unlink:Ke,propagate:Ot,checkDirty:Xe,shallowPropagate:Ye}=Je({update(e){return e.depsTail!==void 0?rt(e):it(e)},notify(e){let t=le,n=t;do if(W[t++]=e,e.flags&=-3,e=e.subs?.sub,e===void 0||!(e.flags&2))break;while(true);for(le=t;n<--t;){let r=W[n];W[n++]=W[t],W[t]=r;}},unwatched(e){e.flags&1?e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,ye(e)):st.call(e);}});function V(e){let t=z;return z=e,t}function Ze(){++xe;}function Qe(){--xe||ot();}function et(e){return $t.bind({currentValue:e,pendingValue:e,subs:void 0,subsTail:void 0,flags:1})}function tt(e){return Ht.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:0,getter:e})}function nt(e){let t={fn:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:6},n=V(t);n!==void 0&&Ce(t,n,0);try{t.fn();}finally{z=n,t.flags&=-5;}return Ft.bind(t)}function rt(e){++Ee,e.depsTail=void 0,e.flags=5;let t=V(e);try{let n=e.value;return n!==(e.value=e.getter(n))}finally{z=t,e.flags&=-5,ye(e);}}function it(e){return e.flags=1,e.currentValue!==(e.currentValue=e.pendingValue)}function It(e){let t=e.flags;if(t&16||t&32&&Xe(e.deps,e)){++Ee,e.depsTail=void 0,e.flags=6;let n=V(e);try{e.fn();}finally{z=n,e.flags&=-5,ye(e);}}else e.flags=2;}function ot(){try{for(;K<le;){let e=W[K];W[K++]=void 0,It(e);}}finally{for(;K<le;){let e=W[K];W[K++]=void 0,e.flags|=10;}K=0,le=0;}}function Ht(){let e=this.flags;if(e&16||e&32&&(Xe(this.deps,this)||(this.flags=e&-33,false))){if(rt(this)){let n=this.subs;n!==void 0&&Ye(n);}}else if(!e){this.flags=5;let n=V(this);try{this.value=this.getter();}finally{z=n,this.flags&=-5;}}let t=z;return t!==void 0&&Ce(this,t,Ee),this.value}function $t(...e){if(e.length){if(this.pendingValue!==(this.pendingValue=e[0])){this.flags=17;let t=this.subs;t!==void 0&&(Ot(t),xe||ot());}}else {if(this.flags&16&&it(this)){let n=this.subs;n!==void 0&&Ye(n);}let t=z;for(;t!==void 0;){if(t.flags&3){Ce(this,t,Ee);break}t=t.subs?.sub;}return this.currentValue}}function Ft(){st.call(this);}function st(){this.depsTail=void 0,this.flags=0,ye(this);let e=this.subs;e!==void 0&&Ke(e);}function ye(e){let t=e.depsTail,n=t!==void 0?t.nextDep:e.deps;for(;n!==void 0;)n=Ke(n,e);}function Pt(e,t,n){if(typeof t!="function"){e(t);return}let r=V(void 0),i=e();V(r);let a=t(i);e(a);}function te(e,t){let n=et(e),r=n;return [r,s=>Pt(n,s)]}function B(e){let t=nt(e);return t}function Ne(e){return tt(e)}function H(e){Ze();try{e();}finally{Qe();}}function ct(e){let t=e.length;if(t===0)return [];let n=new Int32Array(t),r=new Int32Array(t),i=new Int32Array(t).fill(-1),a=0;for(let f=0;f<t;f++){let o=e[f],l=0,p=a;for(;l<p;){let m=l+p>>1;n[m]<o?l=m+1:p=m;}n[l]=o,r[l]=f,l>0&&(i[f]=r[l-1]),l>=a&&a++;}let s=new Array(a),c=r[a-1];for(let f=a-1;f>=0;f--)s[f]=c,c=i[c];return s}var Wt=32;function Vt(e,t,n,r,i,a,s,c,f){let o=t.length,l=n.length,p=new Array(o);for(let d=0;d<o;d++)p[d]=i(t[d]);let m=new Array(l),u=new Uint8Array(o);for(let d=0;d<l;d++){let g=i(n[d]),b=-1;for(let T=0;T<o;T++)if(!u[T]&&p[T]===g){b=T,u[T]=1;break}m[d]=b;}for(let d=0;d<o;d++)if(!u[d])if(f?.onBeforeRemove){let g=r[d];f.onBeforeRemove(g,()=>{g.parentNode&&g.parentNode.removeChild(g);});}else e.removeChild(r[d]);if(o===l){let d=true;for(let g=0;g<l;g++)if(m[g]!==g){d=false;break}if(d){let g=new Array(l);for(let b=0;b<l;b++){let T=r[b];s(T,n[b]),g[b]=T;}return {nodes:g,items:n}}}let h=[],E=[];for(let d=0;d<l;d++)m[d]!==-1&&(h.push(m[d]),E.push(d));let S=ct(h),_=new Uint8Array(l);for(let d of S)_[E[d]]=1;let y=new Array(l),v=null;for(let d=l-1;d>=0;d--){let g,b=false;if(m[d]===-1)g=a(n[d]),b=true;else if(g=r[m[d]],s(g,n[d]),_[d]){y[d]=g,v=g;continue}v?e.insertBefore(g,v):e.appendChild(g),b&&f?.onInsert?.(g),y[d]=g,v=g;}return {nodes:y,items:n}}function De(e,t,n,r,i,a,s,c,f){let o=t.length,l=n.length;if(l===0){for(let d=0;d<o;d++)if(f?.onBeforeRemove){let g=r[d];f.onBeforeRemove(g,()=>{g.parentNode&&g.parentNode.removeChild(g);});}else e.removeChild(r[d]);return {nodes:[],items:[]}}if(o===0){let d=new Array(l);for(let g=0;g<l;g++){let b=a(n[g]);e.appendChild(b),f?.onInsert?.(b),d[g]=b;}return {nodes:d,items:n}}if(o<Wt)return Vt(e,t,n,r,i,a,s,c,f);let p=new Map;for(let d=0;d<o;d++)p.set(i(t[d]),d);let m=new Array(l),u=new Uint8Array(o);for(let d=0;d<l;d++){let g=i(n[d]),b=p.get(g);b!==void 0?(m[d]=b,u[b]=1):m[d]=-1;}for(let d=0;d<o;d++)if(!u[d])if(f?.onBeforeRemove){let g=r[d];f.onBeforeRemove(g,()=>{g.parentNode&&g.parentNode.removeChild(g);});}else e.removeChild(r[d]);if(o===l){let d=true;for(let g=0;g<l;g++)if(m[g]!==g){d=false;break}if(d){let g=new Array(l);for(let b=0;b<l;b++){let T=r[b];s(T,n[b]),g[b]=T;}return {nodes:g,items:n}}}let h=[],E=[];for(let d=0;d<l;d++)m[d]!==-1&&(h.push(m[d]),E.push(d));let S=ct(h),_=new Uint8Array(l);for(let d of S)_[E[d]]=1;let y=new Array(l),v=null;for(let d=l-1;d>=0;d--){let g,b=false;if(m[d]===-1)g=a(n[d]),b=true;else if(g=r[m[d]],s(g,n[d]),_[d]){y[d]=g,v=g;continue}v?e.insertBefore(g,v):e.appendChild(g),b&&f?.onInsert?.(g),y[d]=g,v=g;}return {nodes:y,items:n}}function qt(e){let t=new Set,n=e.attributes;for(let r=0;r<n.length;r++){let i=n[r].name;i.startsWith("data-bind:")&&t.add(i.slice(10));}return t}function Gt(e){return e.hasAttribute("data-list")||e.hasAttribute("data-if")}function ut(e){try{let t=JSON.parse(e);return Object.keys(t).sort()}catch{return []}}function jt(e,t){if(e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}function zt(e,t){let n=e.getAttribute("data-module"),r=t.getAttribute("data-module");if(n!==r)return "REPLACE";let a=e.__formaInitialState??e.getAttribute("data-forma-state")??"{}",s=t.getAttribute("data-forma-state")??"{}",c=ut(a),f=ut(s);return jt(c,f)?"PRESERVE":"RESET"}var Se=null;function Jt(e){return Se||(Se=document.createElement("template")),Se.innerHTML=e,Se.content}function Le(e,t){let n=qt(e),r=e.hasAttribute("data-show"),i=e.hasAttribute("data-model"),a=false,s=e.attributes;for(let f=0;f<s.length;f++)if(s[f].name.startsWith("data-class:")){a=true;break}let c=t.attributes;for(let f=0;f<c.length;f++){let o=c[f];if(o.name==="style"&&r||o.name==="class"&&a||(o.name==="value"||o.name==="checked")&&i||n.has(o.name))continue;e.getAttribute(o.name)!==o.value&&e.setAttribute(o.name,o.value);}for(let f=s.length-1;f>=0;f--){let o=s[f];if(!t.hasAttribute(o.name)){if(o.name==="style"&&r||o.name==="class"&&a||(o.name==="value"||o.name==="checked")&&i||n.has(o.name))continue;e.removeAttribute(o.name);}}}function Kt(e,t){if(e.hasAttribute("data-text"))return;let n=[],r=[];for(let s of Array.from(e.childNodes))s.nodeType===Node.TEXT_NODE&&n.push(s);for(let s=0;s<t.childNodes.length;s++){let c=t.childNodes[s];c.nodeType===Node.TEXT_NODE&&r.push({node:c,index:s});}if(n.length===r.length){for(let s=0;s<n.length;s++)n[s].textContent!==r[s].node.textContent&&(n[s].textContent=r[s].node.textContent);return}let i=new Set,a=0;for(let{node:s,index:c}of r)if(a<n.length){let f=n[a];a++,i.add(f),f.textContent!==s.textContent&&(f.textContent=s.textContent);}else {let f=Xt(e,t,c);e.insertBefore(document.createTextNode(s.textContent??""),f);}for(let s of n)!i.has(s)&&s.parentNode===e&&e.removeChild(s);}function Xt(e,t,n){for(let r=n+1;r<t.childNodes.length;r++){let i=t.childNodes[r];if(i.nodeType===Node.ELEMENT_NODE){let a=i.getAttribute("data-forma-id");if(a){let s=e.querySelector(`[data-forma-id="${CSS.escape(a)}"]`);if(s&&s.parentElement===e)return s}}}return null}function Oe(e,t,n){if(Gt(e))return;Kt(e,t);let r=Array.from(e.children),i=Array.from(t.children),a=new Map,s=[];for(let o of r){if(o.hasAttribute("data-forma-leaving"))continue;let l=o.getAttribute("data-forma-id");l?a.set(l,o):s.push(o);}let c=0,f=new Set;for(let o of i){let l=o.getAttribute("data-forma-id"),p;if(l)p=a.get(l);else for(;c<s.length;){let m=s[c];if(c++,m.tagName===o.tagName&&!f.has(m)){p=m;break}}if(p){if(f.add(p),p.hasAttribute("data-forma-state")&&o.hasAttribute("data-forma-state"))switch(zt(p,o)){case "PRESERVE":Le(p,o),Oe(p,o,n);break;case "RESET":n.unmountScope(p),Le(p,o),Yt(p,o),n.mountScope(p);break;case "REPLACE":{n.unmountScope(p);let u=o.cloneNode(true);e.replaceChild(u,p),n.mountScope(u),f.delete(p),p=u,f.add(u);break}}else Le(p,o),Oe(p,o,n);Zt(e,p,o,i);}else {let m=o.cloneNode(true),u=Qt(e,o,i);e.insertBefore(m,u),f.add(m),m.hasAttribute("data-forma-state")&&n.mountScope(m);let h=m.querySelectorAll("[data-forma-state]");for(let E of Array.from(h))n.mountScope(E);}}for(let o of r)if(!f.has(o)){if(o.parentElement!==e||o.hasAttribute("data-forma-leaving"))continue;o.hasAttribute("data-forma-state")&&n.unmountScope(o);let l=o.querySelectorAll("[data-forma-state]");for(let p of Array.from(l))n.unmountScope(p);e.removeChild(o);}}function Yt(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let n of Array.from(t.childNodes))e.appendChild(n.cloneNode(true));}function Zt(e,t,n,r){let i=r.indexOf(n);if(Array.from(e.children).indexOf(t)!==i){let c=r[i+1];if(c){let f=c.getAttribute("data-forma-id");if(f){let o=e.querySelector(`[data-forma-id="${CSS.escape(f)}"]`);if(o&&o.parentElement===e){e.insertBefore(t,o);return}}}e.appendChild(t);}}function Qt(e,t,n){let r=n.indexOf(t);for(let i=r+1;i<n.length;i++){let a=n[i].getAttribute("data-forma-id");if(a){let s=e.querySelector(`[data-forma-id="${CSS.escape(a)}"]`);if(s&&s.parentElement===e)return s}}return null}function ft(e){let t="";return function(r,i){let a=i.trim();if(a&&!(a===t&&r.hasChildNodes())){t=a,e.disconnectObserver();try{if(!r.hasChildNodes()||r.children.length===0){r.innerHTML=a,e.batch(()=>{let l=r.querySelectorAll("[data-forma-state]");for(let p of Array.from(l))e.mountScope(p);});return}let s=Jt(a),c=document.createElement("div");c.appendChild(s);let f=new Set;for(let l of Array.from(r.children)){if(l.hasAttribute("data-forma-leaving"))continue;let p=l.getAttribute("data-forma-id");p&&f.add(p);}let o=!1;if(f.size>0)for(let l of Array.from(c.children)){let p=l.getAttribute("data-forma-id");if(p&&f.has(p)){o=!0;break}}if(f.size>0&&!o){e.batch(()=>{let l=r.querySelectorAll("[data-forma-state]");for(let m of Array.from(l))e.unmountScope(m);r.innerHTML=a;let p=r.querySelectorAll("[data-forma-state]");for(let m of Array.from(p))e.mountScope(m);});return}e.batch(()=>{Oe(r,c,e);});}finally{e.reconnectObserver();}}}}var Be=new Map;function St(e){let t=Be.get(e);t?t():O&&N(`$refetch: no data-fetch with id "${e}" found`);}function Ie(e,t){let n=Object.create(null);for(let r of Object.keys(t))n[r]=()=>t[r];return {getters:new Proxy(e.getters,{get(r,i){return i in n?n[i]:r[i]},has(r,i){return i in n||i in r}}),setters:e.setters}}var O=false,$="mutable",F=false,qe=true;function N(...e){(O||typeof window<"u"&&window.__FORMA_DEBUG)&&console.log("[FormaJS]",...e);}var pe=new Map;function Te(e){if(e==null)return;let t=e.trim().toLowerCase();if(t==="1"||t==="true"||t==="on"||t==="yes")return true;if(t==="0"||t==="false"||t==="off"||t==="no")return false}function Ue(e){if(e==null)return;let t=e.trim().toLowerCase();if(t==="mutable")return "mutable";if(t==="locked-off"||t==="off"||t==="disabled")return "locked-off";if(t==="locked-on"||t==="on"||t==="enabled")return "locked-on"}function en(){let e={};if(typeof window<"u"){let t=window.__FORMA_RUNTIME_CONFIG;if(t){if(typeof t.allowUnsafeEval=="boolean"&&(e.allowUnsafeEval=t.allowUnsafeEval),typeof t.unsafeEvalMode=="string"){let n=Ue(t.unsafeEvalMode);n&&(e.unsafeEvalMode=n);}typeof t.lockUnsafeEval=="boolean"&&(e.lockUnsafeEval=t.lockUnsafeEval),typeof t.diagnostics=="boolean"&&(e.diagnostics=t.diagnostics),typeof t.autoContainment=="boolean"&&(e.autoContainment=t.autoContainment);}}if(typeof document<"u"){let t=document.currentScript;if(t){let n=Te(t.getAttribute("data-forma-unsafe-eval"));n!==void 0&&(e.allowUnsafeEval=n);let r=Ue(t.getAttribute("data-forma-unsafe-eval-mode"));r!==void 0&&(e.unsafeEvalMode=r);let i=Te(t.getAttribute("data-forma-lock-unsafe-eval"));i!==void 0&&(e.lockUnsafeEval=i);let a=Te(t.getAttribute("data-forma-diagnostics"));a!==void 0&&(e.diagnostics=a);let s=Te(t.getAttribute("data-forma-auto-containment"));s!==void 0&&(e.autoContainment=s);}}return e}function ne(e,t,n){if(!qe)return;let r=`${e}|${n}|${t}`,i=Date.now(),a=pe.get(r);a?(a.count+=1,a.lastSeenAt=i):(pe.set(r,{kind:e,expr:t,reason:n,count:1,firstSeenAt:i,lastSeenAt:i}),console.warn(`[FormaJS] ${n}: ${t}`));try{if(typeof window<"u"){let s={kind:e,expr:t,reason:n,count:pe.get(r)?.count??1};window.dispatchEvent(new CustomEvent("formajs:diagnostic",{detail:s}));}}catch{}}var dt=Ue("locked-off");dt&&($=dt,$==="locked-off"&&(F=false),$==="locked-on"&&(F=true),$==="mutable"&&(F=true));var ee=en(),mt=ee.lockUnsafeEval?"locked-off":ee.unsafeEvalMode;mt&&($=mt,$==="locked-off"&&(F=false),$==="locked-on"&&(F=true));$==="mutable"&&typeof ee.allowUnsafeEval=="boolean"&&(F=ee.allowUnsafeEval);typeof ee.diagnostics=="boolean"&&(qe=ee.diagnostics);var tn=ee.autoContainment===true;function nn(){let e=globalThis?.scheduler;if(e&&(typeof e.yield=="function"||typeof e.postTask=="function"))return e}async function rn(){let e=nn();if(e?.yield){await e.yield();return}if(e?.postTask){await e.postTask(()=>{},{priority:"background"});return}await new Promise(t=>setTimeout(t,0));}function on(e=document,t={}){let n=t.selector??"[data-forma-contain]";if(!n||typeof e.querySelectorAll!="function")return 0;let r=e.querySelectorAll(n),i=0;for(let a=0;a<r.length;a++){let s=r[a];if(!s?.style)continue;let c=s.getAttribute("data-forma-contain")??t.contain??"layout style paint",f=s.getAttribute("data-forma-content-visibility")??t.contentVisibility??"auto",o=s.getAttribute("data-forma-contain-intrinsic-size")??t.containIntrinsicSize??"auto 800px",l=t.skipIfAlreadySet===true,p=false,m=s.style.getPropertyValue("contain"),u=s.style.getPropertyValue("content-visibility"),h=s.style.getPropertyValue("contain-intrinsic-size");c!=="off"&&(!l||!m)&&(s.style.setProperty("contain",c),p=true),f!=="off"&&(!l||!u)&&(s.style.setProperty("content-visibility",f),p=true),o!=="off"&&(!l||!h)&&(s.style.setProperty("contain-intrinsic-size",o),p=true),p&&i++;}return O&&i>0&&N("applyContainmentHints: applied to",i,"element(s)"),i}var At=/^'[^']*'$/,_t=/^"[^"]*"$/,wt=/^-?\d+(\.\d+)?$/,Rt=/^[a-zA-Z_$]\w*$/,sn=/^(\w+)\.(\w+)$/;var an=/^(\w+)\[(\d+|'[^']*'|"[^"]*")\]$/,ln=/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/,cn=/^(.+?)\s*\?\?\s*(.+)$/,un=/^(.+?)\s*&&\s*(.+)$/,fn=/^(.+?)\s*\|\|\s*(.+)$/,dn=/^(.+?)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/,mn=/^(.+?)\s*([*/%])\s*(.+)$/,pn=/^(.+?)\s*([+-])\s*(.+)$/,gn=/^`([^`]*)`$/,hn=/\$\{([^}]+)\}/g;var bn=/^\((.+)\)\.(\w+)\((.*)\)$/,We=/^\{|\}$/g;var vn=/^\d+$/,En=/^(\w+)(\+\+|--)$/,yn=/^(\+\+|--)(\w+)$/,Sn=/^(\w+)\s*=\s*!(\w+)$/,Tn=/^(\w+)\s*=\s*(.+)$/,An=/^(\w+)\s*(\+=|-=|\*=|\/=)\s*(.+)$/,_n=/^if\b/,wn=/^(\w+)\s*=\s*(.+)$/,Rn=/^(.+?)(?:→|->)\s*(\S+)(.*)$/,Mn=/^(GET|POST|PUT|PATCH|DELETE)\s+(.+)$/i,xn=/^\{item\.?|\}$/g,Cn=/\bevent\s*[.([]|\$event\b/,kn=/^\$refetch\(\s*['"]([^'"]+)['"]\s*\)$/,Re=Symbol.for("forma-transition-state"),Nn=2048,ue=new Map;function ce(e,t){if(ue.size>=Nn){let n=ue.keys().next().value;n!==void 0&&ue.delete(n);}ue.set(e,t);}var Ge=new WeakMap,je=new WeakMap,fe=new Map,Dn=2048;function Ln(e,t){if(fe.size>=Dn){let n=fe.keys().next().value;n!==void 0&&fe.delete(n);}fe.set(e,t);}var re=new Set(["constructor","__proto__","prototype","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","eval","Function"]);(()=>{let e=[];for(let t of re){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e.push({name:t,dotRe:new RegExp(`(?:^|\\.)${n}(?:\\s*\\(|\\s*$|[^\\w$])`,"m"),bracketRe:new RegExp(`\\[\\s*(?:'${n}'|"${n}"|\``+n+"`)\\s*\\]")});}return e})();var pt=Symbol.for("forma-text-binding-cache");function Hn(e){return e==null?"":typeof e=="string"?e:typeof e=="symbol"?e.toString():String(e)}function $n(e,t){let n=e[pt];if(n||(n={initialized:false,last:"",node:null},e[pt]=n),n.initialized&&n.last===t)return;let r=n.node;if(!r||r.parentNode!==e||e.childNodes.length!==1||e.firstChild!==r)if(e.childNodes.length===1&&e.firstChild?.nodeType===Node.TEXT_NODE)r=e.firstChild,n.node=r;else {e.textContent=t;let i=e.firstChild;n.node=i&&i.nodeType===Node.TEXT_NODE&&e.childNodes.length===1?i:null,n.last=t,n.initialized=true;return}r.data=t,n.last=t,n.initialized=true;}function Ve(e){let t=[];if(e.trim()==="")return t;let n=0,r=false,i=false,a=false,s=0;for(let c=0;c<e.length;c++){let f=e[c];if(a){a=false;continue}if(f==="\\"){a=true;continue}if(r){f==="'"&&(r=false);continue}if(i){f==='"'&&(i=false);continue}if(f==="'"){r=true;continue}if(f==='"'){i=true;continue}if(f==="("){n++;continue}if(f===")"){n>0&&n--;continue}f===","&&n===0&&(t.push(e.slice(s,c).trim()),s=c+1);}return t.push(e.slice(s).trim()),t.filter(Boolean)}function ie(e,t,n,r){if(e[t]!==n)return null;let i=0,a=false,s=false,c=false,f=false;for(let o=t;o<e.length;o++){let l=e[o];if(f){f=false;continue}if(l==="\\"&&(a||s||c)){f=true;continue}if(a){l==="'"&&(a=false);continue}if(s){l==='"'&&(s=false);continue}if(c){l==="`"&&(c=false);continue}if(l==="'"){a=true;continue}if(l==='"'){s=true;continue}if(l==="`"){c=true;continue}if(l===n){i++;continue}if(l===r&&(i--,i===0))return {inner:e.slice(t+1,o),end:o}}return null}function Fn(e){let t=e.trim();if(!t)return [];let n=[],r=0,i=0,a=0,s=false,c=false,f=false,o=false,l=0;for(let m=0;m<t.length;m++){let u=t[m];if(o){o=false;continue}if(u==="\\"&&(s||c||f)){o=true;continue}if(s){u==="'"&&(s=false);continue}if(c){u==='"'&&(c=false);continue}if(f){u==="`"&&(f=false);continue}if(u==="'"){s=true;continue}if(u==='"'){c=true;continue}if(u==="`"){f=true;continue}if(u==="("?r++:u===")"&&r>0?r--:u==="{"?i++:u==="}"&&i>0?i--:u==="["?a++:u==="]"&&a>0&&a--,u===";"&&r===0&&i===0&&a===0){let h=t.slice(l,m).trim();h&&n.push(h),l=m+1;}}let p=t.slice(l).trim();return p&&n.push(p),n}function gt(e){let t=e.trim();if(!t)return null;if(t.startsWith("{")){let o=ie(t,0,"{","}");if(!o)return null;let l=o.inner.trim(),p=t.slice(o.end+1).trim();return p.startsWith(";")&&(p=p.slice(1).trim()),{body:l,rest:p}}let n=0,r=0,i=0,a=false,s=false,c=false,f=false;for(let o=0;o<t.length;o++){let l=t[o];if(f){f=false;continue}if(l==="\\"&&(a||s||c)){f=true;continue}if(a){l==="'"&&(a=false);continue}if(s){l==='"'&&(s=false);continue}if(c){l==="`"&&(c=false);continue}if(l==="'"){a=true;continue}if(l==='"'){s=true;continue}if(l==="`"){c=true;continue}if(l==="("?n++:l===")"&&n>0?n--:l==="{"?r++:l==="}"&&r>0?r--:l==="["?i++:l==="]"&&i>0&&i--,l===";"&&n===0&&r===0&&i===0)return {body:t.slice(0,o).trim(),rest:t.slice(o+1).trim()}}return {body:t,rest:""}}function Pn(e,t){let n=e.trim();if(!_n.test(n)||Cn.test(n))return null;let r=2;for(;r<n.length&&/\s/.test(n[r]);)r++;if(n[r]!=="(")return null;let i=ie(n,r,"(",")");if(!i)return null;let a=x(i.inner.trim(),t);if(!a)return null;let s=n.slice(i.end+1).trim(),c=gt(s);if(!c||!c.body)return null;let f=Me(c.body,t);if(!f)return null;s=c.rest.trim();let o=null;if(s.startsWith("else")){s=s.slice(4).trim();let l=gt(s);if(!l||!l.body||(o=Me(l.body,t),!o))return null;s=l.rest.trim();}return s.length>0?null:l=>{H(()=>{a()?f(l):o?.(l);});}}function Bn(e){let t=e.trim();for(;t.startsWith("(");){let n=ie(t,0,"(",")");if(!n||n.end!==t.length-1)break;let r=n.inner.trim();if(!r)break;t=r;}return t}function xt(e){let t=fe.get(e);if(t)return t;let n=[],r=[],i=0,a=/\{item\.?(\w*)\}/g,s;for(;(s=a.exec(e))!==null;)n.push(e.slice(i,s.index)),r.push(s[1]),i=a.lastIndex;n.push(e.slice(i));let c={statics:n,dynamics:r,hasItemRef:r.length>0};return Ln(e,c),c}var Ct=new WeakMap;function ze(e,t){if(!e.hasItemRef)return e.statics[0];let n=e.statics[0];for(let r=0;r<e.dynamics.length;r++){let i=e.dynamics[r];i?n+=String(t?.[i]??""):n+=typeof t=="object"?JSON.stringify(t):String(t??""),n+=e.statics[r+1]??"";}return n}function Un(e,t){let n=e.cloneNode(true),r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(;r.nextNode();){let i=r.currentNode,a=i.textContent??"";if(a.includes("{item")){let s=xt(a);Ct.set(i,s),i.textContent=ze(s,t);}}return Kn(n,t),n}function Wn(e,t){let n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;n.nextNode();){let r=n.currentNode,i=Ct.get(r);i&&(r.textContent=ze(i,t));}}var Vn=new WeakMap,qn=["data-list","data-show","data-text","data-if","data-model","data-on:","data-class:","data-bind:","data-computed","data-persist","data-fetch","data-transition","data-transition:"];function Gn(e){for(let t of qn)if(e===t||e.startsWith(t))return true;return false}function de(e){return e?e.trim().split(/\s+/).map(t=>t.trim()).filter(Boolean):[]}function ge(e){let t=e.trim().toLowerCase();if(t.endsWith("ms")){let n=Number(t.slice(0,-2));return Number.isFinite(n)&&n>=0?n:null}if(t.endsWith("s")){let n=Number(t.slice(0,-1));return Number.isFinite(n)&&n>=0?n*1e3:null}return null}function He(e){let t=[],n;for(let r of de(e)){let i=ge(r);i!=null?n=i:t.push(r);}return {classes:t,durationMs:n}}function J(e){return Array.from(new Set(e.filter(Boolean)))}function Ae(e){return e?e.split(",").map(t=>ge(t.trim())).filter(t=>t!=null):[]}function ht(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return Math.max(...t,0);if(t.length===0)return Math.max(...e,0);let n=Math.max(e.length,t.length),r=0;for(let i=0;i<n;i++){let a=e[i%e.length]??0,s=t[i%t.length]??0;a+s>r&&(r=a+s);}return r}function jn(e,t){if(typeof t=="number")return t;let n=window.getComputedStyle(e),r=ht(Ae(n.transitionDuration),Ae(n.transitionDelay)),i=ht(Ae(n.animationDuration),Ae(n.animationDelay));return Math.max(r,i)}function G(e){let t=e[Re];if(t)return t;let n={token:0,cancel:null};return e[Re]=n,n}function _e(e){let t=e[Re];t?.cancel&&t.cancel(),delete e[Re];}function $e(e){if(!(e.hasAttribute("data-transition")||Array.from(e.attributes).some(m=>m.name.startsWith("data-transition:"))))return null;let n=He(e.getAttribute("data-transition")).classes,r=He(e.getAttribute("data-transition:enter")),i=He(e.getAttribute("data-transition:leave")),a=de(e.getAttribute("data-transition:enter-from")??e.getAttribute("data-transition:enter-start")),s=de(e.getAttribute("data-transition:enter-to")??e.getAttribute("data-transition:enter-end")),c=de(e.getAttribute("data-transition:leave-from")??e.getAttribute("data-transition:leave-start")),f=de(e.getAttribute("data-transition:leave-to")??e.getAttribute("data-transition:leave-end")),o=ge(e.getAttribute("data-transition:duration")??""),l=ge(e.getAttribute("data-transition:duration-enter")??"")??r.durationMs??o??void 0,p=ge(e.getAttribute("data-transition:duration-leave")??"")??i.durationMs??o??void 0;return {enter:J([...n,...r.classes]),enterFrom:J(a),enterTo:J(s),leave:J([...n,...i.classes]),leaveFrom:J(c),leaveTo:J(f),enterDurationMs:l,leaveDurationMs:p}}function we(e,t){for(let n of t)e.classList.remove(n);}function Fe(e,t){for(let n of t)e.classList.add(n);}function be(e,t,n){let r=J([...t.base,...t.from,...t.to]),i=false,a=null,s=null,c=null,f=()=>{i||(i=true,a!=null&&window.clearTimeout(a),s!=null&&cancelAnimationFrame(s),c!=null&&cancelAnimationFrame(c),we(e,r),n());};return Fe(e,t.base),Fe(e,t.from),we(e,t.to),s=requestAnimationFrame(()=>{c=requestAnimationFrame(()=>{if(i)return;we(e,t.from),Fe(e,t.to);let o=jn(e,t.durationMs);if(o<=0){f();return}a=window.setTimeout(f,o+25);});}),f}function zn(e,t,n,r){if(t.insertBefore(e,n),!r)return;let i=G(e);i.token+=1;let a=i.token;i.cancel&&i.cancel(),i.cancel=be(e,{base:r.enter,from:r.enterFrom,to:r.enterTo,durationMs:r.enterDurationMs},()=>{let s=G(e);s.token===a&&(s.cancel=null);});}function bt(e,t,n){if(e.hasAttribute("data-forma-leaving")){n();return}if(!t){n();return}e.setAttribute("data-forma-leaving","");let r=G(e);r.token+=1;let i=r.token;r.cancel&&r.cancel(),r.cancel=be(e,{base:t.leave,from:t.leaveFrom,to:t.leaveTo,durationMs:t.leaveDurationMs},()=>{let a=G(e);a.token===i&&(a.cancel=null),e.removeAttribute("data-forma-leaving"),n();});}function Jn(e,t,n,r){if(!n||r){e.style.display=t?"":"none",n&&we(e,J([...n.enter,...n.enterFrom,...n.enterTo,...n.leave,...n.leaveFrom,...n.leaveTo]));return}let i=G(e);i.token+=1;let a=i.token;if(i.cancel&&i.cancel(),i.cancel=null,t){e.style.display="",i.cancel=be(e,{base:n.enter,from:n.enterFrom,to:n.enterTo,durationMs:n.enterDurationMs},()=>{let s=G(e);s.token===a&&(s.cancel=null);});return}i.cancel=be(e,{base:n.leave,from:n.leaveFrom,to:n.leaveTo,durationMs:n.leaveDurationMs},()=>{let s=G(e);s.token===a&&(e.style.display="none",s.cancel=null);});}function Kn(e,t){let n=[e,...Array.from(e.querySelectorAll("*"))];for(let r of n){let i=[];for(let a of Array.from(r.attributes))if(!Gn(a.name)&&a.value.includes("{item")){let s=xt(a.value);i.push({attr:a.name,compiled:s}),r.setAttribute(a.name,ze(s,t));}i.length>0&&Vn.set(r,i);}}function Xn(e,t){let n=0,r=e.match(/^[a-zA-Z_$]\w*/);if(!r)return null;let i=r[0];if(n=i.length,n>=e.length||e[n]!=="."&&!(e[n]==="?"&&e[n+1]==="."))return null;let a=[];for(;n<e.length;){let c=false;if(e[n]==="?"&&e[n+1]===".")c=true,n+=2;else if(e[n]===".")n+=1;else return null;let f=e.slice(n).match(/^\w+/);if(!f)return null;let o=f[0];if(n+=o.length,re.has(o))return ()=>{};if(n<e.length&&e[n]==="("){let l=ie(e,n,"(",")");if(!l)return null;let p=l.inner.trim(),m=[];for(let u of Ve(p)){let h=x(u,t);if(!h)return null;m.push(h);}a.push({type:"call",name:o,optional:c,argFns:m}),n=l.end+1;}else a.push({type:"prop",name:o,optional:c});}if(n!==e.length||a.length===0)return null;let s=i==="Math"?(()=>Math):(()=>t.getters[i]?.());return ()=>{let c=s();for(let f of a){if(c==null)return f.optional,void 0;if(f.type==="prop")c=c[f.name];else {let o=c[f.name];if(typeof o!="function")return;let l=f.argFns.map(p=>p());c=o.apply(c,l);}}return c}}function x(e,t){let n=ue.get(e);if(n)return n(t);let r=Yn(e,t);if(r!==null)if(e==="true"||e==="false"||e==="null"||e==="undefined"){let i=e==="true"?true:e==="false"?false:e==="null"?null:void 0;ce(e,()=>()=>i);}else if(Rt.test(e))ce(e,i=>()=>i.getters[e]?.());else if(At.test(e)||_t.test(e)){let i=e.slice(1,-1);ce(e,()=>()=>i);}else if(wt.test(e)){let i=Number(e);ce(e,()=>()=>i);}else {let i=e.match(sn);if(i){let a=i[1],s=i[2];ce(e,c=>()=>c.getters[a]?.()?.[s]);}}return r}function Yn(e,t){e=e.trim();let n=Bn(e);if(n!==e)return x(n,t);if(At.test(e)||_t.test(e)){let u=e.slice(1,-1);return ()=>u}if(wt.test(e)){let u=Number(e);return ()=>u}if(e==="true")return ()=>true;if(e==="false")return ()=>false;if(e==="null")return ()=>null;if(e==="undefined")return ()=>{};if(Rt.test(e))return ()=>t.getters[e]?.();{let u=Xn(e,t);if(u)return u}let r=e.match(bn);if(r){let u=r[1].trim(),h=r[2],E=r[3].trim();if(re.has(h))return ()=>{};let S=x(u,t);if(!S)return null;let _=[];for(let y of Ve(E)){let v=x(y,t);if(!v)return null;_.push(v);}return ()=>{let y=S(),v=y?.[h];if(typeof v!="function")return;let d=_.map(g=>g());return v.apply(y,d)}}if(e.startsWith("!")){let u=x(e.slice(1).trim(),t);if(u)return ()=>!u()}let i=e.match(an);if(i){let u=x(i[1],t),h,E=i[2];if(vn.test(E)?h=Number(E):h=E.slice(1,-1),u)return ()=>u()?.[h]}if(e.startsWith("[")){let u=ie(e,0,"[","]");if(u&&u.end===e.length-1){let h=u.inner.trim();if(h==="")return ()=>[];let E=Ve(h),S=[],_=true;for(let y of E){let v=x(y.trim(),t);if(!v){_=false;break}S.push(v);}if(_)return ()=>S.map(y=>y())}}let a=e.match(ln);if(a){let u=x(a[1].trim(),t),h=x(a[2].trim(),t),E=x(a[3].trim(),t);if(u&&h&&E)return ()=>u()?h():E()}let s=e.match(cn);if(s){let u=x(s[1].trim(),t),h=x(s[2].trim(),t);if(u&&h)return ()=>u()??h()}let c=e.match(fn);if(c){let u=x(c[1].trim(),t),h=x(c[2].trim(),t);if(u&&h)return ()=>u()||h()}let f=e.match(un);if(f){let u=x(f[1].trim(),t),h=x(f[2].trim(),t);if(u&&h)return ()=>u()&&h()}let o=e.match(dn);if(o){let u=x(o[1].trim(),t),h=x(o[3].trim(),t);if(u&&h){let E=o[2];return ()=>{let S=u(),_=h();switch(E){case "===":return S===_;case "!==":return S!==_;case "==":return S==_;case "!=":return S!=_;case ">":return S>_;case "<":return S<_;case ">=":return S>=_;case "<=":return S<=_}}}}let l=e.match(pn);if(l){let u=x(l[1].trim(),t),h=x(l[3].trim(),t);if(u&&h){let E=l[2];return ()=>{let S=u(),_=h();return E==="+"?S+_:S-_}}}let p=e.match(mn);if(p){let u=x(p[1].trim(),t),h=x(p[3].trim(),t);if(u&&h){let E=p[2];return ()=>{let S=u(),_=h();switch(E){case "*":return S*_;case "/":return S/_;case "%":return S%_}}}}let m=e.match(gn);if(m){let u=m[1],h=[],E=[],S=0,_=new RegExp(hn.source,"g"),y;for(;(y=_.exec(u))!==null;){h.push(u.slice(S,y.index));let v=x(y[1].trim(),t);if(!v)return null;E.push(v),S=_.lastIndex;}return h.push(u.slice(S)),()=>{let v=h[0];for(let d=0;d<E.length;d++)v+=String(E[d]()??""),v+=h[d+1]??"";return v}}return null}function kt(e,t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}function Nt(e){return e.includes("...")?"Unsupported expression in CSP-safe mode: spread syntax detected. Use .concat() instead, or enable unsafe-eval via setUnsafeEval(true).":e.includes("=>")?"Unsupported expression in CSP-safe mode: arrow function detected. Extract logic to a data-computed attribute, or enable unsafe-eval via setUnsafeEval(true).":"Unsupported expression in CSP-safe mode. Simplify the expression or enable unsafe-eval via setUnsafeEval(true)."}function X(e,t){let n=e.replace(We,"").trim(),r=kt(Ge,t),i=r.get(n);if(i)return i;let a=x(n,t);if(a)return r.set(n,a),a;{N("buildEvaluator: blocked unsafe eval fallback for expression:",n),ne("expression-unsupported",n,Nt(n));let c=()=>{};return r.set(n,c),c}}function Me(e,t){let n=e.trim().replace(/;+$/g,"").trim();if(!n)return null;let r=Pn(n,t);if(r)return r;let i=Fn(n);if(i.length>1){let m=i.map(u=>Me(u,t));return m.every(u=>u!==null)?u=>{H(()=>{for(let h of m)h(u);});}:null}let a=i[0]??n,s=a.match(En);if(s){let m=s[1],u=s[2];return ()=>{H(()=>{let h=t.getters[m]?.()??0;t.setters[m]?.(u==="++"?h+1:h-1);});}}let c=a.match(yn);if(c){let m=c[1],u=c[2];return ()=>{H(()=>{let h=t.getters[u]?.()??0;t.setters[u]?.(m==="++"?h+1:h-1);});}}let f=a.match(Sn);if(f&&f[1]===f[2]){let m=f[1];return ()=>{H(()=>{t.setters[m]?.(!t.getters[m]?.());});}}let o=a.match(Tn);if(o){let m=o[1],u=x(o[2].trim(),t);if(u)return O&&N(`parseHandler: assignment "${m} = ..." \u2014 setter exists:`,!!t.setters[m],", getter exists:",!!t.getters[m]),()=>{H(()=>{let h=u();O&&N(`SETTER: ${m} = ${h} (was: ${t.getters[m]?.()})`),t.setters[m]?.(h);});}}let l=a.match(An);if(l){let m=l[1],u=l[2],h=x(l[3].trim(),t);if(h)return ()=>{H(()=>{let E=t.getters[m]?.()??0,S=h();switch(u){case "+=":t.setters[m]?.(E+S);break;case "-=":t.setters[m]?.(E-S);break;case "*=":t.setters[m]?.(E*S);break;case "/=":t.setters[m]?.(E/S);break}});}}let p=a.match(kn);if(p){let m=p[1];return ()=>St(m)}return null}function Zn(e,t){let n=e.trim();if(n.startsWith("{")){let c=ie(n,0,"{","}");c&&c.end===n.length-1&&(n=c.inner.trim());}let r=kt(je,t),i=r.get(n);if(i)return i;let a=Me(n,t);if(a){let c={handler:a,supported:true};return r.set(n,c),c}{N("buildHandler: blocked unsafe eval fallback for expression:",n),ne("handler-unsupported",n,Nt(n));let c={handler:()=>{},supported:false};return r.set(n,c),c}}var Qn=new Set(["__proto__","constructor","prototype"]);function Dt(e){let t;try{t=JSON.parse(e);}catch{return O&&N("parseState: Invalid JSON in data-forma-state \u2014 use valid JSON with quoted keys. Got:",e.slice(0,200)),{}}for(let n of Qn)n in t&&delete t[n];return t}function er(e){let t=e.getAttribute("data-forma-state")??"{}",n=Dt(t),r=Object.keys(n);O&&(N("initScope: parsed",r.length,"keys:",r.join(", ")),r.length===0&&N("initScope: WARNING \u2014 empty state! Raw attribute:",t.slice(0,200)));let i={},a={};for(let[s,c]of Object.entries(n)){let[f,o]=te(c);i[s]=f,a[s]=o;}return i.$refetch=()=>St,{getters:i,setters:a}}var vt=new Set(["id","className","tagName","nodeName","getAttribute","setAttribute","removeAttribute","hasAttribute","toggleAttribute","dataset","classList","textContent","innerText","value","checked","disabled","selected","type","name","placeholder","readOnly","required","min","max","step","pattern","getBoundingClientRect","offsetWidth","offsetHeight","offsetTop","offsetLeft","clientWidth","clientHeight","scrollWidth","scrollHeight","scrollTop","scrollLeft","style","hidden","focus","blur","click","scrollIntoView","scrollTo","closest","matches","querySelector","querySelectorAll","children","childElementCount","firstElementChild","lastElementChild","nextElementSibling","previousElementSibling"]);function tr(e){return new Proxy(e,{get(t,n){if(typeof n=="symbol")return Reflect.get(t,n);if(!vt.has(n))return;let r=Reflect.get(t,n);return typeof r=="function"?r.bind(t):r},set(t,n,r){return typeof n=="symbol"||!vt.has(n)?false:Reflect.set(t,n,r)}})}function Y(e,t,n){let r={$el:tr(e),$dispatch:(y,v)=>{e.dispatchEvent(new CustomEvent(y,{bubbles:true,composed:true,detail:v}));}};t=Ie(t,r);let i=ir(e),a=!i||i.has("data-computed")?e.getAttribute("data-computed"):null;if(a){let y=a.split(/;\s*(?=\w+\s*=[^=])/);for(let v of y){let d=v.trim();if(!d)continue;let g=d.match(wn);if(g){let b=g[1],T=g[2],k=t.getters[b];delete t.getters[b];let R=X(`{${T}}`,t),D=Ne(R);t.getters[b]=D,k||delete t.setters[b];}}}let s=!i||i.has("data-text")?e.getAttribute("data-text"):null;if(s){let y=X(s,t),v=B(()=>{$n(e,Hn(y()));});n.push(v);}let c=!i||i.has("data-show")?e.getAttribute("data-show"):null;if(c){let y=X(c,t),v=$e(e);if(O){let b=e.tagName.toLowerCase(),T=e.className?`.${String(e.className).split(" ")[0]}`:"";N(`bindElement: data-show="${c}" on <${b}${T}>`);}let d=false,g=B(()=>{let b=!!y();O&&N(`data-show effect: "${c}" \u2192 ${b}`),Jn(e,b,v,!d),d=true;});n.push(g),v&&n.push(()=>_e(e));}let f=!i||i.has("data-if")?e.getAttribute("data-if"):null;if(f){let y=X(f,t),v=$e(e),d=document.createComment("forma-if"),g=e.parentNode,b=true,T=false,k=B(()=>{let R=!!y();R&&!b?(_e(e),e.removeAttribute("data-forma-leaving"),T&&v?zn(e,g,d,v):g?.insertBefore(e,d),b=true):!R&&b&&(T&&v?bt(e,v,()=>{e.parentNode&&(g?.insertBefore(d,e),e.remove());}):(g?.insertBefore(d,e),e.remove()),b=false),T=true;});n.push(k),v&&n.push(()=>_e(e));}let o=!i||i.has("data-model")?e.getAttribute("data-model"):null;if(o){let y=o.replace(We,"").trim(),v=t.getters[y],d=t.setters[y];if(v&&d){let g=e,b=B(()=>{let R=v();g.type==="checkbox"?g.checked=!!R:g.value=String(R??"");});n.push(b);let T=g.type==="checkbox"?"change":"input",k=()=>{g.type==="checkbox"?d(g.checked):g.type==="number"||g.type==="range"?d(Number(g.value)):d(g.value);};g.addEventListener(T,k),n.push(()=>{g.removeEventListener(T,k);});}}let l=!i||or(i,"data-on:","data-class:","data-bind:"),p=e.attributes;if(l)for(let y=0;y<p.length;y++){let v=p[y],d=v.name;if(d.startsWith("data-on:")){let g=d.slice(8),b=Zn(v.value,t),T=b.handler;if(O){let k=e.tagName.toLowerCase(),R=e.id?`#${e.id}`:"",D=e.className?`.${String(e.className).split(" ")[0]}`:"";N(`bindElement: data-on:${g}="${v.value}" on <${k}${R}${D}>`);}if(b.supported?e.hasAttribute("data-forma-handler-error")&&e.removeAttribute("data-forma-handler-error"):e.setAttribute("data-forma-handler-error","unsupported"),O){let k=v.value,R=D=>{N(`HANDLER FIRED: data-on:${g}="${k}"`,"isTrusted:",D.isTrusted),T(D);};e.addEventListener(g,R),n.push(()=>{e.removeEventListener(g,R);});}else e.addEventListener(g,T),n.push(()=>{e.removeEventListener(g,T);});}else if(d.startsWith("data-class:")){let g=d.slice(11),b=X(v.value,t),T=B(()=>{e.classList.toggle(g,!!b());});n.push(T);}else if(d.startsWith("data-bind:")){let g=d.slice(10),b=X(v.value,t),T=B(()=>{let k=b();k==null||k===false?e.removeAttribute(g):e.setAttribute(g,String(k));});n.push(T);}}let m=!i||i.has("data-persist")?e.getAttribute("data-persist"):null;if(m){let y=m.replace(We,"").trim(),v=t.getters[y],d=t.setters[y];if(v&&d){let g="forma:"+y;try{let T=localStorage.getItem(g);T!==null&&d(JSON.parse(T));}catch{}let b=B(()=>{try{localStorage.setItem(g,JSON.stringify(v()));}catch{}});n.push(b);}}let u=!i||i.has("data-list")?e.getAttribute("data-list"):null;if(u){let y=X(u,t),v=e.children[0];if(v){let D=function(C){let w=C;if(Array.isArray(w.__formaDisposers)){for(let A of w.__formaDisposers)try{A();}catch{}delete w.__formaDisposers;}},j=function(C,w){let A=Un(d,C),L=Ie(t,{item:C,index:w}),M=[];Y(A,L,M);for(let P of Array.from(A.querySelectorAll("*")))Y(P,L,M);return A.__formaDisposers=M,A},oe=function(C,w,A){D(C),Wn(C,w);let L=Ie(t,{item:w,index:A}),M=[];Y(C,L,M);for(let P of Array.from(C.querySelectorAll("*")))Y(P,L,M);C.__formaDisposers=M;};let d=v.cloneNode(true);e.removeChild(v);let g=d.getAttribute("data-key"),b=g?g.replace(xn,"").trim():null,T=$e(e),k=[],R=[],se=T?{onInsert:C=>{let w=C;if(!w.setAttribute)return;let A=G(w);A.token+=1;let L=A.token;A.cancel&&A.cancel(),A.cancel=be(w,{base:T.enter,from:T.enterFrom,to:T.enterTo,durationMs:T.enterDurationMs},()=>{let M=G(w);M.token===L&&(M.cancel=null);});},onBeforeRemove:(C,w)=>{let A=C;if(!A.setAttribute){w();return}D(C),bt(A,T,()=>{w();});}}:void 0,ae=B(()=>{let C=y();if(!Array.isArray(C)){for(let A of R)D(A),e.removeChild(A);k=[],R=[];return}if(T){let A=e.querySelectorAll("[data-forma-leaving]");for(let L of Array.from(A))_e(L),L.removeAttribute("data-forma-leaving"),L.parentNode&&L.parentNode.removeChild(L);}let w=new Set(R);if(b){let A=De(e,k,C,R,M=>String(M?.[b]??""),M=>{let P=C.indexOf(M);return j(M,P)},(M,P)=>{let I=C.indexOf(P);oe(M,P,I);},void 0,se),L=new Set(A.nodes);for(let M of w)if(!L.has(M)){if(M.hasAttribute?.("data-forma-leaving"))continue;D(M);}k=A.items,R=A.nodes;}else {let A=C.map((I,ve)=>({__idx:ve,__item:I})),M=De(e,k,A,R,I=>I.__idx,I=>j(I.__item,I.__idx),(I,ve)=>oe(I,ve.__item,ve.__idx),void 0,se),P=new Set(M.nodes);for(let I of w)if(!P.has(I)){if(I.hasAttribute?.("data-forma-leaving"))continue;D(I);}k=M.items,R=M.nodes;}});n.push(ae);}}let h=!i||i.has("data-fetch")?e.getAttribute("data-fetch"):null;if(h){let y=h.match(Rn);if(y){let v=y[1].trim(),d=y[2].trim(),g=y[3]?.trim()??"",b="GET",T=v,k=v.match(Mn);k&&(b=k[1].toUpperCase(),T=k[2].trim());let R,D,j;for(let w of g.split("|").filter(Boolean)){let[A,L]=w.split(":").map(M=>M.trim());A==="loading"?R=L:A==="error"?D=L:A==="poll"&&(j=parseInt(L??"0",10));}let[oe,se]=te(null);if(t.getters[d]=oe,t.setters[d]=se,R){let[w,A]=te(false);t.getters[R]=w,t.setters[R]=A;}if(D){let[w,A]=te(null);t.getters[D]=w,t.setters[D]=A;}let ae=()=>{R&&t.setters[R](true),fetch(T,{method:b}).then(w=>w.json()).then(w=>{se(w),R&&t.setters[R](false);}).catch(w=>{D&&t.setters[D](w.message),R&&t.setters[R](false);});},C=e.getAttribute("data-fetch-id");if(C&&(Be.set(C,ae),n.push(()=>Be.delete(C))),ae(),j&&j>0){let w=setInterval(ae,j);n.push(()=>clearInterval(w));}}}}function nr(e){let t=e.attributes;for(let n=0;n<t.length;n++){let r=t[n].name;if(r.startsWith("data-text")||r.startsWith("data-show")||r.startsWith("data-if")||r.startsWith("data-model")||r.startsWith("data-computed")||r.startsWith("data-persist")||r.startsWith("data-list")||r.startsWith("data-fetch")||r.startsWith("data-on:")||r.startsWith("data-class:")||r.startsWith("data-bind:")||r.startsWith("data-transition"))return true}return false}var q=null;function zr(e){if(!e||Object.keys(e).length===0){q=null;return}q=new Map;for(let t in e)q.set(t,new Set(e[t]));}function rr(){if(!q||q.size===0||q.size>200)return null;let e=[];for(let t of q.keys())e.push(`[data-forma-id="${t}"]`);return e.join(",")}function ir(e){if(!q)return null;let t=e.getAttribute("data-forma-id");return t?q.get(t)??null:null}function or(e,...t){for(let n of e)for(let r of t)if(n.startsWith(r))return true;return false}function Z(e){if(e.__formaDisposers){O&&N("mountScope: SKIPPED (already mounted)");return}let t=er(e),n=[],r=new Map,i=e.querySelectorAll("[data-ref]");for(let f=0;f<i.length;f++){let o=i[f],l=o.getAttribute("data-ref");l&&r.set(l,o);}let a=e.getAttribute("data-ref");a&&r.set(a,e),t.getters.$refs=()=>new Proxy({},{get(f,o){return r.get(o)??void 0},has(f,o){return r.has(o)}}),Y(e,t,n);let s=0,c=rr();if(c){let f=e.querySelectorAll(c);for(let o=0;o<f.length;o++)Y(f[o],t,n),s++;}else {let f=e.querySelectorAll("*");for(let o=0;o<f.length;o++){let l=f[o];nr(l)&&(Y(l,t,n),s++);}}e.__formaDisposers=n,e.__formaScope=t,e.__formaInitialState=e.getAttribute("data-forma-state")??"{}",O&&N("mountScope: DONE \u2014",s,"elements bound,",n.length,"disposers",c?"(targeted)":"(full scan)");}function Q(e){let t=e.__formaDisposers;if(t){for(let n of t)try{n();}catch{}delete e.__formaDisposers,delete e.__formaScope,delete e.__formaInitialState;}}var U=null,Et=1,sr=40,me=[],he=false;function ar(e){for(let t=0;t<e.removedNodes.length;t++){let n=e.removedNodes[t];if(n.nodeType!==Et)continue;let r=n;r.hasAttribute("data-forma-state")&&(O&&N("MutationObserver: REMOVED scope"),Q(r));let i=r.querySelectorAll("[data-forma-state]");for(let a=0;a<i.length;a++)Q(i[a]);}for(let t=0;t<e.addedNodes.length;t++){let n=e.addedNodes[t];if(n.nodeType!==Et)continue;let r=n;if(r.closest("[data-forma-leaving]"))continue;r.hasAttribute("data-forma-state")&&(O&&N("MutationObserver: ADDED scope via mutation"),Z(r));let i=r.querySelectorAll("[data-forma-state]");O&&i.length>0&&N("MutationObserver: found",i.length,"nested scope(s) in added subtree");for(let a=0;a<i.length;a++){let s=i[a];s.closest("[data-forma-leaving]")||Z(s);}}if(e.type==="attributes"&&e.attributeName==="data-forma-state"){let t=e.target;Q(t),t.hasAttribute("data-forma-state")&&Z(t);}}async function Lt(){try{for(;me.length>0;){let e=me.splice(0,sr);for(let t=0;t<e.length;t++)ar(e[t]);me.length>0&&await rn();}}finally{he=false,me.length>0&&!he&&(he=true,Lt());}}function lr(e){O&&N("MutationObserver: queued",e.length,"mutation(s)"),me.push(...e),!he&&(he=true,Lt());}function cr(){if(U)return;U=new MutationObserver(lr);let e=document.body||document.documentElement;e&&U.observe(e,{childList:true,subtree:true,attributes:true,attributeFilter:["data-forma-state"]});}function ur(){U&&(U.disconnect(),U=null);}function yt(){tn&&on(document,{skipIfAlreadySet:true});let e=document.querySelectorAll("[data-forma-state]");O&&N("initRuntime: found",e.length,"scope(s)");for(let t of Array.from(e))Z(t);cr(),O&&N("initRuntime: MutationObserver started");}function Jr(){ur();let e=document.querySelectorAll("[data-forma-state]");for(let t of Array.from(e))Q(t);}function Kr(e){e.hasAttribute("data-forma-state")&&Z(e);let t=e.querySelectorAll("[data-forma-state]");for(let n of Array.from(t))Z(n);}function Xr(e){e.hasAttribute("data-forma-state")&&Q(e);let t=e.querySelectorAll("[data-forma-state]");for(let n of Array.from(t))Q(n);}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",yt):yt());function Yr(e){O=e;}function Zr(e){$!==e&&($=e,e==="locked-off"&&(F=false),e==="locked-on"&&(F=true),e==="mutable"&&(F=true),Ge=new WeakMap,je=new WeakMap);}function Qr(e){if($!=="mutable"){N(`setUnsafeEval ignored (mode=${$}); unsafe fallback is locked`);return}F!==e&&(F=e,Ge=new WeakMap,je=new WeakMap);}function ei(){return $}function ti(e){qe=e;}function ni(){return Array.from(pe.values()).map(e=>({...e}))}function ri(){pe.clear();}function ii(){let e=document.querySelectorAll("[data-forma-state]"),t=[];for(let n of Array.from(e)){if(n.closest("[data-forma-leaving]"))continue;let r=n.__formaScope,i=n.__formaInitialState;if(!r)continue;let a={};for(let s of Object.keys(r.getters)){let c=r.getters[s]();a[s]={value:c,type:typeof c};}t.push({element:n,id:n.getAttribute("data-forma-id")||n.id||n.tagName.toLowerCase(),values:a,initialJSON:i??"{}"});}return t}function oi(e,t,n){let r=e.__formaScope;r?.setters[t]&&H(()=>{r.setters[t](n);});}function si(e){let t=e.__formaScope,n=e.__formaInitialState;if(!t||!n)return;let r=Dt(n);H(()=>{for(let[i,a]of Object.entries(r))t.setters[i]?.(a);});}var Pe=null;function fr(){return Pe||(Pe=ft({mountScope:Z,unmountScope:Q,disconnectObserver(){U&&U.disconnect();},reconnectObserver(){if(U){let e=document.body||document.documentElement;e&&U.observe(e,{childList:true,subtree:true,attributes:true,attributeFilter:["data-forma-state"]});}},batch:H})),Pe}function ai(e,t){fr()(e,t);}exports.applyContainmentHints=on;exports.clearDiagnostics=ri;exports.destroyRuntime=Jr;exports.getDiagnostics=ni;exports.getScopes=ii;exports.getUnsafeEvalMode=ei;exports.initRuntime=yt;exports.mount=Kr;exports.reconcile=ai;exports.resetScope=si;exports.setDebug=Yr;exports.setDiagnostics=ti;exports.setDirectiveMap=zr;exports.setScopeValue=oi;exports.setUnsafeEval=Qr;exports.setUnsafeEvalMode=Zr;exports.unmount=Xr;exports.yieldToMain=rn;return exports;})({});//# sourceMappingURL=formajs-runtime-hardened.global.js.map
1
+ var FormaRuntime = (function (exports) {
2
+ 'use strict';
3
+
4
+ // node_modules/alien-signals/esm/system.mjs
5
+ function createReactiveSystem({ update, notify, unwatched }) {
6
+ return {
7
+ link: link2,
8
+ unlink: unlink2,
9
+ propagate: propagate2,
10
+ checkDirty: checkDirty2,
11
+ shallowPropagate: shallowPropagate2
12
+ };
13
+ function link2(dep, sub, version) {
14
+ const prevDep = sub.depsTail;
15
+ if (prevDep !== void 0 && prevDep.dep === dep) {
16
+ return;
17
+ }
18
+ const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
19
+ if (nextDep !== void 0 && nextDep.dep === dep) {
20
+ nextDep.version = version;
21
+ sub.depsTail = nextDep;
22
+ return;
23
+ }
24
+ const prevSub = dep.subsTail;
25
+ if (prevSub !== void 0 && prevSub.version === version && prevSub.sub === sub) {
26
+ return;
27
+ }
28
+ const newLink = sub.depsTail = dep.subsTail = {
29
+ version,
30
+ dep,
31
+ sub,
32
+ prevDep,
33
+ nextDep,
34
+ prevSub,
35
+ nextSub: void 0
36
+ };
37
+ if (nextDep !== void 0) {
38
+ nextDep.prevDep = newLink;
39
+ }
40
+ if (prevDep !== void 0) {
41
+ prevDep.nextDep = newLink;
42
+ } else {
43
+ sub.deps = newLink;
44
+ }
45
+ if (prevSub !== void 0) {
46
+ prevSub.nextSub = newLink;
47
+ } else {
48
+ dep.subs = newLink;
49
+ }
50
+ }
51
+ function unlink2(link3, sub = link3.sub) {
52
+ const dep = link3.dep;
53
+ const prevDep = link3.prevDep;
54
+ const nextDep = link3.nextDep;
55
+ const nextSub = link3.nextSub;
56
+ const prevSub = link3.prevSub;
57
+ if (nextDep !== void 0) {
58
+ nextDep.prevDep = prevDep;
59
+ } else {
60
+ sub.depsTail = prevDep;
61
+ }
62
+ if (prevDep !== void 0) {
63
+ prevDep.nextDep = nextDep;
64
+ } else {
65
+ sub.deps = nextDep;
66
+ }
67
+ if (nextSub !== void 0) {
68
+ nextSub.prevSub = prevSub;
69
+ } else {
70
+ dep.subsTail = prevSub;
71
+ }
72
+ if (prevSub !== void 0) {
73
+ prevSub.nextSub = nextSub;
74
+ } else if ((dep.subs = nextSub) === void 0) {
75
+ unwatched(dep);
76
+ }
77
+ return nextDep;
78
+ }
79
+ function propagate2(link3) {
80
+ let next = link3.nextSub;
81
+ let stack;
82
+ top: do {
83
+ const sub = link3.sub;
84
+ let flags = sub.flags;
85
+ if (!(flags & (4 | 8 | 16 | 32))) {
86
+ sub.flags = flags | 32;
87
+ } else if (!(flags & (4 | 8))) {
88
+ flags = 0;
89
+ } else if (!(flags & 4)) {
90
+ sub.flags = flags & -9 | 32;
91
+ } else if (!(flags & (16 | 32)) && isValidLink(link3, sub)) {
92
+ sub.flags = flags | (8 | 32);
93
+ flags &= 1;
94
+ } else {
95
+ flags = 0;
96
+ }
97
+ if (flags & 2) {
98
+ notify(sub);
99
+ }
100
+ if (flags & 1) {
101
+ const subSubs = sub.subs;
102
+ if (subSubs !== void 0) {
103
+ const nextSub = (link3 = subSubs).nextSub;
104
+ if (nextSub !== void 0) {
105
+ stack = { value: next, prev: stack };
106
+ next = nextSub;
107
+ }
108
+ continue;
109
+ }
110
+ }
111
+ if ((link3 = next) !== void 0) {
112
+ next = link3.nextSub;
113
+ continue;
114
+ }
115
+ while (stack !== void 0) {
116
+ link3 = stack.value;
117
+ stack = stack.prev;
118
+ if (link3 !== void 0) {
119
+ next = link3.nextSub;
120
+ continue top;
121
+ }
122
+ }
123
+ break;
124
+ } while (true);
125
+ }
126
+ function checkDirty2(link3, sub) {
127
+ let stack;
128
+ let checkDepth = 0;
129
+ let dirty = false;
130
+ top: do {
131
+ const dep = link3.dep;
132
+ const flags = dep.flags;
133
+ if (sub.flags & 16) {
134
+ dirty = true;
135
+ } else if ((flags & (1 | 16)) === (1 | 16)) {
136
+ if (update(dep)) {
137
+ const subs = dep.subs;
138
+ if (subs.nextSub !== void 0) {
139
+ shallowPropagate2(subs);
140
+ }
141
+ dirty = true;
142
+ }
143
+ } else if ((flags & (1 | 32)) === (1 | 32)) {
144
+ if (link3.nextSub !== void 0 || link3.prevSub !== void 0) {
145
+ stack = { value: link3, prev: stack };
146
+ }
147
+ link3 = dep.deps;
148
+ sub = dep;
149
+ ++checkDepth;
150
+ continue;
151
+ }
152
+ if (!dirty) {
153
+ const nextDep = link3.nextDep;
154
+ if (nextDep !== void 0) {
155
+ link3 = nextDep;
156
+ continue;
157
+ }
158
+ }
159
+ while (checkDepth--) {
160
+ const firstSub = sub.subs;
161
+ const hasMultipleSubs = firstSub.nextSub !== void 0;
162
+ if (hasMultipleSubs) {
163
+ link3 = stack.value;
164
+ stack = stack.prev;
165
+ } else {
166
+ link3 = firstSub;
167
+ }
168
+ if (dirty) {
169
+ if (update(sub)) {
170
+ if (hasMultipleSubs) {
171
+ shallowPropagate2(firstSub);
172
+ }
173
+ sub = link3.sub;
174
+ continue;
175
+ }
176
+ dirty = false;
177
+ } else {
178
+ sub.flags &= -33;
179
+ }
180
+ sub = link3.sub;
181
+ const nextDep = link3.nextDep;
182
+ if (nextDep !== void 0) {
183
+ link3 = nextDep;
184
+ continue top;
185
+ }
186
+ }
187
+ return dirty;
188
+ } while (true);
189
+ }
190
+ function shallowPropagate2(link3) {
191
+ do {
192
+ const sub = link3.sub;
193
+ const flags = sub.flags;
194
+ if ((flags & (32 | 16)) === 32) {
195
+ sub.flags = flags | 16;
196
+ if ((flags & (2 | 4)) === 2) {
197
+ notify(sub);
198
+ }
199
+ }
200
+ } while ((link3 = link3.nextSub) !== void 0);
201
+ }
202
+ function isValidLink(checkLink, sub) {
203
+ let link3 = sub.depsTail;
204
+ while (link3 !== void 0) {
205
+ if (link3 === checkLink) {
206
+ return true;
207
+ }
208
+ link3 = link3.prevDep;
209
+ }
210
+ return false;
211
+ }
212
+ }
213
+
214
+ // node_modules/alien-signals/esm/index.mjs
215
+ var cycle = 0;
216
+ var batchDepth = 0;
217
+ var notifyIndex = 0;
218
+ var queuedLength = 0;
219
+ var activeSub;
220
+ var queued = [];
221
+ var { link, unlink, propagate, checkDirty, shallowPropagate } = createReactiveSystem({
222
+ update(node) {
223
+ if (node.depsTail !== void 0) {
224
+ return updateComputed(node);
225
+ } else {
226
+ return updateSignal(node);
227
+ }
228
+ },
229
+ notify(effect2) {
230
+ let insertIndex = queuedLength;
231
+ let firstInsertedIndex = insertIndex;
232
+ do {
233
+ queued[insertIndex++] = effect2;
234
+ effect2.flags &= -3;
235
+ effect2 = effect2.subs?.sub;
236
+ if (effect2 === void 0 || !(effect2.flags & 2)) {
237
+ break;
238
+ }
239
+ } while (true);
240
+ queuedLength = insertIndex;
241
+ while (firstInsertedIndex < --insertIndex) {
242
+ const left = queued[firstInsertedIndex];
243
+ queued[firstInsertedIndex++] = queued[insertIndex];
244
+ queued[insertIndex] = left;
245
+ }
246
+ },
247
+ unwatched(node) {
248
+ if (!(node.flags & 1)) {
249
+ effectScopeOper.call(node);
250
+ } else if (node.depsTail !== void 0) {
251
+ node.depsTail = void 0;
252
+ node.flags = 1 | 16;
253
+ purgeDeps(node);
254
+ }
255
+ }
256
+ });
257
+ function setActiveSub(sub) {
258
+ const prevSub = activeSub;
259
+ activeSub = sub;
260
+ return prevSub;
261
+ }
262
+ function startBatch() {
263
+ ++batchDepth;
264
+ }
265
+ function endBatch() {
266
+ if (!--batchDepth) {
267
+ flush();
268
+ }
269
+ }
270
+ function signal(initialValue) {
271
+ return signalOper.bind({
272
+ currentValue: initialValue,
273
+ pendingValue: initialValue,
274
+ subs: void 0,
275
+ subsTail: void 0,
276
+ flags: 1
277
+ });
278
+ }
279
+ function computed(getter) {
280
+ return computedOper.bind({
281
+ value: void 0,
282
+ subs: void 0,
283
+ subsTail: void 0,
284
+ deps: void 0,
285
+ depsTail: void 0,
286
+ flags: 0,
287
+ getter
288
+ });
289
+ }
290
+ function effect(fn) {
291
+ const e = {
292
+ fn,
293
+ subs: void 0,
294
+ subsTail: void 0,
295
+ deps: void 0,
296
+ depsTail: void 0,
297
+ flags: 2 | 4
298
+ };
299
+ const prevSub = setActiveSub(e);
300
+ if (prevSub !== void 0) {
301
+ link(e, prevSub, 0);
302
+ }
303
+ try {
304
+ e.fn();
305
+ } finally {
306
+ activeSub = prevSub;
307
+ e.flags &= -5;
308
+ }
309
+ return effectOper.bind(e);
310
+ }
311
+ function updateComputed(c) {
312
+ ++cycle;
313
+ c.depsTail = void 0;
314
+ c.flags = 1 | 4;
315
+ const prevSub = setActiveSub(c);
316
+ try {
317
+ const oldValue = c.value;
318
+ return oldValue !== (c.value = c.getter(oldValue));
319
+ } finally {
320
+ activeSub = prevSub;
321
+ c.flags &= -5;
322
+ purgeDeps(c);
323
+ }
324
+ }
325
+ function updateSignal(s) {
326
+ s.flags = 1;
327
+ return s.currentValue !== (s.currentValue = s.pendingValue);
328
+ }
329
+ function run(e) {
330
+ const flags = e.flags;
331
+ if (flags & 16 || flags & 32 && checkDirty(e.deps, e)) {
332
+ ++cycle;
333
+ e.depsTail = void 0;
334
+ e.flags = 2 | 4;
335
+ const prevSub = setActiveSub(e);
336
+ try {
337
+ e.fn();
338
+ } finally {
339
+ activeSub = prevSub;
340
+ e.flags &= -5;
341
+ purgeDeps(e);
342
+ }
343
+ } else {
344
+ e.flags = 2;
345
+ }
346
+ }
347
+ function flush() {
348
+ try {
349
+ while (notifyIndex < queuedLength) {
350
+ const effect2 = queued[notifyIndex];
351
+ queued[notifyIndex++] = void 0;
352
+ run(effect2);
353
+ }
354
+ } finally {
355
+ while (notifyIndex < queuedLength) {
356
+ const effect2 = queued[notifyIndex];
357
+ queued[notifyIndex++] = void 0;
358
+ effect2.flags |= 2 | 8;
359
+ }
360
+ notifyIndex = 0;
361
+ queuedLength = 0;
362
+ }
363
+ }
364
+ function computedOper() {
365
+ const flags = this.flags;
366
+ if (flags & 16 || flags & 32 && (checkDirty(this.deps, this) || (this.flags = flags & -33, false))) {
367
+ if (updateComputed(this)) {
368
+ const subs = this.subs;
369
+ if (subs !== void 0) {
370
+ shallowPropagate(subs);
371
+ }
372
+ }
373
+ } else if (!flags) {
374
+ this.flags = 1 | 4;
375
+ const prevSub = setActiveSub(this);
376
+ try {
377
+ this.value = this.getter();
378
+ } finally {
379
+ activeSub = prevSub;
380
+ this.flags &= -5;
381
+ }
382
+ }
383
+ const sub = activeSub;
384
+ if (sub !== void 0) {
385
+ link(this, sub, cycle);
386
+ }
387
+ return this.value;
388
+ }
389
+ function signalOper(...value2) {
390
+ if (value2.length) {
391
+ if (this.pendingValue !== (this.pendingValue = value2[0])) {
392
+ this.flags = 1 | 16;
393
+ const subs = this.subs;
394
+ if (subs !== void 0) {
395
+ propagate(subs);
396
+ if (!batchDepth) {
397
+ flush();
398
+ }
399
+ }
400
+ }
401
+ } else {
402
+ if (this.flags & 16) {
403
+ if (updateSignal(this)) {
404
+ const subs = this.subs;
405
+ if (subs !== void 0) {
406
+ shallowPropagate(subs);
407
+ }
408
+ }
409
+ }
410
+ let sub = activeSub;
411
+ while (sub !== void 0) {
412
+ if (sub.flags & (1 | 2)) {
413
+ link(this, sub, cycle);
414
+ break;
415
+ }
416
+ sub = sub.subs?.sub;
417
+ }
418
+ return this.currentValue;
419
+ }
420
+ }
421
+ function effectOper() {
422
+ effectScopeOper.call(this);
423
+ }
424
+ function effectScopeOper() {
425
+ this.depsTail = void 0;
426
+ this.flags = 0;
427
+ purgeDeps(this);
428
+ const sub = this.subs;
429
+ if (sub !== void 0) {
430
+ unlink(sub);
431
+ }
432
+ }
433
+ function purgeDeps(sub) {
434
+ const depsTail = sub.depsTail;
435
+ let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
436
+ while (dep !== void 0) {
437
+ dep = unlink(dep, sub);
438
+ }
439
+ }
440
+
441
+ // src/reactive/signal.ts
442
+ function applySignalSet(s, v, equals) {
443
+ if (typeof v !== "function") {
444
+ s(v);
445
+ return;
446
+ }
447
+ const prevSub = setActiveSub(void 0);
448
+ const prev = s();
449
+ setActiveSub(prevSub);
450
+ const next = v(prev);
451
+ s(next);
452
+ }
453
+ function createSignal(initialValue, options) {
454
+ const s = signal(initialValue);
455
+ const getter = s;
456
+ const setter = (v) => applySignalSet(s, v);
457
+ return [getter, setter];
458
+ }
459
+ function internalEffect(fn) {
460
+ const dispose = effect(fn);
461
+ return dispose;
462
+ }
463
+
464
+ // src/reactive/computed.ts
465
+ function createComputed(fn) {
466
+ return computed(fn);
467
+ }
468
+
469
+ // src/reactive/batch.ts
470
+ function batch(fn) {
471
+ startBatch();
472
+ try {
473
+ fn();
474
+ } finally {
475
+ endBatch();
476
+ }
477
+ }
478
+
479
+ // src/dom/list.ts
480
+ function longestIncreasingSubsequence(arr) {
481
+ const n = arr.length;
482
+ if (n === 0) return [];
483
+ const tails = new Int32Array(n);
484
+ const tailIndices = new Int32Array(n);
485
+ const predecessor = new Int32Array(n).fill(-1);
486
+ let tailsLen = 0;
487
+ for (let i = 0; i < n; i++) {
488
+ const val = arr[i];
489
+ let lo = 0, hi = tailsLen;
490
+ while (lo < hi) {
491
+ const mid = lo + hi >> 1;
492
+ if (tails[mid] < val) lo = mid + 1;
493
+ else hi = mid;
494
+ }
495
+ tails[lo] = val;
496
+ tailIndices[lo] = i;
497
+ if (lo > 0) predecessor[i] = tailIndices[lo - 1];
498
+ if (lo >= tailsLen) tailsLen++;
499
+ }
500
+ const result = new Array(tailsLen);
501
+ let idx = tailIndices[tailsLen - 1];
502
+ for (let i = tailsLen - 1; i >= 0; i--) {
503
+ result[i] = idx;
504
+ idx = predecessor[idx];
505
+ }
506
+ return result;
507
+ }
508
+ var SMALL_LIST_THRESHOLD = 32;
509
+ function reconcileSmall(parent, oldItems, newItems, oldNodes, keyFn, createFn, updateFn, beforeNode, hooks) {
510
+ const oldLen = oldItems.length;
511
+ const newLen = newItems.length;
512
+ const oldKeys = new Array(oldLen);
513
+ for (let i = 0; i < oldLen; i++) {
514
+ oldKeys[i] = keyFn(oldItems[i]);
515
+ }
516
+ const oldIndices = new Array(newLen);
517
+ const oldUsed = new Uint8Array(oldLen);
518
+ for (let i = 0; i < newLen; i++) {
519
+ const key = keyFn(newItems[i]);
520
+ let found = -1;
521
+ for (let j = 0; j < oldLen; j++) {
522
+ if (!oldUsed[j] && oldKeys[j] === key) {
523
+ found = j;
524
+ oldUsed[j] = 1;
525
+ break;
526
+ }
527
+ }
528
+ oldIndices[i] = found;
529
+ }
530
+ for (let i = 0; i < oldLen; i++) {
531
+ if (!oldUsed[i]) {
532
+ if (hooks?.onBeforeRemove) {
533
+ const node = oldNodes[i];
534
+ hooks.onBeforeRemove(node, () => {
535
+ if (node.parentNode) node.parentNode.removeChild(node);
536
+ });
537
+ } else {
538
+ parent.removeChild(oldNodes[i]);
539
+ }
540
+ }
541
+ }
542
+ if (oldLen === newLen) {
543
+ let allSameOrder = true;
544
+ for (let i = 0; i < newLen; i++) {
545
+ if (oldIndices[i] !== i) {
546
+ allSameOrder = false;
547
+ break;
548
+ }
549
+ }
550
+ if (allSameOrder) {
551
+ const nodes = new Array(newLen);
552
+ for (let i = 0; i < newLen; i++) {
553
+ const node = oldNodes[i];
554
+ updateFn(node, newItems[i]);
555
+ nodes[i] = node;
556
+ }
557
+ return { nodes, items: newItems };
558
+ }
559
+ }
560
+ const reusedIndices = [];
561
+ const reusedPositions = [];
562
+ for (let i = 0; i < newLen; i++) {
563
+ if (oldIndices[i] !== -1) {
564
+ reusedIndices.push(oldIndices[i]);
565
+ reusedPositions.push(i);
566
+ }
567
+ }
568
+ const lisOfReused = longestIncreasingSubsequence(reusedIndices);
569
+ const lisFlags = new Uint8Array(newLen);
570
+ for (const li of lisOfReused) {
571
+ lisFlags[reusedPositions[li]] = 1;
572
+ }
573
+ const newNodes = new Array(newLen);
574
+ let nextSibling = null;
575
+ for (let i = newLen - 1; i >= 0; i--) {
576
+ let node;
577
+ let isNew = false;
578
+ if (oldIndices[i] === -1) {
579
+ node = createFn(newItems[i]);
580
+ isNew = true;
581
+ } else {
582
+ node = oldNodes[oldIndices[i]];
583
+ updateFn(node, newItems[i]);
584
+ if (lisFlags[i]) {
585
+ newNodes[i] = node;
586
+ nextSibling = node;
587
+ continue;
588
+ }
589
+ }
590
+ if (nextSibling) {
591
+ parent.insertBefore(node, nextSibling);
592
+ } else {
593
+ parent.appendChild(node);
594
+ }
595
+ if (isNew) hooks?.onInsert?.(node);
596
+ newNodes[i] = node;
597
+ nextSibling = node;
598
+ }
599
+ return { nodes: newNodes, items: newItems };
600
+ }
601
+ function reconcileList(parent, oldItems, newItems, oldNodes, keyFn, createFn, updateFn, beforeNode, hooks) {
602
+ const oldLen = oldItems.length;
603
+ const newLen = newItems.length;
604
+ if (newLen === 0) {
605
+ for (let i = 0; i < oldLen; i++) {
606
+ if (hooks?.onBeforeRemove) {
607
+ const node = oldNodes[i];
608
+ hooks.onBeforeRemove(node, () => {
609
+ if (node.parentNode) node.parentNode.removeChild(node);
610
+ });
611
+ } else {
612
+ parent.removeChild(oldNodes[i]);
613
+ }
614
+ }
615
+ return { nodes: [], items: [] };
616
+ }
617
+ if (oldLen === 0) {
618
+ const nodes = new Array(newLen);
619
+ for (let i = 0; i < newLen; i++) {
620
+ const node = createFn(newItems[i]);
621
+ {
622
+ parent.appendChild(node);
623
+ }
624
+ hooks?.onInsert?.(node);
625
+ nodes[i] = node;
626
+ }
627
+ return { nodes, items: newItems };
628
+ }
629
+ if (oldLen < SMALL_LIST_THRESHOLD) {
630
+ return reconcileSmall(parent, oldItems, newItems, oldNodes, keyFn, createFn, updateFn, beforeNode, hooks);
631
+ }
632
+ const oldKeyMap = /* @__PURE__ */ new Map();
633
+ for (let i = 0; i < oldLen; i++) {
634
+ oldKeyMap.set(keyFn(oldItems[i]), i);
635
+ }
636
+ const oldIndices = new Array(newLen);
637
+ const oldUsed = new Uint8Array(oldLen);
638
+ for (let i = 0; i < newLen; i++) {
639
+ const key = keyFn(newItems[i]);
640
+ const oldIdx = oldKeyMap.get(key);
641
+ if (oldIdx !== void 0) {
642
+ oldIndices[i] = oldIdx;
643
+ oldUsed[oldIdx] = 1;
644
+ } else {
645
+ oldIndices[i] = -1;
646
+ }
647
+ }
648
+ for (let i = 0; i < oldLen; i++) {
649
+ if (!oldUsed[i]) {
650
+ if (hooks?.onBeforeRemove) {
651
+ const node = oldNodes[i];
652
+ hooks.onBeforeRemove(node, () => {
653
+ if (node.parentNode) node.parentNode.removeChild(node);
654
+ });
655
+ } else {
656
+ parent.removeChild(oldNodes[i]);
657
+ }
658
+ }
659
+ }
660
+ if (oldLen === newLen) {
661
+ let allSameOrder = true;
662
+ for (let i = 0; i < newLen; i++) {
663
+ if (oldIndices[i] !== i) {
664
+ allSameOrder = false;
665
+ break;
666
+ }
667
+ }
668
+ if (allSameOrder) {
669
+ const nodes = new Array(newLen);
670
+ for (let i = 0; i < newLen; i++) {
671
+ const node = oldNodes[i];
672
+ updateFn(node, newItems[i]);
673
+ nodes[i] = node;
674
+ }
675
+ return { nodes, items: newItems };
676
+ }
677
+ }
678
+ const reusedIndices = [];
679
+ const reusedPositions = [];
680
+ for (let i = 0; i < newLen; i++) {
681
+ if (oldIndices[i] !== -1) {
682
+ reusedIndices.push(oldIndices[i]);
683
+ reusedPositions.push(i);
684
+ }
685
+ }
686
+ const lisOfReused = longestIncreasingSubsequence(reusedIndices);
687
+ const lisFlags = new Uint8Array(newLen);
688
+ for (const li of lisOfReused) {
689
+ lisFlags[reusedPositions[li]] = 1;
690
+ }
691
+ const newNodes = new Array(newLen);
692
+ let nextSibling = null;
693
+ for (let i = newLen - 1; i >= 0; i--) {
694
+ let node;
695
+ let isNew = false;
696
+ if (oldIndices[i] === -1) {
697
+ node = createFn(newItems[i]);
698
+ isNew = true;
699
+ } else {
700
+ node = oldNodes[oldIndices[i]];
701
+ updateFn(node, newItems[i]);
702
+ if (lisFlags[i]) {
703
+ newNodes[i] = node;
704
+ nextSibling = node;
705
+ continue;
706
+ }
707
+ }
708
+ if (nextSibling) {
709
+ parent.insertBefore(node, nextSibling);
710
+ } else {
711
+ parent.appendChild(node);
712
+ }
713
+ if (isNew) hooks?.onInsert?.(node);
714
+ newNodes[i] = node;
715
+ nextSibling = node;
716
+ }
717
+ return { nodes: newNodes, items: newItems };
718
+ }
719
+
720
+ // src/dom/reconcile.ts
721
+ function getBindTargets(el) {
722
+ const targets = /* @__PURE__ */ new Set();
723
+ const attrs = el.attributes;
724
+ for (let i = 0; i < attrs.length; i++) {
725
+ const name = attrs[i].name;
726
+ if (name.startsWith("data-bind:")) {
727
+ targets.add(name.slice(10));
728
+ }
729
+ }
730
+ return targets;
731
+ }
732
+ function ownsSubtree(el) {
733
+ return el.hasAttribute("data-list") || el.hasAttribute("data-if");
734
+ }
735
+ function getStateKeys(json) {
736
+ try {
737
+ const obj = JSON.parse(json);
738
+ return Object.keys(obj).sort();
739
+ } catch {
740
+ return [];
741
+ }
742
+ }
743
+ function sameShape(keysA, keysB) {
744
+ if (keysA.length !== keysB.length) return false;
745
+ for (let i = 0; i < keysA.length; i++) {
746
+ if (keysA[i] !== keysB[i]) return false;
747
+ }
748
+ return true;
749
+ }
750
+ function determineScopeMode(liveEl, newEl) {
751
+ const liveModule = liveEl.getAttribute("data-module");
752
+ const newModule = newEl.getAttribute("data-module");
753
+ if (liveModule !== newModule) return "REPLACE";
754
+ const liveInitialState = liveEl.__formaInitialState;
755
+ const liveStateJSON = liveInitialState ?? liveEl.getAttribute("data-forma-state") ?? "{}";
756
+ const newStateJSON = newEl.getAttribute("data-forma-state") ?? "{}";
757
+ const liveKeys = getStateKeys(liveStateJSON);
758
+ const newKeys = getStateKeys(newStateJSON);
759
+ if (sameShape(liveKeys, newKeys)) return "PRESERVE";
760
+ return "RESET";
761
+ }
762
+ var _parseTemplate = null;
763
+ function parseHTML(html) {
764
+ if (!_parseTemplate) _parseTemplate = document.createElement("template");
765
+ _parseTemplate.innerHTML = html;
766
+ return _parseTemplate.content;
767
+ }
768
+ function patchAttributes(liveEl, newEl) {
769
+ const bindTargets = getBindTargets(liveEl);
770
+ const hasDataShow = liveEl.hasAttribute("data-show");
771
+ const hasDataModel = liveEl.hasAttribute("data-model");
772
+ let liveHasClassDirectives = false;
773
+ const liveAttrs = liveEl.attributes;
774
+ for (let i = 0; i < liveAttrs.length; i++) {
775
+ if (liveAttrs[i].name.startsWith("data-class:")) {
776
+ liveHasClassDirectives = true;
777
+ break;
778
+ }
779
+ }
780
+ const newAttrs = newEl.attributes;
781
+ for (let i = 0; i < newAttrs.length; i++) {
782
+ const attr = newAttrs[i];
783
+ if (attr.name === "style" && hasDataShow) continue;
784
+ if (attr.name === "class" && liveHasClassDirectives) continue;
785
+ if ((attr.name === "value" || attr.name === "checked") && hasDataModel) continue;
786
+ if (bindTargets.has(attr.name)) continue;
787
+ const liveVal = liveEl.getAttribute(attr.name);
788
+ if (liveVal !== attr.value) {
789
+ liveEl.setAttribute(attr.name, attr.value);
790
+ }
791
+ }
792
+ for (let i = liveAttrs.length - 1; i >= 0; i--) {
793
+ const attr = liveAttrs[i];
794
+ if (!newEl.hasAttribute(attr.name)) {
795
+ if (attr.name === "style" && hasDataShow) continue;
796
+ if (attr.name === "class" && liveHasClassDirectives) continue;
797
+ if ((attr.name === "value" || attr.name === "checked") && hasDataModel) continue;
798
+ if (bindTargets.has(attr.name)) continue;
799
+ liveEl.removeAttribute(attr.name);
800
+ }
801
+ }
802
+ }
803
+ function patchTextNodes(liveEl, newEl) {
804
+ if (liveEl.hasAttribute("data-text")) return;
805
+ const liveTexts = [];
806
+ const newTexts = [];
807
+ for (const child of Array.from(liveEl.childNodes)) {
808
+ if (child.nodeType === Node.TEXT_NODE) liveTexts.push(child);
809
+ }
810
+ for (let i = 0; i < newEl.childNodes.length; i++) {
811
+ const child = newEl.childNodes[i];
812
+ if (child.nodeType === Node.TEXT_NODE) newTexts.push({ node: child, index: i });
813
+ }
814
+ if (liveTexts.length === newTexts.length) {
815
+ for (let i = 0; i < liveTexts.length; i++) {
816
+ if (liveTexts[i].textContent !== newTexts[i].node.textContent) {
817
+ liveTexts[i].textContent = newTexts[i].node.textContent;
818
+ }
819
+ }
820
+ return;
821
+ }
822
+ const usedLive = /* @__PURE__ */ new Set();
823
+ let liveIdx = 0;
824
+ for (const { node: newText, index: newChildIdx } of newTexts) {
825
+ if (liveIdx < liveTexts.length) {
826
+ const liveText = liveTexts[liveIdx];
827
+ liveIdx++;
828
+ usedLive.add(liveText);
829
+ if (liveText.textContent !== newText.textContent) {
830
+ liveText.textContent = newText.textContent;
831
+ }
832
+ } else {
833
+ const ref = findTextInsertionRef(liveEl, newEl, newChildIdx);
834
+ liveEl.insertBefore(document.createTextNode(newText.textContent ?? ""), ref);
835
+ }
836
+ }
837
+ for (const lt of liveTexts) {
838
+ if (!usedLive.has(lt) && lt.parentNode === liveEl) {
839
+ liveEl.removeChild(lt);
840
+ }
841
+ }
842
+ }
843
+ function findTextInsertionRef(liveEl, newEl, newIdx) {
844
+ for (let j = newIdx + 1; j < newEl.childNodes.length; j++) {
845
+ const sibling = newEl.childNodes[j];
846
+ if (sibling.nodeType === Node.ELEMENT_NODE) {
847
+ const key = sibling.getAttribute("data-forma-id");
848
+ if (key) {
849
+ const match = liveEl.querySelector(`[data-forma-id="${CSS.escape(key)}"]`);
850
+ if (match && match.parentElement === liveEl) return match;
851
+ }
852
+ }
853
+ }
854
+ return null;
855
+ }
856
+ function diffChildren(liveParent, newParent, config) {
857
+ if (ownsSubtree(liveParent)) return;
858
+ patchTextNodes(liveParent, newParent);
859
+ const liveChildren = Array.from(liveParent.children);
860
+ const newChildren = Array.from(newParent.children);
861
+ const liveKeyed = /* @__PURE__ */ new Map();
862
+ const liveUnkeyed = [];
863
+ for (const child of liveChildren) {
864
+ if (child.hasAttribute("data-forma-leaving")) continue;
865
+ const key = child.getAttribute("data-forma-id");
866
+ if (key) {
867
+ liveKeyed.set(key, child);
868
+ } else {
869
+ liveUnkeyed.push(child);
870
+ }
871
+ }
872
+ let unkeyedIdx = 0;
873
+ const usedLiveElements = /* @__PURE__ */ new Set();
874
+ for (const newChild of newChildren) {
875
+ const key = newChild.getAttribute("data-forma-id");
876
+ let liveMatch;
877
+ if (key) {
878
+ liveMatch = liveKeyed.get(key);
879
+ } else {
880
+ while (unkeyedIdx < liveUnkeyed.length) {
881
+ const candidate = liveUnkeyed[unkeyedIdx];
882
+ unkeyedIdx++;
883
+ if (candidate.tagName === newChild.tagName && !usedLiveElements.has(candidate)) {
884
+ liveMatch = candidate;
885
+ break;
886
+ }
887
+ }
888
+ }
889
+ if (liveMatch) {
890
+ usedLiveElements.add(liveMatch);
891
+ if (liveMatch.hasAttribute("data-forma-state") && newChild.hasAttribute("data-forma-state")) {
892
+ const mode = determineScopeMode(liveMatch, newChild);
893
+ switch (mode) {
894
+ case "PRESERVE":
895
+ patchAttributes(liveMatch, newChild);
896
+ diffChildren(liveMatch, newChild, config);
897
+ break;
898
+ case "RESET":
899
+ config.unmountScope(liveMatch);
900
+ patchAttributes(liveMatch, newChild);
901
+ replaceInnerContent(liveMatch, newChild);
902
+ config.mountScope(liveMatch);
903
+ break;
904
+ case "REPLACE": {
905
+ config.unmountScope(liveMatch);
906
+ const replacement = newChild.cloneNode(true);
907
+ liveParent.replaceChild(replacement, liveMatch);
908
+ config.mountScope(replacement);
909
+ usedLiveElements.delete(liveMatch);
910
+ liveMatch = replacement;
911
+ usedLiveElements.add(replacement);
912
+ break;
913
+ }
914
+ }
915
+ } else {
916
+ patchAttributes(liveMatch, newChild);
917
+ diffChildren(liveMatch, newChild, config);
918
+ }
919
+ ensurePosition(liveParent, liveMatch, newChild, newChildren);
920
+ } else {
921
+ const clone = newChild.cloneNode(true);
922
+ const insertionRef = findInsertionPoint(liveParent, newChild, newChildren);
923
+ liveParent.insertBefore(clone, insertionRef);
924
+ usedLiveElements.add(clone);
925
+ if (clone.hasAttribute("data-forma-state")) {
926
+ config.mountScope(clone);
927
+ }
928
+ const nestedScopes = clone.querySelectorAll("[data-forma-state]");
929
+ for (const nested of Array.from(nestedScopes)) {
930
+ config.mountScope(nested);
931
+ }
932
+ }
933
+ }
934
+ for (const child of liveChildren) {
935
+ if (!usedLiveElements.has(child)) {
936
+ if (child.parentElement !== liveParent) continue;
937
+ if (child.hasAttribute("data-forma-leaving")) continue;
938
+ if (child.hasAttribute("data-forma-state")) {
939
+ config.unmountScope(child);
940
+ }
941
+ const nestedScopes = child.querySelectorAll("[data-forma-state]");
942
+ for (const nested of Array.from(nestedScopes)) {
943
+ config.unmountScope(nested);
944
+ }
945
+ liveParent.removeChild(child);
946
+ }
947
+ }
948
+ }
949
+ function replaceInnerContent(liveEl, newEl) {
950
+ while (liveEl.firstChild) {
951
+ liveEl.removeChild(liveEl.firstChild);
952
+ }
953
+ for (const child of Array.from(newEl.childNodes)) {
954
+ liveEl.appendChild(child.cloneNode(true));
955
+ }
956
+ }
957
+ function ensurePosition(parent, liveEl, _newEl, newChildren) {
958
+ const newIdx = newChildren.indexOf(_newEl);
959
+ const liveChildElements = Array.from(parent.children);
960
+ const currentIdx = liveChildElements.indexOf(liveEl);
961
+ if (currentIdx !== newIdx) {
962
+ const nextNewChild = newChildren[newIdx + 1];
963
+ if (nextNewChild) {
964
+ const nextKey = nextNewChild.getAttribute("data-forma-id");
965
+ if (nextKey) {
966
+ const nextLive = parent.querySelector(`[data-forma-id="${CSS.escape(nextKey)}"]`);
967
+ if (nextLive && nextLive.parentElement === parent) {
968
+ parent.insertBefore(liveEl, nextLive);
969
+ return;
970
+ }
971
+ }
972
+ }
973
+ parent.appendChild(liveEl);
974
+ }
975
+ }
976
+ function findInsertionPoint(parent, newChild, newChildren) {
977
+ const newIdx = newChildren.indexOf(newChild);
978
+ for (let i = newIdx + 1; i < newChildren.length; i++) {
979
+ const key = newChildren[i].getAttribute("data-forma-id");
980
+ if (key) {
981
+ const existing = parent.querySelector(`[data-forma-id="${CSS.escape(key)}"]`);
982
+ if (existing && existing.parentElement === parent) {
983
+ return existing;
984
+ }
985
+ }
986
+ }
987
+ return null;
988
+ }
989
+ function createReconciler(config) {
990
+ let _lastHtml = "";
991
+ return function reconcile2(container, html) {
992
+ const trimmed = html.trim();
993
+ if (!trimmed) return;
994
+ if (trimmed === _lastHtml && container.hasChildNodes()) return;
995
+ _lastHtml = trimmed;
996
+ config.disconnectObserver();
997
+ try {
998
+ if (!container.hasChildNodes() || container.children.length === 0) {
999
+ container.innerHTML = trimmed;
1000
+ config.batch(() => {
1001
+ const scopes = container.querySelectorAll("[data-forma-state]");
1002
+ for (const scope of Array.from(scopes)) {
1003
+ config.mountScope(scope);
1004
+ }
1005
+ });
1006
+ return;
1007
+ }
1008
+ const fragment = parseHTML(trimmed);
1009
+ const templateContainer = document.createElement("div");
1010
+ templateContainer.appendChild(fragment);
1011
+ const liveKeys = /* @__PURE__ */ new Set();
1012
+ for (const child of Array.from(container.children)) {
1013
+ if (child.hasAttribute("data-forma-leaving")) continue;
1014
+ const key = child.getAttribute("data-forma-id");
1015
+ if (key) liveKeys.add(key);
1016
+ }
1017
+ let hasOverlap = false;
1018
+ if (liveKeys.size > 0) {
1019
+ for (const child of Array.from(templateContainer.children)) {
1020
+ const key = child.getAttribute("data-forma-id");
1021
+ if (key && liveKeys.has(key)) {
1022
+ hasOverlap = true;
1023
+ break;
1024
+ }
1025
+ }
1026
+ }
1027
+ if (liveKeys.size > 0 && !hasOverlap) {
1028
+ config.batch(() => {
1029
+ const liveScopes = container.querySelectorAll("[data-forma-state]");
1030
+ for (const scope of Array.from(liveScopes)) {
1031
+ config.unmountScope(scope);
1032
+ }
1033
+ container.innerHTML = trimmed;
1034
+ const newScopes = container.querySelectorAll("[data-forma-state]");
1035
+ for (const scope of Array.from(newScopes)) {
1036
+ config.mountScope(scope);
1037
+ }
1038
+ });
1039
+ return;
1040
+ }
1041
+ config.batch(() => {
1042
+ diffChildren(container, templateContainer, config);
1043
+ });
1044
+ } finally {
1045
+ config.reconnectObserver();
1046
+ }
1047
+ };
1048
+ }
1049
+
1050
+ // src/runtime.ts
1051
+ var _refetchRegistry = /* @__PURE__ */ new Map();
1052
+ function $refetch(id) {
1053
+ const fn = _refetchRegistry.get(id);
1054
+ if (fn) {
1055
+ fn();
1056
+ } else if (_debug) {
1057
+ dbg(`$refetch: no data-fetch with id "${id}" found`);
1058
+ }
1059
+ }
1060
+ function createChildScope(parent, locals) {
1061
+ const localGetters = /* @__PURE__ */ Object.create(null);
1062
+ for (const key of Object.keys(locals)) {
1063
+ localGetters[key] = () => locals[key];
1064
+ }
1065
+ return {
1066
+ getters: new Proxy(parent.getters, {
1067
+ get(target, prop) {
1068
+ if (prop in localGetters) return localGetters[prop];
1069
+ return target[prop];
1070
+ },
1071
+ has(target, prop) {
1072
+ return prop in localGetters || prop in target;
1073
+ }
1074
+ }),
1075
+ setters: parent.setters
1076
+ };
1077
+ }
1078
+ var _debug = false;
1079
+ var _unsafeEvalMode = "mutable";
1080
+ var _allowUnsafeEval = false;
1081
+ var _diagnosticsEnabled = true;
1082
+ function dbg(...args) {
1083
+ if (_debug || typeof window !== "undefined" && window.__FORMA_DEBUG) {
1084
+ console.log("[FormaJS]", ...args);
1085
+ }
1086
+ }
1087
+ var diagnostics = /* @__PURE__ */ new Map();
1088
+ function parseBooleanFlag(raw) {
1089
+ if (raw == null) return void 0;
1090
+ const normalized = raw.trim().toLowerCase();
1091
+ if (normalized === "1" || normalized === "true" || normalized === "on" || normalized === "yes") return true;
1092
+ if (normalized === "0" || normalized === "false" || normalized === "off" || normalized === "no") return false;
1093
+ return void 0;
1094
+ }
1095
+ function parseUnsafeEvalMode(raw) {
1096
+ if (raw == null) return void 0;
1097
+ const normalized = raw.trim().toLowerCase();
1098
+ if (normalized === "mutable") return "mutable";
1099
+ if (normalized === "locked-off" || normalized === "off" || normalized === "disabled") {
1100
+ return "locked-off";
1101
+ }
1102
+ if (normalized === "locked-on" || normalized === "on" || normalized === "enabled") {
1103
+ return "locked-on";
1104
+ }
1105
+ return void 0;
1106
+ }
1107
+ function readRuntimeConfig() {
1108
+ const config = {};
1109
+ if (typeof window !== "undefined") {
1110
+ const globalConfig = window.__FORMA_RUNTIME_CONFIG;
1111
+ if (globalConfig) {
1112
+ if (typeof globalConfig.allowUnsafeEval === "boolean") {
1113
+ config.allowUnsafeEval = globalConfig.allowUnsafeEval;
1114
+ }
1115
+ if (typeof globalConfig.unsafeEvalMode === "string") {
1116
+ const parsed = parseUnsafeEvalMode(globalConfig.unsafeEvalMode);
1117
+ if (parsed) config.unsafeEvalMode = parsed;
1118
+ }
1119
+ if (typeof globalConfig.lockUnsafeEval === "boolean") {
1120
+ config.lockUnsafeEval = globalConfig.lockUnsafeEval;
1121
+ }
1122
+ if (typeof globalConfig.diagnostics === "boolean") {
1123
+ config.diagnostics = globalConfig.diagnostics;
1124
+ }
1125
+ if (typeof globalConfig.autoContainment === "boolean") {
1126
+ config.autoContainment = globalConfig.autoContainment;
1127
+ }
1128
+ }
1129
+ }
1130
+ if (typeof document !== "undefined") {
1131
+ const script = document.currentScript;
1132
+ if (script) {
1133
+ const unsafeFromAttr = parseBooleanFlag(script.getAttribute("data-forma-unsafe-eval"));
1134
+ if (unsafeFromAttr !== void 0) {
1135
+ config.allowUnsafeEval = unsafeFromAttr;
1136
+ }
1137
+ const modeFromAttr = parseUnsafeEvalMode(
1138
+ script.getAttribute("data-forma-unsafe-eval-mode")
1139
+ );
1140
+ if (modeFromAttr !== void 0) {
1141
+ config.unsafeEvalMode = modeFromAttr;
1142
+ }
1143
+ const lockFromAttr = parseBooleanFlag(script.getAttribute("data-forma-lock-unsafe-eval"));
1144
+ if (lockFromAttr !== void 0) {
1145
+ config.lockUnsafeEval = lockFromAttr;
1146
+ }
1147
+ const diagnosticsFromAttr = parseBooleanFlag(script.getAttribute("data-forma-diagnostics"));
1148
+ if (diagnosticsFromAttr !== void 0) {
1149
+ config.diagnostics = diagnosticsFromAttr;
1150
+ }
1151
+ const containmentFromAttr = parseBooleanFlag(script.getAttribute("data-forma-auto-containment"));
1152
+ if (containmentFromAttr !== void 0) {
1153
+ config.autoContainment = containmentFromAttr;
1154
+ }
1155
+ }
1156
+ }
1157
+ return config;
1158
+ }
1159
+ function reportDiagnostic(kind, expr, reason) {
1160
+ if (!_diagnosticsEnabled) return;
1161
+ const key = `${kind}|${reason}|${expr}`;
1162
+ const now = Date.now();
1163
+ const existing = diagnostics.get(key);
1164
+ if (existing) {
1165
+ existing.count += 1;
1166
+ existing.lastSeenAt = now;
1167
+ } else {
1168
+ diagnostics.set(key, {
1169
+ kind,
1170
+ expr,
1171
+ reason,
1172
+ count: 1,
1173
+ firstSeenAt: now,
1174
+ lastSeenAt: now
1175
+ });
1176
+ console.warn(`[FormaJS] ${reason}: ${expr}`);
1177
+ }
1178
+ try {
1179
+ if (typeof window !== "undefined") {
1180
+ const detail = {
1181
+ kind,
1182
+ expr,
1183
+ reason,
1184
+ count: diagnostics.get(key)?.count ?? 1
1185
+ };
1186
+ window.dispatchEvent(new CustomEvent("formajs:diagnostic", { detail }));
1187
+ }
1188
+ } catch {
1189
+ }
1190
+ }
1191
+ var buildUnsafeEvalMode = parseUnsafeEvalMode(
1192
+ "locked-off"
1193
+ );
1194
+ if (buildUnsafeEvalMode) {
1195
+ _unsafeEvalMode = buildUnsafeEvalMode;
1196
+ if (_unsafeEvalMode === "locked-off") _allowUnsafeEval = false;
1197
+ if (_unsafeEvalMode === "locked-on") _allowUnsafeEval = true;
1198
+ if (_unsafeEvalMode === "mutable") _allowUnsafeEval = true;
1199
+ }
1200
+ var runtimeConfig = readRuntimeConfig();
1201
+ var configUnsafeMode = runtimeConfig.lockUnsafeEval ? "locked-off" : runtimeConfig.unsafeEvalMode;
1202
+ if (configUnsafeMode) {
1203
+ _unsafeEvalMode = configUnsafeMode;
1204
+ if (_unsafeEvalMode === "locked-off") _allowUnsafeEval = false;
1205
+ if (_unsafeEvalMode === "locked-on") _allowUnsafeEval = true;
1206
+ }
1207
+ if (_unsafeEvalMode === "mutable" && typeof runtimeConfig.allowUnsafeEval === "boolean") {
1208
+ _allowUnsafeEval = runtimeConfig.allowUnsafeEval;
1209
+ }
1210
+ if (typeof runtimeConfig.diagnostics === "boolean") {
1211
+ _diagnosticsEnabled = runtimeConfig.diagnostics;
1212
+ }
1213
+ var _autoContainment = runtimeConfig.autoContainment === true;
1214
+ function getScheduler() {
1215
+ const candidate = globalThis?.scheduler;
1216
+ if (!candidate) return void 0;
1217
+ if (typeof candidate.yield === "function" || typeof candidate.postTask === "function") {
1218
+ return candidate;
1219
+ }
1220
+ return void 0;
1221
+ }
1222
+ async function yieldToMain() {
1223
+ const scheduler = getScheduler();
1224
+ if (scheduler?.yield) {
1225
+ await scheduler.yield();
1226
+ return;
1227
+ }
1228
+ if (scheduler?.postTask) {
1229
+ await scheduler.postTask(() => {
1230
+ }, { priority: "background" });
1231
+ return;
1232
+ }
1233
+ await new Promise((resolve) => setTimeout(resolve, 0));
1234
+ }
1235
+ function applyContainmentHints(root = document, options = {}) {
1236
+ const selector = options.selector ?? "[data-forma-contain]";
1237
+ if (!selector) return 0;
1238
+ if (typeof root.querySelectorAll !== "function") return 0;
1239
+ const nodes = root.querySelectorAll(selector);
1240
+ let applied = 0;
1241
+ for (let i = 0; i < nodes.length; i++) {
1242
+ const el = nodes[i];
1243
+ if (!el?.style) continue;
1244
+ const contain = el.getAttribute("data-forma-contain") ?? options.contain ?? "layout style paint";
1245
+ const contentVisibility = el.getAttribute("data-forma-content-visibility") ?? options.contentVisibility ?? "auto";
1246
+ const containIntrinsicSize = el.getAttribute("data-forma-contain-intrinsic-size") ?? options.containIntrinsicSize ?? "auto 800px";
1247
+ const skipExisting = options.skipIfAlreadySet === true;
1248
+ let changed = false;
1249
+ const containCurrent = el.style.getPropertyValue("contain");
1250
+ const contentVisCurrent = el.style.getPropertyValue("content-visibility");
1251
+ const containSizeCurrent = el.style.getPropertyValue("contain-intrinsic-size");
1252
+ if (contain !== "off" && (!skipExisting || !containCurrent)) {
1253
+ el.style.setProperty("contain", contain);
1254
+ changed = true;
1255
+ }
1256
+ if (contentVisibility !== "off" && (!skipExisting || !contentVisCurrent)) {
1257
+ el.style.setProperty("content-visibility", contentVisibility);
1258
+ changed = true;
1259
+ }
1260
+ if (containIntrinsicSize !== "off" && (!skipExisting || !containSizeCurrent)) {
1261
+ el.style.setProperty("contain-intrinsic-size", containIntrinsicSize);
1262
+ changed = true;
1263
+ }
1264
+ if (changed) applied++;
1265
+ }
1266
+ if (_debug && applied > 0) {
1267
+ dbg("applyContainmentHints: applied to", applied, "element(s)");
1268
+ }
1269
+ return applied;
1270
+ }
1271
+ var RE_STRING_SINGLE = /^'[^']*'$/;
1272
+ var RE_STRING_DOUBLE = /^"[^"]*"$/;
1273
+ var RE_NUMBER = /^-?\d+(\.\d+)?$/;
1274
+ var RE_IDENTIFIER = /^[a-zA-Z_$]\w*$/;
1275
+ var RE_DOT_ACCESS = /^(\w+)\.(\w+)$/;
1276
+ var RE_BRACKET = /^(\w+)\[(\d+|'[^']*'|"[^"]*")\]$/;
1277
+ var RE_TERNARY = /^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/;
1278
+ var RE_NULLISH = /^(.+?)\s*\?\?\s*(.+)$/;
1279
+ var RE_AND = /^(.+?)\s*&&\s*(.+)$/;
1280
+ var RE_OR = /^(.+?)\s*\|\|\s*(.+)$/;
1281
+ var RE_COMPARISON = /^(.+?)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/;
1282
+ var RE_MUL = /^(.+?)\s*([*/%])\s*(.+)$/;
1283
+ var RE_ADD = /^(.+?)\s*([+-])\s*(.+)$/;
1284
+ var RE_TEMPLATE_LIT = /^`([^`]*)`$/;
1285
+ var RE_TEMPLATE_INTERP = /\$\{([^}]+)\}/g;
1286
+ var RE_GROUP_METHOD_CALL = /^\((.+)\)\.(\w+)\((.*)\)$/;
1287
+ var RE_STRIP_BRACES = /^\{|\}$/g;
1288
+ var RE_DIGIT_ONLY = /^\d+$/;
1289
+ var RE_POST_INCR = /^(\w+)(\+\+|--)$/;
1290
+ var RE_PRE_INCR = /^(\+\+|--)(\w+)$/;
1291
+ var RE_TOGGLE = /^(\w+)\s*=\s*!(\w+)$/;
1292
+ var RE_ASSIGN = /^(\w+)\s*=\s*(.+)$/;
1293
+ var RE_COMPOUND = /^(\w+)\s*(\+=|-=|\*=|\/=)\s*(.+)$/;
1294
+ var RE_IF_PREFIX = /^if\b/;
1295
+ var RE_COMPUTED = /^(\w+)\s*=\s*(.+)$/;
1296
+ var RE_FETCH = /^(.+?)(?:→|->)\s*(\S+)(.*)$/;
1297
+ var RE_FETCH_METHOD = /^(GET|POST|PUT|PATCH|DELETE)\s+(.+)$/i;
1298
+ var RE_STRIP_ITEM_BRACES = /^\{item\.?|\}$/g;
1299
+ var RE_EVENT_REF = /\bevent\s*[.([]|\$event\b/;
1300
+ var RE_REFETCH_CALL = /^\$refetch\(\s*['"]([^'"]+)['"]\s*\)$/;
1301
+ var TRANSITION_STATE_SYM = /* @__PURE__ */ Symbol.for("forma-transition-state");
1302
+ var EXPRESSION_CACHE_MAX = 2048;
1303
+ var expressionCache = /* @__PURE__ */ new Map();
1304
+ function cacheExpression(key, factory) {
1305
+ if (expressionCache.size >= EXPRESSION_CACHE_MAX) {
1306
+ const first = expressionCache.keys().next().value;
1307
+ if (first !== void 0) expressionCache.delete(first);
1308
+ }
1309
+ expressionCache.set(key, factory);
1310
+ }
1311
+ var scopeExpressionCache = /* @__PURE__ */ new WeakMap();
1312
+ var scopeHandlerCache = /* @__PURE__ */ new WeakMap();
1313
+ var compiledTemplateCache = /* @__PURE__ */ new Map();
1314
+ var COMPILED_TEMPLATE_CACHE_MAX = 2048;
1315
+ function cacheCompiledTemplate(key, template) {
1316
+ if (compiledTemplateCache.size >= COMPILED_TEMPLATE_CACHE_MAX) {
1317
+ const first = compiledTemplateCache.keys().next().value;
1318
+ if (first !== void 0) compiledTemplateCache.delete(first);
1319
+ }
1320
+ compiledTemplateCache.set(key, template);
1321
+ }
1322
+ var UNSAFE_METHOD_NAMES = /* @__PURE__ */ new Set([
1323
+ "constructor",
1324
+ "__proto__",
1325
+ "prototype",
1326
+ "__defineGetter__",
1327
+ "__defineSetter__",
1328
+ "__lookupGetter__",
1329
+ "__lookupSetter__",
1330
+ "eval",
1331
+ "Function"
1332
+ ]);
1333
+ (() => {
1334
+ const result = [];
1335
+ for (const name of UNSAFE_METHOD_NAMES) {
1336
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1337
+ result.push({
1338
+ name,
1339
+ // Match as property access (.name) or bare identifier at start
1340
+ dotRe: new RegExp(`(?:^|\\.)${escaped}(?:\\s*\\(|\\s*$|[^\\w$])`, "m"),
1341
+ // Match bracket access with single quotes, double quotes, or backticks
1342
+ bracketRe: new RegExp(`\\[\\s*(?:'${escaped}'|"${escaped}"|\`` + escaped + `\`)\\s*\\]`)
1343
+ });
1344
+ }
1345
+ return result;
1346
+ })();
1347
+ var TEXT_BINDING_SYM = /* @__PURE__ */ Symbol.for("forma-text-binding-cache");
1348
+ function toTextValue(value2) {
1349
+ if (value2 == null) return "";
1350
+ if (typeof value2 === "string") return value2;
1351
+ if (typeof value2 === "symbol") return value2.toString();
1352
+ return String(value2);
1353
+ }
1354
+ function setElementTextFast(el, next) {
1355
+ let cache = el[TEXT_BINDING_SYM];
1356
+ if (!cache) {
1357
+ cache = { initialized: false, last: "", node: null };
1358
+ el[TEXT_BINDING_SYM] = cache;
1359
+ }
1360
+ if (cache.initialized && cache.last === next) return;
1361
+ let node = cache.node;
1362
+ if (!node || node.parentNode !== el || el.childNodes.length !== 1 || el.firstChild !== node) {
1363
+ if (el.childNodes.length === 1 && el.firstChild?.nodeType === Node.TEXT_NODE) {
1364
+ node = el.firstChild;
1365
+ cache.node = node;
1366
+ } else {
1367
+ el.textContent = next;
1368
+ const first = el.firstChild;
1369
+ cache.node = first && first.nodeType === Node.TEXT_NODE && el.childNodes.length === 1 ? first : null;
1370
+ cache.last = next;
1371
+ cache.initialized = true;
1372
+ return;
1373
+ }
1374
+ }
1375
+ node.data = next;
1376
+ cache.last = next;
1377
+ cache.initialized = true;
1378
+ }
1379
+ function splitCallArgs(raw) {
1380
+ const out = [];
1381
+ if (raw.trim() === "") return out;
1382
+ let depth = 0;
1383
+ let inSingle = false;
1384
+ let inDouble = false;
1385
+ let escaped = false;
1386
+ let start = 0;
1387
+ for (let i = 0; i < raw.length; i++) {
1388
+ const ch = raw[i];
1389
+ if (escaped) {
1390
+ escaped = false;
1391
+ continue;
1392
+ }
1393
+ if (ch === "\\") {
1394
+ escaped = true;
1395
+ continue;
1396
+ }
1397
+ if (inSingle) {
1398
+ if (ch === "'") inSingle = false;
1399
+ continue;
1400
+ }
1401
+ if (inDouble) {
1402
+ if (ch === '"') inDouble = false;
1403
+ continue;
1404
+ }
1405
+ if (ch === "'") {
1406
+ inSingle = true;
1407
+ continue;
1408
+ }
1409
+ if (ch === '"') {
1410
+ inDouble = true;
1411
+ continue;
1412
+ }
1413
+ if (ch === "(") {
1414
+ depth++;
1415
+ continue;
1416
+ }
1417
+ if (ch === ")") {
1418
+ if (depth > 0) depth--;
1419
+ continue;
1420
+ }
1421
+ if (ch === "," && depth === 0) {
1422
+ out.push(raw.slice(start, i).trim());
1423
+ start = i + 1;
1424
+ }
1425
+ }
1426
+ out.push(raw.slice(start).trim());
1427
+ return out.filter(Boolean);
1428
+ }
1429
+ function readBalancedSegment(input, start, open, close) {
1430
+ if (input[start] !== open) return null;
1431
+ let depth = 0;
1432
+ let inSingle = false;
1433
+ let inDouble = false;
1434
+ let inTemplate = false;
1435
+ let escaped = false;
1436
+ for (let i = start; i < input.length; i++) {
1437
+ const ch = input[i];
1438
+ if (escaped) {
1439
+ escaped = false;
1440
+ continue;
1441
+ }
1442
+ if (ch === "\\" && (inSingle || inDouble || inTemplate)) {
1443
+ escaped = true;
1444
+ continue;
1445
+ }
1446
+ if (inSingle) {
1447
+ if (ch === "'") inSingle = false;
1448
+ continue;
1449
+ }
1450
+ if (inDouble) {
1451
+ if (ch === '"') inDouble = false;
1452
+ continue;
1453
+ }
1454
+ if (inTemplate) {
1455
+ if (ch === "`") inTemplate = false;
1456
+ continue;
1457
+ }
1458
+ if (ch === "'") {
1459
+ inSingle = true;
1460
+ continue;
1461
+ }
1462
+ if (ch === '"') {
1463
+ inDouble = true;
1464
+ continue;
1465
+ }
1466
+ if (ch === "`") {
1467
+ inTemplate = true;
1468
+ continue;
1469
+ }
1470
+ if (ch === open) {
1471
+ depth++;
1472
+ continue;
1473
+ }
1474
+ if (ch === close) {
1475
+ depth--;
1476
+ if (depth === 0) {
1477
+ return {
1478
+ inner: input.slice(start + 1, i),
1479
+ end: i
1480
+ };
1481
+ }
1482
+ }
1483
+ }
1484
+ return null;
1485
+ }
1486
+ function splitTopLevelStatements(raw) {
1487
+ const input = raw.trim();
1488
+ if (!input) return [];
1489
+ const out = [];
1490
+ let depthParen = 0;
1491
+ let depthBrace = 0;
1492
+ let depthBracket = 0;
1493
+ let inSingle = false;
1494
+ let inDouble = false;
1495
+ let inTemplate = false;
1496
+ let escaped = false;
1497
+ let start = 0;
1498
+ for (let i = 0; i < input.length; i++) {
1499
+ const ch = input[i];
1500
+ if (escaped) {
1501
+ escaped = false;
1502
+ continue;
1503
+ }
1504
+ if (ch === "\\" && (inSingle || inDouble || inTemplate)) {
1505
+ escaped = true;
1506
+ continue;
1507
+ }
1508
+ if (inSingle) {
1509
+ if (ch === "'") inSingle = false;
1510
+ continue;
1511
+ }
1512
+ if (inDouble) {
1513
+ if (ch === '"') inDouble = false;
1514
+ continue;
1515
+ }
1516
+ if (inTemplate) {
1517
+ if (ch === "`") inTemplate = false;
1518
+ continue;
1519
+ }
1520
+ if (ch === "'") {
1521
+ inSingle = true;
1522
+ continue;
1523
+ }
1524
+ if (ch === '"') {
1525
+ inDouble = true;
1526
+ continue;
1527
+ }
1528
+ if (ch === "`") {
1529
+ inTemplate = true;
1530
+ continue;
1531
+ }
1532
+ if (ch === "(") depthParen++;
1533
+ else if (ch === ")" && depthParen > 0) depthParen--;
1534
+ else if (ch === "{") depthBrace++;
1535
+ else if (ch === "}" && depthBrace > 0) depthBrace--;
1536
+ else if (ch === "[") depthBracket++;
1537
+ else if (ch === "]" && depthBracket > 0) depthBracket--;
1538
+ if (ch === ";" && depthParen === 0 && depthBrace === 0 && depthBracket === 0) {
1539
+ const stmt = input.slice(start, i).trim();
1540
+ if (stmt) out.push(stmt);
1541
+ start = i + 1;
1542
+ }
1543
+ }
1544
+ const tail = input.slice(start).trim();
1545
+ if (tail) out.push(tail);
1546
+ return out;
1547
+ }
1548
+ function consumeStatement(raw) {
1549
+ const input = raw.trim();
1550
+ if (!input) return null;
1551
+ if (input.startsWith("{")) {
1552
+ const block = readBalancedSegment(input, 0, "{", "}");
1553
+ if (!block) return null;
1554
+ const body = block.inner.trim();
1555
+ let rest = input.slice(block.end + 1).trim();
1556
+ if (rest.startsWith(";")) rest = rest.slice(1).trim();
1557
+ return { body, rest };
1558
+ }
1559
+ let depthParen = 0;
1560
+ let depthBrace = 0;
1561
+ let depthBracket = 0;
1562
+ let inSingle = false;
1563
+ let inDouble = false;
1564
+ let inTemplate = false;
1565
+ let escaped = false;
1566
+ for (let i = 0; i < input.length; i++) {
1567
+ const ch = input[i];
1568
+ if (escaped) {
1569
+ escaped = false;
1570
+ continue;
1571
+ }
1572
+ if (ch === "\\" && (inSingle || inDouble || inTemplate)) {
1573
+ escaped = true;
1574
+ continue;
1575
+ }
1576
+ if (inSingle) {
1577
+ if (ch === "'") inSingle = false;
1578
+ continue;
1579
+ }
1580
+ if (inDouble) {
1581
+ if (ch === '"') inDouble = false;
1582
+ continue;
1583
+ }
1584
+ if (inTemplate) {
1585
+ if (ch === "`") inTemplate = false;
1586
+ continue;
1587
+ }
1588
+ if (ch === "'") {
1589
+ inSingle = true;
1590
+ continue;
1591
+ }
1592
+ if (ch === '"') {
1593
+ inDouble = true;
1594
+ continue;
1595
+ }
1596
+ if (ch === "`") {
1597
+ inTemplate = true;
1598
+ continue;
1599
+ }
1600
+ if (ch === "(") depthParen++;
1601
+ else if (ch === ")" && depthParen > 0) depthParen--;
1602
+ else if (ch === "{") depthBrace++;
1603
+ else if (ch === "}" && depthBrace > 0) depthBrace--;
1604
+ else if (ch === "[") depthBracket++;
1605
+ else if (ch === "]" && depthBracket > 0) depthBracket--;
1606
+ if (ch === ";" && depthParen === 0 && depthBrace === 0 && depthBracket === 0) {
1607
+ return {
1608
+ body: input.slice(0, i).trim(),
1609
+ rest: input.slice(i + 1).trim()
1610
+ };
1611
+ }
1612
+ }
1613
+ return {
1614
+ body: input,
1615
+ rest: ""
1616
+ };
1617
+ }
1618
+ function parseIfHandler(expr, scope) {
1619
+ const input = expr.trim();
1620
+ if (!RE_IF_PREFIX.test(input)) return null;
1621
+ if (RE_EVENT_REF.test(input)) return null;
1622
+ let idx = 2;
1623
+ while (idx < input.length && /\s/.test(input[idx])) idx++;
1624
+ if (input[idx] !== "(") return null;
1625
+ const condSegment = readBalancedSegment(input, idx, "(", ")");
1626
+ if (!condSegment) return null;
1627
+ const condExpr = parseExpression(condSegment.inner.trim(), scope);
1628
+ if (!condExpr) return null;
1629
+ let rest = input.slice(condSegment.end + 1).trim();
1630
+ const thenStmt = consumeStatement(rest);
1631
+ if (!thenStmt || !thenStmt.body) return null;
1632
+ const thenHandler = parseHandler(thenStmt.body, scope);
1633
+ if (!thenHandler) return null;
1634
+ rest = thenStmt.rest.trim();
1635
+ let elseHandler = null;
1636
+ if (rest.startsWith("else")) {
1637
+ rest = rest.slice("else".length).trim();
1638
+ const elseStmt = consumeStatement(rest);
1639
+ if (!elseStmt || !elseStmt.body) return null;
1640
+ elseHandler = parseHandler(elseStmt.body, scope);
1641
+ if (!elseHandler) return null;
1642
+ rest = elseStmt.rest.trim();
1643
+ }
1644
+ if (rest.length > 0) return null;
1645
+ return (e) => {
1646
+ batch(() => {
1647
+ if (condExpr()) thenHandler(e);
1648
+ else elseHandler?.(e);
1649
+ });
1650
+ };
1651
+ }
1652
+ function unwrapOuterParens(raw) {
1653
+ let expr = raw.trim();
1654
+ while (expr.startsWith("(")) {
1655
+ const segment = readBalancedSegment(expr, 0, "(", ")");
1656
+ if (!segment || segment.end !== expr.length - 1) break;
1657
+ const inner = segment.inner.trim();
1658
+ if (!inner) break;
1659
+ expr = inner;
1660
+ }
1661
+ return expr;
1662
+ }
1663
+ function compileTemplate(text) {
1664
+ const cached = compiledTemplateCache.get(text);
1665
+ if (cached) return cached;
1666
+ const statics = [];
1667
+ const dynamics = [];
1668
+ let lastIndex = 0;
1669
+ const re = /\{item\.?(\w*)\}/g;
1670
+ let m;
1671
+ while ((m = re.exec(text)) !== null) {
1672
+ statics.push(text.slice(lastIndex, m.index));
1673
+ dynamics.push(m[1]);
1674
+ lastIndex = re.lastIndex;
1675
+ }
1676
+ statics.push(text.slice(lastIndex));
1677
+ const result = {
1678
+ statics,
1679
+ dynamics,
1680
+ hasItemRef: dynamics.length > 0
1681
+ };
1682
+ cacheCompiledTemplate(text, result);
1683
+ return result;
1684
+ }
1685
+ var templateTexts = /* @__PURE__ */ new WeakMap();
1686
+ function evaluateCompiledTemplate(compiled, item) {
1687
+ if (!compiled.hasItemRef) return compiled.statics[0];
1688
+ let result = compiled.statics[0];
1689
+ for (let i = 0; i < compiled.dynamics.length; i++) {
1690
+ const key = compiled.dynamics[i];
1691
+ if (!key) {
1692
+ result += typeof item === "object" ? JSON.stringify(item) : String(item ?? "");
1693
+ } else {
1694
+ result += String(item?.[key] ?? "");
1695
+ }
1696
+ result += compiled.statics[i + 1] ?? "";
1697
+ }
1698
+ return result;
1699
+ }
1700
+ function cloneWithTemplateData(template, item) {
1701
+ const clone = template.cloneNode(true);
1702
+ const walker = document.createTreeWalker(clone, NodeFilter.SHOW_TEXT);
1703
+ while (walker.nextNode()) {
1704
+ const node = walker.currentNode;
1705
+ const text = node.textContent ?? "";
1706
+ if (text.includes("{item")) {
1707
+ const compiled = compileTemplate(text);
1708
+ templateTexts.set(node, compiled);
1709
+ node.textContent = evaluateCompiledTemplate(compiled, item);
1710
+ }
1711
+ }
1712
+ cloneAttributeTemplates(clone, item);
1713
+ return clone;
1714
+ }
1715
+ function updateTemplateData(el, item) {
1716
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
1717
+ while (walker.nextNode()) {
1718
+ const node = walker.currentNode;
1719
+ const compiled = templateTexts.get(node);
1720
+ if (compiled) {
1721
+ node.textContent = evaluateCompiledTemplate(compiled, item);
1722
+ }
1723
+ }
1724
+ }
1725
+ var templateAttrs = /* @__PURE__ */ new WeakMap();
1726
+ var DIRECTIVE_ATTR_PREFIXES = [
1727
+ "data-list",
1728
+ "data-show",
1729
+ "data-text",
1730
+ "data-if",
1731
+ "data-model",
1732
+ "data-on:",
1733
+ "data-class:",
1734
+ "data-bind:",
1735
+ "data-computed",
1736
+ "data-persist",
1737
+ "data-fetch",
1738
+ "data-transition",
1739
+ "data-transition:"
1740
+ ];
1741
+ function isDirectiveAttr(name) {
1742
+ for (const prefix of DIRECTIVE_ATTR_PREFIXES) {
1743
+ if (name === prefix || name.startsWith(prefix)) return true;
1744
+ }
1745
+ return false;
1746
+ }
1747
+ function splitClassTokens(raw) {
1748
+ if (!raw) return [];
1749
+ return raw.trim().split(/\s+/).map((t) => t.trim()).filter(Boolean);
1750
+ }
1751
+ function parseDurationTokenMs(token) {
1752
+ const t = token.trim().toLowerCase();
1753
+ if (t.endsWith("ms")) {
1754
+ const n = Number(t.slice(0, -2));
1755
+ return Number.isFinite(n) && n >= 0 ? n : null;
1756
+ }
1757
+ if (t.endsWith("s")) {
1758
+ const n = Number(t.slice(0, -1));
1759
+ return Number.isFinite(n) && n >= 0 ? n * 1e3 : null;
1760
+ }
1761
+ return null;
1762
+ }
1763
+ function parseClassTokensAndDuration(raw) {
1764
+ const classes = [];
1765
+ let durationMs;
1766
+ for (const token of splitClassTokens(raw)) {
1767
+ const parsed = parseDurationTokenMs(token);
1768
+ if (parsed != null) {
1769
+ durationMs = parsed;
1770
+ } else {
1771
+ classes.push(token);
1772
+ }
1773
+ }
1774
+ return { classes, durationMs };
1775
+ }
1776
+ function uniqueTokens(tokens) {
1777
+ return Array.from(new Set(tokens.filter(Boolean)));
1778
+ }
1779
+ function parseCssTimeListMs(raw) {
1780
+ if (!raw) return [];
1781
+ return raw.split(",").map((part) => parseDurationTokenMs(part.trim())).filter((ms) => ms != null);
1782
+ }
1783
+ function maxCombinedTimingsMs(durations, delays) {
1784
+ if (durations.length === 0 && delays.length === 0) return 0;
1785
+ if (durations.length === 0) return Math.max(...delays, 0);
1786
+ if (delays.length === 0) return Math.max(...durations, 0);
1787
+ const len = Math.max(durations.length, delays.length);
1788
+ let max = 0;
1789
+ for (let i = 0; i < len; i++) {
1790
+ const d = durations[i % durations.length] ?? 0;
1791
+ const delay = delays[i % delays.length] ?? 0;
1792
+ if (d + delay > max) max = d + delay;
1793
+ }
1794
+ return max;
1795
+ }
1796
+ function resolveTransitionDurationMs(el, explicitMs) {
1797
+ if (typeof explicitMs === "number") return explicitMs;
1798
+ const cs = window.getComputedStyle(el);
1799
+ const trans = maxCombinedTimingsMs(
1800
+ parseCssTimeListMs(cs.transitionDuration),
1801
+ parseCssTimeListMs(cs.transitionDelay)
1802
+ );
1803
+ const anim = maxCombinedTimingsMs(
1804
+ parseCssTimeListMs(cs.animationDuration),
1805
+ parseCssTimeListMs(cs.animationDelay)
1806
+ );
1807
+ return Math.max(trans, anim);
1808
+ }
1809
+ function getTransitionState(el) {
1810
+ const existing = el[TRANSITION_STATE_SYM];
1811
+ if (existing) return existing;
1812
+ const created = { token: 0, cancel: null };
1813
+ el[TRANSITION_STATE_SYM] = created;
1814
+ return created;
1815
+ }
1816
+ function clearTransitionState(el) {
1817
+ const state = el[TRANSITION_STATE_SYM];
1818
+ if (state?.cancel) {
1819
+ state.cancel();
1820
+ }
1821
+ delete el[TRANSITION_STATE_SYM];
1822
+ }
1823
+ function parseTransitionSpec(el) {
1824
+ const hasTransitionAttr = el.hasAttribute("data-transition") || Array.from(el.attributes).some((a) => a.name.startsWith("data-transition:"));
1825
+ if (!hasTransitionAttr) return null;
1826
+ const base = parseClassTokensAndDuration(el.getAttribute("data-transition")).classes;
1827
+ const enter = parseClassTokensAndDuration(el.getAttribute("data-transition:enter"));
1828
+ const leave = parseClassTokensAndDuration(el.getAttribute("data-transition:leave"));
1829
+ const enterFrom = splitClassTokens(
1830
+ el.getAttribute("data-transition:enter-from") ?? el.getAttribute("data-transition:enter-start")
1831
+ );
1832
+ const enterTo = splitClassTokens(
1833
+ el.getAttribute("data-transition:enter-to") ?? el.getAttribute("data-transition:enter-end")
1834
+ );
1835
+ const leaveFrom = splitClassTokens(
1836
+ el.getAttribute("data-transition:leave-from") ?? el.getAttribute("data-transition:leave-start")
1837
+ );
1838
+ const leaveTo = splitClassTokens(
1839
+ el.getAttribute("data-transition:leave-to") ?? el.getAttribute("data-transition:leave-end")
1840
+ );
1841
+ const durationBoth = parseDurationTokenMs(el.getAttribute("data-transition:duration") ?? "");
1842
+ const enterDuration = parseDurationTokenMs(el.getAttribute("data-transition:duration-enter") ?? "") ?? enter.durationMs ?? durationBoth ?? void 0;
1843
+ const leaveDuration = parseDurationTokenMs(el.getAttribute("data-transition:duration-leave") ?? "") ?? leave.durationMs ?? durationBoth ?? void 0;
1844
+ return {
1845
+ enter: uniqueTokens([...base, ...enter.classes]),
1846
+ enterFrom: uniqueTokens(enterFrom),
1847
+ enterTo: uniqueTokens(enterTo),
1848
+ leave: uniqueTokens([...base, ...leave.classes]),
1849
+ leaveFrom: uniqueTokens(leaveFrom),
1850
+ leaveTo: uniqueTokens(leaveTo),
1851
+ enterDurationMs: enterDuration,
1852
+ leaveDurationMs: leaveDuration
1853
+ };
1854
+ }
1855
+ function removeClasses(el, classes) {
1856
+ for (const cls of classes) {
1857
+ el.classList.remove(cls);
1858
+ }
1859
+ }
1860
+ function addClasses(el, classes) {
1861
+ for (const cls of classes) {
1862
+ el.classList.add(cls);
1863
+ }
1864
+ }
1865
+ function runTransitionPhase(el, phaseClasses, onDone) {
1866
+ const cleanupClasses = uniqueTokens([
1867
+ ...phaseClasses.base,
1868
+ ...phaseClasses.from,
1869
+ ...phaseClasses.to
1870
+ ]);
1871
+ let done = false;
1872
+ let timeoutId = null;
1873
+ let raf1 = null;
1874
+ let raf2 = null;
1875
+ const finish = () => {
1876
+ if (done) return;
1877
+ done = true;
1878
+ if (timeoutId != null) window.clearTimeout(timeoutId);
1879
+ if (raf1 != null) cancelAnimationFrame(raf1);
1880
+ if (raf2 != null) cancelAnimationFrame(raf2);
1881
+ removeClasses(el, cleanupClasses);
1882
+ onDone();
1883
+ };
1884
+ addClasses(el, phaseClasses.base);
1885
+ addClasses(el, phaseClasses.from);
1886
+ removeClasses(el, phaseClasses.to);
1887
+ raf1 = requestAnimationFrame(() => {
1888
+ raf2 = requestAnimationFrame(() => {
1889
+ if (done) return;
1890
+ removeClasses(el, phaseClasses.from);
1891
+ addClasses(el, phaseClasses.to);
1892
+ const ms = resolveTransitionDurationMs(el, phaseClasses.durationMs);
1893
+ if (ms <= 0) {
1894
+ finish();
1895
+ return;
1896
+ }
1897
+ timeoutId = window.setTimeout(finish, ms + 25);
1898
+ });
1899
+ });
1900
+ return finish;
1901
+ }
1902
+ function transitionInsert(el, parent, ref, spec) {
1903
+ parent.insertBefore(el, ref);
1904
+ if (!spec) return;
1905
+ const state = getTransitionState(el);
1906
+ state.token += 1;
1907
+ const token = state.token;
1908
+ if (state.cancel) state.cancel();
1909
+ state.cancel = runTransitionPhase(
1910
+ el,
1911
+ {
1912
+ base: spec.enter,
1913
+ from: spec.enterFrom,
1914
+ to: spec.enterTo,
1915
+ durationMs: spec.enterDurationMs
1916
+ },
1917
+ () => {
1918
+ const current = getTransitionState(el);
1919
+ if (current.token === token) current.cancel = null;
1920
+ }
1921
+ );
1922
+ }
1923
+ function transitionRemove(el, spec, onDone) {
1924
+ if (el.hasAttribute("data-forma-leaving")) {
1925
+ onDone();
1926
+ return;
1927
+ }
1928
+ if (!spec) {
1929
+ onDone();
1930
+ return;
1931
+ }
1932
+ el.setAttribute("data-forma-leaving", "");
1933
+ const state = getTransitionState(el);
1934
+ state.token += 1;
1935
+ const token = state.token;
1936
+ if (state.cancel) state.cancel();
1937
+ state.cancel = runTransitionPhase(
1938
+ el,
1939
+ {
1940
+ base: spec.leave,
1941
+ from: spec.leaveFrom,
1942
+ to: spec.leaveTo,
1943
+ durationMs: spec.leaveDurationMs
1944
+ },
1945
+ () => {
1946
+ const current = getTransitionState(el);
1947
+ if (current.token === token) current.cancel = null;
1948
+ el.removeAttribute("data-forma-leaving");
1949
+ onDone();
1950
+ }
1951
+ );
1952
+ }
1953
+ function applyShowVisibility(el, visible, transition, initial) {
1954
+ if (!transition || initial) {
1955
+ el.style.display = visible ? "" : "none";
1956
+ if (transition) {
1957
+ removeClasses(el, uniqueTokens([
1958
+ ...transition.enter,
1959
+ ...transition.enterFrom,
1960
+ ...transition.enterTo,
1961
+ ...transition.leave,
1962
+ ...transition.leaveFrom,
1963
+ ...transition.leaveTo
1964
+ ]));
1965
+ }
1966
+ return;
1967
+ }
1968
+ const state = getTransitionState(el);
1969
+ state.token += 1;
1970
+ const token = state.token;
1971
+ if (state.cancel) state.cancel();
1972
+ state.cancel = null;
1973
+ if (visible) {
1974
+ el.style.display = "";
1975
+ state.cancel = runTransitionPhase(
1976
+ el,
1977
+ {
1978
+ base: transition.enter,
1979
+ from: transition.enterFrom,
1980
+ to: transition.enterTo,
1981
+ durationMs: transition.enterDurationMs
1982
+ },
1983
+ () => {
1984
+ const current = getTransitionState(el);
1985
+ if (current.token === token) current.cancel = null;
1986
+ }
1987
+ );
1988
+ return;
1989
+ }
1990
+ state.cancel = runTransitionPhase(
1991
+ el,
1992
+ {
1993
+ base: transition.leave,
1994
+ from: transition.leaveFrom,
1995
+ to: transition.leaveTo,
1996
+ durationMs: transition.leaveDurationMs
1997
+ },
1998
+ () => {
1999
+ const current = getTransitionState(el);
2000
+ if (current.token !== token) return;
2001
+ el.style.display = "none";
2002
+ current.cancel = null;
2003
+ }
2004
+ );
2005
+ }
2006
+ function cloneAttributeTemplates(el, item) {
2007
+ const all = [el, ...Array.from(el.querySelectorAll("*"))];
2008
+ for (const node of all) {
2009
+ const entries = [];
2010
+ for (const attr of Array.from(node.attributes)) {
2011
+ if (isDirectiveAttr(attr.name)) continue;
2012
+ if (attr.value.includes("{item")) {
2013
+ const compiled = compileTemplate(attr.value);
2014
+ entries.push({ attr: attr.name, compiled });
2015
+ node.setAttribute(attr.name, evaluateCompiledTemplate(compiled, item));
2016
+ }
2017
+ }
2018
+ if (entries.length > 0) {
2019
+ templateAttrs.set(node, entries);
2020
+ }
2021
+ }
2022
+ }
2023
+ function parseChainedAccess(expr, scope) {
2024
+ let pos = 0;
2025
+ const identMatch = expr.match(/^[a-zA-Z_$]\w*/);
2026
+ if (!identMatch) return null;
2027
+ const rootName = identMatch[0];
2028
+ pos = rootName.length;
2029
+ if (pos >= expr.length) return null;
2030
+ if (expr[pos] !== "." && !(expr[pos] === "?" && expr[pos + 1] === ".")) return null;
2031
+ const steps = [];
2032
+ while (pos < expr.length) {
2033
+ let optional = false;
2034
+ if (expr[pos] === "?" && expr[pos + 1] === ".") {
2035
+ optional = true;
2036
+ pos += 2;
2037
+ } else if (expr[pos] === ".") {
2038
+ pos += 1;
2039
+ } else {
2040
+ return null;
2041
+ }
2042
+ const nameMatch = expr.slice(pos).match(/^\w+/);
2043
+ if (!nameMatch) return null;
2044
+ const name = nameMatch[0];
2045
+ pos += name.length;
2046
+ if (UNSAFE_METHOD_NAMES.has(name)) return () => void 0;
2047
+ if (pos < expr.length && expr[pos] === "(") {
2048
+ const balanced = readBalancedSegment(expr, pos, "(", ")");
2049
+ if (!balanced) return null;
2050
+ const argsRaw = balanced.inner.trim();
2051
+ const argFns = [];
2052
+ for (const arg of splitCallArgs(argsRaw)) {
2053
+ const parsed = parseExpression(arg, scope);
2054
+ if (!parsed) return null;
2055
+ argFns.push(parsed);
2056
+ }
2057
+ steps.push({ type: "call", name, optional, argFns });
2058
+ pos = balanced.end + 1;
2059
+ } else {
2060
+ steps.push({ type: "prop", name, optional });
2061
+ }
2062
+ }
2063
+ if (pos !== expr.length) return null;
2064
+ if (steps.length === 0) return null;
2065
+ const rootExpr = rootName === "Math" ? (() => Math) : (() => scope.getters[rootName]?.());
2066
+ return () => {
2067
+ let val = rootExpr();
2068
+ for (const step of steps) {
2069
+ if (val == null) {
2070
+ if (step.optional) return void 0;
2071
+ return void 0;
2072
+ }
2073
+ if (step.type === "prop") {
2074
+ val = val[step.name];
2075
+ } else {
2076
+ const method = val[step.name];
2077
+ if (typeof method !== "function") return void 0;
2078
+ const args = step.argFns.map((fn) => fn());
2079
+ val = method.apply(val, args);
2080
+ }
2081
+ }
2082
+ return val;
2083
+ };
2084
+ }
2085
+ function parseExpression(expr, scope) {
2086
+ const cachedFactory = expressionCache.get(expr);
2087
+ if (cachedFactory) return cachedFactory(scope);
2088
+ const result = parseExpressionUncached(expr, scope);
2089
+ if (result !== null) {
2090
+ if (expr === "true" || expr === "false" || expr === "null" || expr === "undefined") {
2091
+ const val = expr === "true" ? true : expr === "false" ? false : expr === "null" ? null : void 0;
2092
+ cacheExpression(expr, () => () => val);
2093
+ } else if (RE_IDENTIFIER.test(expr)) {
2094
+ cacheExpression(expr, (s) => () => s.getters[expr]?.());
2095
+ } else if (RE_STRING_SINGLE.test(expr) || RE_STRING_DOUBLE.test(expr)) {
2096
+ const val = expr.slice(1, -1);
2097
+ cacheExpression(expr, () => () => val);
2098
+ } else if (RE_NUMBER.test(expr)) {
2099
+ const val = Number(expr);
2100
+ cacheExpression(expr, () => () => val);
2101
+ } else {
2102
+ const dotMatch = expr.match(RE_DOT_ACCESS);
2103
+ if (dotMatch) {
2104
+ const p1 = dotMatch[1], p2 = dotMatch[2];
2105
+ cacheExpression(expr, (s) => () => {
2106
+ const obj = s.getters[p1]?.();
2107
+ return obj?.[p2];
2108
+ });
2109
+ }
2110
+ }
2111
+ }
2112
+ return result;
2113
+ }
2114
+ function parseExpressionUncached(expr, scope) {
2115
+ expr = expr.trim();
2116
+ const unwrapped = unwrapOuterParens(expr);
2117
+ if (unwrapped !== expr) {
2118
+ return parseExpression(unwrapped, scope);
2119
+ }
2120
+ if (RE_STRING_SINGLE.test(expr) || RE_STRING_DOUBLE.test(expr)) {
2121
+ const val = expr.slice(1, -1);
2122
+ return () => val;
2123
+ }
2124
+ if (RE_NUMBER.test(expr)) {
2125
+ const val = Number(expr);
2126
+ return () => val;
2127
+ }
2128
+ if (expr === "true") return () => true;
2129
+ if (expr === "false") return () => false;
2130
+ if (expr === "null") return () => null;
2131
+ if (expr === "undefined") return () => void 0;
2132
+ if (RE_IDENTIFIER.test(expr)) {
2133
+ return () => scope.getters[expr]?.();
2134
+ }
2135
+ {
2136
+ const chainResult = parseChainedAccess(expr, scope);
2137
+ if (chainResult) return chainResult;
2138
+ }
2139
+ const groupedCallMatch = expr.match(RE_GROUP_METHOD_CALL);
2140
+ if (groupedCallMatch) {
2141
+ const baseRaw = groupedCallMatch[1].trim();
2142
+ const methodName = groupedCallMatch[2];
2143
+ const argsRaw = groupedCallMatch[3].trim();
2144
+ if (UNSAFE_METHOD_NAMES.has(methodName)) return () => void 0;
2145
+ const baseExpr = parseExpression(baseRaw, scope);
2146
+ if (!baseExpr) return null;
2147
+ const argFns = [];
2148
+ for (const arg of splitCallArgs(argsRaw)) {
2149
+ const parsed = parseExpression(arg, scope);
2150
+ if (!parsed) return null;
2151
+ argFns.push(parsed);
2152
+ }
2153
+ return () => {
2154
+ const base = baseExpr();
2155
+ const method = base?.[methodName];
2156
+ if (typeof method !== "function") return void 0;
2157
+ const args = argFns.map((fn) => fn());
2158
+ return method.apply(base, args);
2159
+ };
2160
+ }
2161
+ if (expr.startsWith("!")) {
2162
+ const inner = parseExpression(expr.slice(1).trim(), scope);
2163
+ if (inner) return () => !inner();
2164
+ }
2165
+ const bracketMatch = expr.match(RE_BRACKET);
2166
+ if (bracketMatch) {
2167
+ const objExpr = parseExpression(bracketMatch[1], scope);
2168
+ let key;
2169
+ const rawKey = bracketMatch[2];
2170
+ if (RE_DIGIT_ONLY.test(rawKey)) {
2171
+ key = Number(rawKey);
2172
+ } else {
2173
+ key = rawKey.slice(1, -1);
2174
+ }
2175
+ if (objExpr) {
2176
+ return () => objExpr()?.[key];
2177
+ }
2178
+ }
2179
+ if (expr.startsWith("[")) {
2180
+ const balanced = readBalancedSegment(expr, 0, "[", "]");
2181
+ if (balanced && balanced.end === expr.length - 1) {
2182
+ const inner = balanced.inner.trim();
2183
+ if (inner === "") {
2184
+ return () => [];
2185
+ }
2186
+ const elements = splitCallArgs(inner);
2187
+ const elementFns = [];
2188
+ let allParsed = true;
2189
+ for (const el of elements) {
2190
+ const parsed = parseExpression(el.trim(), scope);
2191
+ if (!parsed) {
2192
+ allParsed = false;
2193
+ break;
2194
+ }
2195
+ elementFns.push(parsed);
2196
+ }
2197
+ if (allParsed) {
2198
+ return () => elementFns.map((fn) => fn());
2199
+ }
2200
+ }
2201
+ }
2202
+ const ternaryMatch = expr.match(RE_TERNARY);
2203
+ if (ternaryMatch) {
2204
+ const cond = parseExpression(ternaryMatch[1].trim(), scope);
2205
+ const then = parseExpression(ternaryMatch[2].trim(), scope);
2206
+ const els = parseExpression(ternaryMatch[3].trim(), scope);
2207
+ if (cond && then && els) {
2208
+ return () => cond() ? then() : els();
2209
+ }
2210
+ }
2211
+ const nullishMatch = expr.match(RE_NULLISH);
2212
+ if (nullishMatch) {
2213
+ const left = parseExpression(nullishMatch[1].trim(), scope);
2214
+ const right = parseExpression(nullishMatch[2].trim(), scope);
2215
+ if (left && right) {
2216
+ return () => left() ?? right();
2217
+ }
2218
+ }
2219
+ const orMatch = expr.match(RE_OR);
2220
+ if (orMatch) {
2221
+ const left = parseExpression(orMatch[1].trim(), scope);
2222
+ const right = parseExpression(orMatch[2].trim(), scope);
2223
+ if (left && right) {
2224
+ return () => left() || right();
2225
+ }
2226
+ }
2227
+ const andMatch = expr.match(RE_AND);
2228
+ if (andMatch) {
2229
+ const left = parseExpression(andMatch[1].trim(), scope);
2230
+ const right = parseExpression(andMatch[2].trim(), scope);
2231
+ if (left && right) {
2232
+ return () => left() && right();
2233
+ }
2234
+ }
2235
+ const compMatch = expr.match(RE_COMPARISON);
2236
+ if (compMatch) {
2237
+ const left = parseExpression(compMatch[1].trim(), scope);
2238
+ const right = parseExpression(compMatch[3].trim(), scope);
2239
+ if (left && right) {
2240
+ const op = compMatch[2];
2241
+ return () => {
2242
+ const l = left(), r = right();
2243
+ switch (op) {
2244
+ case "===":
2245
+ return l === r;
2246
+ case "!==":
2247
+ return l !== r;
2248
+ case "==":
2249
+ return l == r;
2250
+ case "!=":
2251
+ return l != r;
2252
+ case ">":
2253
+ return l > r;
2254
+ case "<":
2255
+ return l < r;
2256
+ case ">=":
2257
+ return l >= r;
2258
+ case "<=":
2259
+ return l <= r;
2260
+ }
2261
+ };
2262
+ }
2263
+ }
2264
+ const addMatch = expr.match(RE_ADD);
2265
+ if (addMatch) {
2266
+ const left = parseExpression(addMatch[1].trim(), scope);
2267
+ const right = parseExpression(addMatch[3].trim(), scope);
2268
+ if (left && right) {
2269
+ const op = addMatch[2];
2270
+ return () => {
2271
+ const l = left(), r = right();
2272
+ if (op === "+") return l + r;
2273
+ return l - r;
2274
+ };
2275
+ }
2276
+ }
2277
+ const mulMatch = expr.match(RE_MUL);
2278
+ if (mulMatch) {
2279
+ const left = parseExpression(mulMatch[1].trim(), scope);
2280
+ const right = parseExpression(mulMatch[3].trim(), scope);
2281
+ if (left && right) {
2282
+ const op = mulMatch[2];
2283
+ return () => {
2284
+ const l = left(), r = right();
2285
+ switch (op) {
2286
+ case "*":
2287
+ return l * r;
2288
+ case "/":
2289
+ return l / r;
2290
+ case "%":
2291
+ return l % r;
2292
+ }
2293
+ };
2294
+ }
2295
+ }
2296
+ const tmplMatch = expr.match(RE_TEMPLATE_LIT);
2297
+ if (tmplMatch) {
2298
+ const raw = tmplMatch[1];
2299
+ const staticParts = [];
2300
+ const dynamicFns = [];
2301
+ let lastIndex = 0;
2302
+ const re = new RegExp(RE_TEMPLATE_INTERP.source, "g");
2303
+ let m;
2304
+ while ((m = re.exec(raw)) !== null) {
2305
+ staticParts.push(raw.slice(lastIndex, m.index));
2306
+ const inner = parseExpression(m[1].trim(), scope);
2307
+ if (!inner) return null;
2308
+ dynamicFns.push(inner);
2309
+ lastIndex = re.lastIndex;
2310
+ }
2311
+ staticParts.push(raw.slice(lastIndex));
2312
+ return () => {
2313
+ let result = staticParts[0];
2314
+ for (let i = 0; i < dynamicFns.length; i++) {
2315
+ result += String(dynamicFns[i]() ?? "");
2316
+ result += staticParts[i + 1] ?? "";
2317
+ }
2318
+ return result;
2319
+ };
2320
+ }
2321
+ return null;
2322
+ }
2323
+ function getScopeCache(cache, scope) {
2324
+ let scoped = cache.get(scope);
2325
+ if (!scoped) {
2326
+ scoped = /* @__PURE__ */ new Map();
2327
+ cache.set(scope, scoped);
2328
+ }
2329
+ return scoped;
2330
+ }
2331
+ function cspExpressionHint(expr) {
2332
+ if (expr.includes("...")) {
2333
+ return `Unsupported expression in CSP-safe mode: spread syntax detected. Use .concat() instead, or enable unsafe-eval via setUnsafeEval(true).`;
2334
+ }
2335
+ if (expr.includes("=>")) {
2336
+ return `Unsupported expression in CSP-safe mode: arrow function detected. Extract logic to a data-computed attribute, or enable unsafe-eval via setUnsafeEval(true).`;
2337
+ }
2338
+ return `Unsupported expression in CSP-safe mode. Simplify the expression or enable unsafe-eval via setUnsafeEval(true).`;
2339
+ }
2340
+ function buildEvaluator(expr, scope) {
2341
+ const cleaned = expr.replace(RE_STRIP_BRACES, "").trim();
2342
+ const cache = getScopeCache(scopeExpressionCache, scope);
2343
+ const cached = cache.get(cleaned);
2344
+ if (cached) return cached;
2345
+ const cspFn = parseExpression(cleaned, scope);
2346
+ if (cspFn) {
2347
+ cache.set(cleaned, cspFn);
2348
+ return cspFn;
2349
+ }
2350
+ {
2351
+ dbg("buildEvaluator: blocked unsafe eval fallback for expression:", cleaned);
2352
+ reportDiagnostic("expression-unsupported", cleaned, cspExpressionHint(cleaned));
2353
+ const blocked = () => void 0;
2354
+ cache.set(cleaned, blocked);
2355
+ return blocked;
2356
+ }
2357
+ }
2358
+ function parseHandler(expr, scope) {
2359
+ const normalized = expr.trim().replace(/;+$/g, "").trim();
2360
+ if (!normalized) return null;
2361
+ const ifHandler = parseIfHandler(normalized, scope);
2362
+ if (ifHandler) return ifHandler;
2363
+ const stmts = splitTopLevelStatements(normalized);
2364
+ if (stmts.length > 1) {
2365
+ const handlers = stmts.map((s) => parseHandler(s, scope));
2366
+ if (handlers.every((h) => h !== null)) {
2367
+ return (e) => {
2368
+ batch(() => {
2369
+ for (const h of handlers) h(e);
2370
+ });
2371
+ };
2372
+ }
2373
+ return null;
2374
+ }
2375
+ const single = stmts[0] ?? normalized;
2376
+ const incrMatch = single.match(RE_POST_INCR);
2377
+ if (incrMatch) {
2378
+ const name = incrMatch[1];
2379
+ const op = incrMatch[2];
2380
+ return () => {
2381
+ batch(() => {
2382
+ const val = scope.getters[name]?.() ?? 0;
2383
+ scope.setters[name]?.(op === "++" ? val + 1 : val - 1);
2384
+ });
2385
+ };
2386
+ }
2387
+ const preIncrMatch = single.match(RE_PRE_INCR);
2388
+ if (preIncrMatch) {
2389
+ const op = preIncrMatch[1];
2390
+ const name = preIncrMatch[2];
2391
+ return () => {
2392
+ batch(() => {
2393
+ const val = scope.getters[name]?.() ?? 0;
2394
+ scope.setters[name]?.(op === "++" ? val + 1 : val - 1);
2395
+ });
2396
+ };
2397
+ }
2398
+ const toggleMatch = single.match(RE_TOGGLE);
2399
+ if (toggleMatch && toggleMatch[1] === toggleMatch[2]) {
2400
+ const name = toggleMatch[1];
2401
+ return () => {
2402
+ batch(() => {
2403
+ scope.setters[name]?.(!scope.getters[name]?.());
2404
+ });
2405
+ };
2406
+ }
2407
+ const assignMatch = single.match(RE_ASSIGN);
2408
+ if (assignMatch) {
2409
+ const name = assignMatch[1];
2410
+ const valExpr = parseExpression(assignMatch[2].trim(), scope);
2411
+ if (valExpr) {
2412
+ if (_debug) dbg(`parseHandler: assignment "${name} = ..." \u2014 setter exists:`, !!scope.setters[name], ", getter exists:", !!scope.getters[name]);
2413
+ return () => {
2414
+ batch(() => {
2415
+ const val = valExpr();
2416
+ if (_debug) dbg(`SETTER: ${name} = ${val} (was: ${scope.getters[name]?.()})`);
2417
+ scope.setters[name]?.(val);
2418
+ });
2419
+ };
2420
+ }
2421
+ }
2422
+ const compoundMatch = single.match(RE_COMPOUND);
2423
+ if (compoundMatch) {
2424
+ const name = compoundMatch[1];
2425
+ const op = compoundMatch[2];
2426
+ const valExpr = parseExpression(compoundMatch[3].trim(), scope);
2427
+ if (valExpr) {
2428
+ return () => {
2429
+ batch(() => {
2430
+ const current = scope.getters[name]?.() ?? 0;
2431
+ const val = valExpr();
2432
+ switch (op) {
2433
+ case "+=":
2434
+ scope.setters[name]?.(current + val);
2435
+ break;
2436
+ case "-=":
2437
+ scope.setters[name]?.(current - val);
2438
+ break;
2439
+ case "*=":
2440
+ scope.setters[name]?.(current * val);
2441
+ break;
2442
+ case "/=":
2443
+ scope.setters[name]?.(current / val);
2444
+ break;
2445
+ }
2446
+ });
2447
+ };
2448
+ }
2449
+ }
2450
+ const refetchMatch = single.match(RE_REFETCH_CALL);
2451
+ if (refetchMatch) {
2452
+ const fetchId = refetchMatch[1];
2453
+ return () => $refetch(fetchId);
2454
+ }
2455
+ return null;
2456
+ }
2457
+ function buildHandler(expr, scope) {
2458
+ let cleaned = expr.trim();
2459
+ if (cleaned.startsWith("{")) {
2460
+ const seg = readBalancedSegment(cleaned, 0, "{", "}");
2461
+ if (seg && seg.end === cleaned.length - 1) {
2462
+ cleaned = seg.inner.trim();
2463
+ }
2464
+ }
2465
+ const cache = getScopeCache(scopeHandlerCache, scope);
2466
+ const cached = cache.get(cleaned);
2467
+ if (cached) return cached;
2468
+ const cspFn = parseHandler(cleaned, scope);
2469
+ if (cspFn) {
2470
+ const result = { handler: cspFn, supported: true };
2471
+ cache.set(cleaned, result);
2472
+ return result;
2473
+ }
2474
+ {
2475
+ dbg("buildHandler: blocked unsafe eval fallback for expression:", cleaned);
2476
+ reportDiagnostic("handler-unsupported", cleaned, cspExpressionHint(cleaned));
2477
+ const result = {
2478
+ handler: () => {
2479
+ },
2480
+ supported: false
2481
+ };
2482
+ cache.set(cleaned, result);
2483
+ return result;
2484
+ }
2485
+ }
2486
+ var FORBIDDEN_STATE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2487
+ function parseState(raw) {
2488
+ let parsed;
2489
+ try {
2490
+ parsed = JSON.parse(raw);
2491
+ } catch {
2492
+ if (_debug) {
2493
+ dbg("parseState: Invalid JSON in data-forma-state \u2014 use valid JSON with quoted keys. Got:", raw.slice(0, 200));
2494
+ }
2495
+ return {};
2496
+ }
2497
+ for (const key of FORBIDDEN_STATE_KEYS) {
2498
+ if (key in parsed) delete parsed[key];
2499
+ }
2500
+ return parsed;
2501
+ }
2502
+ function initScope(stateEl) {
2503
+ const raw = stateEl.getAttribute("data-forma-state") ?? "{}";
2504
+ const state = parseState(raw);
2505
+ const keys = Object.keys(state);
2506
+ if (_debug) {
2507
+ dbg("initScope: parsed", keys.length, "keys:", keys.join(", "));
2508
+ if (keys.length === 0) {
2509
+ dbg("initScope: WARNING \u2014 empty state! Raw attribute:", raw.slice(0, 200));
2510
+ }
2511
+ }
2512
+ const getters = {};
2513
+ const setters = {};
2514
+ for (const [key, initial] of Object.entries(state)) {
2515
+ const [get, set] = createSignal(initial);
2516
+ getters[key] = get;
2517
+ setters[key] = set;
2518
+ }
2519
+ getters["$refetch"] = () => $refetch;
2520
+ return { getters, setters };
2521
+ }
2522
+ var SAFE_EL_PROPS = /* @__PURE__ */ new Set([
2523
+ // Identity & attributes
2524
+ "id",
2525
+ "className",
2526
+ "tagName",
2527
+ "nodeName",
2528
+ "getAttribute",
2529
+ "setAttribute",
2530
+ "removeAttribute",
2531
+ "hasAttribute",
2532
+ "toggleAttribute",
2533
+ "dataset",
2534
+ "classList",
2535
+ // Content
2536
+ "textContent",
2537
+ "innerText",
2538
+ // Form elements
2539
+ "value",
2540
+ "checked",
2541
+ "disabled",
2542
+ "selected",
2543
+ "type",
2544
+ "name",
2545
+ "placeholder",
2546
+ "readOnly",
2547
+ "required",
2548
+ "min",
2549
+ "max",
2550
+ "step",
2551
+ "pattern",
2552
+ // Dimensions & position
2553
+ "getBoundingClientRect",
2554
+ "offsetWidth",
2555
+ "offsetHeight",
2556
+ "offsetTop",
2557
+ "offsetLeft",
2558
+ "clientWidth",
2559
+ "clientHeight",
2560
+ "scrollWidth",
2561
+ "scrollHeight",
2562
+ "scrollTop",
2563
+ "scrollLeft",
2564
+ // Style
2565
+ "style",
2566
+ "hidden",
2567
+ // Focus & interaction
2568
+ "focus",
2569
+ "blur",
2570
+ "click",
2571
+ "scrollIntoView",
2572
+ "scrollTo",
2573
+ // Traversal (safe — returns elements, not window/document)
2574
+ "closest",
2575
+ "matches",
2576
+ "querySelector",
2577
+ "querySelectorAll",
2578
+ "children",
2579
+ "childElementCount",
2580
+ "firstElementChild",
2581
+ "lastElementChild",
2582
+ "nextElementSibling",
2583
+ "previousElementSibling"
2584
+ ]);
2585
+ function createSafeElProxy(el) {
2586
+ return new Proxy(el, {
2587
+ get(target, prop) {
2588
+ if (typeof prop === "symbol") return Reflect.get(target, prop);
2589
+ if (!SAFE_EL_PROPS.has(prop)) return void 0;
2590
+ const val = Reflect.get(target, prop);
2591
+ return typeof val === "function" ? val.bind(target) : val;
2592
+ },
2593
+ set(target, prop, value2) {
2594
+ if (typeof prop === "symbol") return false;
2595
+ if (!SAFE_EL_PROPS.has(prop)) return false;
2596
+ return Reflect.set(target, prop, value2);
2597
+ }
2598
+ });
2599
+ }
2600
+ function bindElement(el, scope, disposers) {
2601
+ const elMagics = {
2602
+ $el: createSafeElProxy(el),
2603
+ $dispatch: (name, detail) => {
2604
+ el.dispatchEvent(new CustomEvent(name, {
2605
+ bubbles: true,
2606
+ composed: true,
2607
+ // crosses Shadow DOM boundaries (important for <forma-stage>)
2608
+ detail
2609
+ }));
2610
+ }
2611
+ };
2612
+ scope = createChildScope(scope, elMagics);
2613
+ const known = getDirectives(el);
2614
+ const computedAttr = !known || known.has("data-computed") ? el.getAttribute("data-computed") : null;
2615
+ if (computedAttr) {
2616
+ const parts = computedAttr.split(/;\s*(?=\w+\s*=[^=])/);
2617
+ for (const part of parts) {
2618
+ const trimmed = part.trim();
2619
+ if (!trimmed) continue;
2620
+ const match = trimmed.match(RE_COMPUTED);
2621
+ if (match) {
2622
+ const name = match[1];
2623
+ const expr = match[2];
2624
+ const prevGetter = scope.getters[name];
2625
+ delete scope.getters[name];
2626
+ const evaluate = buildEvaluator(`{${expr}}`, scope);
2627
+ const getter = createComputed(evaluate);
2628
+ scope.getters[name] = getter;
2629
+ if (!prevGetter) {
2630
+ delete scope.setters[name];
2631
+ }
2632
+ }
2633
+ }
2634
+ }
2635
+ const textExpr = !known || known.has("data-text") ? el.getAttribute("data-text") : null;
2636
+ if (textExpr) {
2637
+ const evaluate = buildEvaluator(textExpr, scope);
2638
+ const dispose = internalEffect(() => {
2639
+ setElementTextFast(el, toTextValue(evaluate()));
2640
+ });
2641
+ disposers.push(dispose);
2642
+ }
2643
+ const showExpr = !known || known.has("data-show") ? el.getAttribute("data-show") : null;
2644
+ if (showExpr) {
2645
+ const evaluate = buildEvaluator(showExpr, scope);
2646
+ const transition = parseTransitionSpec(el);
2647
+ if (_debug) {
2648
+ const tag = el.tagName.toLowerCase();
2649
+ const cls = el.className ? `.${String(el.className).split(" ")[0]}` : "";
2650
+ dbg(`bindElement: data-show="${showExpr}" on <${tag}${cls}>`);
2651
+ }
2652
+ let initialized = false;
2653
+ const dispose = internalEffect(() => {
2654
+ const visible = !!evaluate();
2655
+ if (_debug) dbg(`data-show effect: "${showExpr}" \u2192 ${visible}`);
2656
+ applyShowVisibility(el, visible, transition, !initialized);
2657
+ initialized = true;
2658
+ });
2659
+ disposers.push(dispose);
2660
+ if (transition) {
2661
+ disposers.push(() => clearTransitionState(el));
2662
+ }
2663
+ }
2664
+ const ifExpr = !known || known.has("data-if") ? el.getAttribute("data-if") : null;
2665
+ if (ifExpr) {
2666
+ const evaluate = buildEvaluator(ifExpr, scope);
2667
+ const transition = parseTransitionSpec(el);
2668
+ const placeholder = document.createComment("forma-if");
2669
+ const parent = el.parentNode;
2670
+ let inserted = true;
2671
+ let initialized = false;
2672
+ const dispose = internalEffect(() => {
2673
+ const show = !!evaluate();
2674
+ if (show && !inserted) {
2675
+ clearTransitionState(el);
2676
+ el.removeAttribute("data-forma-leaving");
2677
+ if (initialized && transition) {
2678
+ transitionInsert(el, parent, placeholder, transition);
2679
+ } else {
2680
+ parent?.insertBefore(el, placeholder);
2681
+ }
2682
+ inserted = true;
2683
+ } else if (!show && inserted) {
2684
+ if (initialized && transition) {
2685
+ transitionRemove(el, transition, () => {
2686
+ if (el.parentNode) {
2687
+ parent?.insertBefore(placeholder, el);
2688
+ el.remove();
2689
+ }
2690
+ });
2691
+ } else {
2692
+ parent?.insertBefore(placeholder, el);
2693
+ el.remove();
2694
+ }
2695
+ inserted = false;
2696
+ }
2697
+ initialized = true;
2698
+ });
2699
+ disposers.push(dispose);
2700
+ if (transition) {
2701
+ disposers.push(() => clearTransitionState(el));
2702
+ }
2703
+ }
2704
+ const modelExpr = !known || known.has("data-model") ? el.getAttribute("data-model") : null;
2705
+ if (modelExpr) {
2706
+ const prop = modelExpr.replace(RE_STRIP_BRACES, "").trim();
2707
+ const getter = scope.getters[prop];
2708
+ const setter = scope.setters[prop];
2709
+ if (getter && setter) {
2710
+ const input = el;
2711
+ const dispose = internalEffect(() => {
2712
+ const val = getter();
2713
+ if (input.type === "checkbox") {
2714
+ input.checked = !!val;
2715
+ } else {
2716
+ input.value = String(val ?? "");
2717
+ }
2718
+ });
2719
+ disposers.push(dispose);
2720
+ const event = input.type === "checkbox" ? "change" : "input";
2721
+ const onModelInput = () => {
2722
+ if (input.type === "checkbox") {
2723
+ setter(input.checked);
2724
+ } else if (input.type === "number" || input.type === "range") {
2725
+ setter(Number(input.value));
2726
+ } else {
2727
+ setter(input.value);
2728
+ }
2729
+ };
2730
+ input.addEventListener(event, onModelInput);
2731
+ disposers.push(() => {
2732
+ input.removeEventListener(event, onModelInput);
2733
+ });
2734
+ }
2735
+ }
2736
+ const hasColonDirectives = !known || hasAnyPrefix(known, "data-on:", "data-class:", "data-bind:");
2737
+ const attrs = el.attributes;
2738
+ if (hasColonDirectives) for (let i = 0; i < attrs.length; i++) {
2739
+ const attr = attrs[i];
2740
+ const name = attr.name;
2741
+ if (name.startsWith("data-on:")) {
2742
+ const event = name.slice(8);
2743
+ const built = buildHandler(attr.value, scope);
2744
+ const handler = built.handler;
2745
+ if (_debug) {
2746
+ const tag = el.tagName.toLowerCase();
2747
+ const id = el.id ? `#${el.id}` : "";
2748
+ const cls = el.className ? `.${String(el.className).split(" ")[0]}` : "";
2749
+ dbg(`bindElement: data-on:${event}="${attr.value}" on <${tag}${id}${cls}>`);
2750
+ }
2751
+ if (!built.supported) {
2752
+ el.setAttribute("data-forma-handler-error", "unsupported");
2753
+ } else if (el.hasAttribute("data-forma-handler-error")) {
2754
+ el.removeAttribute("data-forma-handler-error");
2755
+ }
2756
+ if (_debug) {
2757
+ const attrVal = attr.value;
2758
+ const tracedHandler = (e) => {
2759
+ dbg(`HANDLER FIRED: data-on:${event}="${attrVal}"`, "isTrusted:", e.isTrusted);
2760
+ handler(e);
2761
+ };
2762
+ el.addEventListener(event, tracedHandler);
2763
+ disposers.push(() => {
2764
+ el.removeEventListener(event, tracedHandler);
2765
+ });
2766
+ } else {
2767
+ el.addEventListener(event, handler);
2768
+ disposers.push(() => {
2769
+ el.removeEventListener(event, handler);
2770
+ });
2771
+ }
2772
+ } else if (name.startsWith("data-class:")) {
2773
+ const cls = name.slice(11);
2774
+ const evaluate = buildEvaluator(attr.value, scope);
2775
+ const dispose = internalEffect(() => {
2776
+ el.classList.toggle(cls, !!evaluate());
2777
+ });
2778
+ disposers.push(dispose);
2779
+ } else if (name.startsWith("data-bind:")) {
2780
+ const attrName = name.slice(10);
2781
+ const evaluate = buildEvaluator(attr.value, scope);
2782
+ const dispose = internalEffect(() => {
2783
+ const val = evaluate();
2784
+ if (val == null || val === false) {
2785
+ el.removeAttribute(attrName);
2786
+ } else {
2787
+ el.setAttribute(attrName, String(val));
2788
+ }
2789
+ });
2790
+ disposers.push(dispose);
2791
+ }
2792
+ }
2793
+ const persistExpr = !known || known.has("data-persist") ? el.getAttribute("data-persist") : null;
2794
+ if (persistExpr) {
2795
+ const prop = persistExpr.replace(RE_STRIP_BRACES, "").trim();
2796
+ const getter = scope.getters[prop];
2797
+ const setter = scope.setters[prop];
2798
+ if (getter && setter) {
2799
+ const key = "forma:" + prop;
2800
+ try {
2801
+ const saved = localStorage.getItem(key);
2802
+ if (saved !== null) setter(JSON.parse(saved));
2803
+ } catch {
2804
+ }
2805
+ const dispose = internalEffect(() => {
2806
+ try {
2807
+ localStorage.setItem(key, JSON.stringify(getter()));
2808
+ } catch {
2809
+ }
2810
+ });
2811
+ disposers.push(dispose);
2812
+ }
2813
+ }
2814
+ const listExpr = !known || known.has("data-list") ? el.getAttribute("data-list") : null;
2815
+ if (listExpr) {
2816
+ const evaluate = buildEvaluator(listExpr, scope);
2817
+ const templateEl = el.children[0];
2818
+ if (templateEl) {
2819
+ let disposeCloneBindings2 = function(node) {
2820
+ const el2 = node;
2821
+ if (Array.isArray(el2.__formaDisposers)) {
2822
+ for (const d of el2.__formaDisposers) {
2823
+ try {
2824
+ d();
2825
+ } catch {
2826
+ }
2827
+ }
2828
+ delete el2.__formaDisposers;
2829
+ }
2830
+ }, createBoundClone2 = function(item, index) {
2831
+ const clone = cloneWithTemplateData(template, item);
2832
+ const childScope = createChildScope(scope, { item, index });
2833
+ const itemDisposers = [];
2834
+ bindElement(clone, childScope, itemDisposers);
2835
+ for (const desc of Array.from(clone.querySelectorAll("*"))) {
2836
+ bindElement(desc, childScope, itemDisposers);
2837
+ }
2838
+ clone.__formaDisposers = itemDisposers;
2839
+ return clone;
2840
+ }, updateBoundClone2 = function(node, item, index) {
2841
+ disposeCloneBindings2(node);
2842
+ updateTemplateData(node, item);
2843
+ const childScope = createChildScope(scope, { item, index });
2844
+ const itemDisposers = [];
2845
+ bindElement(node, childScope, itemDisposers);
2846
+ for (const desc of Array.from(node.querySelectorAll("*"))) {
2847
+ bindElement(desc, childScope, itemDisposers);
2848
+ }
2849
+ node.__formaDisposers = itemDisposers;
2850
+ };
2851
+ const template = templateEl.cloneNode(true);
2852
+ el.removeChild(templateEl);
2853
+ const keyAttr = template.getAttribute("data-key");
2854
+ const keyProp = keyAttr ? keyAttr.replace(RE_STRIP_ITEM_BRACES, "").trim() : null;
2855
+ const listTransition = parseTransitionSpec(el);
2856
+ let oldItems = [];
2857
+ let oldNodes = [];
2858
+ const listHooks = listTransition ? {
2859
+ onInsert: (node) => {
2860
+ const htmlEl = node;
2861
+ if (!htmlEl.setAttribute) return;
2862
+ const state = getTransitionState(htmlEl);
2863
+ state.token += 1;
2864
+ const token = state.token;
2865
+ if (state.cancel) state.cancel();
2866
+ state.cancel = runTransitionPhase(
2867
+ htmlEl,
2868
+ {
2869
+ base: listTransition.enter,
2870
+ from: listTransition.enterFrom,
2871
+ to: listTransition.enterTo,
2872
+ durationMs: listTransition.enterDurationMs
2873
+ },
2874
+ () => {
2875
+ const current = getTransitionState(htmlEl);
2876
+ if (current.token === token) current.cancel = null;
2877
+ }
2878
+ );
2879
+ },
2880
+ onBeforeRemove: (node, done) => {
2881
+ const htmlEl = node;
2882
+ if (!htmlEl.setAttribute) {
2883
+ done();
2884
+ return;
2885
+ }
2886
+ disposeCloneBindings2(node);
2887
+ transitionRemove(htmlEl, listTransition, () => {
2888
+ done();
2889
+ });
2890
+ }
2891
+ } : void 0;
2892
+ const dispose = internalEffect(() => {
2893
+ const rawItems = evaluate();
2894
+ if (!Array.isArray(rawItems)) {
2895
+ for (const n of oldNodes) {
2896
+ disposeCloneBindings2(n);
2897
+ el.removeChild(n);
2898
+ }
2899
+ oldItems = [];
2900
+ oldNodes = [];
2901
+ return;
2902
+ }
2903
+ if (listTransition) {
2904
+ const leavingNodes = el.querySelectorAll("[data-forma-leaving]");
2905
+ for (const ln of Array.from(leavingNodes)) {
2906
+ clearTransitionState(ln);
2907
+ ln.removeAttribute("data-forma-leaving");
2908
+ if (ln.parentNode) ln.parentNode.removeChild(ln);
2909
+ }
2910
+ }
2911
+ const prevNodes = new Set(oldNodes);
2912
+ if (keyProp) {
2913
+ const result = reconcileList(
2914
+ el,
2915
+ oldItems,
2916
+ rawItems,
2917
+ oldNodes,
2918
+ (item) => String(item?.[keyProp] ?? ""),
2919
+ (item) => {
2920
+ const idx = rawItems.indexOf(item);
2921
+ return createBoundClone2(item, idx);
2922
+ },
2923
+ (node, item) => {
2924
+ const idx = rawItems.indexOf(item);
2925
+ updateBoundClone2(node, item, idx);
2926
+ },
2927
+ void 0,
2928
+ // beforeNode
2929
+ listHooks
2930
+ );
2931
+ const nextNodes = new Set(result.nodes);
2932
+ for (const n of prevNodes) {
2933
+ if (!nextNodes.has(n)) {
2934
+ if (n.hasAttribute?.("data-forma-leaving")) continue;
2935
+ disposeCloneBindings2(n);
2936
+ }
2937
+ }
2938
+ oldItems = result.items;
2939
+ oldNodes = result.nodes;
2940
+ } else {
2941
+ const wrapped = rawItems.map((item, i) => ({ __idx: i, __item: item }));
2942
+ const oldWrapped = oldItems;
2943
+ const result = reconcileList(
2944
+ el,
2945
+ oldWrapped,
2946
+ wrapped,
2947
+ oldNodes,
2948
+ (w) => w.__idx,
2949
+ (w) => createBoundClone2(w.__item, w.__idx),
2950
+ (node, w) => updateBoundClone2(node, w.__item, w.__idx),
2951
+ void 0,
2952
+ // beforeNode
2953
+ listHooks
2954
+ );
2955
+ const nextNodes = new Set(result.nodes);
2956
+ for (const n of prevNodes) {
2957
+ if (!nextNodes.has(n)) {
2958
+ if (n.hasAttribute?.("data-forma-leaving")) continue;
2959
+ disposeCloneBindings2(n);
2960
+ }
2961
+ }
2962
+ oldItems = result.items;
2963
+ oldNodes = result.nodes;
2964
+ }
2965
+ });
2966
+ disposers.push(dispose);
2967
+ }
2968
+ }
2969
+ const fetchExpr = !known || known.has("data-fetch") ? el.getAttribute("data-fetch") : null;
2970
+ if (fetchExpr) {
2971
+ const arrowMatch = fetchExpr.match(RE_FETCH);
2972
+ if (arrowMatch) {
2973
+ const urlPart = arrowMatch[1].trim();
2974
+ const target = arrowMatch[2].trim();
2975
+ const modifiers = arrowMatch[3]?.trim() ?? "";
2976
+ let method = "GET";
2977
+ let url = urlPart;
2978
+ const methodMatch = urlPart.match(RE_FETCH_METHOD);
2979
+ if (methodMatch) {
2980
+ method = methodMatch[1].toUpperCase();
2981
+ url = methodMatch[2].trim();
2982
+ }
2983
+ let loadingTarget;
2984
+ let errorTarget;
2985
+ let interval;
2986
+ for (const mod of modifiers.split("|").filter(Boolean)) {
2987
+ const [k, v] = mod.split(":").map((s) => s.trim());
2988
+ if (k === "loading") loadingTarget = v;
2989
+ else if (k === "error") errorTarget = v;
2990
+ else if (k === "poll") interval = parseInt(v ?? "0", 10);
2991
+ }
2992
+ const [getTarget, setTarget] = createSignal(null);
2993
+ scope.getters[target] = getTarget;
2994
+ scope.setters[target] = setTarget;
2995
+ if (loadingTarget) {
2996
+ const [gl, sl] = createSignal(false);
2997
+ scope.getters[loadingTarget] = gl;
2998
+ scope.setters[loadingTarget] = sl;
2999
+ }
3000
+ if (errorTarget) {
3001
+ const [ge, se] = createSignal(null);
3002
+ scope.getters[errorTarget] = ge;
3003
+ scope.setters[errorTarget] = se;
3004
+ }
3005
+ const doFetch = () => {
3006
+ if (loadingTarget) scope.setters[loadingTarget](true);
3007
+ fetch(url, { method }).then((r) => r.json()).then((data) => {
3008
+ setTarget(data);
3009
+ if (loadingTarget) scope.setters[loadingTarget](false);
3010
+ }).catch((err) => {
3011
+ if (errorTarget) scope.setters[errorTarget](err.message);
3012
+ if (loadingTarget) scope.setters[loadingTarget](false);
3013
+ });
3014
+ };
3015
+ const fetchId = el.getAttribute("data-fetch-id");
3016
+ if (fetchId) {
3017
+ _refetchRegistry.set(fetchId, doFetch);
3018
+ disposers.push(() => _refetchRegistry.delete(fetchId));
3019
+ }
3020
+ doFetch();
3021
+ if (interval && interval > 0) {
3022
+ const id = setInterval(doFetch, interval);
3023
+ disposers.push(() => clearInterval(id));
3024
+ }
3025
+ }
3026
+ }
3027
+ }
3028
+ function hasDirective(el) {
3029
+ const attrs = el.attributes;
3030
+ for (let i = 0; i < attrs.length; i++) {
3031
+ const name = attrs[i].name;
3032
+ if (name.startsWith("data-text") || name.startsWith("data-show") || name.startsWith("data-if") || name.startsWith("data-model") || name.startsWith("data-computed") || name.startsWith("data-persist") || name.startsWith("data-list") || name.startsWith("data-fetch") || name.startsWith("data-on:") || name.startsWith("data-class:") || name.startsWith("data-bind:") || name.startsWith("data-transition")) {
3033
+ return true;
3034
+ }
3035
+ }
3036
+ return false;
3037
+ }
3038
+ var _directiveMap = null;
3039
+ function setDirectiveMap(map) {
3040
+ if (!map || Object.keys(map).length === 0) {
3041
+ _directiveMap = null;
3042
+ return;
3043
+ }
3044
+ _directiveMap = /* @__PURE__ */ new Map();
3045
+ for (const id in map) {
3046
+ _directiveMap.set(id, new Set(map[id]));
3047
+ }
3048
+ }
3049
+ function buildDirectiveSelector() {
3050
+ if (!_directiveMap || _directiveMap.size === 0) return null;
3051
+ if (_directiveMap.size > 200) return null;
3052
+ const parts = [];
3053
+ for (const id of _directiveMap.keys()) {
3054
+ parts.push(`[data-forma-id="${id}"]`);
3055
+ }
3056
+ return parts.join(",");
3057
+ }
3058
+ function getDirectives(el) {
3059
+ if (!_directiveMap) return null;
3060
+ const id = el.getAttribute("data-forma-id");
3061
+ if (!id) return null;
3062
+ return _directiveMap.get(id) ?? null;
3063
+ }
3064
+ function hasAnyPrefix(set, ...prefixes) {
3065
+ for (const entry of set) {
3066
+ for (const prefix of prefixes) {
3067
+ if (entry.startsWith(prefix)) return true;
3068
+ }
3069
+ }
3070
+ return false;
3071
+ }
3072
+ function mountScope(root) {
3073
+ if (root.__formaDisposers) {
3074
+ if (_debug) dbg("mountScope: SKIPPED (already mounted)");
3075
+ return;
3076
+ }
3077
+ const scope = initScope(root);
3078
+ const disposers = [];
3079
+ const refsMap = /* @__PURE__ */ new Map();
3080
+ const refEls = root.querySelectorAll("[data-ref]");
3081
+ for (let i = 0; i < refEls.length; i++) {
3082
+ const el = refEls[i];
3083
+ const name = el.getAttribute("data-ref");
3084
+ if (name) refsMap.set(name, el);
3085
+ }
3086
+ const rootRefName = root.getAttribute("data-ref");
3087
+ if (rootRefName) refsMap.set(rootRefName, root);
3088
+ scope.getters["$refs"] = () => new Proxy({}, {
3089
+ get(_, name) {
3090
+ return refsMap.get(name) ?? void 0;
3091
+ },
3092
+ has(_, name) {
3093
+ return refsMap.has(name);
3094
+ }
3095
+ });
3096
+ bindElement(root, scope, disposers);
3097
+ let boundCount = 0;
3098
+ const selector = buildDirectiveSelector();
3099
+ if (selector) {
3100
+ const targets = root.querySelectorAll(selector);
3101
+ for (let i = 0; i < targets.length; i++) {
3102
+ bindElement(targets[i], scope, disposers);
3103
+ boundCount++;
3104
+ }
3105
+ } else {
3106
+ const descendants = root.querySelectorAll("*");
3107
+ for (let i = 0; i < descendants.length; i++) {
3108
+ const el = descendants[i];
3109
+ if (hasDirective(el)) {
3110
+ bindElement(el, scope, disposers);
3111
+ boundCount++;
3112
+ }
3113
+ }
3114
+ }
3115
+ root.__formaDisposers = disposers;
3116
+ root.__formaScope = scope;
3117
+ root.__formaInitialState = root.getAttribute("data-forma-state") ?? "{}";
3118
+ if (_debug) dbg("mountScope: DONE \u2014", boundCount, "elements bound,", disposers.length, "disposers", selector ? "(targeted)" : "(full scan)");
3119
+ }
3120
+ function unmountScope(root) {
3121
+ const disposers = root.__formaDisposers;
3122
+ if (disposers) {
3123
+ for (const d of disposers) {
3124
+ try {
3125
+ d();
3126
+ } catch {
3127
+ }
3128
+ }
3129
+ delete root.__formaDisposers;
3130
+ delete root.__formaScope;
3131
+ delete root.__formaInitialState;
3132
+ }
3133
+ }
3134
+ var _observer = null;
3135
+ var ELEMENT_NODE = 1;
3136
+ var MUTATION_CHUNK_SIZE = 40;
3137
+ var _pendingMutations = [];
3138
+ var _drainingMutations = false;
3139
+ function processMutation(mutation) {
3140
+ for (let i = 0; i < mutation.removedNodes.length; i++) {
3141
+ const node = mutation.removedNodes[i];
3142
+ if (node.nodeType !== ELEMENT_NODE) continue;
3143
+ const el = node;
3144
+ if (el.hasAttribute("data-forma-state")) {
3145
+ if (_debug) dbg("MutationObserver: REMOVED scope");
3146
+ unmountScope(el);
3147
+ }
3148
+ const removed = el.querySelectorAll("[data-forma-state]");
3149
+ for (let j = 0; j < removed.length; j++) {
3150
+ unmountScope(removed[j]);
3151
+ }
3152
+ }
3153
+ for (let i = 0; i < mutation.addedNodes.length; i++) {
3154
+ const node = mutation.addedNodes[i];
3155
+ if (node.nodeType !== ELEMENT_NODE) continue;
3156
+ const el = node;
3157
+ if (el.closest("[data-forma-leaving]")) continue;
3158
+ if (el.hasAttribute("data-forma-state")) {
3159
+ if (_debug) dbg("MutationObserver: ADDED scope via mutation");
3160
+ mountScope(el);
3161
+ }
3162
+ const added = el.querySelectorAll("[data-forma-state]");
3163
+ if (_debug && added.length > 0) {
3164
+ dbg("MutationObserver: found", added.length, "nested scope(s) in added subtree");
3165
+ }
3166
+ for (let j = 0; j < added.length; j++) {
3167
+ const desc = added[j];
3168
+ if (desc.closest("[data-forma-leaving]")) continue;
3169
+ mountScope(desc);
3170
+ }
3171
+ }
3172
+ if (mutation.type === "attributes" && mutation.attributeName === "data-forma-state") {
3173
+ const target = mutation.target;
3174
+ unmountScope(target);
3175
+ if (target.hasAttribute("data-forma-state")) {
3176
+ mountScope(target);
3177
+ }
3178
+ }
3179
+ }
3180
+ async function drainMutationQueue() {
3181
+ try {
3182
+ while (_pendingMutations.length > 0) {
3183
+ const batch2 = _pendingMutations.splice(0, MUTATION_CHUNK_SIZE);
3184
+ for (let i = 0; i < batch2.length; i++) {
3185
+ processMutation(batch2[i]);
3186
+ }
3187
+ if (_pendingMutations.length > 0) {
3188
+ await yieldToMain();
3189
+ }
3190
+ }
3191
+ } finally {
3192
+ _drainingMutations = false;
3193
+ if (_pendingMutations.length > 0 && !_drainingMutations) {
3194
+ _drainingMutations = true;
3195
+ void drainMutationQueue();
3196
+ }
3197
+ }
3198
+ }
3199
+ function handleMutations(mutations) {
3200
+ if (_debug) dbg("MutationObserver: queued", mutations.length, "mutation(s)");
3201
+ _pendingMutations.push(...mutations);
3202
+ if (_drainingMutations) return;
3203
+ _drainingMutations = true;
3204
+ void drainMutationQueue();
3205
+ }
3206
+ function startObserver() {
3207
+ if (_observer) return;
3208
+ _observer = new MutationObserver(handleMutations);
3209
+ const target = document.body || document.documentElement;
3210
+ if (target) {
3211
+ _observer.observe(target, {
3212
+ childList: true,
3213
+ subtree: true,
3214
+ attributes: true,
3215
+ attributeFilter: ["data-forma-state"]
3216
+ });
3217
+ }
3218
+ }
3219
+ function stopObserver() {
3220
+ if (_observer) {
3221
+ _observer.disconnect();
3222
+ _observer = null;
3223
+ }
3224
+ }
3225
+ function initRuntime() {
3226
+ if (_autoContainment) {
3227
+ applyContainmentHints(document, { skipIfAlreadySet: true });
3228
+ }
3229
+ const stateRoots = document.querySelectorAll("[data-forma-state]");
3230
+ if (_debug) dbg("initRuntime: found", stateRoots.length, "scope(s)");
3231
+ for (const root of Array.from(stateRoots)) {
3232
+ mountScope(root);
3233
+ }
3234
+ startObserver();
3235
+ if (_debug) dbg("initRuntime: MutationObserver started");
3236
+ }
3237
+ function destroyRuntime() {
3238
+ stopObserver();
3239
+ const stateRoots = document.querySelectorAll("[data-forma-state]");
3240
+ for (const root of Array.from(stateRoots)) {
3241
+ unmountScope(root);
3242
+ }
3243
+ }
3244
+ function mount(el) {
3245
+ if (el.hasAttribute("data-forma-state")) {
3246
+ mountScope(el);
3247
+ }
3248
+ const descendants = el.querySelectorAll("[data-forma-state]");
3249
+ for (const desc of Array.from(descendants)) {
3250
+ mountScope(desc);
3251
+ }
3252
+ }
3253
+ function unmount(el) {
3254
+ if (el.hasAttribute("data-forma-state")) {
3255
+ unmountScope(el);
3256
+ }
3257
+ const descendants = el.querySelectorAll("[data-forma-state]");
3258
+ for (const desc of Array.from(descendants)) {
3259
+ unmountScope(desc);
3260
+ }
3261
+ }
3262
+ if (typeof document !== "undefined") {
3263
+ if (document.readyState === "loading") {
3264
+ document.addEventListener("DOMContentLoaded", initRuntime);
3265
+ } else {
3266
+ initRuntime();
3267
+ }
3268
+ }
3269
+ function setDebug(on) {
3270
+ _debug = on;
3271
+ }
3272
+ function setUnsafeEvalMode(mode) {
3273
+ if (_unsafeEvalMode === mode) return;
3274
+ _unsafeEvalMode = mode;
3275
+ if (mode === "locked-off") _allowUnsafeEval = false;
3276
+ if (mode === "locked-on") _allowUnsafeEval = true;
3277
+ if (mode === "mutable") _allowUnsafeEval = true;
3278
+ scopeExpressionCache = /* @__PURE__ */ new WeakMap();
3279
+ scopeHandlerCache = /* @__PURE__ */ new WeakMap();
3280
+ }
3281
+ function setUnsafeEval(on) {
3282
+ if (_unsafeEvalMode !== "mutable") {
3283
+ dbg(
3284
+ `setUnsafeEval ignored (mode=${_unsafeEvalMode}); unsafe fallback is locked`
3285
+ );
3286
+ return;
3287
+ }
3288
+ if (_allowUnsafeEval === on) return;
3289
+ _allowUnsafeEval = on;
3290
+ scopeExpressionCache = /* @__PURE__ */ new WeakMap();
3291
+ scopeHandlerCache = /* @__PURE__ */ new WeakMap();
3292
+ }
3293
+ function getUnsafeEvalMode() {
3294
+ return _unsafeEvalMode;
3295
+ }
3296
+ function setDiagnostics(on) {
3297
+ _diagnosticsEnabled = on;
3298
+ }
3299
+ function getDiagnostics() {
3300
+ return Array.from(diagnostics.values()).map((d) => ({ ...d }));
3301
+ }
3302
+ function clearDiagnostics() {
3303
+ diagnostics.clear();
3304
+ }
3305
+ function getScopes() {
3306
+ const roots = document.querySelectorAll("[data-forma-state]");
3307
+ const result = [];
3308
+ for (const root of Array.from(roots)) {
3309
+ if (root.closest("[data-forma-leaving]")) continue;
3310
+ const scope = root.__formaScope;
3311
+ const initialJSON = root.__formaInitialState;
3312
+ if (!scope) continue;
3313
+ const values = {};
3314
+ for (const key of Object.keys(scope.getters)) {
3315
+ const val = scope.getters[key]();
3316
+ values[key] = { value: val, type: typeof val };
3317
+ }
3318
+ result.push({
3319
+ element: root,
3320
+ id: root.getAttribute("data-forma-id") || root.id || root.tagName.toLowerCase(),
3321
+ values,
3322
+ initialJSON: initialJSON ?? "{}"
3323
+ });
3324
+ }
3325
+ return result;
3326
+ }
3327
+ function setScopeValue(element, key, value2) {
3328
+ const scope = element.__formaScope;
3329
+ if (!scope?.setters[key]) return;
3330
+ batch(() => {
3331
+ scope.setters[key](value2);
3332
+ });
3333
+ }
3334
+ function resetScope(element) {
3335
+ const scope = element.__formaScope;
3336
+ const initialJSON = element.__formaInitialState;
3337
+ if (!scope || !initialJSON) return;
3338
+ const initial = parseState(initialJSON);
3339
+ batch(() => {
3340
+ for (const [key, val] of Object.entries(initial)) {
3341
+ scope.setters[key]?.(val);
3342
+ }
3343
+ });
3344
+ }
3345
+ var _reconciler = null;
3346
+ function getReconciler() {
3347
+ if (!_reconciler) {
3348
+ _reconciler = createReconciler({
3349
+ mountScope,
3350
+ unmountScope,
3351
+ disconnectObserver() {
3352
+ if (_observer) {
3353
+ _observer.disconnect();
3354
+ }
3355
+ },
3356
+ reconnectObserver() {
3357
+ if (_observer) {
3358
+ const target = document.body || document.documentElement;
3359
+ if (target) {
3360
+ _observer.observe(target, {
3361
+ childList: true,
3362
+ subtree: true,
3363
+ attributes: true,
3364
+ attributeFilter: ["data-forma-state"]
3365
+ });
3366
+ }
3367
+ }
3368
+ },
3369
+ batch
3370
+ });
3371
+ }
3372
+ return _reconciler;
3373
+ }
3374
+ function reconcile(container, html) {
3375
+ getReconciler()(container, html);
3376
+ }
3377
+
3378
+ exports.applyContainmentHints = applyContainmentHints;
3379
+ exports.clearDiagnostics = clearDiagnostics;
3380
+ exports.destroyRuntime = destroyRuntime;
3381
+ exports.getDiagnostics = getDiagnostics;
3382
+ exports.getScopes = getScopes;
3383
+ exports.getUnsafeEvalMode = getUnsafeEvalMode;
3384
+ exports.initRuntime = initRuntime;
3385
+ exports.mount = mount;
3386
+ exports.reconcile = reconcile;
3387
+ exports.resetScope = resetScope;
3388
+ exports.setDebug = setDebug;
3389
+ exports.setDiagnostics = setDiagnostics;
3390
+ exports.setDirectiveMap = setDirectiveMap;
3391
+ exports.setScopeValue = setScopeValue;
3392
+ exports.setUnsafeEval = setUnsafeEval;
3393
+ exports.setUnsafeEvalMode = setUnsafeEvalMode;
3394
+ exports.unmount = unmount;
3395
+ exports.yieldToMain = yieldToMain;
3396
+
3397
+ return exports;
3398
+
3399
+ })({});
3400
+ //# sourceMappingURL=formajs-runtime-hardened.global.js.map
2
3401
  //# sourceMappingURL=formajs-runtime-hardened.global.js.map