haori 0.26.0 → 0.26.2

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,9 +1,9 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Q=class Q{static isEnabled(){return Q.devMode}static enable(){Q.devMode=!0}static disable(){Q.devMode=!1}static set(e){Q.devMode=e}};Q.devMode=!1;let L=Q;const pe="embedded";function De(f){return f==="embedded"||f==="demo"}function We(f){return f===null?null:De(f)?f:pe}const V=class V{static get runtime(){return V._runtime}static setRuntime(e){V._runtime=De(e)?e:pe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||V._prefix;V._prefix=r.endsWith("-")?r:r+"-";const i=We(e.getAttribute("data-runtime"));i!==null&&(V._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${V._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 V._prefix}};V._prefix="data-",V._runtime=pe;let u=V;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",u.detect):u.detect();class p{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 Fe="yyyy/MM/dd HH:mm",Ke="en-US",Te=1e4;function z(f){return String(f).padStart(2,"0")}function Ne(f,e,t,r,i,n){return{yyyy:String(f).padStart(4,"0"),yy:z(f%100),MM:z(e),M:String(e),dd:z(t),d:String(t),HH:z(r),H:String(r),mm:z(i),ss:z(n)}}function Me(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 d of t)d.type!=="literal"&&(r[d.type]=d.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:Ne(i,n,s,a,o,l)}function de(f,e=Fe,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=Me(r,t.trim()),i===null)return""}else i=Ne(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])}const ze="yyyy-MM-dd";function xe(f=Fe,e){return de(new Date,f,e)}function Pe(f=0,e=ze,t){const r=Number.isFinite(f)?Math.trunc(f):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const l=Me(new Date,i);if(l===null)return"";n=Number(l.yyyy),s=Number(l.MM),a=Number(l.dd)}else{const l=new Date;n=l.getFullYear(),s=l.getMonth()+1,a=l.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return de(o,e,"UTC")}function Ie(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(Ke,r).format(t)}function ke(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<Te;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Te;a+=n)s.push(a);return s}function Ce(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 c=0;c<s&&c<r;c+=1)a.add(c);for(let c=Math.max(0,r-s);c<r;c+=1)a.add(c);for(let c=Math.max(0,i-n);c<=Math.min(r-1,i+n);c+=1)a.add(c);const o=Array.from(a).sort((c,m)=>c-m),l=[];let d=null;for(const c of o){if(d!==null&&c-d>1)if(c-d===2){const m=d+1;l.push({page:m,label:m+1,active:m===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:c,label:c+1,active:c===i,ellipsis:!1}),d=c}return l}const Ge=/^(\d{4})-(\d{1,2})$/,Ye=1200;function ie(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function he(f,e){if(typeof f!="string")return"";const t=Ge.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")}-${z(o)}`}function Je(f){if(typeof f=="string"&&f.trim()!=="")return he(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${z(e.getMonth()+1)}`}function Be(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=Je(e);if(r==="")return[];const i=Math.min(t,Ye),n=[];for(let s=0;s<=i;s+=1){const a=he(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function $e(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=ie(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,ie(r.number,0)),s=Math.max(0,ie(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 c=ie(r.numberOfElements,NaN);l=Number.isFinite(c)?c:Math.min(s,i-a)}const d=Math.min(a+l,i);return{start:o,end:Math.max(d,o),total:i,empty:!1}}function Oe(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 He(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 Le(f,e){return e==null||f==null?String(f):String(f[e])}function Ue(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const n=Le(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function Ve(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const n=Le(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 Xe=Object.freeze({date:de,now:xe,today:Pe,number:Ie,pages:Ce,range:ke,monthAdd:he,monthRange:Be,pageSummary:$e,findBy:Oe,sum:He,distinct:Ue,groupBy:Ve}),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 p.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const l=this.detectDisallowedKeywords(e);if(l.length>0){const d=l.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.";p.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+l.join(", ")+"."+d)}else p.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(),p.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 p.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&&p.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 d=this.prepareEvaluator(e,a);if(d.compileFailed||d.evaluator===null)return{value:null,unresolvedReference:!1};try{const c=[],m=this.wrapBoundValues(a);return d.bindKeys.forEach(y=>{c.push(m[y])}),{value:this.withBlockedPropertyAccess(()=>d.evaluator(...c)),unresolvedReference:!1}}catch(c){if(o&&c instanceof ReferenceError){const y=this.extractMissingIdentifier(c);if(y!==null&&this.canRecoverMissingIdentifier(y,a)){a[y]=void 0;continue}}const m=this.detectForbiddenIdentifiers(e);return m.length>0&&p.warn("[Haori]","Expression references blocked identifier(s): "+m.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),p.error("[Haori]","Expression evaluation error:",e,c),c instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return p.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";
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const Q=class Q{static isEnabled(){return Q.devMode}static enable(){Q.devMode=!0}static disable(){Q.devMode=!1}static set(e){Q.devMode=e}};Q.devMode=!1;let U=Q;const ye="embedded";function De(f){return f==="embedded"||f==="demo"}function We(f){return f===null?null:De(f)?f:ye}const V=class V{static get runtime(){return V._runtime}static setRuntime(e){V._runtime=De(e)?e:ye}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||V._prefix;V._prefix=r.endsWith("-")?r:r+"-";const i=We(e.getAttribute("data-runtime"));i!==null&&(V._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${V._prefix}dev`)){U.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){U.set(!0);return}U.set(!1)}catch{}}static get prefix(){return V._prefix}};V._prefix="data-",V._runtime=ye;let u=V;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",u.detect):u.detect();class p{static info(e,...t){U.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){U.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const Fe="yyyy/MM/dd HH:mm",Ke="en-US",Te=1e4;function G(f){return String(f).padStart(2,"0")}function Ne(f,e,t,r,i,n){return{yyyy:String(f).padStart(4,"0"),yy:G(f%100),MM:G(e),M:String(e),dd:G(t),d:String(t),HH:G(r),H:String(r),mm:G(i),ss:G(n)}}function Me(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:Ne(i,n,s,a,o,l)}function de(f,e=Fe,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=Me(r,t.trim()),i===null)return""}else i=Ne(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])}const ze="yyyy-MM-dd";function xe(f=Fe,e){return de(new Date,f,e)}function ke(f=0,e=ze,t){const r=Number.isFinite(f)?Math.trunc(f):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const l=Me(new Date,i);if(l===null)return"";n=Number(l.yyyy),s=Number(l.MM),a=Number(l.dd)}else{const l=new Date;n=l.getFullYear(),s=l.getMonth()+1,a=l.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return de(o,e,"UTC")}function Pe(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(Ke,r).format(t)}function Ie(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<Te;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Te;a+=n)s.push(a);return s}function Ce(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 c=0;c<s&&c<r;c+=1)a.add(c);for(let c=Math.max(0,r-s);c<r;c+=1)a.add(c);for(let c=Math.max(0,i-n);c<=Math.min(r-1,i+n);c+=1)a.add(c);const o=Array.from(a).sort((c,m)=>c-m),l=[];let h=null;for(const c of o){if(h!==null&&c-h>1)if(c-h===2){const m=h+1;l.push({page:m,label:m+1,active:m===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:c,label:c+1,active:c===i,ellipsis:!1}),h=c}return l}const Ge=/^(\d{4})-(\d{1,2})$/,Ye=1200;function ne(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function fe(f,e){if(typeof f!="string")return"";const t=Ge.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")}-${G(o)}`}function Je(f){if(typeof f=="string"&&f.trim()!=="")return fe(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${G(e.getMonth()+1)}`}function Be(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=Je(e);if(r==="")return[];const i=Math.min(t,Ye),n=[];for(let s=0;s<=i;s+=1){const a=fe(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function $e(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=ne(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,ne(r.number,0)),s=Math.max(0,ne(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 c=ne(r.numberOfElements,NaN);l=Number.isFinite(c)?c: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 Oe(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 He(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 Le(f,e){return e==null||f==null?String(f):String(f[e])}function Ue(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const n=Le(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function Ve(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const n=Le(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 Xe=Object.freeze({date:de,now:xe,today:ke,number:Pe,pages:Ce,range:Ie,monthAdd:fe,monthRange:Be,pageSummary:$e,findBy:Oe,sum:He,distinct:Ue,groupBy:Ve}),$=class ${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 p.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(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.";p.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+l.join(", ")+"."+h)}else p.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(),p.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 p.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&&p.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 c=[],m=this.wrapBoundValues(a);return h.bindKeys.forEach(y=>{c.push(m[y])}),{value:this.withBlockedPropertyAccess(()=>h.evaluator(...c)),unresolvedReference:!1}}catch(c){if(o&&c instanceof ReferenceError){const y=this.extractMissingIdentifier(c);if(y!==null&&this.canRecoverMissingIdentifier(y,a)){a[y]=void 0;continue}}const m=this.detectForbiddenIdentifiers(e);return m.length>0&&p.warn("[Haori]","Expression references blocked identifier(s): "+m.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),p.error("[Haori]","Expression evaluation error:",e,c),c instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return p.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
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 p.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,d=t[n-3]||null;if(this.startsObjectKey(o,i,l,d)&&(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 c=this.startsMemberAccess(i)?"member":"array";r.push(c);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={...Xe},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 Y=B;class ye{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),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.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 ye.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const Ee=class Ee{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)}};Ee.ASYNC_QUEUE=new ye;let P=Ee;const I=class I{static reset(){I.ELEMENT_STORES.clear(),I.ensureGlobalAccess()}static snapshot(){return I.ensureGlobalAccess(),[...I.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:I.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:I.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;I.ensureGlobalAccess();const i=I.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=I.getOrCreateCounter(i.attributes,e.rawName,e.template);I.updateCounter(s,t,r);return}const n=I.getOrCreateCounter(i.texts,String(e.childIndex),e.template);I.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!L.isEnabled())return;const e=globalThis;e[I.GLOBAL_KEY]===void 0&&(e[I.GLOBAL_KEY]={reset:()=>I.reset(),snapshot:()=>I.snapshot()})}static getOrCreateElementStore(e){const t=I.createElementId(e),r=I.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return I.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=I.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=I.now();return{value:e(),durationMs:I.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(`${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})`),t.unshift(i),r=a}return t.join(" > ")}};I.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",I.ELEMENT_STORES=new Map;let ae=I;const Z=class Z{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Z.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Z.FRAGMENT_CACHE.has(e))return Z.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new j(e);break;case Node.COMMENT_NODE:t=new ve(e);break;default:return p.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),Z.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Z.FRAGMENT_CACHE=new WeakMap;let S=Z;const G=class G extends S{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(`${u.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new oe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=S.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof G)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new G(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(`${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(e=>{e instanceof G&&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 G&&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==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():P.enqueue(()=>{r.value=""})):(p.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());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 HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,P.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&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 p.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 if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):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 oe(e,r);if(n){const fe=this.attributeMap.get(e);if(fe&&(fe.isEvaluate||fe.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,d=e===t&&G.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),c=s.isSingleExpression(),m=J.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:m,T=!s.isForceEvaluation()&&(t!==e||d||c?o.hasUnresolvedReference||y===null||y===void 0||y===!1:l&&m===""),k=s.isForceEvaluation()?r:c?y:m,H=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),E=a.getRootNode(),b=H&&a===E.activeElement,v=T||k===null||k===!1?null:String(k),R=e!==t&&a.getAttribute(e)!==r,C=v===null?a.hasAttribute(t):a.getAttribute(t)!==v,F=H&&!b&&v!==null&&a.value!==v,U=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),$=t==="selected"&&a instanceof HTMLOptionElement,K=E.activeElement,Ae=K!==null&&(U&&a===K||$&&a.closest("select")===K),re=v!==null,Se=U&&!Ae&&a.checked!==re,we=$&&!Ae&&a.selected!==re;return!R&&!C&&!F&&!Se&&!we?(H&&!b&&v!==null&&(this.value=this.normalizeValueForElement(a,v)),Promise.resolve()):(this.skipMutationAttributes=!0,P.enqueue(()=>{R&&a.setAttribute(e,r),v===null?a.removeAttribute(t):(C&&(a.setAttribute(t,v),t===`${u.prefix}bind`&&this.recordSelfWrittenBind(v)),H&&!b&&(this.value=this.normalizeValueForElement(a,v),F&&(a.value=v))),Se&&(a.checked=re),we&&(a.selected=re)}).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:J.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=S.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 p.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 p.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 d=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let m;if(s?a!==-1&&a<o?m=o-1:m=o:m=this.children.indexOf(t),m===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),d=y.referenceNode)}else this.children.splice(m,0,e)}e.setParent(this),e.setMounted(this.mounted);const c=this.skipMutationNodes;return this.skipMutationNodes=!0,P.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=c})}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?(p.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(`${u.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(`${u.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)}};G.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=G;class j extends S{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new J(this.text)}clone(){const e=new j(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 J(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=J.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 ve extends S{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new ve(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 ue=class ue{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ue.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&&(p.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 d=ae.measure(()=>Y.evaluateDetailed(l.text,e)),c=d.value;a+=d.durationMs,s.push({expression:l.text,durationMs:d.durationMs}),o=o||c.unresolvedReference,n.push(c.value)}else n.push(l.text)}catch(d){p.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,d),s.push({expression:l.text,durationMs:0}),n.push("")}}),ae.record(t,s,a),{results:n,hasUnresolvedReference:o}}};ue.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let J=ue;const ce=class ce extends J{constructor(e,t){super(t),this.forceEvaluation=ce.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?(p.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ce.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let oe=ce;class q{static get runtime(){return u.runtime}static setRuntime(e){u.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?(q.clearMessagesSync(e),e.showModal()):p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return P.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.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(()=>{q.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return de(e,t,r)}static now(e,t){return xe(e,t)}static today(e,t,r){return Pe(e,t,r)}static number(e,t){return Ie(e,t)}static range(e,t,r){return ke(e,t,r)}static pages(e,t,r){return Ce(e,t,r)}static monthAdd(e,t){return he(e,t)}static monthRange(e,t){return Be(e,t)}static pageSummary(e,t){return $e(e,t)}static findBy(e,t,r){return Oe(e,t,r)}static sum(e,t){return He(e,t)}static distinct(e,t){return Ue(e,t)}static groupBy(e,t){return Ve(e,t)}}const Qe=["addErrorMessage","clearMessages"];function Re(){const e=globalThis.window?.Haori;return Qe.every(r=>typeof e?.[r]=="function")?e:q}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(A.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}return e.getValue()}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getPartValues(e,t){if(e.getTarget().hasAttribute(`${u.prefix}if-false`))return t;const r=e.getAttribute("name"),i=e.getAttribute(`${u.prefix}form-object`),n=e.getAttribute(`${u.prefix}form-list`);if(r){if(n){const s=A.resolveCollectedValue(e),a=A.isFileInput(e)&&Array.isArray(s)?s:[s];Array.isArray(t[String(r)])?t[String(r)].push(...a):t[String(r)]=a}else if(A.isGroupedCheckable(e)){const s=e.getTarget(),o=(s instanceof HTMLInputElement?s.checked:!0)?e.getValue():null,l=String(r);o===null?l in t||(t[l]=null):t[l]===null||t[l]===void 0?t[l]=o:Array.isArray(t[l])?t[l].push(o):t[l]=[t[l],o]}else t[String(r)]=A.resolveCollectedValue(e);i&&p.warn("Haori",`Element cannot have both ${u.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())A.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())A.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&p.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 e.getChildElementFragments()){const o={};A.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())A.getPartValues(s,t);return t}static setValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return A.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 isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}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(`${u.prefix}form-object`),l=e.getAttribute(`${u.prefix}form-list`),d=e.getAttribute(`${u.prefix}form-detach`);if(a){if(!d||i){const c=t[String(a)];if(A.isFileInput(e))return(c===null||c==="")&&s.push(A.applyFragmentValue(e,null,n)),Promise.all(s).then(()=>{});l&&Array.isArray(c)&&r!==null?s.push(A.applyFragmentValue(e,c[r]??null,n)):typeof c>"u"||(Array.isArray(c)&&A.isGroupedCheckable(e)||Array.isArray(c)&&A.isMultipleSelect(e)||typeof c=="string"||typeof c=="number"||typeof c=="boolean"||c===null?s.push(A.applyFragmentValue(e,c,n)):s.push(A.applyFragmentValue(e,String(c),n)))}}else if(o){const c=t[String(o)];if(c&&typeof c=="object")for(const m of e.getChildElementFragments())s.push(A.setPartValues(m,c,null,i,n))}else if(l){const c=t[String(l)];if(Array.isArray(c)){const m=e.getChildElementFragments();for(let y=0;y<m.length;y++){const T=m[y];c.length>y?s.push(A.setPartValues(T,c[y],y,i,n)):s.push(A.setPartValues(T,{},y,i,n))}}}else for(const c of e.getChildElementFragments())s.push(A.setPartValues(c,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.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=A.collectBindingTargetForms(e);for(const r of t){const i=A.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}A.syncValuesFromDom(e);for(const r of t){const i=A.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=A.getValues(r),s=r.getAttribute(`${u.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())A.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=S.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],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&&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())A.clearValues(t)}static clearMessages(e){return Re().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Re(),a=s.addMessage,o=d=>typeof a=="function"?a.call(s,d,r,i):s.addErrorMessage(d,r),l=A.findFragmentsByKey(e,t);return l.forEach(d=>{n.push(o(d.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return A.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(`${u.prefix}form-object`))t.length>1&&e.getAttribute(`${u.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${u.prefix}form-list`)){if(t.length>1){const n=e.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),d=Number(l);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const c=e.getChildElementFragments().filter(m=>m.hasAttribute(`${u.prefix}row`));d<c.length&&r.push(...A.findFragmentByKeyParts(c[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${u.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class N{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){N.dispatch(document,"ready",{version:e})}static importStart(e,t){N.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){N.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){N.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 d=t?.[l],c=r[l];d!==c&&n.push(l)}N.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){N.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){N.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){N.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){N.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){N.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){N.dispatch(e,"show",{visible:!0})}static hide(e){N.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){N.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){N.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){N.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 _e(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function et(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=S.get(f),i=r instanceof M?r.getBindingData():{},n=_e(t,i);return n===""?null:n}function tt(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 je(f){const e=Ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${u.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=et(i,t);if(n===null)continue;const s=tt(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 qe{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 rt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],it="__haoriHistoryState__",ge="data-haori-click-lock";function ne(){const e=globalThis.window?.Haori;return rt.every(r=>typeof e?.[r]=="function")?e:q}const nt=new Set(["GET","HEAD","OPTIONS"]);function st(f){return nt.has(f.toUpperCase())}function at(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 ot(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return at(r,e),t.search=r.toString(),t.toString()}function lt(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 te(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(te):f!==null&&typeof f=="object"?Object.values(f).some(te):!1}function ut(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&te(t)):te(e))}function se(f){return me(A.getValues(f))}function me(f){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(f))t[r]=e(i);return t}function ct(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:lt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!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?`${u.prefix}${e}-${t}`:r?`${u.prefix}fetch-${t}`:`${u.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=Y.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=Y.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,`
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 p.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 c=this.startsMemberAccess(i)?"member":"array";r.push(c);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}};$.MAX_IDENTIFIER_RECOVERY_COUNT=8,$.BUILTIN_NAMESPACE="haori",$.BUILTIN_HELPERS={...Xe},$.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,$.forbiddenBindingValueCache=new WeakMap,$.forbiddenBindingValueCacheResetScheduled=!1,$.loggedForbiddenKeySignatures=new Set,$.loggedForbiddenKeyResetScheduled=!1,$.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"],$.STRICT_FORBIDDEN_NAMES=["eval","arguments"],$.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),$.FORBIDDEN_BINDING_NAMES=new Set([...$.FORBIDDEN_NAMES.filter(e=>!$.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...$.STRICT_FORBIDDEN_NAMES]),$.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),$.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),$.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"]),$.EXPRESSION_CACHE=new Map;let Y=$;class Ae{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),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.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 Ae.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const we=class we{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)}};we.ASYNC_QUEUE=new Ae;let k=we;const P=class P{static reset(){P.ELEMENT_STORES.clear(),P.ensureGlobalAccess()}static snapshot(){return P.ensureGlobalAccess(),[...P.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:P.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:P.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(!U.isEnabled()||!e||t.length===0)return;P.ensureGlobalAccess();const i=P.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=P.getOrCreateCounter(i.attributes,e.rawName,e.template);P.updateCounter(s,t,r);return}const n=P.getOrCreateCounter(i.texts,String(e.childIndex),e.template);P.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!U.isEnabled())return;const e=globalThis;e[P.GLOBAL_KEY]===void 0&&(e[P.GLOBAL_KEY]={reset:()=>P.reset(),snapshot:()=>P.snapshot()})}static getOrCreateElementStore(e){const t=P.createElementId(e),r=P.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return P.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=P.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=P.now();return{value:e(),durationMs:P.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(`${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})`),t.unshift(i),r=a}return t.join(" > ")}};P.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",P.ELEMENT_STORES=new Map;let oe=P;const Z=class Z{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Z.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Z.FRAGMENT_CACHE.has(e))return Z.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new j(e);break;case Node.COMMENT_NODE:t=new Se(e);break;default:return p.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 k.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 k.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 k.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),Z.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Z.FRAGMENT_CACHE=new WeakMap;let S=Z;const q=class q extends S{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(`${u.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new le(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=S.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof q)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new q(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(`${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(e=>{e instanceof q&&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 q&&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==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():k.enqueue(()=>{r.value=""})):(p.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());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,k.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,k.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&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,k.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 p.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 if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=S.get(t);r instanceof q&&r.syncValue()}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 k.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 le(e,r);if(n){const me=this.attributeMap.get(e);if(me&&(me.isEvaluate||me.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,k.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&&q.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),c=s.isSingleExpression(),m=J.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:m,T=!s.isForceEvaluation()&&(t!==e||h||c?o.hasUnresolvedReference||y===null||y===void 0||y===!1:l&&m===""),I=s.isForceEvaluation()?r:c?y:m,H=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),E=a.getRootNode(),b=H&&a===E.activeElement,v=T||I===null||I===!1?null:String(I),R=e!==t&&a.getAttribute(e)!==r,C=v===null?a.hasAttribute(t):a.getAttribute(t)!==v,F=H&&!b&&v!==null&&a.value!==v,L=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),B=t==="selected"&&a instanceof HTMLOptionElement,z=E.activeElement,ge=z!==null&&(L&&a===z||B&&a.closest("select")===z),re=v!==null,pe=L&&!ge&&a.checked!==re,ie=B&&!ge&&a.selected!==re;return!R&&!C&&!F&&!pe&&!ie?(H&&!b&&v!==null&&(this.value=this.normalizeValueForElement(a,v)),(L||B)&&!ge&&this.syncCheckableValueFromDom(B),Promise.resolve()):(this.skipMutationAttributes=!0,k.enqueue(()=>{R&&a.setAttribute(e,r),v===null?a.removeAttribute(t):(C&&(a.setAttribute(t,v),t===`${u.prefix}bind`&&this.recordSelfWrittenBind(v)),H&&!b&&(this.value=this.normalizeValueForElement(a,v),F&&(a.value=v))),pe&&(a.checked=re),ie&&(a.selected=re),(pe||ie)&&this.syncCheckableValueFromDom(ie)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return k.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:J.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=S.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 p.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 p.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 m;if(s?a!==-1&&a<o?m=o-1:m=o:m=this.children.indexOf(t),m===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),h=y.referenceNode)}else this.children.splice(m,0,e)}e.setParent(this),e.setMounted(this.mounted);const c=this.skipMutationNodes;return this.skipMutationNodes=!0,k.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=c})}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?(p.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(`${u.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(`${u.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)}};q.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=q;class j extends S{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new J(this.text)}clone(){const e=new j(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 J(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):k.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=J.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 Se extends S{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Se(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,k.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ce=class ce{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ce.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&&(p.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=oe.measure(()=>Y.evaluateDetailed(l.text,e)),c=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||c.unresolvedReference,n.push(c.value)}else n.push(l.text)}catch(h){p.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),oe.record(t,s,a),{results:n,hasUnresolvedReference:o}}};ce.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let J=ce;const he=class he extends J{constructor(e,t){super(t),this.forceEvaluation=he.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?(p.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};he.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let le=he;class W{static get runtime(){return u.runtime}static setRuntime(e){u.setRuntime(e)}static waitForRenders(){return k.waitForIdle()}static dialog(e){return k.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 k.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return k.enqueue(()=>{e instanceof HTMLDialogElement?(W.clearMessagesSync(e),e.showModal()):p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return k.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return W.addMessage(e,t,"error")}static addMessage(e,t,r){return k.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 k.enqueue(()=>{W.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return de(e,t,r)}static now(e,t){return xe(e,t)}static today(e,t,r){return ke(e,t,r)}static number(e,t){return Pe(e,t)}static range(e,t,r){return Ie(e,t,r)}static pages(e,t,r){return Ce(e,t,r)}static monthAdd(e,t){return fe(e,t)}static monthRange(e,t){return Be(e,t)}static pageSummary(e,t){return $e(e,t)}static findBy(e,t,r){return Oe(e,t,r)}static sum(e,t){return He(e,t)}static distinct(e,t){return Ue(e,t)}static groupBy(e,t){return Ve(e,t)}}const Qe=["addErrorMessage","clearMessages"];function Re(){const e=globalThis.window?.Haori;return Qe.every(r=>typeof e?.[r]=="function")?e:W}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(A.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(A.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getPartValues(e,t){if(e.getTarget().hasAttribute(`${u.prefix}if-false`))return t;const r=e.getAttribute("name"),i=e.getAttribute(`${u.prefix}form-object`),n=e.getAttribute(`${u.prefix}form-list`);if(r){if(n){const s=A.resolveCollectedValue(e),a=A.isFileInput(e)&&Array.isArray(s)?s:[s];Array.isArray(t[String(r)])?t[String(r)].push(...a):t[String(r)]=a}else if(A.isGroupedCheckable(e)){const s=e.getTarget(),o=(s instanceof HTMLInputElement?s.checked:!0)?e.getValue():null,l=String(r);o===null?l in t||(t[l]=null):t[l]===null||t[l]===void 0?t[l]=o:Array.isArray(t[l])?t[l].push(o):t[l]=[t[l],o]}else t[String(r)]=A.resolveCollectedValue(e);i&&p.warn("Haori",`Element cannot have both ${u.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())A.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())A.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&p.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 e.getChildElementFragments()){const o={};A.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())A.getPartValues(s,t);return t}static setValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return A.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 isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}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(`${u.prefix}form-object`),l=e.getAttribute(`${u.prefix}form-list`),h=e.getAttribute(`${u.prefix}form-detach`);if(a){if(!h||i){const c=t[String(a)];if(A.isFileInput(e))return(c===null||c==="")&&s.push(A.applyFragmentValue(e,null,n)),Promise.all(s).then(()=>{});l&&Array.isArray(c)&&r!==null?s.push(A.applyFragmentValue(e,c[r]??null,n)):typeof c>"u"||(Array.isArray(c)&&A.isGroupedCheckable(e)||Array.isArray(c)&&A.isMultipleSelect(e)||typeof c=="string"||typeof c=="number"||typeof c=="boolean"||c===null?s.push(A.applyFragmentValue(e,c,n)):s.push(A.applyFragmentValue(e,String(c),n)))}}else if(o){const c=t[String(o)];if(c&&typeof c=="object")for(const m of e.getChildElementFragments())s.push(A.setPartValues(m,c,null,i,n))}else if(l){const c=t[String(l)];if(Array.isArray(c)){const m=e.getChildElementFragments();for(let y=0;y<m.length;y++){const T=m[y];c.length>y?s.push(A.setPartValues(T,c[y],y,i,n)):s.push(A.setPartValues(T,{},y,i,n))}}}else for(const c of e.getChildElementFragments())s.push(A.setPartValues(c,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.clearEachClones(e)]),await k.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=A.collectBindingTargetForms(e);for(const r of t){const i=A.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}A.syncValuesFromDom(e);for(const r of t){const i=A.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=A.getValues(r),s=r.getAttribute(`${u.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())A.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=S.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],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&&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())A.clearValues(t)}static clearMessages(e){return Re().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Re(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=A.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 A.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(`${u.prefix}form-object`))t.length>1&&e.getAttribute(`${u.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${u.prefix}form-list`)){if(t.length>1){const n=e.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),h=Number(l);if(isNaN(h))p.error("Haori",`Invalid index: ${i}`);else{const c=e.getChildElementFragments().filter(m=>m.hasAttribute(`${u.prefix}row`));h<c.length&&r.push(...A.findFragmentByKeyParts(c[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${u.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class N{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){N.dispatch(document,"ready",{version:e})}static importStart(e,t){N.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){N.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){N.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],c=r[l];h!==c&&n.push(l)}N.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){N.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){N.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){N.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){N.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){N.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){N.dispatch(e,"show",{visible:!0})}static hide(e){N.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){N.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){N.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){N.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 _e(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function et(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=S.get(f),i=r instanceof M?r.getBindingData():{},n=_e(t,i);return n===""?null:n}function tt(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 je(f){const e=Ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${u.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=et(i,t);if(n===null)continue;const s=tt(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 qe{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 rt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],it="__haoriHistoryState__",be="data-haori-click-lock";function se(){const e=globalThis.window?.Haori;return rt.every(r=>typeof e?.[r]=="function")?e:W}const nt=new Set(["GET","HEAD","OPTIONS"]);function st(f){return nt.has(f.toUpperCase())}function at(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 ot(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return at(r,e),t.search=r.toString(),t.toString()}function lt(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 te(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(te):f!==null&&typeof f=="object"?Object.values(f).some(te):!1}function ut(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&te(t)):te(e))}function ae(f){return ve(A.getValues(f))}function ve(f){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(f))t[r]=e(i);return t}function ct(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:lt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!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?`${u.prefix}${e}-${t}`:r?`${u.prefix}fetch-${t}`:`${u.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=Y.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=Y.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
7
  `)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const b=e.getRawAttribute(g.attrName(t,"form"));if(b){const v=document.body.querySelector(b);v!==null?r.formFragment=A.getFormFragment(S.get(v)):p.error("Haori",`Form element not found: ${b} (${g.attrName(t,"form")})`)}else r.formFragment=A.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=A.getFormFragment(e),r.formFragment===null&&g.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${u.prefix}${t}-before-run`)){const b=e.getRawAttribute(`${u.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
9
  ${b}
@@ -11,16 +11,16 @@ ${b}
11
11
  ${b}
12
12
  );`)}catch{try{v=new Function("event",`"use strict";
13
13
  ${b}
14
- `)}catch(R){p.error("Haori",`Invalid run script: ${R}`)}}v&&(r.runScript=v)}}const i=g.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const E=e.getAttributeEvaluation(i);E&&(r.fetchHasUnresolvedReference=E.hasUnresolvedReference,r.fetchUrl=E.hasUnresolvedReference?null:E.value)}const s={};if(t){const E=g.attrName(t,"fetch-method");if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=b?.value}}else{const E=g.attrName(null,"method",!0);if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=b?.value}}if(t){const E=g.attrName(t,"fetch-headers");if(e.hasAttribute(E)){const b=e.getRawAttribute(E);try{s.headers=x.parseDataBind(b)}catch(v){p.error("Haori",`Invalid fetch headers: ${v}`)}}}else{const E=g.attrName(null,"headers",!0);if(e.hasAttribute(E)){const b=e.getRawAttribute(E);try{s.headers=x.parseDataBind(b)}catch(v){p.error("Haori",`Invalid fetch headers: ${v}`)}}}if(t){const E=g.attrName(t,"fetch-content-type");if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":b?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let b=!1;s.headers&&typeof s.headers=="object"&&(b="Content-Type"in s.headers),b||(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 E=g.attrName(null,"content-type",!0);if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":b?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let b=!1;s.headers&&typeof s.headers=="object"&&(b="Content-Type"in s.headers),b||(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 E=e.getRawAttribute(a);if(E){const b=document.body.querySelectorAll(E);b.length>0?(r.bindFragments=[],b.forEach(v=>{const R=S.get(v);R&&r.bindFragments.push(R)})):p.error("Haori",`Bind element not found: ${E} (${a})`)}}const o=g.attrName(t,"bind-arg"),l=g.attrName(null,"arg",!0),d=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(d)&&(r.bindArg=e.getRawAttribute(d));const c=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(c)){const E=e.getRawAttribute(c);r.bindParams=E.split("&").map(b=>b.trim())}const m=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(m)){const E=e.getRawAttribute(m);r.bindAppendParams=E.split("&").map(b=>b.trim()).filter(Boolean)}const y=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(y)&&(r.bindMerge=!0);const T=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(T)&&(r.bindTransform=e.getRawAttribute(T));const k=t?g.attrName(t,"copy-params"):null;if(k&&e.hasAttribute(k)){const E=e.getRawAttribute(k);r.copyParams=E.split("&").map(b=>b.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const v=e.getRawAttribute(g.attrName(t,"adjust"));if(v){const R=document.body.querySelectorAll(v);R.length>0?(r.adjustFragments=[],R.forEach(C=>{const F=S.get(C);F&&r.adjustFragments.push(F)})):p.error("Haori",`Adjust element not found: ${v} (${g.attrName(t,"adjust")})`)}if(e.hasAttribute(g.attrName(t,"adjust-value"))){const R=e.getRawAttribute(g.attrName(t,"adjust-value")),C=Number(R);isNaN(C)||(r.adjustValue=C)}}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(`${u.prefix}${t}-after-run`)){const v=e.getRawAttribute(`${u.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
14
+ `)}catch(R){p.error("Haori",`Invalid run script: ${R}`)}}v&&(r.runScript=v)}}const i=g.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const E=e.getAttributeEvaluation(i);E&&(r.fetchHasUnresolvedReference=E.hasUnresolvedReference,r.fetchUrl=E.hasUnresolvedReference?null:E.value)}const s={};if(t){const E=g.attrName(t,"fetch-method");if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=b?.value}}else{const E=g.attrName(null,"method",!0);if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=b?.value}}if(t){const E=g.attrName(t,"fetch-headers");if(e.hasAttribute(E)){const b=e.getRawAttribute(E);try{s.headers=x.parseDataBind(b)}catch(v){p.error("Haori",`Invalid fetch headers: ${v}`)}}}else{const E=g.attrName(null,"headers",!0);if(e.hasAttribute(E)){const b=e.getRawAttribute(E);try{s.headers=x.parseDataBind(b)}catch(v){p.error("Haori",`Invalid fetch headers: ${v}`)}}}if(t){const E=g.attrName(t,"fetch-content-type");if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":b?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let b=!1;s.headers&&typeof s.headers=="object"&&(b="Content-Type"in s.headers),b||(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 E=g.attrName(null,"content-type",!0);if(e.hasAttribute(E)){const b=e.getAttributeEvaluation(E);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":b?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let b=!1;s.headers&&typeof s.headers=="object"&&(b="Content-Type"in s.headers),b||(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 E=e.getRawAttribute(a);if(E){const b=document.body.querySelectorAll(E);b.length>0?(r.bindFragments=[],b.forEach(v=>{const R=S.get(v);R&&r.bindFragments.push(R)})):p.error("Haori",`Bind element not found: ${E} (${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 c=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(c)){const E=e.getRawAttribute(c);r.bindParams=E.split("&").map(b=>b.trim())}const m=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(m)){const E=e.getRawAttribute(m);r.bindAppendParams=E.split("&").map(b=>b.trim()).filter(Boolean)}const y=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(y)&&(r.bindMerge=!0);const T=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(T)&&(r.bindTransform=e.getRawAttribute(T));const I=t?g.attrName(t,"copy-params"):null;if(I&&e.hasAttribute(I)){const E=e.getRawAttribute(I);r.copyParams=E.split("&").map(b=>b.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const v=e.getRawAttribute(g.attrName(t,"adjust"));if(v){const R=document.body.querySelectorAll(v);R.length>0?(r.adjustFragments=[],R.forEach(C=>{const F=S.get(C);F&&r.adjustFragments.push(F)})):p.error("Haori",`Adjust element not found: ${v} (${g.attrName(t,"adjust")})`)}if(e.hasAttribute(g.attrName(t,"adjust-value"))){const R=e.getRawAttribute(g.attrName(t,"adjust-value")),C=Number(R);isNaN(C)||(r.adjustValue=C)}}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(`${u.prefix}${t}-after-run`)){const v=e.getRawAttribute(`${u.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
15
15
  "use strict";
16
16
  ${v}
17
17
  `)}catch(R){p.error("Haori",`Invalid after script: ${R}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(g.attrName(t,"dialog")).replace(/\\n/g,`
18
- `)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const v=e.getRawAttribute(g.attrName(t,"toast-level")),C=["info","warning","error","success"].includes(v);r.toastLevel=C?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 R=document.body.querySelector(v);R!==null?r.historyFormFragment=A.getFormFragment(S.get(R)):p.error("Haori",`Form element not found: ${v} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(v=>{const R=g.attrName(t,v);if(!e.hasAttribute(R))return;const C=e.getRawAttribute(R),F=[];if(C)document.body.querySelectorAll(C).forEach($=>{const K=S.get($);K&&F.push(K)}),F.length===0&&p.error("Haori",`Element not found: ${C} (${R})`);else if(v==="open"||v==="close"){const U=e.getTarget().closest("dialog");U?F.push(S.get(U)):p.error("Haori",`Ancestor <dialog> not found (${R})`)}else F.push(e);if(F.length>0)switch(v){case"reset-before":r.resetBeforeFragments=F;break;case"reset":r.resetFragments=F;break;case"refetch":r.refetchFragments=F;break;case"click":r.clickFragments=F;break;case"copy":r.copyFragments=F;break;case"open":r.openFragments=F;break;case"close":r.closeFragments=F;break}});const b=g.attrName(t,"copy-source");if(e.hasAttribute(b)){const v=e.getRawAttribute(b);if(v){const R=document.body.querySelector(v);if(R!==null){const C=S.get(R);C?r.copySourceFragment=C:p.error("Haori",`Element is not managed by Haori: ${v} (${b})`)}else p.error("Haori",`Element not found: ${v} (${b})`)}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 E=e.getRawAttribute(g.attrName(null,"form",!0));if(E){const b=document.body.querySelector(E);b!==null?r.formFragment=A.getFormFragment(S.get(b)):p.error("Haori",`Form element not found: ${E} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}const H=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(H)){const E=e.getRawAttribute(H),b=[];E?(document.body.querySelectorAll(E).forEach(R=>{const C=S.get(R);C&&b.push(C)}),b.length===0&&p.error("Haori",`Element not found: ${E} (${H})`)):b.push(e),b.length>0&&(r.fetchStateFragments=b)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null:!1}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 d=this.options.targetFragment?.getTarget()??null;try{const c=this.options.runScript.call(d,this.domEvent);c===!1&&this.domEvent&&this.domEvent.preventDefault(),c!=null&&typeof c.then=="function"&&await c}catch(c){p.error("Haori",`Run script execution error: ${c}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>A.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(n||null,s||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(n="fetchUrl"in d?d.fetchUrl:n,s="fetchOptions"in d?d.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const d={...s||{}},c=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const k=performance.now(),H={runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return N.fetchStart(this.options.targetFragment.getTarget(),n,d,a?i:void 0,H),await this.injectFetchState("loading"),fetch(n,d).then(E=>this.handleFetchResult(E,n||void 0,k)).catch(async E=>{throw n&&N.fetchError(this.options.targetFragment.getTarget(),n,E),await this.injectFetchState("error",null,E instanceof Error?E.message:String(E)),E})}return fetch(n,d).then(k=>this.handleFetchResult(k,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,c=d.getTarget(),m=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const y=d.getBindingData();Object.assign(y,me(i)),await x.setBindingData(c,y,m)}this.suppressEmptyReplaceBind=!a&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input");const o=a?me(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(ge))return!1;const r=t.hasAttribute(`${u.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(ge,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(ge),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ne();if(!e.ok)return je(e.status)||(this.options.targetFragment&&t&&N.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&N.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),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.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)):p.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)):p.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 d=new URLSearchParams(window.location.search).get(o);if(d!==null){const c=d.trim();qe.isSafeLocalPath(c)?a=c:p.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${d}`)}}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();p.error("Haori",l);return}const o=l=>{for(const[d,c]of Object.entries(l))c!=null&&(Array.isArray(c)?c.forEach(m=>a.searchParams.append(d,String(m))):typeof c=="object"?a.searchParams.set(d,JSON.stringify(c)):a.searchParams.set(d,String(c)))};i&&o(t),n&&o(r),history.pushState({[it]:!0},"",a.toString())}catch(s){p.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ne().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ne().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,d=[];for(const c of a)if(c&&typeof c=="object"&&!Array.isArray(c)){const m=c.key,y=c.message,T=typeof m=="string"&&m.length>0?m:null,k=typeof y=="string"?y:y!=null?String(y):"";if(k.length===0)continue;if(T!==null){const H=l.get(T)??[];H.push(k),l.set(T,H)}else d.push(k)}else typeof c=="string"&&c.length>0&&d.push(c);for(const[c,m]of l)o.push({key:c,message:m.join(`
19
- `)});for(const c of d)o.push({message:c})}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,d]of Object.entries(a.errors))Array.isArray(d)?o.push({key:l,message:d.join(`
20
- `)}):typeof d=="string"?o.push({key:l,message:d}):d!=null&&o.push({key:l,message:String(d)});if(o.length===0)for(const[l,d]of Object.entries(a))l==="message"||l==="messages"||l==="errors"||(Array.isArray(d)?o.push({key:l,message:d.join(`
21
- `)}):typeof d=="string"&&o.push({key:l,message:d}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await A.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):ne().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=Y.evaluate(this.options.bindTransform,{response:i})}catch(s){p.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}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${u.prefix}${this.eventType}-form.`);return}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],d=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,d)}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){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.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=>{N.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"?se(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?se(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,A.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.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=u.runtime==="demo"&&!st(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&te(t)){const c=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(c)?ut(t)&&p.warn("Haori",`A File value nested under ${u.prefix}form-object / ${u.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${u.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=ot(i,t));else if(Object.keys(t).length>0){const c=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){s.delete("Content-Type");const m=new FormData;for(const[y,T]of Object.entries(t))T==null?m.append(y,""):T instanceof Blob?m.append(y,T):Array.isArray(T)?T.forEach(k=>{k instanceof Blob?m.append(y,k):m.append(y,String(k))}):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(c)){const m=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?m.append(y,""):Array.isArray(T)?T.forEach(k=>m.append(y,String(k))):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let d;return o&&(d=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:d,transportMode:o?"query-get":"http",signature:ct(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?se(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 se(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 p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(p.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(A.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(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.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()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return x.setBindingData(a,o,new Set,!1,!1)}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let W=g;class dt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){je(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.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:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=S.get(e);return r instanceof M?r.hasAttribute(`${u.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>h.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(h.evaluateAll(r)):r instanceof j&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=h.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=h.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.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(`${u.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(h.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=h.getReactiveFetchState(t),i=W.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 W(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.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 t.setAttribute(`${u.prefix}importing`,""),N.importStart(t,n),dt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return P.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${u.prefix}importing`),N.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(d=>{const c=S.get(d);c instanceof M?l.push(h.scan(c.getTarget())):c instanceof j&&l.push(h.evaluateText(c))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),N.importError(t,n,a),p.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.executeManagedImport(e)})}static scan(e){const t=S.get(e);return t?h.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e,t)){h.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(h.initializeElementFragment(i,t)):i instanceof j&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.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 h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>h.setAttribute(e.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&h.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=S.get(e),s=h.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`${u.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(h.parseDataBind(r))}break}case`${u.prefix}derive`:l=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),o=h.evaluateDerive(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${u.prefix}derive-name`:l=h.createDeriveInputSignature(n,n.getRawAttribute(`${u.prefix}derive`),r),o=h.evaluateDerive(n,n.getRawAttribute(`${u.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${u.prefix}if`:a.push(h.evaluateIf(n));break;case`${u.prefix}each`:a.push(h.evaluateEach(n));break;case`${u.prefix}fetch`:a.push(h.executeManagedFetch(n));break;case`${u.prefix}import`:typeof r=="string"&&a.push(h.executeManagedImport(n));break;case`${u.prefix}url-param`:{const d=n.getAttribute(`${u.prefix}url-arg`),c=qe.readParams();if(d===null)a.push(h.setBindingData(e,c,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(d)]=c,a.push(h.setBindingData(e,m,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(d=>{if(d)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=S.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&N.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let d=n?s.setAttribute(`${u.prefix}bind`,JSON.stringify(l)):Promise.resolve();if(e.tagName==="FORM"){const c=s.getAttribute(`${u.prefix}form-arg`),m=c&&l[String(c)]&&typeof l[String(c)]=="object"&&!Array.isArray(l[String(c)])?l[String(c)]:c?{}:l;d=d.then(()=>A.syncValues(s,m))}return d=d.then(()=>h.evaluateAll(s,r)),d=d.then(()=>h.reevaluateReactiveSpecialAttributes(s,r)),d.then(()=>s.markBindingWorkEnd(),c=>{throw s.markBindingWorkEnd(),c})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=S.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=S.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const d=l.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},s=(l,d,c,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(d),kind:c,depth:m})};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()&&p.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 p.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=S.get(e);if(r.isSkipMutationNodes())return;const i=S.get(t.nextSibling),n=S.get(t);n&&(r.insertBefore(n,i),n instanceof M?h.scan(n.getTarget()):n instanceof j&&h.evaluateText(n))}static removeNode(e){const t=S.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=S.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=S.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=h.getFormFragment(r);if(n){const s=A.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(h.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?h.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${u.prefix}derive`),n=e.hasAttribute(`${u.prefix}if`),s=e.hasAttribute(`${u.prefix}each`),a=e.getRawAttribute(`${u.prefix}derive`),o=e.getRawAttribute(`${u.prefix}derive-name`);let l=!1,d=!1,c=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const m=h.createDeriveInputSignature(e,a,o);m===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==m&&(r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>h.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}c=h.createDescendantBindingSignature(e,"evaluateAll"),d=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===c,h.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const m=[];return e.getChildren().forEach(y=>{if(y instanceof M){if(h.canSkipUnchangedNestedEach(y))return;m.push(h.evaluateAll(y,t))}else y instanceof j&&m.push(h.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{d&&c!==null&&e.setDeriveSubtreeSignature(c)}))}static evaluateDerive(e,t=e.getRawAttribute(`${u.prefix}derive`),r=e.getRawAttribute(`${u.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=Y.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 h.createBindingSignature(i)===h.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(`${u.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=h.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])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(h.isHiddenIfCondition(r))L.isEnabled()&&h.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{N.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?h.evaluateAll(s):h.scan(s.getTarget())):s instanceof j&&n.push(h.evaluateText(s))}),t.push(e.show().then(()=>{N.show(e.getTarget()),i||h.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${u.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new W(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=h.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=h.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):h.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),h.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}h.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${u.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
18
+ `)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const v=e.getRawAttribute(g.attrName(t,"toast-level")),C=["info","warning","error","success"].includes(v);r.toastLevel=C?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 R=document.body.querySelector(v);R!==null?r.historyFormFragment=A.getFormFragment(S.get(R)):p.error("Haori",`Form element not found: ${v} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(v=>{const R=g.attrName(t,v);if(!e.hasAttribute(R))return;const C=e.getRawAttribute(R),F=[];if(C)document.body.querySelectorAll(C).forEach(B=>{const z=S.get(B);z&&F.push(z)}),F.length===0&&p.error("Haori",`Element not found: ${C} (${R})`);else if(v==="open"||v==="close"){const L=e.getTarget().closest("dialog");L?F.push(S.get(L)):p.error("Haori",`Ancestor <dialog> not found (${R})`)}else F.push(e);if(F.length>0)switch(v){case"reset-before":r.resetBeforeFragments=F;break;case"reset":r.resetFragments=F;break;case"refetch":r.refetchFragments=F;break;case"click":r.clickFragments=F;break;case"copy":r.copyFragments=F;break;case"open":r.openFragments=F;break;case"close":r.closeFragments=F;break}});const b=g.attrName(t,"copy-source");if(e.hasAttribute(b)){const v=e.getRawAttribute(b);if(v){const R=document.body.querySelector(v);if(R!==null){const C=S.get(R);C?r.copySourceFragment=C:p.error("Haori",`Element is not managed by Haori: ${v} (${b})`)}else p.error("Haori",`Element not found: ${v} (${b})`)}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 E=e.getRawAttribute(g.attrName(null,"form",!0));if(E){const b=document.body.querySelector(E);b!==null?r.formFragment=A.getFormFragment(S.get(b)):p.error("Haori",`Form element not found: ${E} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}const H=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(H)){const E=e.getRawAttribute(H),b=[];E?(document.body.querySelectorAll(E).forEach(R=>{const C=S.get(R);C&&b.push(C)}),b.length===0&&p.error("Haori",`Element not found: ${E} (${H})`)):b.push(e),b.length>0&&(r.fetchStateFragments=b)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null:!1}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 c=this.options.runScript.call(h,this.domEvent);c===!1&&this.domEvent&&this.domEvent.preventDefault(),c!=null&&typeof c.then=="function"&&await c}catch(c){p.error("Haori",`Run script execution error: ${c}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>A.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||{}},c=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const I=performance.now(),H={runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return N.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,H),await this.injectFetchState("loading"),fetch(n,h).then(E=>this.handleFetchResult(E,n||void 0,I)).catch(async E=>{throw n&&N.fetchError(this.options.targetFragment.getTarget(),n,E),await this.injectFetchState("error",null,E instanceof Error?E.message:String(E)),E})}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,c=h.getTarget(),m=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const y=h.getBindingData();Object.assign(y,ve(i)),await x.setBindingData(c,y,m)}this.suppressEmptyReplaceBind=!a&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input");const o=a?ve(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(be))return!1;const r=t.hasAttribute(`${u.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(be,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(be),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=se();if(!e.ok)return je(e.status)||(this.options.targetFragment&&t&&N.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&N.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),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.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)):p.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)):p.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 c=h.trim();qe.isSafeLocalPath(c)?a=c:p.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();p.error("Haori",l);return}const o=l=>{for(const[h,c]of Object.entries(l))c!=null&&(Array.isArray(c)?c.forEach(m=>a.searchParams.append(h,String(m))):typeof c=="object"?a.searchParams.set(h,JSON.stringify(c)):a.searchParams.set(h,String(c)))};i&&o(t),n&&o(r),history.pushState({[it]:!0},"",a.toString())}catch(s){p.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await se().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await se().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 c of a)if(c&&typeof c=="object"&&!Array.isArray(c)){const m=c.key,y=c.message,T=typeof m=="string"&&m.length>0?m:null,I=typeof y=="string"?y:y!=null?String(y):"";if(I.length===0)continue;if(T!==null){const H=l.get(T)??[];H.push(I),l.set(T,H)}else h.push(I)}else typeof c=="string"&&c.length>0&&h.push(c);for(const[c,m]of l)o.push({key:c,message:m.join(`
19
+ `)});for(const c of h)o.push({message:c})}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(`
20
+ `)}):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(`
21
+ `)}):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 A.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):se().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=Y.evaluate(this.options.bindTransform,{response:i})}catch(s){p.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}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${u.prefix}${this.eventType}-form.`);return}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){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.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=>{N.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"?ae(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?ae(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,A.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.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=u.runtime==="demo"&&!st(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&te(t)){const c=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(c)?ut(t)&&p.warn("Haori",`A File value nested under ${u.prefix}form-object / ${u.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${u.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=ot(i,t));else if(Object.keys(t).length>0){const c=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){s.delete("Content-Type");const m=new FormData;for(const[y,T]of Object.entries(t))T==null?m.append(y,""):T instanceof Blob?m.append(y,T):Array.isArray(T)?T.forEach(I=>{I instanceof Blob?m.append(y,I):m.append(y,String(I))}):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(c)){const m=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?m.append(y,""):Array.isArray(T)?T.forEach(I=>m.append(y,String(I))):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T)));n.body=m}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:ct(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?ae(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 ae(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 p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.prefix}row`);return e||(p.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(A.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(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.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()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return x.setBindingData(a,o,new Set,!1,!1)}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let K=g;class ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){je(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.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:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.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===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=S.get(e);return r instanceof M?r.hasAttribute(`${u.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 j&&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(`${u.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${u.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=K.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 K(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(`${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 t.setAttribute(`${u.prefix}importing`,""),N.importStart(t,n),ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return k.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${u.prefix}importing`),N.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const c=S.get(h);c instanceof M?l.push(d.scan(c.getTarget())):c instanceof j&&l.push(d.evaluateText(c))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),N.importError(t,n,a),p.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=S.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 j&&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=u.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=u.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(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=S.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`${u.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`${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 h=n.getAttribute(`${u.prefix}url-arg`),c=qe.readParams();if(h===null)a.push(d.setBindingData(e,c,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(h)]=c,a.push(d.setBindingData(e,m,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=S.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&N.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${u.prefix}bind`,JSON.stringify(l)):Promise.resolve();return e.tagName==="FORM"&&(h=h.then(()=>{const c=s.getRawBindingData()??t,m=s.getAttribute(`${u.prefix}form-arg`),y=m&&c[String(m)]&&typeof c[String(m)]=="object"&&!Array.isArray(c[String(m)])?c[String(m)]:m?{}:c;return A.syncValues(s,y)})),h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),c=>{throw s.markBindingWorkEnd(),c})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=S.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=S.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,c,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(h),kind:c,depth:m})};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 U.isEnabled()&&p.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 p.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=S.get(e);if(r.isSkipMutationNodes())return;const i=S.get(t.nextSibling),n=S.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof j&&d.evaluateText(n))}static removeNode(e){const t=S.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=S.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=S.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=A.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(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(`${u.prefix}derive`),n=e.hasAttribute(`${u.prefix}if`),s=e.hasAttribute(`${u.prefix}each`),a=e.getRawAttribute(`${u.prefix}derive`),o=e.getRawAttribute(`${u.prefix}derive-name`);let l=!1,h=!1,c=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const m=d.createDeriveInputSignature(e,a,o);m===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==m&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(m)})))}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}c=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===c,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const m=[];return e.getChildren().forEach(y=>{if(y instanceof M){if(d.canSkipUnchangedNestedEach(y))return;m.push(d.evaluateAll(y,t))}else y instanceof j&&m.push(d.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{h&&c!==null&&e.setDeriveSubtreeSignature(c)}))}static evaluateDerive(e,t=e.getRawAttribute(`${u.prefix}derive`),r=e.getRawAttribute(`${u.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=Y.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(`${u.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])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(d.isHiddenIfCondition(r))U.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{N.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 j&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{N.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${u.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new K(e,"load").run().catch(i=>{p.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(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),d.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}d.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${u.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
22
22
  ${r}
23
23
  );`)}catch{try{i=new Function(`"use strict";
24
24
  ${r}
25
- `)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${u.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(h.EACH_RENDERED_CHANGE_WARNED.has(r)||(h.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),h.countEachRenderedRows(e)!==0){if(!n){if(h.EACH_RENDERED_CHANGE_FIRED.has(r))return;h.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${u.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=h.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${u.prefix}each-key`),n=h.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(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),h.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(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const c=S.get(l);c instanceof M&&(r=c.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const d=S.get(l);d instanceof M&&e.getChildren().includes(d)&&(e.removeChild(d),d.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(`${u.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(p.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${u.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${u.prefix}derive`)||t?.closestByAttribute(`${u.prefix}derive-name`)||t?.closestByAttribute(`${u.prefix}if`)||t?.closestByAttribute(`${u.prefix}fetch`)||t?.closestByAttribute(`${u.prefix}import`)||h.hasNonEachDynamicElementState(e))return!1;const r=h.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}if`)||e.hasAttribute(`${u.prefix}each`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return h.recordDerivedSubtreeSignatureComputation(e,t),h.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:h.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(h.createDescendantBindingSignature(e,"refresh")),h.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!L.isEnabled()||!e.hasAttribute(`${u.prefix}derive`))return null;const t=h.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:h.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.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(`${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 M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.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([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof j&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!h.markFreshInitializationSkippable(n):n instanceof j?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${u.prefix}attr-`)||t.startsWith(u.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${u.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${u.prefix}each-key`),s=e.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];t.forEach((b,v)=>{const R=h.createListKey(b,n?String(n):null,v);o.push(R),a.set(R,{item:b,itemIndex:v})});const l=new Set(o),d=[];let c=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const m=c.map(b=>b.getListKey());c=c.filter(b=>l.has(String(b.getListKey()))?!0:(d.push(b.remove()),!1));const y=c.map(b=>b.getListKey()),T=new Map;c.forEach(b=>{const v=b.getListKey();v!==null&&!T.has(v)&&T.set(v,b)});const k=e.getChildElementFragments().slice(),H=k.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((b,v)=>{const{item:R,itemIndex:C}=a.get(b);let F;const U=T.get(b);if(U)F=U,E=E.then(()=>h.updateRowFragment(F,R,i,C,s?String(s):null,b).then($=>{if($)return h.evaluateAll(F)}));else{F=r.clone();const $=H+v;E=E.then(()=>h.updateRowFragment(F,R,i,C,s?String(s):null,b).then(()=>{const K=k[$]??null;return e.insertBefore(F,K).then(()=>{k.splice($,0,F)}).then(()=>h.initializeFreshEachRow(F))}))}}),Promise.all(d).then(()=>E).then(()=>{const b=o.filter($=>$!==null),v=y.filter($=>$!==null),R=new Set(v),C=b.filter($=>!R.has($)),U=m.filter($=>$!==null).filter($=>!l.has($));N.eachUpdate(e.getTarget(),C,U,b)})}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 p.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=h.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(`${u.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()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${u.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(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;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=>h.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)}:${h.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{h.evaluateAll(e)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap,h.EACH_RENDERED_CHANGE_FIRED=new WeakSet,h.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let x=h;const ee=class ee{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],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=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[ee.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=S.get(e);t&&new W(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,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))}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),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;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`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ee.BUILTIN_EVENT_NAMES.has(e)){p.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){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=S.get(i);n instanceof M&&new W(n,"on",t).run().catch(s=>{p.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){if(t==="input"){const i=`${u.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${u.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=S.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof M&&(i.syncValue(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=S.get(a);o instanceof M&&o.syncValue()}}const n=()=>{new W(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${u.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=`${u.prefix}click-`,r=`${u.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}};ee.HISTORY_STATE_KEY="__haoriHistoryState__",ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let be=ee;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=S.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(`${u.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 d=D.registrations.get(e);d&&l.forEach(c=>{!c.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new W(d.fragment,"intersect").runWithResult().then(m=>{m&&d.once&&(d.observer.disconnect(),D.registrations.delete(e))}).catch(m=>{p.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(e);m&&(m.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(`${u.prefix}intersect-`))return!1;const r=t.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${u.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:(p.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${u.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=`${u.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 _=D;function ht(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=S.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)),p.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 d=w.registrations.get(e);if(!d)return;let c=!1;l.forEach(m=>{const y=m.target;d.observedRows.has(y)&&(m.isIntersecting?d.visibleRows.has(y)||(d.visibleRows.add(y),c=!0):d.visibleRows.delete(y)&&(c=!0))}),c&&w.scheduleCompute(d)},{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(`${u.prefix}each`)&&e.hasAttribute(`${u.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${u.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${u.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:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.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(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.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,ht(()=>{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){p.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=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${u.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 X=w;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=new be;O._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await P.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),_.syncTree(document.body),X.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return O._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(O.isExternallyManaged(i.target))continue;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),_.syncElement(n),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{_.cleanupTree(n),X.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),_.syncTree(n),X.syncTree(n))}),i.target instanceof Element&&X.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[],O._dispatcher=null;let le=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",le.init):le.init();const ft=()=>q.waitForRenders(),gt="0.26.0";exports.Core=x;exports.Env=u;exports.Form=A;exports.Fragment=S;exports.Haori=q;exports.Log=p;exports.Queue=P;exports.default=q;exports.version=gt;exports.waitForRenders=ft;
25
+ `)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${u.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(d.EACH_RENDERED_CHANGE_WARNED.has(r)||(d.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),d.countEachRenderedRows(e)!==0){if(!n){if(d.EACH_RENDERED_CHANGE_FIRED.has(r))return;d.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${u.prefix}row`)&&(t+=1);return t}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(`${u.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(`${u.prefix}each-before`)||a.hasAttribute(`${u.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(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const c=S.get(l);c instanceof M&&(r=c.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=S.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(`${u.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(p.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${u.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${u.prefix}derive`)||t?.closestByAttribute(`${u.prefix}derive-name`)||t?.closestByAttribute(`${u.prefix}if`)||t?.closestByAttribute(`${u.prefix}fetch`)||t?.closestByAttribute(`${u.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}if`)||e.hasAttribute(`${u.prefix}each`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.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(!U.isEnabled()||!e.hasAttribute(`${u.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(`${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 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),p.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([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof j&&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 j?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${u.prefix}attr-`)||t.startsWith(u.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${u.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${u.prefix}each-key`),s=e.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];t.forEach((b,v)=>{const R=d.createListKey(b,n?String(n):null,v);o.push(R),a.set(R,{item:b,itemIndex:v})});const l=new Set(o),h=[];let c=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const m=c.map(b=>b.getListKey());c=c.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const y=c.map(b=>b.getListKey()),T=new Map;c.forEach(b=>{const v=b.getListKey();v!==null&&!T.has(v)&&T.set(v,b)});const I=e.getChildElementFragments().slice(),H=I.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((b,v)=>{const{item:R,itemIndex:C}=a.get(b);let F;const L=T.get(b);if(L)F=L,E=E.then(()=>d.updateRowFragment(F,R,i,C,s?String(s):null,b).then(B=>{if(B)return d.evaluateAll(F)}));else{F=r.clone();const B=H+v;E=E.then(()=>d.updateRowFragment(F,R,i,C,s?String(s):null,b).then(()=>{const z=I[B]??null;return e.insertBefore(F,z).then(()=>{I.splice(B,0,F)}).then(()=>d.initializeFreshEachRow(F))}))}}),Promise.all(h).then(()=>E).then(()=>{const b=o.filter(B=>B!==null),v=y.filter(B=>B!==null),R=new Set(v),C=b.filter(B=>!R.has(B)),L=m.filter(B=>B!==null).filter(B=>!l.has(B));N.eachUpdate(e.getTarget(),C,L,b)})}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 p.error("[Haori]",`Primitive value requires '${u.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(`${u.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(`${u.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(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;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,d.EACH_RENDERED_CHANGE_FIRED=new WeakSet,d.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let x=d;const ee=class ee{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],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=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[ee.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=S.get(e);t&&new K(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,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))}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),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;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`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ee.BUILTIN_EVENT_NAMES.has(e)){p.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){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=S.get(i);n instanceof M&&new K(n,"on",t).run().catch(s=>{p.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){if(t==="input"){const i=`${u.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${u.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=S.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof M&&(i.syncValue(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=S.get(a);o instanceof M&&o.syncValue()}}const n=()=>{new K(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${u.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=`${u.prefix}click-`,r=`${u.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}};ee.HISTORY_STATE_KEY="__haoriHistoryState__",ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ee=ee;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=S.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(`${u.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(c=>{!c.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new K(h.fragment,"intersect").runWithResult().then(m=>{m&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(m=>{p.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(e);m&&(m.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(`${u.prefix}intersect-`))return!1;const r=t.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${u.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:(p.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${u.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=`${u.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 _=D;function dt(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=S.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)),p.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 c=!1;l.forEach(m=>{const y=m.target;h.observedRows.has(y)&&(m.isIntersecting?h.visibleRows.has(y)||(h.visibleRows.add(y),c=!0):h.visibleRows.delete(y)&&(c=!0))}),c&&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(`${u.prefix}each`)&&e.hasAttribute(`${u.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${u.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${u.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:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.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(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.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,dt(()=>{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){p.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=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${u.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 X=w;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=new Ee;O._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await k.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),_.syncTree(document.body),X.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return O._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(O.isExternallyManaged(i.target))continue;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),_.syncElement(n),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{_.cleanupTree(n),X.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),_.syncTree(n),X.syncTree(n))}),i.target instanceof Element&&X.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[],O._dispatcher=null;let ue=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ue.init):ue.init();const ft=()=>W.waitForRenders(),gt="0.26.2";exports.Core=x;exports.Env=u;exports.Form=A;exports.Fragment=S;exports.Haori=W;exports.Log=p;exports.Queue=k;exports.default=W;exports.version=gt;exports.waitForRenders=ft;
26
26
  //# sourceMappingURL=haori.cjs.js.map