haori 0.20.1 → 0.22.0

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.
package/dist/haori.cjs.js CHANGED
@@ -1,21 +1,21 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const G=class G{static isEnabled(){return G.devMode}static enable(){G.devMode=!0}static disable(){G.devMode=!1}static set(t){G.devMode=t}};G.devMode=!1;let H=G;const ct="embedded";function Et(p){return p==="embedded"||p==="demo"}function kt(p){return p===null?null:Et(p)?p:ct}const L=class L{static get runtime(){return L._runtime}static setRuntime(t){L._runtime=Et(t)?t:ct}static detect(){try{const t=document.currentScript||document.querySelector('script[src*="haori"]');if(t instanceof HTMLScriptElement){const r=t.getAttribute("data-prefix")||L._prefix;L._prefix=r.endsWith("-")?r:r+"-";const i=kt(t.getAttribute("data-runtime"));i!==null&&(L._runtime=i)}if(t instanceof HTMLScriptElement&&t.hasAttribute(`${L._prefix}dev`)){H.set(!0);return}const e=window.location.hostname;if(e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"||e.endsWith(".local")){H.set(!0);return}H.set(!1)}catch{}}static get prefix(){return L._prefix}};L._prefix="data-",L._runtime=ct;let u=L;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",u.detect):u.detect();class m{static info(t,...e){H.isEnabled()&&console.log&&console.log(t,...e)}static warn(t,...e){H.isEnabled()&&console.warn&&console.warn(t,...e)}static error(t,...e){console.error(t,...e)}}const Pt="yyyy/MM/dd HH:mm",It="en-US",vt=1e4;function q(p){return String(p).padStart(2,"0")}function At(p,t=Pt){if(p==null||p==="")return"";const e=p instanceof Date?p:new Date(p);if(Number.isNaN(e.getTime()))return"";const r={yyyy:String(e.getFullYear()).padStart(4,"0"),yy:q(e.getFullYear()%100),MM:q(e.getMonth()+1),M:String(e.getMonth()+1),dd:q(e.getDate()),d:String(e.getDate()),HH:q(e.getHours()),H:String(e.getHours()),mm:q(e.getMinutes()),ss:q(e.getSeconds())};return t.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(i,n)=>n!==void 0?n===""?"'":n:r[i])}function St(p,t){if(p==null)return"";let e;if(typeof p=="number")e=p;else{const i=String(p).trim();if(i==="")return"";e=Number(i)}if(!Number.isFinite(e))return"";const r={};if(t!==void 0&&Number.isFinite(t)){const i=Math.max(0,Math.trunc(t));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(It,r).format(e)}function wt(p,t,e){let r,i,n;if(t===void 0?(r=0,i=p,n=1):(r=p,i=t,n=e===void 0?1:e),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<vt;a+=n)s.push(a);else for(let a=r;a>i&&s.length<vt;a+=n)s.push(a);return s}function Tt(p,t,e={}){const r=Math.trunc(Number(p));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(t))||0,0),r-1),n=Math.max(0,Math.trunc(e.window??2)),s=Math.max(0,Math.trunc(e.boundary??1)),a=new Set;for(let h=0;h<s&&h<r;h+=1)a.add(h);for(let h=Math.max(0,r-s);h<r;h+=1)a.add(h);for(let h=Math.max(0,i-n);h<=Math.min(r-1,i+n);h+=1)a.add(h);const o=Array.from(a).sort((h,g)=>h-g),l=[];let c=null;for(const h of o){if(c!==null&&h-c>1)if(h-c===2){const g=c+1;l.push({page:g,label:g+1,active:g===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:h,label:h+1,active:h===i,ellipsis:!1}),c=h}return l}const Ct=/^(\d{4})-(\d{1,2})$/,Bt=1200;function tt(p,t){const e=Number(p);return Number.isFinite(e)?Math.trunc(e):t}function ot(p,t){if(typeof p!="string")return"";const e=Ct.exec(p.trim());if(!e)return"";const r=Number(e[1]),i=Number(e[2]);if(i<1||i>12)return"";const n=Number.isFinite(t)?Math.trunc(t):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${q(o)}`}function $t(p){if(typeof p=="string"&&p.trim()!=="")return ot(p,0);const t=new Date;return`${String(t.getFullYear()).padStart(4,"0")}-${q(t.getMonth()+1)}`}function Dt(p,t){const e=Math.trunc(Number(p));if(!Number.isFinite(e)||e<0)return[];const r=$t(t);if(r==="")return[];const i=Math.min(e,Bt),n=[];for(let s=0;s<=i;s+=1){const a=ot(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function Rt(p,t){const e={start:0,end:0,total:0,empty:!0};if(!p||typeof p!="object")return e;const r=p,i=tt(r.totalElements??r.totalCount,0);if(i<=0)return e;const n=Math.max(0,tt(r.number,0)),s=Math.max(0,tt(r.size,0)),a=n*s,o=Math.min(a+1,i);let l;if(t!==void 0&&Number.isFinite(t))l=Math.max(0,Math.trunc(t));else{const h=tt(r.numberOfElements,NaN);l=Number.isFinite(h)?h:Math.min(s,i-a)}const c=Math.min(a+l,i);return{start:o,end:Math.max(c,o),total:i,empty:!1}}function Nt(p,t,e){if(!Array.isArray(p)||p.length===0)return null;const r=String(e),i=p.find(n=>n!=null&&String(n[t])===r);return i===void 0?null:i}function Ft(p,t){if(!Array.isArray(p))return 0;let e=0;for(const r of p){const i=t==null?r:r?.[t];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(e+=n)}return e}const Ot=Object.freeze({date:At,number:St,pages:Tt,range:wt,monthAdd:ot,monthRange:Dt,pageSummary:Rt,findBy:Nt,sum:Ft}),B=class B{static getForbiddenBindingValues(){const t=globalThis,e=[t,t.window,t.document,t.navigator,t.history,t.localStorage,t.sessionStorage,t.fetch,t.Function,t.setTimeout,t.setInterval,t.requestAnimationFrame,t.alert,t.confirm,t.prompt];return t.window?.location&&e.push(t.window.location),e.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(t){const e=new Set(t);return this.FORBIDDEN_NAMES.filter(r=>!e.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
- `)}static detectForbiddenIdentifiers(t){return this.FORBIDDEN_NAMES.filter(e=>new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`).test(t))}static evaluate(t,e={}){return this.evaluateDetailed(t,e).value}static evaluateDetailed(t,e={}){if(this.scheduleForbiddenBindingValueCacheReset(),t.trim()==="")return m.warn("[Haori]",t,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(t)){const o=this.detectDisallowedKeywords(t);if(o.length>0){const l=o.some(c=>c==="function"||c==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",t,"Expression uses disallowed keyword(s): "+o.join(", ")+"."+l)}else m.warn("[Haori]",t,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}if(this.containsForbiddenKeys(e))return m.warn("[Haori]",e,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(e,new WeakSet,r))return m.warn("[Haori]",e,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i=t.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),n=this.BUILTIN_REFERENCE_PATTERN.test(i);n&&this.BUILTIN_NAMESPACE in e&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const s=n?{...e,[this.BUILTIN_NAMESPACE]:this.BUILTIN_HELPERS}:{...e},a=this.canAttemptMissingIdentifierRecovery(t);for(let o=0;o<=this.MAX_IDENTIFIER_RECOVERY_COUNT;o+=1){const l=this.prepareEvaluator(t,s);if(l.compileFailed||l.evaluator===null)return{value:null,unresolvedReference:!1};try{const c=[],h=this.wrapBoundValues(s);return l.bindKeys.forEach(g=>{c.push(h[g])}),{value:this.withBlockedPropertyAccess(()=>l.evaluator(...c)),unresolvedReference:!1}}catch(c){if(a&&c instanceof ReferenceError){const g=this.extractMissingIdentifier(c);if(g!==null&&this.canRecoverMissingIdentifier(g,s)){s[g]=void 0;continue}}const h=this.detectForbiddenIdentifiers(t);return h.length>0&&m.warn("[Haori]","Expression references blocked identifier(s): "+h.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",t),m.error("[Haori]","Expression evaluation error:",t,c),c instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",t,s),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(t,e){const r=Object.keys(e).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${t}:${r.join(",")}`;let n=this.EXPRESSION_CACHE.get(i)||null;if(n!==null)return{bindKeys:r,evaluator:n,compileFailed:!1};const s=this.buildAssignments(r),a=s?`"use strict";
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const J=class J{static isEnabled(){return J.devMode}static enable(){J.devMode=!0}static disable(){J.devMode=!1}static set(e){J.devMode=e}};J.devMode=!1;let L=J;const de="embedded";function Se(f){return f==="embedded"||f==="demo"}function Oe(f){return f===null?null:Se(f)?f:de}const U=class U{static get runtime(){return U._runtime}static setRuntime(e){U._runtime=Se(e)?e:de}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||U._prefix;U._prefix=r.endsWith("-")?r:r+"-";const i=Oe(e.getAttribute("data-runtime"));i!==null&&(U._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${U._prefix}dev`)){L.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){L.set(!0);return}L.set(!1)}catch{}}static get prefix(){return U._prefix}};U._prefix="data-",U._runtime=de;let c=U;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c.detect):c.detect();class m{static info(e,...t){L.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){L.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const He="yyyy/MM/dd HH:mm",Le="en-US",Ee=1e4;function W(f){return String(f).padStart(2,"0")}function we(f,e,t,r,i,n){return{yyyy:String(f).padStart(4,"0"),yy:W(f%100),MM:W(e),M:String(e),dd:W(t),d:String(t),HH:W(r),H:String(r),mm:W(i),ss:W(n)}}function Ue(f,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(f)}catch{return null}const r={};for(const h of t)h.type!=="literal"&&(r[h.type]=h.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),l=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(l)?null:we(i,n,s,a,o,l)}function Te(f,e=He,t){if(f==null||f==="")return"";const r=f instanceof Date?f:new Date(f);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=Ue(r,t.trim()),i===null)return""}else i=we(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}function Re(f,e){if(f==null)return"";let t;if(typeof f=="number")t=f;else{const i=String(f).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(Le,r).format(t)}function De(f,e,t){let r,i,n;if(e===void 0?(r=0,i=f,n=1):(r=f,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<Ee;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ee;a+=n)s.push(a);return s}function Fe(f,e,t={}){const r=Math.trunc(Number(f));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let u=0;u<s&&u<r;u+=1)a.add(u);for(let u=Math.max(0,r-s);u<r;u+=1)a.add(u);for(let u=Math.max(0,i-n);u<=Math.min(r-1,i+n);u+=1)a.add(u);const o=Array.from(a).sort((u,p)=>u-p),l=[];let h=null;for(const u of o){if(h!==null&&u-h>1)if(u-h===2){const p=h+1;l.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:u,label:u+1,active:u===i,ellipsis:!1}),h=u}return l}const Ve=/^(\d{4})-(\d{1,2})$/,je=1200;function re(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function ue(f,e){if(typeof f!="string")return"";const t=Ve.exec(f.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${W(o)}`}function qe(f){if(typeof f=="string"&&f.trim()!=="")return ue(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${W(e.getMonth()+1)}`}function Ne(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=qe(e);if(r==="")return[];const i=Math.min(t,je),n=[];for(let s=0;s<=i;s+=1){const a=ue(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function Me(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=re(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,re(r.number,0)),s=Math.max(0,re(r.size,0)),a=n*s,o=Math.min(a+1,i);let l;if(e!==void 0&&Number.isFinite(e))l=Math.max(0,Math.trunc(e));else{const u=re(r.numberOfElements,NaN);l=Number.isFinite(u)?u:Math.min(s,i-a)}const h=Math.min(a+l,i);return{start:o,end:Math.max(h,o),total:i,empty:!1}}function xe(f,e,t){if(!Array.isArray(f)||f.length===0)return null;const r=String(t),i=f.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function Pe(f,e){if(!Array.isArray(f))return 0;let t=0;for(const r of f){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ke(f,e){return e==null||f==null?String(f):String(f[e])}function Ie(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const n=ke(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function Ce(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const n=ke(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const We=Object.freeze({date:Te,number:Re,pages:Fe,range:De,monthAdd:ue,monthRange:Ne,pageSummary:Me,findBy:xe,sum:Pe,distinct:Ie,groupBy:Ce}),B=class B{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
+ `)}static detectForbiddenIdentifiers(e){return this.FORBIDDEN_NAMES.filter(t=>new RegExp(`(^|[^\\w$.])${t}(?![\\w$])`).test(e))}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const l=this.detectDisallowedKeywords(e);if(l.length>0){const h=l.some(u=>u==="function"||u==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+l.join(", ")+"."+h)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const l=r.join(",");this.loggedForbiddenKeySignatures.has(l)||(this.loggedForbiddenKeySignatures.add(l),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const l of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(l)||(a[l]=t[l]);s&&(a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS);const o=this.canAttemptMissingIdentifierRecovery(e);for(let l=0;l<=this.MAX_IDENTIFIER_RECOVERY_COUNT;l+=1){const h=this.prepareEvaluator(e,a);if(h.compileFailed||h.evaluator===null)return{value:null,unresolvedReference:!1};try{const u=[],p=this.wrapBoundValues(a);return h.bindKeys.forEach(b=>{u.push(p[b])}),{value:this.withBlockedPropertyAccess(()=>h.evaluator(...u)),unresolvedReference:!1}}catch(u){if(o&&u instanceof ReferenceError){const b=this.extractMissingIdentifier(u);if(b!==null&&this.canRecoverMissingIdentifier(b,a)){a[b]=void 0;continue}}const p=this.detectForbiddenIdentifiers(e);return p.length>0&&m.warn("[Haori]","Expression references blocked identifier(s): "+p.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",e),m.error("[Haori]","Expression evaluation error:",e,u),u instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t){const r=Object.keys(t).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${e}:${r.join(",")}`;let n=this.EXPRESSION_CACHE.get(i)||null;if(n!==null)return{bindKeys:r,evaluator:n,compileFailed:!1};const s=this.buildAssignments(r),a=s?`"use strict";
3
3
  ${s};
4
- return (${t});`:`"use strict";
5
- return (${t});`;try{return n=new Function(...r,a),this.EXPRESSION_CACHE.set(i,n),{bindKeys:r,evaluator:n,compileFailed:!1}}catch(o){return m.error("[Haori]","Failed to compile expression:",t,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(t){return String(t.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?e[t]===void 0&&!(t in e):!1}static canAttemptMissingIdentifierRecovery(t){return t.includes("?.")||t.includes("??")||t.includes("||")||t.includes("&&")}static containsDangerousPatterns(t){return this.hasAllowedSyntax(t)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(t)):!0}static detectDisallowedKeywords(t){const e=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(t)&&e.push(r)}),e}static hasAllowedSyntax(t){const e=this.tokenizeExpression(t);if(e===null||e.length===0)return!1;const r=[];let i=null;for(let n=0;n<e.length;n++){const s=e[n],a=e[n+1]||null,o=r[r.length-1]||null,l=e[n-2]||null,c=e[n-3]||null;if(this.startsObjectKey(o,i,l,c)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(t){const e=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<t.length;){const s=t[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(t[n+1]==="/"||t[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(t,n);if(o===null)return null;e.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>t.startsWith(o,n));if(a){e.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(t,n);e.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(t,n);e.push(o.token),n=o.nextIndex;continue}if(i.has(s)){e.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return e}static readStringToken(t,e){const r=t[e];let i=e+1;for(;i<t.length;){const n=t[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:t.slice(e,i+1),position:e},nextIndex:i+1};i+=1}return null}static readNumberToken(t,e){let r=e;for(;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;if(t[r]===".")for(r+=1;r<t.length&&/[0-9_]/.test(t[r]);)r+=1;return{token:{type:"number",value:t.slice(e,r),position:e},nextIndex:r}}static readIdentifierToken(t,e){let r=e;for(;r<t.length&&/[A-Za-z0-9_$]/.test(t[r]);)r+=1;return{token:{type:"identifier",value:t.slice(e,r),position:e},nextIndex:r}}static startsMemberAccess(t){return t===null?!1:t.type==="identifier"||t.type==="number"?!0:t.value===")"||t.value==="]"||t.value==="?."}static startsObjectKey(t,e,r,i){return t!=="object"?!1:e?.value==="{"||e?.value===","||e?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(e.value)&&(r?.value==="{"||r?.value===",")?!0:e?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(t){return t.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(e,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(e,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(e,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(t){const e=new WeakMap,r={};return Object.entries(t).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,e)}),r}static wrapBoundValue(t,e){if(!this.shouldWrapValue(t))return t;const r=t,i=e.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,e)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,e)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),e)});return e.set(r,n),n}static shouldWrapValue(t){if(typeof t=="function")return!0;if(t===null||typeof t!="object")return!1;if(Array.isArray(t))return!0;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}static withBlockedPropertyAccess(t){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return t()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(t){return t===null||typeof t!="object"?!1:typeof t.next=="function"}static containsForbiddenKeys(t){if(!t||typeof t!="object")return!1;for(const e of Object.keys(t))if(this.FORBIDDEN_BINDING_NAMES.has(e))return!0;return!1}static containsForbiddenBindingValues(t,e=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!t||typeof t!="object")return!1;const i=this.forbiddenBindingValueCache.get(t);if(i!==void 0)return i;if(e.has(t))return!1;if(e.add(t),r.has(t))return this.forbiddenBindingValueCache.set(t,!0),!0;for(const n of Object.values(t)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(t,!0),!0;continue}if(this.containsForbiddenBindingValues(n,e,r))return this.forbiddenBindingValueCache.set(t,!0),!0}return this.forbiddenBindingValueCache.set(t,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...Ot},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(t=>!B.REBINDABLE_FORBIDDEN_NAMES.has(t)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class dt{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(t,e=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:t,timestamp:performance.now(),promise:n,resolve:r,reject:i};return e?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const t=performance.now();for(;this.queue.length>0;){const e=this.queue.shift();if(!e)return;try{const r=await e.task();e.resolve(r)}catch(r){e.reject(r),m.error("[Haori]",`Task ${e.timestamp} failed:`,r)}if(performance.now()-t>this.MAX_BUDGET)break}}catch(t){m.error("[Haori]","Error processing queue:",t)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const t=this.queue.map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}async waitForIdle(t=1e3){let e=0,r=0;for(;e<2&&r<t;)this.processing||this.queue.length>0?(await this.wait(),e=0):e+=1,await dt.nextTick(),r+=1}static nextTick(){return new Promise(t=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}}const pt=class pt{static enqueue(t,e=!1){return this.ASYNC_QUEUE.enqueue(t,e)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(t=1e3){return this.ASYNC_QUEUE.waitForIdle(t)}};pt.ASYNC_QUEUE=new dt;let M=pt;const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([t,e])=>({elementId:t,tagName:e.tagName,attributes:[...e.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...e.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((t,e)=>{const r=t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0);return e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(t,e,r){if(!H.isEnabled()||!t||e.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(t.element);if(t.kind==="attribute"){const s=N.getOrCreateCounter(i.attributes,t.rawName,t.template);N.updateCounter(s,e,r);return}const n=N.getOrCreateCounter(i.texts,String(t.childIndex),t.template);N.updateCounter(n,e,r)}static ensureGlobalAccess(){if(!H.isEnabled())return;const t=globalThis;t[N.GLOBAL_KEY]===void 0&&(t[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(t){const e=N.createElementId(t),r=N.ELEMENT_STORES.get(e);if(r)return r;const i={tagName:t.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(e,i),i}static getOrCreateCounter(t,e,r){const i=t.get(e);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return t.set(e,n),n}static getOrCreatePlaceholder(t,e){const r=t.get(e);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return t.set(e,i),i}static updateCounter(t,e,r){t.calls+=1,t.totalDurationMs+=r,t.maxDurationMs=Math.max(t.maxDurationMs,r),e.forEach(i=>{const n=N.getOrCreatePlaceholder(t.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(t){return[...t.entries()].map(([e,r])=>({expression:e,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((e,r)=>r.calls!==e.calls?r.calls-e.calls:r.totalDurationMs-e.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(t){const e=N.now();return{value:t(),durationMs:N.now()-e}}static createElementId(t){const e=[];let r=t;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,e.unshift(i);break}const s=r.getAttribute(`${u.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),e.unshift(i),r=a}return e.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let rt=N;const Y=class Y{constructor(t){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=t,Y.FRAGMENT_CACHE.set(t,this)}static get(t){if(t==null)return null;if(Y.FRAGMENT_CACHE.has(t))return Y.FRAGMENT_CACHE.get(t);let e;switch(t.nodeType){case Node.ELEMENT_NODE:e=new k(t);break;case Node.TEXT_NODE:e=new U(t);break;case Node.COMMENT_NODE:e=new ft(t);break;default:return m.warn("[Haori]","Unsupported node type:",t.nodeType),null}return e}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode===t.getTarget()&&t.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{t.skipMutationNodes=e})}else{const t=this.target.parentNode;if(t)return M.enqueue(()=>{this.target.parentNode===t&&t.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const t=this.parent,e=t.skipMutationNodes;return M.enqueue(()=>{t.skipMutationNodes=!0,this.target.parentNode!==t.getTarget()&&t.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{t.skipMutationNodes=e})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(t){this.mounted=t}remove(t=!0){return this.parent&&this.parent.removeChild(this),Y.FRAGMENT_CACHE.delete(this.target),t?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(t){this.parent=t}};Y.FRAGMENT_CACHE=new WeakMap;let T=Y;const W=class W extends T{constructor(t){super(t),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=t.getAttribute(`${u.prefix}bind`),t.getAttributeNames().forEach(e=>{const r=t.getAttribute(e);if(r!==null&&!this.attributeMap.has(e)){const i=new it(e,r);this.attributeMap.set(e,i)}}),t.childNodes.forEach(e=>{const r=T.get(e);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(t=>t instanceof W)}pushChild(t){this.children.push(t),t.setParent(this)}removeChild(t){const e=this.children.indexOf(t);if(e<0){m.warn("[Haori]","Child fragment not found.",t);return}this.children.splice(e,1),t.setParent(null)}clone(){const t=new W(this.target.cloneNode(!1));return this.attributeMap.forEach((e,r)=>{t.attributeMap.set(r,e)}),this.children.forEach(e=>{const r=e.clone();t.getTarget().appendChild(r.getTarget()),t.pushChild(r)}),t.mounted=!1,t.bindingData=this.bindingData,t.derivedBindingData=this.derivedBindingData,t.clearBindingDataCache(),t.visible=!0,t.display=this.display,t.displayPriority=this.displayPriority,t.template=this.template,t.renderSignature=this.renderSignature,t.eachInputSignature=this.eachInputSignature,t.deriveSubtreeSignature=null,t.deriveInputSignature=null,t.freshInitializationSkippable=this.freshInitializationSkippable,t.normalizeClonedVisibilityState(),t}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${u.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${u.prefix}if-false`)),this.children.forEach(t=>{t instanceof W&&t.normalizeClonedVisibilityState()})}remove(t=!0){const e=[];return this.children.forEach(r=>{e.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(e.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,e.push(super.remove(t)),Promise.all(e).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(t){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(t,(this.selfWrittenBind.get(t)??0)+1)}consumeSelfWrittenBind(t){const e=this.selfWrittenBind.get(t);return e===void 0?!1:(e<=1?this.selfWrittenBind.delete(t):this.selfWrittenBind.set(t,e-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(t){this.bindingData=t,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(t){const e=this.bindingWorkChain.then(t,t);return this.bindingWorkChain=e.then(()=>{},()=>{}),e}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(t){this.derivedBindingData=t,this.clearBindingDataCache()}setParent(t){this.parent!==t&&(this.parent=t,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(t=>{t instanceof W&&t.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(t){this.template=t}setListKey(t){this.listKey=t}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(t){this.renderSignature=t}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(t){this.eachInputSignature=t}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(t){this.deriveSubtreeSignature=t}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(t){this.deriveInputSignature=t}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(t){this.freshInitializationSkippable=t}setValue(t){return this.applyValue(t,!0)}syncBindingValue(t){return this.applyValue(t,!1)}applyValue(t,e){if(this.skipChangeValue||this.value===t)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=t===!0||t==="true":i==="false"?s=t===!1:Array.isArray(t)?s=t.map(String).includes(String(i)):s=i===String(t),n?this.value=s:s?Array.isArray(t)?this.value=String(i):this.value=t:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=s,e&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(t)?t.join(","):t;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,M.enqueue(()=>{r.value=i===null?"":String(i),e&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(t,e){if(t instanceof HTMLInputElement&&t.type==="number"){if(e===null||e==="")return null;const r=typeof e=="number"?e:Number(e);return Number.isNaN(r)?null:r}return e}syncValue(){const t=this.getTarget();if(t instanceof HTMLInputElement)if(t.type==="checkbox"||t.type==="radio"){const e=t.type==="checkbox"&&t.value==="true";if(t.checked){const r=t.value;e?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=t.value;e?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(t,t.value);else t instanceof HTMLTextAreaElement?this.value=t.value:t instanceof HTMLSelectElement&&(this.value=t.value)}setAttribute(t,e,r=!1){return this.setAttributeInternal(t,t,e,!0,r)}setAliasedAttribute(t,e,r,i=!1){return this.setAttributeInternal(t,e,r,!1,i)}removeAliasedAttribute(t,e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(t),e!==t&&r.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(t,e,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return t===e?this.removeAttribute(t):this.removeAliasedAttribute(t,e);const s=new it(t,r);if(n){const lt=this.attributeMap.get(t);if(lt&&(lt.isEvaluate||lt.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(t,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:t,template:r}),l=s.isEvaluate||s.isRawEvaluate,c=t===e&&W.BOOLEAN_ATTRIBUTES.has(e.toLowerCase()),h=s.isSingleExpression(),g=K.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:g,w=!s.isForceEvaluation()&&(e!==t||c||h?o.hasUnresolvedReference||y===null||y===void 0||y===!1:l&&g===""),P=s.isForceEvaluation()?r:h?y:g,A=i&&s.isEvaluate&&e==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),v=a.getRootNode(),b=A&&a===v.activeElement,S=w||P===null||P===!1?null:String(P),x=t!==e&&a.getAttribute(t)!==r,I=S===null?a.hasAttribute(e):a.getAttribute(e)!==S,$=A&&!b&&S!==null&&a.value!==S,V=e==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),C=e==="selected"&&a instanceof HTMLOptionElement,Z=v.activeElement,gt=Z!==null&&(V&&a===Z||C&&a.closest("select")===Z),_=S!==null,mt=V&&!gt&&a.checked!==_,bt=C&&!gt&&a.selected!==_;return!x&&!I&&!$&&!mt&&!bt?(A&&!b&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{x&&a.setAttribute(t,r),S===null?a.removeAttribute(e):(I&&(a.setAttribute(e,S),e===`${u.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!b&&(this.value=this.normalizeValueForElement(a,S),$&&(a.value=S))),mt&&(a.checked=_),bt&&(a.selected=_)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(t),this.skipMutationAttributes=!0;const e=this.getTarget();return M.enqueue(()=>{e.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(t){return this.getAttributeEvaluation(t)?.value??null}getAttributeEvaluation(t){const e=this.attributeMap.get(t);if(e===void 0)return null;const r=e.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:t,template:e.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:K.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(t){const e=this.attributeMap.get(t);return e===void 0?null:e.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(t){return this.attributeMap.has(t)}resolveInsertionPointFromDom(t,e){const r=t.getTarget();if(r.parentNode!==this.target)return null;const i=e?r.nextSibling:r;let n=e?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(t,e,r){if(this.skipMutationNodes)return Promise.resolve();if(t===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(t))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=t.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(t),e!==null&&(o=this.children.indexOf(e)));const l=t.getParent();l!==null&&l.removeChild(t);let c=r===void 0?e?.getTarget()||null:r;if(e===null)this.children.push(t);else{let g;if(s?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(e),g===-1){const y=this.resolveInsertionPointFromDom(e,!1);y===null?(m.warn("[Haori]","Reference child not found in children.",e),this.children.push(t)):(this.children.splice(y.index,0,t),c=y.referenceNode)}else this.children.splice(g,0,t)}t.setParent(this),t.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(t.getTarget(),c)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(t,e){if(e==null)return this.insertBefore(t,null);const r=this.children.indexOf(e);if(r===-1){const i=this.resolveInsertionPointFromDom(e,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",e),this.insertBefore(t,null)):this.insertBefore(t,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(t,this.children[r+1]||null)}getPrevious(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<=0?null:e[r-1]}getNext(){const t=this.getParent();if(t===null)return null;const e=t.getChildElementFragments(),r=e.indexOf(this);return r<0||r+1>=e.length?null:e[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const t=this.getTarget();return this.display=t.style.getPropertyValue("display"),this.displayPriority=t.style.getPropertyPriority("display"),t.style.setProperty("display","none","important"),t.setAttribute(`${u.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const t=this.getTarget();return this.display===null||this.display===""?t.style.removeProperty("display"):t.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,t.removeAttribute(`${u.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(t){if(this.hasAttribute(t))return this;const e=this.getParent();return e===null?null:e.closestByAttribute(t)}};W.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let k=W;class U extends T{constructor(t){super(t),this.skipMutation=!1,this.renderedText=null,this.text=t.textContent||"",this.contents=new K(this.text)}clone(){const t=new U(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t.contents=this.contents,t.renderedText=this.renderedText,t}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,this.contents=new K(t),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let t=this.text;this.contents.isRawEvaluate?t=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(t=K.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const e=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===t&&e===t||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=t:this.target.textContent=t,this.renderedText=t)}).finally(()=>{this.skipMutation=!1})}}class ft extends T{constructor(t){super(t),this.skipMutation=!1,this.text=t.textContent||""}clone(){const t=new ft(this.target.cloneNode(!0));return t.mounted=!1,t.text=this.text,t}getTarget(){return this.target}setContent(t){return this.skipMutation||this.text===t?Promise.resolve():(this.text=t,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const st=class st{constructor(t){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=t;const e=[...t.matchAll(st.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of e){s.index>r&&this.contents.push({text:t.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<t.length&&this.contents.push({text:t.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(t){return t===null||t.length===0?"":t.map(e=>e==null||e===!1||Number.isNaN(e)?"":typeof e!="string"?String(e):e).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let t=0;t<this.contents.length;t++)this.contents[t].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[t].type=1)}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(t,e,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(t,e,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const c=rt.measure(()=>z.evaluateDetailed(l.text,t)),h=c.value;a+=c.durationMs,s.push({expression:l.text,durationMs:c.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(l.text)}catch(c){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,c),s.push({expression:l.text,durationMs:0}),n.push("")}}),rt.record(e,s,a),{results:n,hasUnresolvedReference:o}}};st.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let K=st;const at=class at extends K{constructor(t,e){super(e),this.forceEvaluation=at.FORCE_EVALUATION_ATTRIBUTES.includes(t)}isForceEvaluation(){return this.forceEvaluation}evaluate(t,e){return this.evaluateDetailed(t,e).results}evaluateDetailed(t,e){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(t,e,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};at.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let it=at;class J{static get runtime(){return u.runtime}static setRuntime(t){u.setRuntime(t)}static waitForRenders(){return M.waitForIdle()}static dialog(t){return M.enqueue(()=>{window.alert(t)},!0)}static async toast(t,e="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${e}`,r.textContent=t,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",e==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(t){return M.enqueue(()=>window.confirm(t),!0)}static openDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.showModal():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static closeDialog(t){return M.enqueue(()=>{t instanceof HTMLDialogElement?t.close():m.error("[Haori]","Element is not a dialog: ",t)},!0)}static addErrorMessage(t,e){return J.addMessage(t,e,"error")}static addMessage(t,e,r){return M.enqueue(()=>{const i=t instanceof HTMLFormElement?t:t.parentElement??t;i.setAttribute("data-message",e),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(t){return M.enqueue(()=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level"),t.querySelectorAll("[data-message]").forEach(e=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level")})},!0)}static date(t,e){return At(t,e)}static number(t,e){return St(t,e)}static range(t,e,r){return wt(t,e,r)}static pages(t,e,r){return Tt(t,e,r)}static monthAdd(t,e){return ot(t,e)}static monthRange(t,e){return Dt(t,e)}static pageSummary(t,e){return Rt(t,e)}static findBy(t,e,r){return Nt(t,e,r)}static sum(t,e){return Ft(t,e)}}const Ht=["addErrorMessage","clearMessages"];function yt(){const t=globalThis.window?.Haori;return Ht.every(r=>typeof t?.[r]=="function")?t:J}class E{static getValues(t){const e={};return E.getPartValues(t,e)}static getPartValues(t,e){const r=t.getAttribute("name"),i=t.getAttribute(`${u.prefix}form-object`),n=t.getAttribute(`${u.prefix}form-list`);if(r){if(n)Array.isArray(e[String(r)])?e[String(r)].push(t.getValue()):e[String(r)]=[t.getValue()];else if(E.isGroupedCheckable(t)){const s=t.getValue(),a=String(r);s===null?a in e||(e[a]=null):e[a]===null||e[a]===void 0?e[a]=s:Array.isArray(e[a])?e[a].push(s):e[a]=[e[a],s]}else e[String(r)]=t.getValue();i&&m.warn("Haori",`Element cannot have both ${u.prefix}form-object and name attributes.`);for(const s of t.getChildElementFragments())E.getPartValues(s,e)}else if(i){const s={};for(const a of t.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(e[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${u.prefix}form-list and ${u.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of t.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(e[String(n)]=s)}else for(const s of t.getChildElementFragments())E.getPartValues(s,e);return e}static setValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!0)}static syncValues(t,e,r=!1){return E.setPartValues(t,e,null,r,!1)}static isGroupedCheckable(t){const e=t.getTarget();return e instanceof HTMLInputElement?e.type==="radio"?!0:e.type!=="checkbox"?!1:e.value!=="true"&&e.value!=="false":!1}static applyFragmentValue(t,e,r){return r?t.setValue(e):t.syncBindingValue(e)}static setPartValues(t,e,r=null,i=!1,n=!0){const s=[],a=t.getAttribute("name"),o=t.getAttribute(`${u.prefix}form-object`),l=t.getAttribute(`${u.prefix}form-list`),c=t.getAttribute(`${u.prefix}form-detach`);if(a){if(!c||i){const h=e[String(a)];l&&Array.isArray(h)&&r!==null?s.push(E.applyFragmentValue(t,h[r]??null,n)):typeof h>"u"||(Array.isArray(h)&&E.isGroupedCheckable(t)||typeof h=="string"||typeof h=="number"||typeof h=="boolean"||h===null?s.push(E.applyFragmentValue(t,h,n)):s.push(E.applyFragmentValue(t,String(h),n)))}}else if(o){const h=e[String(o)];if(h&&typeof h=="object")for(const g of t.getChildElementFragments())s.push(E.setPartValues(g,h,null,i,n))}else if(l){const h=e[String(l)];if(Array.isArray(h)){const g=t.getChildElementFragments();for(let y=0;y<g.length;y++){const w=g[y];h.length>y?s.push(E.setPartValues(w,h[y],y,i,n)):s.push(E.setPartValues(w,{},y,i,n))}}}else for(const h of t.getChildElementFragments())s.push(E.setPartValues(h,e,null,i,n));return Promise.all(s).then(()=>{})}static async reset(t){E.clearValues(t),await Promise.all([E.clearMessages(t),E.clearEachClones(t)]),await M.enqueue(()=>{const r=t.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const e=E.collectBindingTargetForms(t);for(const r of e){const i=E.getInitialBindingData(r);i&&await F.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(t);for(const r of e){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${u.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await F.setBindingData(r.getTarget(),a)}await F.evaluateAll(t)}static getInitialBindingData(t){const e=t.getInitialBindAttribute();return e===null?null:F.parseDataBind(e)}static syncValuesFromDom(t){const e=t.getTarget();(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.syncValue();for(const r of t.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(t){const e=t.getTarget(),r=[];e instanceof HTMLFormElement?r.push(e):r.push(...Array.from(e.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof k&&i.push(s)}return i}static clearEachClones(t){const e=[],r=n=>{if(n.hasAttribute(`${u.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${u.prefix}each-before`),o=s.hasAttribute(`${u.prefix}each-after`);!a&&!o&&e.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(t);for(const n of t.getChildElementFragments())i(n);return Promise.all(e).then(()=>{})}static clearValues(t){t.clearValue();for(const e of t.getChildElementFragments())E.clearValues(e)}static clearMessages(t){return yt().clearMessages(t.getTarget())}static addErrorMessage(t,e,r){return E.addMessage(t,e,r,"error")}static addMessage(t,e,r,i){const n=[],s=yt(),a=s.addMessage,o=c=>typeof a=="function"?a.call(s,c,r,i):s.addErrorMessage(c,r),l=E.findFragmentsByKey(t,e);return l.forEach(c=>{n.push(o(c.getTarget()))}),l.length===0&&n.push(o(t.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(t,e){return E.findFragmentByKeyParts(t,e.split("."))}static findFragmentByKeyParts(t,e){const r=[],i=e[0];if(e.length==1&&t.getAttribute("name")===i&&r.push(t),t.hasAttribute(`${u.prefix}form-object`))e.length>1&&t.getAttribute(`${u.prefix}form-object`)===i&&t.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,e.slice(1)))});else if(t.hasAttribute(`${u.prefix}form-list`)){if(e.length>1){const n=t.getAttribute(`${u.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),c=Number(l);if(isNaN(c))m.error("Haori",`Invalid index: ${i}`);else{const h=t.getChildElementFragments().filter(g=>g.hasAttribute(`${u.prefix}row`));c<h.length&&r.push(...E.findFragmentByKeyParts(h[c],e.slice(1)))}}}}}else t.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,e))});return r}static getFormFragment(t){const e=t.getTarget();if(e instanceof HTMLFormElement||e instanceof HTMLElement&&e.hasAttribute(`${u.prefix}form`))return t;const r=t.getParent();return r?this.getFormFragment(r):null}}class R{static dispatch(t,e,r,i){const n=new CustomEvent(`haori:${e}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return t.dispatchEvent(n)}static ready(t){R.dispatch(document,"ready",{version:t})}static render(t){R.dispatch(t,"render",{target:t})}static importStart(t,e){R.dispatch(t,"importstart",{url:e,startedAt:performance.now()})}static importEnd(t,e,r,i){R.dispatch(t,"importend",{url:e,bytes:r,durationMs:performance.now()-i})}static importError(t,e,r){R.dispatch(t,"importerror",{url:e,error:r})}static bindChange(t,e,r,i="other"){const n=[],s=new Set(Object.keys(e||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const c=e?.[l],h=r[l];c!==h&&n.push(l)}R.dispatch(t,"bindchange",{previous:e||{},next:r,changedKeys:n,reason:i})}static bindComplete(t,e=null,r="other"){R.dispatch(t,"bindcomplete",{bindArg:e,reason:r})}static eachUpdate(t,e,r,i){R.dispatch(t,"eachupdate",{added:e,removed:r,order:i,total:i.length})}static rowAdd(t,e,r,i){R.dispatch(t,"rowadd",{key:e,index:r,item:i})}static rowRemove(t,e,r){R.dispatch(t,"rowremove",{key:e,index:r})}static rowMove(t,e,r,i){R.dispatch(t,"rowmove",{key:e,from:r,to:i})}static show(t){R.dispatch(t,"show",{visible:!0})}static hide(t){R.dispatch(t,"hide",{visible:!1})}static fetchStart(t,e,r,i,n){R.dispatch(t,"fetchstart",{url:e,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(t,e,r,i){R.dispatch(t,"fetchend",{url:e,status:r,durationMs:performance.now()-i})}static fetchError(t,e,r,i,n){R.dispatch(t,"fetcherror",{url:e,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Lt={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ut(p,t){return p.replace(/\{\{([\s\S]+?)\}\}/g,(e,r)=>{try{const i=z.evaluate(String(r).trim(),t);return i==null?"":String(i)}catch{return""}})}function Vt(p,t){const e=p.getAttribute(t);if(e===null||e==="")return null;if(!e.includes("{{"))return e;const r=T.get(p),i=r instanceof k?r.getBindingData():{},n=Ut(e,i);return n===""?null:n}function jt(p,t,e){const r=p.getAttribute(`${t}-return-param`);if(r===null||r==="")return e;try{if(new URL(e,window.location.href).searchParams.has(r))return e}catch{return e}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=e.indexOf("#"),a=s>=0?e.slice(s):"",o=s>=0?e.slice(0,s):e,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Mt(p){const t=Lt[p];if(t===void 0||typeof document>"u")return!1;const e=`${u.prefix}${t}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Vt(i,e);if(n===null)continue;const s=jt(i,e,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class xt{static readParams(){const t={},e=window.location.search;return new URLSearchParams(e).forEach((i,n)=>{t[n]=i}),t}static isSafeLocalPath(t){const e=t.trim();if(e===""||e[0]!=="/"||e[1]==="/"||e[1]==="\\")return!1;try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}}const qt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Wt="__haoriHistoryState__",ut="data-haori-click-lock";function et(){const t=globalThis.window?.Haori;return qt.every(r=>typeof t?.[r]=="function")?t:J}const zt=new Set(["GET","HEAD","OPTIONS"]);function Kt(p){return zt.has(p.toUpperCase())}function Gt(p,t){for(const[e,r]of Object.entries(t))r!==void 0&&(r===null?p.append(e,""):Array.isArray(r)?r.forEach(i=>{p.append(e,String(i))}):typeof r=="object"||typeof r=="function"?p.append(e,JSON.stringify(r)):p.append(e,String(r)))}function Yt(p,t){const e=new URL(p,window.location.href),r=new URLSearchParams(e.search);return Gt(r,t),e.search=r.toString(),e.toString()}function Jt(p){return p==null?null:typeof p=="string"?p:p instanceof URLSearchParams?p.toString():p instanceof FormData?Array.from(p.entries()).map(([t,e])=>e instanceof File?[t,{type:"file",name:e.name,size:e.size,mimeType:e.type}]:[t,String(e)]):String(p)}function Xt(p,t){const e=new Headers(t.headers||void 0),r=Array.from(e.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:p,method:String(t.method||"GET").toUpperCase(),headers:r,body:Jt(t.body||null)})}const f=class f{constructor(t,e=null,r=null){this.reentrantBind=!1,f.isElementFragment(t)?(this.options=f.buildOptions(t,e),this.eventType=e):(this.options=t,this.eventType=null),this.domEvent=r}static attrName(t,e,r=!1){return t?`${u.prefix}${t}-${e}`:r?`${u.prefix}fetch-${e}`:`${u.prefix}${e}`}static resolveDataParamString(t,e){return f.resolveDataParamStringDetailed(t,e).value}static resolveDataParamStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",e);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(t,e){let r=!1,i=!1;for(let n=0;n<e;n+=1){const s=t[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(t){if(t===void 0||Number.isNaN(t))return"null";try{return JSON.stringify(t)??JSON.stringify(String(t))}catch{return JSON.stringify(String(t))}}static stringifyJsonTemplateStringContent(t){if(t==null||Number.isNaN(t))return"";const e=typeof t=="object"?f.stringifyJsonTemplateValue(t):String(t);return JSON.stringify(e).slice(1,-1)}static resolveDataJsonString(t,e){return f.resolveDataJsonStringDetailed(t,e).value}static resolveDataJsonStringDetailed(t,e){let r=!1;return{value:t.replace(f.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=z.evaluateDetailed(s??a??"",e);return r=r||l.unresolvedReference,f.isJsonStringContext(t,o)?f.stringifyJsonTemplateStringContent(l.value):f.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(t,e){return f.resolveDataAttributeDetailed(t,e).value}static resolveDataAttributeDetailed(t,e){const r=t.getRawAttribute(e),i=t.getAttributeEvaluation(e),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:F.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=f.resolveDataJsonStringDetailed(r,t.getBindingData());return{value:F.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=f.resolveDataParamStringDetailed(r,t.getBindingData());return{value:F.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(t,e){const r={targetFragment:t};if(e){if(t.hasAttribute(f.attrName(e,"validate"))&&(r.valid=!0),t.hasAttribute(f.attrName(e,"confirm"))&&(r.confirmMessage=t.getAttribute(f.attrName(e,"confirm")).replace(/\\n/g,`
7
- `)),t.hasAttribute(f.attrName(e,"data"))&&(r.dataAttrName=f.attrName(e,"data")),t.hasAttribute(f.attrName(e,"form"))){const v=t.getRawAttribute(f.attrName(e,"form"));if(v){const b=document.body.querySelector(v);b!==null?r.formFragment=E.getFormFragment(T.get(b)):m.error("Haori",`Form element not found: ${v} (${f.attrName(e,"form")})`)}else r.formFragment=E.getFormFragment(t)}else(e==="change"||e==="input")&&(r.formFragment=E.getFormFragment(t));if(t.hasAttribute(`${u.prefix}${e}-before-run`)){const v=t.getRawAttribute(`${u.prefix}${e}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
4
+ return (${e});`:`"use strict";
5
+ return (${e});`;try{return n=new Function(...r,a),this.EXPRESSION_CACHE.set(i,n),{bindKeys:r,evaluator:n,compileFailed:!1}}catch(o){return m.error("[Haori]","Failed to compile expression:",e,o),{bindKeys:r,evaluator:null,compileFailed:!0}}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,l=t[n-2]||null,h=t[n-3]||null;if(this.startsObjectKey(o,i,l,h)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const u=this.startsMemberAccess(i)?"member":"array";r.push(u);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};B.MAX_IDENTIFIER_RECOVERY_COUNT=8,B.BUILTIN_NAMESPACE="haori",B.BUILTIN_HELPERS={...We},B.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,B.forbiddenBindingValueCache=new WeakMap,B.forbiddenBindingValueCacheResetScheduled=!1,B.loggedForbiddenKeySignatures=new Set,B.loggedForbiddenKeyResetScheduled=!1,B.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],B.STRICT_FORBIDDEN_NAMES=["eval","arguments"],B.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),B.FORBIDDEN_BINDING_NAMES=new Set([...B.FORBIDDEN_NAMES.filter(e=>!B.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...B.STRICT_FORBIDDEN_NAMES]),B.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),B.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),B.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),B.EXPRESSION_CACHE=new Map;let z=B;class ge{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ge.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const me=class me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};me.ASYNC_QUEUE=new ge;let P=me;const N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:N.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!L.isEnabled()||!e||t.length===0)return;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(s,t,r);return}const n=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=N.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=N.now();return{value:e(),durationMs:N.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let ne=N;const X=class X{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,X.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(X.FRAGMENT_CACHE.has(e))return X.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new V(e);break;case Node.COMMENT_NODE:t=new pe(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return P.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return P.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),X.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};X.FRAGMENT_CACHE=new WeakMap;let T=X;const K=class K extends T{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new se(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof K)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new K(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${c.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${c.prefix}if-false`)),this.children.forEach(e=>{e instanceof K&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof K&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,P.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,P.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return m.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return P.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new se(e,r);if(n){const ce=this.attributeMap.get(e);if(ce&&(ce.isEvaluate||ce.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,P.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&K.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),u=s.isSingleExpression(),p=G.joinEvaluateResults(o.results),b=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||h||u?o.hasUnresolvedReference||b===null||b===void 0||b===!1:l&&p===""),I=s.isForceEvaluation()?r:u?b:p,A=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),y=a.getRootNode(),v=A&&a===y.activeElement,S=R||I===null||I===!1?null:String(I),k=e!==t&&a.getAttribute(e)!==r,C=S===null?a.hasAttribute(t):a.getAttribute(t)!==S,O=A&&!v&&S!==null&&a.value!==S,j=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,ee=y.activeElement,be=ee!==null&&(j&&a===ee||$&&a.closest("select")===ee),te=S!==null,ve=j&&!be&&a.checked!==te,ye=$&&!be&&a.selected!==te;return!k&&!C&&!O&&!ve&&!ye?(A&&!v&&S!==null&&(this.value=this.normalizeValueForElement(a,S)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{k&&a.setAttribute(e,r),S===null?a.removeAttribute(t):(C&&(a.setAttribute(t,S),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(S)),A&&!v&&(this.value=this.normalizeValueForElement(a,S),O&&(a.value=S))),ve&&(a.checked=te),ye&&(a.selected=te)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return P.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:G.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const b=this.resolveInsertionPointFromDom(t,!1);b===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(b.index,0,e),h=b.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const u=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=u})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${c.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${c.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};K.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let M=K;class V extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new G(this.text)}clone(){const e=new V(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new G(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):P.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=G.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class pe extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new pe(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,P.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const oe=class oe{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(oe.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=ne.measure(()=>z.evaluateDetailed(l.text,e)),u=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||u.unresolvedReference,n.push(u.value)}else n.push(l.text)}catch(h){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};oe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let G=oe;const le=class le extends G{constructor(e,t){super(t),this.forceEvaluation=le.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};le.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let se=le;class Q{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static waitForRenders(){return P.waitForIdle()}static dialog(e){return P.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return P.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Q.addMessage(e,t,"error")}static addMessage(e,t,r){return P.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return P.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}static date(e,t,r){return Te(e,t,r)}static number(e,t){return Re(e,t)}static range(e,t,r){return De(e,t,r)}static pages(e,t,r){return Fe(e,t,r)}static monthAdd(e,t){return ue(e,t)}static monthRange(e,t){return Ne(e,t)}static pageSummary(e,t){return Me(e,t)}static findBy(e,t,r){return xe(e,t,r)}static sum(e,t){return Pe(e,t)}static distinct(e,t){return Ie(e,t)}static groupBy(e,t){return Ce(e,t)}}const Ke=["addErrorMessage","clearMessages"];function Ae(){const e=globalThis.window?.Haori;return Ke.every(r=>typeof e?.[r]=="function")?e:Q}class E{static getValues(e){const t={};return E.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${c.prefix}form-object`),n=e.getAttribute(`${c.prefix}form-list`);if(r){if(n)Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()];else if(E.isGroupedCheckable(e)){const s=e.getValue(),a=String(r);s===null?a in t||(t[a]=null):t[a]===null||t[a]===void 0?t[a]=s:Array.isArray(t[a])?t[a].push(s):t[a]=[t[a],s]}else t[String(r)]=e.getValue();i&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())E.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())E.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};E.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())E.getPartValues(s,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!1)}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${c.prefix}form-object`),l=e.getAttribute(`${c.prefix}form-list`),h=e.getAttribute(`${c.prefix}form-detach`);if(a){if(!h||i){const u=t[String(a)];l&&Array.isArray(u)&&r!==null?s.push(E.applyFragmentValue(e,u[r]??null,n)):typeof u>"u"||(Array.isArray(u)&&E.isGroupedCheckable(e)||typeof u=="string"||typeof u=="number"||typeof u=="boolean"||u===null?s.push(E.applyFragmentValue(e,u,n)):s.push(E.applyFragmentValue(e,String(u),n)))}}else if(o){const u=t[String(o)];if(u&&typeof u=="object")for(const p of e.getChildElementFragments())s.push(E.setPartValues(p,u,null,i,n))}else if(l){const u=t[String(l)];if(Array.isArray(u)){const p=e.getChildElementFragments();for(let b=0;b<p.length;b++){const R=p[b];u.length>b?s.push(E.setPartValues(R,u[b],b,i,n)):s.push(E.setPartValues(R,{},b,i,n))}}}else for(const u of e.getChildElementFragments())s.push(E.setPartValues(u,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await P.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${c.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await x.setBindingData(r.getTarget(),a)}await x.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:x.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return Ae().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ae(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=E.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),h=Number(l);if(isNaN(h))m.error("Haori",`Invalid index: ${i}`);else{const u=e.getChildElementFragments().filter(p=>p.hasAttribute(`${c.prefix}row`));h<u.length&&r.push(...E.findFragmentByKeyParts(u[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class F{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){F.dispatch(document,"ready",{version:e})}static render(e){F.dispatch(e,"render",{target:e})}static importStart(e,t){F.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){F.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){F.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],u=r[l];h!==u&&n.push(l)}F.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){F.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){F.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){F.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){F.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){F.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){F.dispatch(e,"show",{visible:!0})}static hide(e){F.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){F.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){F.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){F.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const ze={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ge(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=z.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ye(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(f),i=r instanceof M?r.getBindingData():{},n=Ge(t,i);return n===""?null:n}function Je(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function Be(f){const e=ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ye(i,t);if(n===null)continue;const s=Je(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class $e{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const Xe=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Qe="__haoriHistoryState__",he="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return Xe.every(r=>typeof e?.[r]=="function")?e:Q}const Ze=new Set(["GET","HEAD","OPTIONS"]);function _e(f){return Ze.has(f.toUpperCase())}function et(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function tt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return et(r,e),t.search=r.toString(),t.toString()}function rt(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function it(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:rt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=z.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=z.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:x.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"confirm")).replace(/\\n/g,`
7
+ `)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const y=e.getRawAttribute(g.attrName(t,"form"));if(y){const v=document.body.querySelector(y);v!==null?r.formFragment=E.getFormFragment(T.get(v)):m.error("Haori",`Form element not found: ${y} (${g.attrName(t,"form")})`)}else r.formFragment=E.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=E.getFormFragment(e));if(e.hasAttribute(`${c.prefix}${t}-before-run`)){const y=e.getRawAttribute(`${c.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
- ${v}
10
- `)}catch(b){m.error("Haori",`Invalid before script: ${b}`)}}const A=f.attrName(e,"run");if(t.hasAttribute(A)){const v=String(t.getAttribute(A)??"");try{r.runScript=new Function("event",`
9
+ ${y}
10
+ `)}catch(v){m.error("Haori",`Invalid before script: ${v}`)}}const A=g.attrName(t,"run");if(e.hasAttribute(A)){const y=String(e.getAttribute(A)??"");try{r.runScript=new Function("event",`
11
11
  "use strict";
12
- ${v}
13
- `)}catch(b){m.error("Haori",`Invalid run script: ${b}`)}}}const i=f.attrName(e,"fetch"),n=t.hasAttribute(i);if(n){const A=t.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(e){const A=f.attrName(e,"fetch-method");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}else{const A=f.attrName(null,"method",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=v?.value}}if(e){const A=f.attrName(e,"fetch-headers");if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=F.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}else{const A=f.attrName(null,"headers",!0);if(t.hasAttribute(A)){const v=t.getRawAttribute(A);try{s.headers=F.parseDataBind(v)}catch(b){m.error("Haori",`Invalid fetch headers: ${b}`)}}}if(e){const A=f.attrName(e,"fetch-content-type");if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=f.attrName(null,"content-type",!0);if(t.hasAttribute(A)){const v=t.getAttributeEvaluation(A);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":v?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let v=!1;s.headers&&typeof s.headers=="object"&&(v="Content-Type"in s.headers),v||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=e?f.attrName(e,"bind"):f.attrName(null,"bind",!0);if(t.hasAttribute(a)){const A=t.getRawAttribute(a);if(A){const v=document.body.querySelectorAll(A);v.length>0?(r.bindFragments=[],v.forEach(b=>{const S=T.get(b);S&&r.bindFragments.push(S)})):m.error("Haori",`Bind element not found: ${A} (${a})`)}}const o=f.attrName(e,"bind-arg"),l=f.attrName(null,"arg",!0),c=f.attrName(null,"bind-arg",!0);e?t.hasAttribute(o)&&(r.bindArg=t.getRawAttribute(o)):t.hasAttribute(l)?r.bindArg=t.getRawAttribute(l):t.hasAttribute(c)&&(r.bindArg=t.getRawAttribute(c));const h=e?f.attrName(e,"bind-params"):f.attrName(null,"bind-params",!0);if(t.hasAttribute(h)){const A=t.getRawAttribute(h);r.bindParams=A.split("&").map(v=>v.trim())}const g=e?f.attrName(e,"bind-append"):f.attrName(null,"bind-append",!0);if(t.hasAttribute(g)){const A=t.getRawAttribute(g);r.bindAppendParams=A.split("&").map(v=>v.trim()).filter(Boolean)}const y=e?f.attrName(e,"bind-merge"):f.attrName(null,"bind-merge",!0);t.hasAttribute(y)&&(r.bindMerge=!0);const w=e?f.attrName(e,"bind-transform"):f.attrName(null,"bind-transform",!0);t.hasAttribute(w)&&(r.bindTransform=t.getRawAttribute(w));const P=e?f.attrName(e,"copy-params"):null;if(P&&t.hasAttribute(P)){const A=t.getRawAttribute(P);r.copyParams=A.split("&").map(v=>v.trim()).filter(Boolean)}if(e){if(t.hasAttribute(f.attrName(e,"adjust"))){const b=t.getRawAttribute(f.attrName(e,"adjust"));if(b){const S=document.body.querySelectorAll(b);S.length>0?(r.adjustFragments=[],S.forEach(x=>{const I=T.get(x);I&&r.adjustFragments.push(I)})):m.error("Haori",`Adjust element not found: ${b} (${f.attrName(e,"adjust")})`)}if(t.hasAttribute(f.attrName(e,"adjust-value"))){const S=t.getRawAttribute(f.attrName(e,"adjust-value")),x=Number(S);isNaN(x)||(r.adjustValue=x)}}if(t.hasAttribute(f.attrName(e,"row-add"))&&(r.rowAdd=!0),t.hasAttribute(f.attrName(e,"row-remove"))&&(r.rowRemove=!0),t.hasAttribute(f.attrName(e,"row-prev"))&&(r.rowMovePrev=!0),t.hasAttribute(f.attrName(e,"row-next"))&&(r.rowMoveNext=!0),t.hasAttribute(`${u.prefix}${e}-after-run`)){const b=t.getRawAttribute(`${u.prefix}${e}-after-run`);try{r.afterCallback=new Function("response",`
12
+ ${y}
13
+ `)}catch(v){m.error("Haori",`Invalid run script: ${v}`)}}}const i=g.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const A=e.getAttributeEvaluation(i);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const s={};if(t){const A=g.attrName(t,"fetch-method");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}else{const A=g.attrName(null,"method",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=y?.value}}if(t){const A=g.attrName(t,"fetch-headers");if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=x.parseDataBind(y)}catch(v){m.error("Haori",`Invalid fetch headers: ${v}`)}}}else{const A=g.attrName(null,"headers",!0);if(e.hasAttribute(A)){const y=e.getRawAttribute(A);try{s.headers=x.parseDataBind(y)}catch(v){m.error("Haori",`Invalid fetch headers: ${v}`)}}}if(t){const A=g.attrName(t,"fetch-content-type");if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=g.attrName(null,"content-type",!0);if(e.hasAttribute(A)){const y=e.getAttributeEvaluation(A);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":y?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let y=!1;s.headers&&typeof s.headers=="object"&&(y="Content-Type"in s.headers),y||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=t?g.attrName(t,"bind"):g.attrName(null,"bind",!0);if(e.hasAttribute(a)){const A=e.getRawAttribute(a);if(A){const y=document.body.querySelectorAll(A);y.length>0?(r.bindFragments=[],y.forEach(v=>{const S=T.get(v);S&&r.bindFragments.push(S)})):m.error("Haori",`Bind element not found: ${A} (${a})`)}}const o=g.attrName(t,"bind-arg"),l=g.attrName(null,"arg",!0),h=g.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(l)?r.bindArg=e.getRawAttribute(l):e.hasAttribute(h)&&(r.bindArg=e.getRawAttribute(h));const u=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(u)){const A=e.getRawAttribute(u);r.bindParams=A.split("&").map(y=>y.trim())}const p=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(p)){const A=e.getRawAttribute(p);r.bindAppendParams=A.split("&").map(y=>y.trim()).filter(Boolean)}const b=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(b)&&(r.bindMerge=!0);const R=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(R)&&(r.bindTransform=e.getRawAttribute(R));const I=t?g.attrName(t,"copy-params"):null;if(I&&e.hasAttribute(I)){const A=e.getRawAttribute(I);r.copyParams=A.split("&").map(y=>y.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const v=e.getRawAttribute(g.attrName(t,"adjust"));if(v){const S=document.body.querySelectorAll(v);S.length>0?(r.adjustFragments=[],S.forEach(k=>{const C=T.get(k);C&&r.adjustFragments.push(C)})):m.error("Haori",`Adjust element not found: ${v} (${g.attrName(t,"adjust")})`)}if(e.hasAttribute(g.attrName(t,"adjust-value"))){const S=e.getRawAttribute(g.attrName(t,"adjust-value")),k=Number(S);isNaN(k)||(r.adjustValue=k)}}if(e.hasAttribute(g.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(g.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(g.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(g.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${c.prefix}${t}-after-run`)){const v=e.getRawAttribute(`${c.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
14
14
  "use strict";
15
- ${b}
16
- `)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(t.hasAttribute(f.attrName(e,"dialog"))&&(r.dialogMessage=t.getAttribute(f.attrName(e,"dialog")).replace(/\\n/g,`
17
- `)),t.hasAttribute(f.attrName(e,"toast"))){r.toastMessage=t.getAttribute(f.attrName(e,"toast"));const b=t.getRawAttribute(f.attrName(e,"toast-level")),x=["info","warning","error","success"].includes(b);r.toastLevel=x?b:null}if(t.hasAttribute(f.attrName(e,"redirect"))){r.redirectUrl=t.getAttribute(f.attrName(e,"redirect"));const b=f.attrName(e,"redirect-return-param");t.hasAttribute(b)&&(r.redirectReturnParam=t.getAttribute(b))}if(t.hasAttribute(f.attrName(e,"scroll-error"))&&(r.scrollOnError=!0),t.hasAttribute(f.attrName(e,"scroll"))&&(r.scrollTarget=t.getAttribute(f.attrName(e,"scroll"))),t.hasAttribute(f.attrName(e,"history"))&&(r.historyUrl=t.getAttribute(f.attrName(e,"history"))),t.hasAttribute(f.attrName(e,"history-data"))&&(r.historyDataAttrName=f.attrName(e,"history-data")),t.hasAttribute(f.attrName(e,"history-form"))){const b=t.getRawAttribute(f.attrName(e,"history-form"));if(b){const S=document.body.querySelector(b);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${b} (${f.attrName(e,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(t)}["reset-before","reset","refetch","click","copy","open","close"].forEach(b=>{const S=f.attrName(e,b);if(!t.hasAttribute(S))return;const x=t.getRawAttribute(S),I=[];if(x?(document.body.querySelectorAll(x).forEach(V=>{const C=T.get(V);C&&I.push(C)}),I.length===0&&m.error("Haori",`Element not found: ${x} (${S})`)):I.push(t),I.length>0)switch(b){case"reset-before":r.resetBeforeFragments=I;break;case"reset":r.resetFragments=I;break;case"refetch":r.refetchFragments=I;break;case"click":r.clickFragments=I;break;case"copy":r.copyFragments=I;break;case"open":r.openFragments=I;break;case"close":r.closeFragments=I;break}});const v=f.attrName(e,"copy-source");if(t.hasAttribute(v)){const b=t.getRawAttribute(v);if(b){const S=document.body.querySelector(b);if(S!==null){const x=T.get(S);x?r.copySourceFragment=x:m.error("Haori",`Element is not managed by Haori: ${b} (${v})`)}else m.error("Haori",`Element not found: ${b} (${v})`)}else r.copySourceFragment=t}}if(!e&&(t.hasAttribute(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),t.hasAttribute(f.attrName(null,"form",!0)))){const A=t.getRawAttribute(f.attrName(null,"form",!0));if(A){const v=document.body.querySelector(A);v!==null?r.formFragment=E.getFormFragment(T.get(v)):m.error("Haori",`Form element not found: ${A} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(t)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[t],r.defaultSelfBind=!0),r}static isElementFragment(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.getTarget=="function"&&typeof e.getChildElementFragments=="function"}static resolveAutoFetchSignature(t){return new f(t,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const t=this.acquireExecutionLock();if(t===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const c=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(c,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){m.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(c=>E.reset(c))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const c=this.options.beforeCallback(n||null,s||null);if(c!=null){if(c===!1||typeof c=="object"&&c.stop)return!1;typeof c=="object"&&(n="fetchUrl"in c?c.fetchUrl:n,s="fetchOptions"in c?c.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const c={...s||{}},h=r.requestedMethod,g=r.effectiveMethod,y=r.transportMode==="query-get",w=r.queryString;if(y&&m.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:h,effectiveMethod:g,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:w}),this.options.targetFragment&&n){const P=performance.now(),A={runtime:u.runtime,requestedMethod:h,effectiveMethod:g,transportMode:y?"query-get":"http",...y?{queryString:w}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),n,c,a?i:void 0,A),fetch(n,c).then(v=>this.handleFetchResult(v,n||void 0,P)).catch(v=>{throw n&&R.fetchError(this.options.targetFragment.getTarget(),n,v),v})}return fetch(n,c).then(P=>this.handleFetchResult(P,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const c=this.options.formFragment,h=c.getTarget(),g=new Set;t&&t.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment);const y=c.getBindingData();Object.assign(y,i),await F.setBindingData(h,y,g)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(t)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment.getTarget();if(f.RUNNING_CLICK_TARGETS.has(e)||e.matches(":disabled")||e.hasAttribute("disabled")||e.hasAttribute(ut))return!1;const r=e.hasAttribute(`${u.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(e),e.setAttribute(ut,""),r||e.setAttribute("disabled",""),{target:e,appliedDisabledAttribute:!r}}releaseExecutionLock(t){t&&(f.RUNNING_CLICK_TARGETS.delete(t.target),t.target.removeAttribute(ut),t.appliedDisabledAttribute&&t.target.removeAttribute("disabled"))}async handleFetchResult(t,e,r){const i=et();if(!t.ok)return Mt(t.status)||(this.options.targetFragment&&e&&R.fetchError(this.options.targetFragment.getTarget(),e,new Error(`${t.status} ${t.statusText}`),t.status,r),await this.handleFetchError(t)),!1;if(this.options.targetFragment&&e&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),e,t.status,r),this.options.afterCallback){const a=this.options.afterCallback(t);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(t="response"in a?a.response:t)}}const n=[];n.push(this.bindResult(t)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new f(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await F.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const c=new URLSearchParams(window.location.search).get(o);if(c!==null){const h=c.trim();xt.isSafeLocalPath(h)?a=h:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${c}`)}}window.location.href=a}return!0}pushHistory(){const t=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,e=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=e!=null,n=r!=null;if(!(!t&&!i&&!n))try{const s=t?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[c,h]of Object.entries(l))h!=null&&(Array.isArray(h)?h.forEach(g=>a.searchParams.append(c,String(g))):typeof h=="object"?a.searchParams.set(c,JSON.stringify(h)):a.searchParams.set(c,String(h)))};i&&o(e),n&&o(r),history.pushState({[Wt]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(t){let e=null;this.options.formFragment?e=this.options.formFragment:this.options.targetFragment&&(e=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=e?e.getTarget():document.body;await et().clearMessages(r);const i=async a=>{const o=e?e.getTarget():document.body;await et().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=e?e.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((t.headers.get("Content-Type")||"").includes("application/json"))try{const a=await t.json(),o=[];if(Array.isArray(a)){const l=new Map,c=[];for(const h of a)if(h&&typeof h=="object"&&!Array.isArray(h)){const g=h.key,y=h.message,w=typeof g=="string"&&g.length>0?g:null,P=typeof y=="string"?y:y!=null?String(y):"";if(P.length===0)continue;if(w!==null){const A=l.get(w)??[];A.push(P),l.set(w,A)}else c.push(P)}else typeof h=="string"&&h.length>0&&c.push(h);for(const[h,g]of l)o.push({key:h,message:g.join(`
18
- `)});for(const h of c)o.push({message:h})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,c]of Object.entries(a.errors))Array.isArray(c)?o.push({key:l,message:c.join(`
19
- `)}):typeof c=="string"?o.push({key:l,message:c}):c!=null&&o.push({key:l,message:String(c)});if(o.length===0)for(const[l,c]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(c)?o.push({key:l,message:c.join(`
20
- `)}):typeof c=="string"&&o.push({key:l,message:c}))}if(o.length===0)return await i(`${t.status} ${t.statusText}`),n(),!1;for(const l of o)l.key&&e?await E.addErrorMessage(e,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await t.text();a&&a.trim().length>0?await i(a.trim()):await i(`${t.status} ${t.statusText}`)}catch{await i(`${t.status} ${t.statusText}`)}return n(),!1}validate(t){if(this.options.valid!==!0)return!0;const e=this.findFirstInvalid(t);return e===null?!0:(e.reportValidity(),e.focus(),this.options.scrollOnError&&e.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(t){let e=null;for(const r of t.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(e=i)}return this.checkOne(t)?e:t.getTarget()}checkOne(t){const e=t.getTarget();return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?e.checkValidity():!0}confirm(){const t=this.options.confirmMessage;return t==null?Promise.resolve(!0):et().confirm(t)}bindResult(t){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const e=t.headers.get("Content-Type")?.includes("application/json");return t.text().then(r=>{if(r==="")return;let i=e?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],c=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,c)}else a[o]=i;n.push(F.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(F.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{R.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(t,e,r=t.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return e;const i={...e},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const t=this.resolveCopySourceData(),e=this.pickCopyData(t),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...e};return F.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const t={};let e=!1;if(this.options.formFragment&&Object.assign(t,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(t,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=f.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);e=e||r.hasUnresolvedReference,r.value&&Object.assign(t,r.value)}return{payload:t,hasUnresolvedReference:e}}resolveFetchSignature(){const t=this.prepareFetchRequest();return{signature:t.signature,hasUnresolvedReference:t.hasUnresolvedReference}}prepareFetchRequest(){const t=this.buildPayloadResolution(),e=t.payload,r=!!this.options.fetchHasUnresolvedReference||t.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:e,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=u.runtime==="demo"&&!Kt(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(e).length>0&&(i=Yt(i,e));else if(Object.keys(e).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const g=new FormData;for(const[y,w]of Object.entries(e))w==null?g.append(y,""):w instanceof Blob?g.append(y,w):Array.isArray(w)?w.forEach(P=>g.append(y,String(P))):typeof w=="object"?g.append(y,JSON.stringify(w)):g.append(y,String(w));n.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[y,w]of Object.entries(e))w!==void 0&&(w===null?g.append(y,""):Array.isArray(w)?w.forEach(P=>g.append(y,String(P))):typeof w=="object"?g.append(y,JSON.stringify(w)):g.append(y,String(w)));n.body=g}else s.set("Content-Type","application/json"),n.body=JSON.stringify(e)}n.headers=s;let c;return o&&(c=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:e,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:c,transportMode:o?"query-get":"http",signature:Xt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(t){if(!this.options.copyParams||this.options.copyParams.length===0)return t;const e=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}e.add(a)}});const i={};return(e.size>0?Array.from(e):Object.keys(t)).forEach(s=>{s in t&&(r.has(s)||(i[s]=t[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const t=this.options.adjustValue??0,e=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=t,e.push(r.setValue(String(n)))}return Promise.all(e).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const t=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return t||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=[],r=t.clone();return e.push(t.getParent().insertAfter(r,t)),e.push(F.evaluateAll(r)),e.push(E.reset(r)),Promise.all(e).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getParent();return e&&e.getChildElementFragments().filter(i=>!i.hasAttribute(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.prefix}each-after`)).length<=1?Promise.resolve():t.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getPrevious();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertBefore(t,e):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const t=this.getRowFragment();if(!t)return Promise.reject(new Error("Row fragment not found."));const e=t.getNext();if(!e)return Promise.resolve();const r=t.getParent();return r?r.insertAfter(t,e):Promise.resolve()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let j=f;class Qt{static async load(t,e){let r;try{r=await fetch(t,e)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",t,n),new Error(`Failed to fetch: ${t}`)}if(!r.ok){Mt(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",t,n),new Error(`Failed to load ${t}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",t,n),new Error(`Failed to read response from: ${t}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",t),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",t,n),i}}}const d=class d{static isDeferredAttributeName(t){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(e=>t===`${u.prefix}${e}`)}static isEvaluateAllExcludedAttributeName(t){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(e=>t===`${u.prefix}${e}`)}static shouldReevaluateAttribute(t,e){return e!==null&&!d.isEvaluateAllExcludedAttributeName(t)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(e)}static getAliasedAttributeName(t){const e=`${u.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!t.startsWith(e)||t.length<=e.length?null:t.slice(e.length)}static isAliasedAttributeReflection(t,e){const r=T.get(t);return r instanceof k?r.hasAttribute(`${u.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${e}`):!1}static reevaluateInterpolatedAttributes(t){let e=Promise.resolve();for(const r of t.getAttributeNames()){const i=t.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(e=e.then(()=>d.setAttribute(t.getTarget(),r,i)))}return e.then(()=>{})}static reevaluateChildren(t){const e=[];return t.getChildren().forEach(r=>{r instanceof k?e.push(d.evaluateAll(r)):r instanceof U&&e.push(d.evaluateText(r))}),Promise.all(e).then(()=>{})}static getReactiveFetchState(t){const e=d.REACTIVE_FETCH_STATES.get(t);if(e)return e;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(t,r),r}static getReactiveImportState(t){const e=d.REACTIVE_IMPORT_STATES.get(t);if(e)return e;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(t,r),r}static reevaluateReactiveSpecialAttributes(t,e=new Set){if(e.has(t))return Promise.resolve();const r=[];return t.hasAttribute(`${u.prefix}fetch`)&&r.push(d.executeManagedFetch(t)),t.hasAttribute(`${u.prefix}import`)&&r.push(d.executeManagedImport(t)),t.getChildren().forEach(i=>{i instanceof k&&r.push(d.reevaluateReactiveSpecialAttributes(i,e))}),Promise.all(r).then(()=>{})}static executeManagedFetch(t){const e=t.getTarget(),r=d.getReactiveFetchState(e),i=j.resolveAutoFetchSignature(t);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new j(t,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(t)})}static executeManagedImport(t){const e=t.getTarget(),r=d.getReactiveImportState(e),i=t.getAttributeEvaluation(`${u.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return e.setAttribute(`${u.prefix}importing`,""),R.importStart(e,n),Qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{e.innerHTML=a}).then(()=>{if(e.removeAttribute(`${u.prefix}importing`),R.importEnd(e,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return e.childNodes.forEach(c=>{const h=T.get(c);h instanceof k?l.push(d.scan(h.getTarget())):h instanceof U&&l.push(d.evaluateText(h))}),Promise.all(l).then(()=>{})}})}).catch(a=>{e.removeAttribute(`${u.prefix}importing`),R.importError(e,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(t)})}static scan(t){const e=T.get(t);return e?d.initializeElementFragment(e,!1):Promise.resolve()}static initializeFreshEachRow(t){return d.initializeElementFragment(t,!0).then(()=>{d.needsScheduledEvaluateAll(t)&&d.scheduleEvaluateAll(t)})}static initializeElementFragment(t,e){return d.syncMountedState(t),e&&t.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(t).then(()=>{if(d.shouldSkipChildInitialization(t,e)){d.refreshDerivedSubtreeSignature(t);return}const r=[];return t.getChildren().forEach(i=>{i instanceof k?r.push(d.initializeElementFragment(i,e)):i instanceof U&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(t)})})}static syncMountedState(t){if(t.getParent()?.isMounted()){t.setMounted(!0);return}const r=t.getTarget();if(r.parentNode&&document.body.contains(r)){t.setMounted(!0);return}t.setMounted(!1)}static initializeElementAttributes(t){let e=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>d.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}for(const i of t.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=t.getRawAttribute(i);n!==null&&(e=e.then(()=>d.setAttribute(t.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;t.hasAttribute(n)&&(e=e.then(()=>d.setAttribute(t.getTarget(),n,t.getRawAttribute(n))),r.add(n))}return e.then(()=>{})}static shouldSkipChildInitialization(t,e){const r=t.getAttribute(`${u.prefix}if`);return t.hasAttribute(`${u.prefix}if`)&&d.isHiddenIfCondition(r)?!0:e&&t.hasAttribute(`${u.prefix}each`)}static setAttribute(t,e,r,i=!1){const n=T.get(t),s=d.getAliasedAttributeName(e);if(s!==null)return r===null?n.removeAliasedAttribute(e,s):n.setAliasedAttribute(e,s,r,i);const a=[];let o=null,l=null;switch(e){case`${u.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof k&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${u.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${u.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${u.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${u.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${u.prefix}if`:a.push(d.evaluateIf(n));break;case`${u.prefix}each`:a.push(d.evaluateEach(n));break;case`${u.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${u.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${u.prefix}url-param`:{const c=n.getAttribute(`${u.prefix}url-arg`),h=xt.readParams();if(c===null)a.push(d.setBindingData(t,h,new Set,!0));else{const g=n.getRawBindingData()||{};g[String(c)]=h,a.push(d.setBindingData(t,g,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(e)):a.push(n.setAttribute(e,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(c=>{if(c)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(t,e,r=new Set,i=!1){const n=T.get(t),s=n.getRawBindingData();n.setBindingData(e),R.bindChange(t,s,e,"manual");const a=()=>{n.markBindingWorkStart();const o=n.getRawBindingData()??e;let l=n.setAttribute(`${u.prefix}bind`,JSON.stringify(o));if(t.tagName==="FORM"){const c=n.getAttribute(`${u.prefix}form-arg`),h=c&&o[String(c)]&&typeof o[String(c)]=="object"&&!Array.isArray(o[String(c)])?o[String(c)]:c?{}:o;l=l.then(()=>E.syncValues(n,h))}return l=l.then(()=>d.evaluateAll(n,r)),l=l.then(()=>d.reevaluateReactiveSpecialAttributes(n,r)),l.then(()=>n.markBindingWorkEnd(),c=>{throw n.markBindingWorkEnd(),c})};return i?a():n.enqueueBindingWork(a)}static getBindingData(t,e={}){const r=T.get(t);return r instanceof k?e.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(t){const e=T.get(t);if(!e)return{resolved:{},sources:{}};const r=e.getBindingData(),i={},n=l=>{const c=l.getTarget();return c.id?`#${c.id}`:c.tagName.toLowerCase()},s=(l,c,h,g)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(c),kind:h,depth:g})};let a=e,o=0;for(;a;)a!==e&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return H.isEnabled()&&m.info("[Haori]","scope dump for",t,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(t){if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch(e){return m.error("[Haori]","Invalid JSON in data-bind:",e),{}}else{const e=new URLSearchParams(t),r={};for(const[i,n]of e.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(t,e){const r=T.get(t);if(r.isSkipMutationNodes())return;const i=T.get(e.nextSibling),n=T.get(e);n&&(r.insertBefore(n,i),n instanceof k?d.scan(n.getTarget()):n instanceof U&&d.evaluateText(n))}static removeNode(t){const e=T.get(t);if(e){const r=e.getParent();if(r&&r.isSkipMutationNodes())return;e.remove()}}static changeText(t,e){const r=T.get(t);r&&r.setContent(e)}static changeValue(t,e){const r=T.get(t);if(r.getValue()===e)return Promise.resolve();const i=[];i.push(r.setValue(e));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(t){if(t.getTarget()instanceof HTMLFormElement)return t;const e=t.getParent();return e?d.getFormFragment(e):null}static evaluateAll(t,e=new Set){if(e.has(t))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(t);const i=t.hasAttribute(`${u.prefix}derive`),n=t.hasAttribute(`${u.prefix}if`),s=t.hasAttribute(`${u.prefix}each`),a=t.getRawAttribute(`${u.prefix}derive`),o=t.getRawAttribute(`${u.prefix}derive-name`);let l=!1,c=!1,h=null;if(!i&&t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),!i&&t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),i){const g=d.createDeriveInputSignature(t,a,o);g===null?(t.getDeriveInputSignature()!==null&&t.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(t,a,o).then(()=>{}))):t.getDeriveInputSignature()!==g&&(r=r.then(()=>d.evaluateDerive(t,a,o).then(()=>{t.setDeriveInputSignature(g)})))}return n&&(r=r.then(()=>d.evaluateIf(t))),s?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(t))):n?(t.getDeriveSubtreeSignature()!==null&&t.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}h=d.createDescendantBindingSignature(t,"evaluateAll"),c=!0,l=t.getDeriveSubtreeSignature()!==null&&t.getDeriveSubtreeSignature()===h,d.logDerivedSubtreeProfileSnapshot(t,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const g=[];return t.getChildren().forEach(y=>{if(y instanceof k){if(d.canSkipUnchangedNestedEach(y))return;g.push(d.evaluateAll(y,e))}else y instanceof U&&g.push(d.evaluateText(y))}),Promise.all(g).then(()=>{})}).then(()=>{c&&h!==null&&t.setDeriveSubtreeSignature(h)}))}static evaluateDerive(t,e=t.getRawAttribute(`${u.prefix}derive`),r=t.getRawAttribute(`${u.prefix}derive-name`)){const i=t.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!e||n==="")return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(e,t.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(t.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(t.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(t){return t.evaluate()}static isHiddenIfCondition(t){return!t}static logFalsyIfDiagnostics(t){const e=t.getRawAttribute(`${u.prefix}if`);if(typeof e!="string"||e.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(t.getTarget()),i=new Set,n=e.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=e.indexOf(o,s);s=l+o.length,!(l>0&&e[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",e,"— referenced scope:",a)}static evaluateIf(t){const e=[],r=t.getAttribute(`${u.prefix}if`);if(d.isHiddenIfCondition(r))H.isEnabled()&&d.logFalsyIfDiagnostics(t),e.push(t.hide().then(()=>{R.hide(t.getTarget())}));else{const i=t.isVisible(),n=[];t.getChildren().forEach(s=>{s instanceof k?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof U&&n.push(d.evaluateText(s))}),e.push(t.show().then(()=>{R.show(t.getTarget()),i||d.triggerLoadOnShow(t)})),e.push(Promise.all(n).then(()=>{}))}return Promise.all(e).then(()=>{})}static triggerLoadOnShow(t){const e=`${u.prefix}load-`;t.getTarget().getAttributeNames().some(i=>i.startsWith(e))&&new j(t,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(t){let e=d.EACH_UPDATE_STATES.get(t);return e||(e={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(t,e)),e}static evaluateEach(t){if(!t.isVisible()||!t.isMounted())return Promise.resolve();const e=d.getEachUpdateState(t);return e.running?(e.rerunRequested=!0,e.settled??Promise.resolve()):d.runEachUpdateLoop(t,e)}static runEachUpdateLoop(t,e){e.running=!0,t.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do e.rerunRequested=!1,await d.performEachUpdate(t);while(e.rerunRequested);t.getTarget().setAttribute(`${u.prefix}each-done`,"")}finally{e.running=!1,e.settled=null}})();return e.settled=r,r}static performEachUpdate(t){const e=d.resolveEachItems(t);if(e===null)return Promise.reject(new Error("Invalid each attribute."));let r=t.getTemplate();const i=t.getAttribute(`${u.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:e});if(r===null){let s=!1;if(t.getChildren().forEach(a=>{if(!s&&a instanceof k){if(a.hasAttribute(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0,t.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=t.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const h=T.get(l);h instanceof k&&(r=h.clone(),d.markFreshInitializationSkippable(r),t.setTemplate(r),s=!0)}const c=T.get(l);c instanceof k&&t.getChildren().includes(c)&&(t.removeChild(c),c.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}return t.getEachInputSignature()===n?Promise.resolve():this.updateDiff(t,e).then(()=>{t.setEachInputSignature(n)})}static resolveEachItems(t){const e=t.getAttributeEvaluation(`${u.prefix}each`),r=e?.value;return e?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(t){if(!t.hasAttribute(`${u.prefix}each`)||t.getEachInputSignature()===null)return!1;const e=t.getParent();if(e?.closestByAttribute(`${u.prefix}derive`)||e?.closestByAttribute(`${u.prefix}derive-name`)||e?.closestByAttribute(`${u.prefix}if`)||e?.closestByAttribute(`${u.prefix}fetch`)||e?.closestByAttribute(`${u.prefix}import`)||d.hasNonEachDynamicElementState(t))return!1;const r=d.resolveEachItems(t);if(r===null)return!1;const i=t.getAttribute(`${u.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return t.getEachInputSignature()===n}static canSkipStableDerivedSubtree(t){return!t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}if`)||t.hasAttribute(`${u.prefix}each`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(t)}static hasDisallowedDerivedSubtreeDescendant(t){return t.getChildren().some(e=>e instanceof k?e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}derive-name`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(e):!1)}static createDescendantBindingSignature(t,e){return d.recordDerivedSubtreeSignatureComputation(t,e),d.createBindingSignature(t.getDescendantBindingData())}static createDeriveInputSignature(t,e,r){const i=typeof r=="string"?r.trim():"";return!e||i===""?null:d.createBindingSignature({expression:e,name:i,scope:t.getBindingData()})}static refreshDerivedSubtreeSignature(t){if(!d.canSkipStableDerivedSubtree(t)){t.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(t,"skip-ineligible");return}t.setDeriveSubtreeSignature(d.createDescendantBindingSignature(t,"refresh")),d.logDerivedSubtreeProfileSnapshot(t,"refresh")}static getOrCreateDerivedSubtreeProfile(t){if(!H.isEnabled()||!t.hasAttribute(`${u.prefix}derive`))return null;const e=d.DERIVE_SUBTREE_PROFILES.get(t);if(e)return e;const r={hostId:d.createDerivedSubtreeHostId(t),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(t,r),r}static createDerivedSubtreeHostId(t){const e=[];let r=t;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,e.unshift(n);break}const s=r.getRawAttribute(`${u.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof k).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}e.unshift(n),r=a}return e.join(" > ")}static recordDerivedSubtreeSignatureComputation(t,e){const r=d.getOrCreateDerivedSubtreeProfile(t);if(r!==null){if(r.signatureComputeTotal+=1,e==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(t,e){const r=d.getOrCreateDerivedSubtreeProfile(t);r!==null&&(e==="skip-hit"?r.skipHitCount+=1:e==="skip-miss"?r.skipMissCount+=1:e==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:e,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(t){const e=new Set([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return t.getAttributeNames().some(i=>{if(e.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=t.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:t.getChildren().some(i=>i instanceof U&&i.hasDynamicContent())}static markFreshInitializationSkippable(t){const e=t.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(t,n)),r=t.getChildren().some(n=>n instanceof k?!d.markFreshInitializationSkippable(n):n instanceof U?n.hasDynamicContent():!1),i=!e&&!r;return t.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(t,e){if(e.startsWith(`${u.prefix}attr-`)||e.startsWith(u.prefix))return!0;const r=t.getRawAttribute(e);return typeof r=="string"&&r.includes("{{")}static updateDiff(t,e){const r=t.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=t.getAttribute(`${u.prefix}each-index`);i&&(i=String(i));const n=t.getAttribute(`${u.prefix}each-key`),s=t.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];e.forEach((b,S)=>{const x=d.createListKey(b,n?String(n):null,S);o.push(x),a.set(x,{item:b,itemIndex:S})});const l=new Set(o),c=[];let h=t.getChildren().filter(b=>b instanceof k).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const g=h.map(b=>b.getListKey());h=h.filter(b=>l.has(String(b.getListKey()))?!0:(c.push(b.remove()),!1));const y=h.map(b=>b.getListKey()),w=new Map;h.forEach(b=>{const S=b.getListKey();S!==null&&!w.has(S)&&w.set(S,b)});const P=t.getChildElementFragments().slice(),A=P.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let v=Promise.resolve();return o.forEach((b,S)=>{const{item:x,itemIndex:I}=a.get(b);let $;const V=w.get(b);if(V)$=V,v=v.then(()=>d.updateRowFragment($,x,i,I,s?String(s):null,b).then(C=>{if(C)return d.evaluateAll($)}));else{$=r.clone();const C=A+S;v=v.then(()=>d.updateRowFragment($,x,i,I,s?String(s):null,b).then(()=>{const Z=P[C]??null;return t.insertBefore($,Z).then(()=>{P.splice(C,0,$)}).then(()=>d.initializeFreshEachRow($))}))}}),Promise.all(c).then(()=>v).then(()=>{const b=o.filter(C=>C!==null),S=y.filter(C=>C!==null),x=new Set(S),I=b.filter(C=>!x.has(C)),V=g.filter(C=>C!==null).filter(C=>!l.has(C));R.eachUpdate(t.getTarget(),I,V,b)})}static createListKey(t,e,r){let i;if(typeof t=="object"&&t!==null)if(e){const n=t[e];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(t);return i}static updateRowFragment(t,e,r,i,n,s){let a=e;if(typeof e=="object"&&e!==null)a={...e},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:e},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${e}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return t.getListKey()===s&&t.getRenderSignature()===l?Promise.resolve(!1):(t.setListKey(s),t.setRenderSignature(l),t.setBindingData(o),t.setAttribute(`${u.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(t){const e=[t];for(;e.length>0;){const r=e.pop();if(r.getChildElementFragments().forEach(i=>{e.push(i)}),r!==t&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(t){return["fetch","import"].some(e=>t.hasAttribute(`${u.prefix}${e}`))}static createBindingSignature(t,e=new WeakMap,r={value:0}){if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);if(typeof t=="function")return`[Function:${t.name||"anonymous"}]`;if(typeof t=="symbol")return t.toString();if(t instanceof Date)return`[Date:${t.toISOString()}]`;if(Array.isArray(t)){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`array-${r.value}`;return r.value+=1,e.set(t,i),`[${t.map(n=>d.createBindingSignature(n,e,r)).join(",")}]`}if(typeof t=="object"){if(e.has(t))return`[Circular:${e.get(t)}]`;const i=`object-${r.value}`;r.value+=1,e.set(t,i);const n=t;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],e,r)}`).join(",")}}`}return String(t)}static scheduleEvaluateAll(t){setTimeout(()=>{d.evaluateAll(t)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let F=d;const Q=class Q{constructor(t=document){this.customEventHandlers=new Map,this.onClick=e=>this.delegate(e,"click"),this.onChange=e=>this.delegate(e,"change"),this.onInput=e=>this.delegate(e,"input"),this.onLoadCapture=e=>this.delegate(e,"load"),this.onWindowLoad=()=>{const e=document.documentElement,r=T.get(e);r&&new j(r,"load").run()},this.onPopstate=e=>{const r=e.state;!r||r[Q.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=t}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[t,e]of this.customEventHandlers)window.removeEventListener(t,e,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(e=>this.subscribeCustomEvent(e.getAttribute(this.onAttributeName)))}subscribeCustomEvent(t){if(t===null||t==="")return;if(Q.BUILTIN_EVENT_NAMES.has(t)){m.warn("[Haori]",`data-on="${t}" は組み込みイベントです。data-${t}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(t))return;const e=r=>this.runCustomEventProcedures(t,r);this.customEventHandlers.set(t,e),window.addEventListener(t,e,!0)}runCustomEventProcedures(t,e){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==t)return;const n=T.get(i);n instanceof k&&new j(n,"on",e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const t=this.root instanceof Document?this.root:this.root.ownerDocument??document,e=this.root instanceof Document?t.body:this.root;e&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(e,{childList:!0,subtree:!0}))}delegate(t,e){const r=this.getElementFromTarget(t.target,e);if(!r)return;if(e==="input"){const s=`${u.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${u.prefix}${e}-prevent`)&&t.preventDefault();const i=T.get(r);if(!i)return;(e==="change"||e==="input")&&i instanceof k&&i.syncValue();const n=()=>{new j(i,e,t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(e==="click"&&r.hasAttribute(`${u.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(t,e){if(!t)return null;if(t instanceof HTMLElement)return e==="click"?this.findClickableElement(t):t;if(t instanceof Node){const r=t.parentElement;return r?e==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(t){const e=`${u.prefix}click-`,r=`${u.prefix}click-passive`;let i=t;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(e)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Q.HISTORY_STATE_KEY="__haoriHistoryState__",Q.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ht=Q;const D=class D{static isHtmlElement(t){if(!(t instanceof Element))return!1;const e=t.ownerDocument?.defaultView?.HTMLElement;return typeof e<"u"&&t instanceof e}static syncTree(t){(t instanceof Element||t instanceof DocumentFragment)&&(D.isHtmlElement(t)&&D.syncElement(t),t.querySelectorAll("*").forEach(e=>{D.syncElement(e)}))}static syncElement(t){const e=D.registrations.get(t),r=T.get(t);if(!r||!D.shouldObserve(r)){e&&(e.observer.disconnect(),D.registrations.delete(t));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${u.prefix}intersect-once`);if(e&&e.observer.root===i&&e.observer.rootMargin===n&&D.sameThreshold(e.observer.thresholds,s)&&e.once===a){e.fragment=r;return}e&&(e.observer.disconnect(),D.registrations.delete(t));const o=new IntersectionObserver(l=>{const c=D.registrations.get(t);c&&l.forEach(h=>{!h.isIntersecting||c.running||D.isDisabled(c.fragment)||(c.running=!0,new j(c.fragment,"intersect").runWithResult().then(g=>{g&&c.once&&(c.observer.disconnect(),D.registrations.delete(t))}).catch(g=>{m.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(t);g&&(g.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(t),D.registrations.set(t,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(t){if(D.isHtmlElement(t)){const e=D.registrations.get(t);e&&(e.observer.disconnect(),D.registrations.delete(t))}(t instanceof Element||t instanceof DocumentFragment)&&t.querySelectorAll("*").forEach(e=>{const r=D.registrations.get(e);r&&(r.observer.disconnect(),D.registrations.delete(e))})}static disconnectAll(){D.registrations.forEach(t=>{t.observer.disconnect()}),D.registrations.clear()}static shouldObserve(t){return t.getAttributeNames().some(e=>{if(!e.startsWith(`${u.prefix}intersect-`))return!1;const r=e.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(t){const e=`${u.prefix}intersect-root`;if(!t.hasAttribute(e))return null;const r=t.getAttribute(e);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(t){const e=`${u.prefix}intersect-root-margin`,r=t.getAttribute(e);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(t){const e=`${u.prefix}intersect-threshold`,r=t.getAttribute(e),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(t){const e=`${u.prefix}intersect-disabled`,r=t.getAttribute(e);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(t,e){return t.length===1&&t[0]===e}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let X=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(t=>{t.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const t=await Promise.allSettled([F.scan(document.head),F.scan(document.body)]),[e,r]=t;e.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",e.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ht().start(),X.syncTree(document.body)}static observe(t){const e=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&F.isAliasedAttributeReflection(n,i.attributeName))break;F.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{X.cleanupTree(n),F.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(F.addNode(n.parentElement,n),X.syncTree(n))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?F.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});e.observe(t,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(e)}};O._initialized=!1,O._mutationObservers=[];let nt=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt.init):nt.init();const Zt=()=>J.waitForRenders(),_t="0.20.0";exports.Core=F;exports.Env=u;exports.Form=E;exports.Fragment=T;exports.Haori=J;exports.Log=m;exports.Queue=M;exports.default=J;exports.version=_t;exports.waitForRenders=Zt;
15
+ ${v}
16
+ `)}catch(S){m.error("Haori",`Invalid after script: ${S}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(g.attrName(t,"dialog")).replace(/\\n/g,`
17
+ `)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const v=e.getRawAttribute(g.attrName(t,"toast-level")),k=["info","warning","error","success"].includes(v);r.toastLevel=k?v:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const v=g.attrName(t,"redirect-return-param");e.hasAttribute(v)&&(r.redirectReturnParam=e.getAttribute(v))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const v=e.getRawAttribute(g.attrName(t,"history-form"));if(v){const S=document.body.querySelector(v);S!==null?r.historyFormFragment=E.getFormFragment(T.get(S)):m.error("Haori",`Form element not found: ${v} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(v=>{const S=g.attrName(t,v);if(!e.hasAttribute(S))return;const k=e.getRawAttribute(S),C=[];if(k?(document.body.querySelectorAll(k).forEach(j=>{const $=T.get(j);$&&C.push($)}),C.length===0&&m.error("Haori",`Element not found: ${k} (${S})`)):C.push(e),C.length>0)switch(v){case"reset-before":r.resetBeforeFragments=C;break;case"reset":r.resetFragments=C;break;case"refetch":r.refetchFragments=C;break;case"click":r.clickFragments=C;break;case"copy":r.copyFragments=C;break;case"open":r.openFragments=C;break;case"close":r.closeFragments=C;break}});const y=g.attrName(t,"copy-source");if(e.hasAttribute(y)){const v=e.getRawAttribute(y);if(v){const S=document.body.querySelector(v);if(S!==null){const k=T.get(S);k?r.copySourceFragment=k:m.error("Haori",`Element is not managed by Haori: ${v} (${y})`)}else m.error("Haori",`Element not found: ${v} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const A=e.getRawAttribute(g.attrName(null,"form",!0));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=E.getFormFragment(T.get(y)):m.error("Haori",`Form element not found: ${A} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.getFormFragment(e)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const u=this.options.runScript.call(h,this.domEvent);u===!1&&this.domEvent&&this.domEvent.preventDefault(),u!=null&&typeof u.then=="function"&&await u}catch(u){m.error("Haori",`Run script execution error: ${u}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>E.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},u=r.requestedMethod,p=r.effectiveMethod,b=r.transportMode==="query-get",R=r.queryString;if(b&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:R}),this.options.targetFragment&&n){const I=performance.now(),A={runtime:c.runtime,requestedMethod:u,effectiveMethod:p,transportMode:b?"query-get":"http",...b?{queryString:R}:{}};return F.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,A),fetch(n,h).then(y=>this.handleFetchResult(y,n||void 0,I)).catch(y=>{throw n&&F.fetchError(this.options.targetFragment.getTarget(),n,y),y})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,u=h.getTarget(),p=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&p.add(this.options.targetFragment);const b=h.getBindingData();Object.assign(b,i),await x.setBindingData(u,b,p)}const o=a?i:{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(he))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(he,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(he),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return Be(e.status)||(this.options.targetFragment&&t&&F.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e)),!1;if(this.options.targetFragment&&t&&r&&F.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>E.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.openDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const u=h.trim();$e.isSafeLocalPath(u)?a=u:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();m.error("Haori",l);return}const o=l=>{for(const[h,u]of Object.entries(l))u!=null&&(Array.isArray(u)?u.forEach(p=>a.searchParams.append(h,String(p))):typeof u=="object"?a.searchParams.set(h,JSON.stringify(u)):a.searchParams.set(h,String(u)))};i&&o(t),n&&o(r),history.pushState({[Qe]:!0},"",a.toString())}catch(s){m.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const u of a)if(u&&typeof u=="object"&&!Array.isArray(u)){const p=u.key,b=u.message,R=typeof p=="string"&&p.length>0?p:null,I=typeof b=="string"?b:b!=null?String(b):"";if(I.length===0)continue;if(R!==null){const A=l.get(R)??[];A.push(I),l.set(R,A)}else h.push(I)}else typeof u=="string"&&u.length>0&&h.push(u);for(const[u,p]of l)o.push({key:u,message:p.join(`
18
+ `)});for(const u of h)o.push({message:u})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const l of a.messages)typeof l=="string"&&o.push({message:l});if(a.errors&&typeof a.errors=="object")for(const[l,h]of Object.entries(a.errors))Array.isArray(h)?o.push({key:l,message:h.join(`
19
+ `)}):typeof h=="string"?o.push({key:l,message:h}):h!=null&&o.push({key:l,message:String(h)});if(o.length===0)for(const[l,h]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(h)?o.push({key:l,message:h.join(`
20
+ `)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await E.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=z.evaluate(this.options.bindTransform,{response:i})}catch(s){m.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(x.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(x.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{F.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return x.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?E.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?E.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,E.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=c.runtime==="demo"&&!_e(a),l=o?"GET":a;if(n.method=l,l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=tt(i,t));else if(Object.keys(t).length>0){const u=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(u)){s.delete("Content-Type");const p=new FormData;for(const[b,R]of Object.entries(t))R==null?p.append(b,""):R instanceof Blob?p.append(b,R):Array.isArray(R)?R.forEach(I=>p.append(b,String(I))):typeof R=="object"?p.append(b,JSON.stringify(R)):p.append(b,String(R));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(u)){const p=new URLSearchParams;for(const[b,R]of Object.entries(t))R!==void 0&&(R===null?p.append(b,""):Array.isArray(R)?R.forEach(I=>p.append(b,String(I))):typeof R=="object"?p.append(b,JSON.stringify(R)):p.append(b,String(R)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:it(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(x.evaluateAll(r)),t.push(E.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${c.prefix}each-before`)&&!i.hasAttribute(`${c.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let q=g;class nt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Be(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof M?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(d.evaluateAll(r)):r instanceof V&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new q(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${c.prefix}importing`,""),F.importStart(t,n),nt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${c.prefix}importing`),F.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const u=T.get(h);u instanceof M?l.push(d.scan(u.getTarget())):u instanceof V&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),F.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(d.initializeElementFragment(i,t)):i instanceof V&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${c.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${c.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${c.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${c.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${c.prefix}if`:a.push(d.evaluateIf(n));break;case`${c.prefix}each`:a.push(d.evaluateEach(n));break;case`${c.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${c.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${c.prefix}url-param`:{const h=n.getAttribute(`${c.prefix}url-arg`),u=$e.readParams();if(h===null)a.push(d.setBindingData(e,u,new Set,!0));else{const p=n.getRawBindingData()||{};p[String(h)]=u,a.push(d.setBindingData(e,p,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&F.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${c.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const u=s.getAttribute(`${c.prefix}form-arg`),p=u&&l[String(u)]&&typeof l[String(u)]=="object"&&!Array.isArray(l[String(u)])?l[String(u)]:u?{}:l;h=h.then(()=>E.syncValues(s,p))}return h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),u=>{throw s.markBindingWorkEnd(),u})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,u,p)=>{if(l)for(const b of Object.keys(l))b in i||(i[b]={value:l[b],source:n(h),kind:u,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return L.isEnabled()&&m.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof V&&d.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=E.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,h=!1,u=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=d.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}u=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===u,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const p=[];return e.getChildren().forEach(b=>{if(b instanceof M){if(d.canSkipUnchangedNestedEach(b))return;p.push(d.evaluateAll(b,t))}else b instanceof V&&p.push(d.evaluateText(b))}),Promise.all(p).then(()=>{})}).then(()=>{h&&u!==null&&e.setDeriveSubtreeSignature(u)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=z.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(r))L.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{F.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof V&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{F.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${c.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof M){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const u=T.get(l);u instanceof M&&(r=u.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=T.get(l);h instanceof M&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${c.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof V&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!d.markFreshInitializationSkippable(n):n instanceof V?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=new Map,o=[];t.forEach((v,S)=>{const k=d.createListKey(v,n?String(n):null,S);o.push(k),a.set(k,{item:v,itemIndex:S})});const l=new Set(o),h=[];let u=e.getChildren().filter(v=>v instanceof M).filter(v=>!v.hasAttribute(`${c.prefix}each-before`)&&!v.hasAttribute(`${c.prefix}each-after`));const p=u.map(v=>v.getListKey());u=u.filter(v=>l.has(String(v.getListKey()))?!0:(h.push(v.remove()),!1));const b=u.map(v=>v.getListKey()),R=new Map;u.forEach(v=>{const S=v.getListKey();S!==null&&!R.has(S)&&R.set(S,v)});const I=e.getChildElementFragments().slice(),A=I.filter(v=>v.hasAttribute(`${c.prefix}each-before`)).length;let y=Promise.resolve();return o.forEach((v,S)=>{const{item:k,itemIndex:C}=a.get(v);let O;const j=R.get(v);if(j)O=j,y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,v).then($=>{if($)return d.evaluateAll(O)}));else{O=r.clone();const $=A+S;y=y.then(()=>d.updateRowFragment(O,k,i,C,s?String(s):null,v).then(()=>{const ee=I[$]??null;return e.insertBefore(O,ee).then(()=>{I.splice($,0,O)}).then(()=>d.initializeFreshEachRow(O))}))}}),Promise.all(h).then(()=>y).then(()=>{const v=o.filter($=>$!==null),S=b.filter($=>$!==null),k=new Set(S),C=v.filter($=>!k.has($)),j=p.filter($=>$!==null).filter($=>!l.has($));F.eachUpdate(e.getTarget(),C,j,v)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap;let x=d;const _=class _{constructor(e=document){this.customEventHandlers=new Map,this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=T.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[_.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate);for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(_.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof M&&new q(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;if(t==="input"){const s=`${c.prefix}input-`;if(!r.getAttributeNames().some(o=>o.startsWith(s)))return}r.hasAttribute(`${c.prefix}${t}-prevent`)&&e.preventDefault();const i=T.get(r);if(!i)return;(t==="change"||t==="input")&&i instanceof M&&i.syncValue();const n=()=>{new q(i,t,e).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&r.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};_.HISTORY_STATE_KEY="__haoriHistoryState__",_.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let fe=_;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=T.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=D.registrations.get(e);h&&l.forEach(u=>{!u.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(p=>{p&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=D.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return D.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Z=D;function st(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=T.get(e);if(!(r instanceof M)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let u=!1;l.forEach(p=>{const b=p.target;h.observedRows.has(b)&&(p.isIntersecting?h.visibleRows.has(b)||(h.visibleRows.add(b),u=!0):h.visibleRows.delete(b)&&(u=!0))}),u&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof M&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,st(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);x.setBindingData(i,n,a,!1,!1).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let Y=w;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers();const e=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),new fe().start(),Z.syncTree(document.body),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&x.isAliasedAttributeReflection(n,i.attributeName))break;x.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),Z.syncElement(n),Y.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{Z.cleanupTree(n),Y.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),Z.syncTree(n),Y.syncTree(n))}),i.target instanceof Element&&Y.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){m.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}};H._initialized=!1,H._mutationObservers=[];let ae=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ae.init):ae.init();const at=()=>Q.waitForRenders(),ot="0.20.0";exports.Core=x;exports.Env=c;exports.Form=E;exports.Fragment=T;exports.Haori=Q;exports.Log=m;exports.Queue=P;exports.default=Q;exports.version=ot;exports.waitForRenders=at;
21
21
  //# sourceMappingURL=haori.cjs.js.map