haori 0.46.2 → 0.47.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,32 +1,32 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const ce=class ce{static isEnabled(){return ce.devMode}static enable(){ce.devMode=!0}static disable(){ce.devMode=!1}static set(e){ce.devMode=e}};ce.devMode=!1;let j=ce;const Le="embedded";function Je(y){return y==="embedded"||y==="demo"}function yt(y){return y===null?null:Je(y)?y:Le}const J=class J{static get strictBind(){return J._strictBind}static setStrictBind(e){J._strictBind=e}static get runtime(){return J._runtime}static setRuntime(e){J._runtime=Je(e)?e:Le}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||J._prefix;J._prefix=r.endsWith("-")?r:r+"-";const i=yt(e.getAttribute("data-runtime"));i!==null&&(J._runtime=i),J._strictBind=e.hasAttribute(`${J._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${J._prefix}dev`)){const r=(e.getAttribute(`${J._prefix}dev`)??"").trim().toLowerCase();j.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){j.set(!0);return}j.set(!1)}catch{}}static get prefix(){return J._prefix}};J._prefix="data-",J._runtime=Le,J._strictBind=!1;let l=J;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){j.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){j.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const bt=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,je="new:",$=class ${static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error("[Haori]","Enhancer name is required.");return}if(!t||typeof t.init!="function"){m.error("[Haori]",`Enhancer "${r}" must have an init function.`);return}$.enhancers.set(r,t),$.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&$.applySubtree(document.body)}static has(e){return $.enhancers.has(e)}static applySubtree(e){$.forEachTarget(e,t=>{$.applyElement(t)})}static refreshSubtree(e){$.forEachTarget(e,t=>{$.refreshElement(t)})}static destroySubtree(e){$.forEachTarget(e,t=>{$.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){const t=$.instances.get(e)??null;$.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=$.enhancers.get(r);if(!i){$.warnUnknownName(r);return}$.run(`enhance "${r}"`,()=>{const n=i.init(e);$.appliedKeys(e).set(r,n)})}),$.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${je}${r}`;if($.instances.get(e)?.has(i))return;const n=$.resolveGlobal(r);n!==null&&$.run(`enhance-new "${r}"`,()=>{const s=new n(e);$.appliedKeys(e).set(i,s)})})}static refreshElement(e){const t=$.instances.get(e);$.names(e,`${l.prefix}enhance`).forEach(r=>{if(!t||!t.has(r))return;const i=$.enhancers.get(r);!i||typeof i.refresh!="function"||$.run(`enhance "${r}" refresh`,()=>{i.refresh(e,t.get(r))})}),$.applyElement(e)}static destroyElement(e){const t=$.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(je))return;const n=$.enhancers.get(i);!n||typeof n.destroy!="function"||$.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),$.instances.delete(e))}static appliedKeys(e){const t=$.instances.get(e);if(t)return t;const r=new Map;return $.instances.set(e,r),r}static names(e,t){const r=e.getAttribute(t);return r===null?[]:Array.from(new Set(r.split(/\s+/).map(i=>i.trim()).filter(i=>i!=="")))}static resolveGlobal(e){if(!bt.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(j.isEnabled()&&!$.warnedMissingGlobals.has(e)&&($.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!j.isEnabled()||$.warnedUnknownNames.has(e)||($.warnedUnknownNames.add(e),m.warn("[Haori]",`Enhancer "${e}" is not registered yet; the declaration is kept pending and applied when it is registered (Haori.enhancers.register('${e}', {init(el) {...}})).`))}static run(e,t){try{t()}catch(r){m.error("[Haori]",`${e} failed:`,r)}}};$.enhancers=new Map,$.instances=new WeakMap,$.warnedUnknownNames=new Set,$.warnedMissingGlobals=new Set;let re=$;const Ze="yyyy/MM/dd HH:mm",Et="en-US",Ke=1e4;function ne(y){return String(y).padStart(2,"0")}function Qe(y,e,t,r,i,n){return{yyyy:String(y).padStart(4,"0"),yy:ne(y%100),MM:ne(e),M:String(e),dd:ne(t),d:String(t),HH:ne(r),H:String(r),mm:ne(i),ss:ne(n)}}function _e(y,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(y)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:Qe(i,n,s,a,o,c)}function Ce(y,e=Ze,t){if(y==null||y==="")return"";const r=y instanceof Date?y:new Date(y);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=_e(r,t.trim()),i===null)return""}else i=Qe(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 At="yyyy-MM-dd";function et(y=Ze,e){return Ce(new Date,y,e)}function tt(y=0,e=At,t){const r=Number.isFinite(y)?Math.trunc(y):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=_e(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return Ce(o,e,"UTC")}function rt(y,e){if(y==null)return"";let t;if(typeof y=="number")t=y;else{const i=String(y).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(Et,r).format(t)}function it(y,e,t){let r,i,n;if(e===void 0?(r=0,i=y,n=1):(r=y,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<Ke;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ke;a+=n)s.push(a);return s}function nt(y,e,t={}){const r=Math.trunc(Number(y));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 d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,p)=>d-p),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const p=u+1;c.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const vt=/^(\d{4})-(\d{1,2})$/,St=1200;function Te(y,e){const t=Number(y);return Number.isFinite(t)?Math.trunc(t):e}function ke(y,e){if(typeof y!="string")return"";const t=vt.exec(y.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")}-${ne(o)}`}function wt(y){if(typeof y=="string"&&y.trim()!=="")return ke(y,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${ne(e.getMonth()+1)}`}function st(y,e){const t=Math.trunc(Number(y));if(!Number.isFinite(t)||t<0)return[];const r=wt(e);if(r==="")return[];const i=Math.min(t,St),n=[];for(let s=0;s<=i;s+=1){const a=ke(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function at(y,e){const t={start:0,end:0,total:0,empty:!0};if(!y||typeof y!="object")return t;const r=y,i=Te(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,Te(r.number,0)),s=Math.max(0,Te(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=Te(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function ot(y,e,t){if(!Array.isArray(y)||y.length===0)return null;const r=String(t),i=y.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function lt(y,e){if(!Array.isArray(y))return 0;let t=0;for(const r of y){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 ct(y,e){return e==null||y==null?String(y):String(y[e])}function ut(y,e){if(!Array.isArray(y))return[];const t=new Set,r=[];for(const i of y){const n=ct(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function dt(y,e){if(!Array.isArray(y))return[];const t=new Map,r=[];for(const i of y){const n=ct(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 Rt=Object.freeze({date:Ce,now:et,today:tt,number:rt,pages:nt,range:it,monthAdd:ke,monthRange:st,pageSummary:at,findBy:ot,sum:lt,distinct:ut,groupBy:dt});class He{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await He.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const qe=class qe{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)}};qe.ASYNC_QUEUE=new He;let K=qe;const T=class T{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,T.readStorageSafely(()=>e.localStorage),T.readStorageSafely(()=>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 getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!j.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const pe=class pe{static isEnabled(){return pe.devMode}static enable(){pe.devMode=!0}static disable(){pe.devMode=!1}static set(e){pe.devMode=e}};pe.devMode=!1;let q=pe;const Le="embedded";function Je(y){return y==="embedded"||y==="demo"}function yt(y){return y===null?null:Je(y)?y:Le}const Q=class Q{static get strictBind(){return Q._strictBind}static setStrictBind(e){Q._strictBind=e}static get runtime(){return Q._runtime}static setRuntime(e){Q._runtime=Je(e)?e:Le}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||Q._prefix;Q._prefix=r.endsWith("-")?r:r+"-";const i=yt(e.getAttribute("data-runtime"));i!==null&&(Q._runtime=i),Q._strictBind=e.hasAttribute(`${Q._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${Q._prefix}dev`)){const r=(e.getAttribute(`${Q._prefix}dev`)??"").trim().toLowerCase();q.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){q.set(!0);return}q.set(!1)}catch{}}static get prefix(){return Q._prefix}};Q._prefix="data-",Q._runtime=Le,Q._strictBind=!1;let l=Q;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){q.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){q.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const bt=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,je="new:",$=class ${static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error("[Haori]","Enhancer name is required.");return}if(!t||typeof t.init!="function"){m.error("[Haori]",`Enhancer "${r}" must have an init function.`);return}$.enhancers.set(r,t),$.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&$.applySubtree(document.body)}static has(e){return $.enhancers.has(e)}static applySubtree(e){$.forEachTarget(e,t=>{$.applyElement(t)})}static refreshSubtree(e){$.forEachTarget(e,t=>{$.refreshElement(t)})}static destroySubtree(e){$.forEachTarget(e,t=>{$.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){const t=$.instances.get(e)??null;$.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=$.enhancers.get(r);if(!i){$.warnUnknownName(r);return}$.run(`enhance "${r}"`,()=>{const n=i.init(e);$.appliedKeys(e).set(r,n)})}),$.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${je}${r}`;if($.instances.get(e)?.has(i))return;const n=$.resolveGlobal(r);n!==null&&$.run(`enhance-new "${r}"`,()=>{const s=new n(e);$.appliedKeys(e).set(i,s)})})}static refreshElement(e){const t=$.instances.get(e);$.names(e,`${l.prefix}enhance`).forEach(r=>{if(!t||!t.has(r))return;const i=$.enhancers.get(r);!i||typeof i.refresh!="function"||$.run(`enhance "${r}" refresh`,()=>{i.refresh(e,t.get(r))})}),$.applyElement(e)}static destroyElement(e){const t=$.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(je))return;const n=$.enhancers.get(i);!n||typeof n.destroy!="function"||$.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),$.instances.delete(e))}static appliedKeys(e){const t=$.instances.get(e);if(t)return t;const r=new Map;return $.instances.set(e,r),r}static names(e,t){const r=e.getAttribute(t);return r===null?[]:Array.from(new Set(r.split(/\s+/).map(i=>i.trim()).filter(i=>i!=="")))}static resolveGlobal(e){if(!bt.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(q.isEnabled()&&!$.warnedMissingGlobals.has(e)&&($.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!q.isEnabled()||$.warnedUnknownNames.has(e)||($.warnedUnknownNames.add(e),m.warn("[Haori]",`Enhancer "${e}" is not registered yet; the declaration is kept pending and applied when it is registered (Haori.enhancers.register('${e}', {init(el) {...}})).`))}static run(e,t){try{t()}catch(r){m.error("[Haori]",`${e} failed:`,r)}}};$.enhancers=new Map,$.instances=new WeakMap,$.warnedUnknownNames=new Set,$.warnedMissingGlobals=new Set;let ne=$;const Ze="yyyy/MM/dd HH:mm",Et="en-US",Ke=1e4;function oe(y){return String(y).padStart(2,"0")}function Qe(y,e,t,r,i,n){return{yyyy:String(y).padStart(4,"0"),yy:oe(y%100),MM:oe(e),M:String(e),dd:oe(t),d:String(t),HH:oe(r),H:String(r),mm:oe(i),ss:oe(n)}}function _e(y,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(y)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:Qe(i,n,s,a,o,c)}function $e(y,e=Ze,t){if(y==null||y==="")return"";const r=y instanceof Date?y:new Date(y);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=_e(r,t.trim()),i===null)return""}else i=Qe(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 At="yyyy-MM-dd";function et(y=Ze,e){return $e(new Date,y,e)}function tt(y=0,e=At,t){const r=Number.isFinite(y)?Math.trunc(y):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=_e(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return $e(o,e,"UTC")}function rt(y,e){if(y==null)return"";let t;if(typeof y=="number")t=y;else{const i=String(y).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(Et,r).format(t)}function it(y,e,t){let r,i,n;if(e===void 0?(r=0,i=y,n=1):(r=y,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<Ke;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ke;a+=n)s.push(a);return s}function nt(y,e,t={}){const r=Math.trunc(Number(y));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 d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,p)=>d-p),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const p=u+1;c.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const vt=/^(\d{4})-(\d{1,2})$/,St=1200;function De(y,e){const t=Number(y);return Number.isFinite(t)?Math.trunc(t):e}function ke(y,e){if(typeof y!="string")return"";const t=vt.exec(y.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")}-${oe(o)}`}function wt(y){if(typeof y=="string"&&y.trim()!=="")return ke(y,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${oe(e.getMonth()+1)}`}function st(y,e){const t=Math.trunc(Number(y));if(!Number.isFinite(t)||t<0)return[];const r=wt(e);if(r==="")return[];const i=Math.min(t,St),n=[];for(let s=0;s<=i;s+=1){const a=ke(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function at(y,e){const t={start:0,end:0,total:0,empty:!0};if(!y||typeof y!="object")return t;const r=y,i=De(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,De(r.number,0)),s=Math.max(0,De(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=De(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function ot(y,e,t){if(!Array.isArray(y)||y.length===0)return null;const r=String(t),i=y.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function lt(y,e){if(!Array.isArray(y))return 0;let t=0;for(const r of y){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 ct(y,e){return e==null||y==null?String(y):String(y[e])}function ut(y,e){if(!Array.isArray(y))return[];const t=new Set,r=[];for(const i of y){const n=ct(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function dt(y,e){if(!Array.isArray(y))return[];const t=new Map,r=[];for(const i of y){const n=ct(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 Rt=Object.freeze({date:$e,now:et,today:tt,number:rt,pages:nt,range:it,monthAdd:ke,monthRange:st,pageSummary:at,findBy:ot,sum:lt,distinct:ut,groupBy:dt});class He{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await He.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const qe=class qe{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)}};qe.ASYNC_QUEUE=new He;let K=qe;const T=class T{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,T.readStorageSafely(()=>e.localStorage),T.readStorageSafely(()=>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 getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!q.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
2
  `)}static detectForbiddenIdentifiers(e){const t=this.FORBIDDEN_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.FORBIDDEN_NAME_PATTERNS.filter(i=>i.pattern.test(e)).map(i=>i.name);return this.FORBIDDEN_IDENTIFIER_CACHE.set(e,r),r}static extractFreeIdentifiers(e){const t=this.FREE_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];if(r!==null){let n=null;for(const s of r){const a=n?.value==="."||n?.value==="?.";s.type==="identifier"&&!a&&!this.NON_SHADOWABLE_IDENTIFIERS.has(s.value)&&!this.DISALLOWED_KEYWORDS.has(s.value)&&!this.STRICT_FORBIDDEN_NAMES.includes(s.value)&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s.value)&&!i.includes(s.value)&&i.push(s.value),n=s}}return this.FREE_IDENTIFIER_CACHE.set(e,i),i}static extractBoundIdentifiers(e){const t=this.BOUND_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=new Set,i=this.tokenizeExpression(e);if(i!==null){const n=new Set(["(",",","{","["]);for(let s=0;s<i.length;s+=1){if(i[s].value!=="=>")continue;const a=i[s-1];if(a===void 0)continue;if(a.type==="identifier"){r.add(a.value);continue}if(a.value!==")")continue;let o=0,c=0;for(let u=s-1;u>=0;u-=1){const d=i[u].value;if(d===")"||d==="]"||d==="}"){o+=1,d===")"&&(c+=1);continue}if(d==="("||d==="["||d==="{"){if(o-=1,d==="("&&(c-=1),o===0)break;continue}c===1&&i[u].type==="identifier"&&n.has(i[u-1]?.value??"")&&r.add(i[u].value)}}}return this.BOUND_IDENTIFIER_CACHE.set(e,r),r}static buildShadowDeclarations(e){return e.length===0?"":`
3
- let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),m.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static toGuardedMemberExpression(e){const t=this.GUARDED_MEMBER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[],s=[];let a=null;for(const o of r){if(o.value==="["){const c=this.startsMemberAccess(a);s.push(c),c&&n.push({start:o.position+1,end:o.position+1,text:T.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&s.pop()===!0&&n.push({start:o.position,end:o.position,text:")"});a=o}for(let o=n.length-1;o>=0;o-=1){const c=n[o];i=i.slice(0,c.start)+c.text+i.slice(c.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(e.length!==0){if(l.strictBind){m.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}j.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,K.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),m.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static recordSuppliedIdentifiers(e){for(const t of Object.keys(e))this.suppliedIdentifiers.add(t)}static recordRowScopeIdentifiers(e){if(j.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,K.waitForIdle().then(()=>{this.scopeMissingReportScheduled=!1,this.reportScopeMissingIdentifiers()}))}static reportScopeMissingIdentifiers(){if(this.pendingScopeMissingIdentifiers.size===0)return;const e=Array.from(this.pendingScopeMissingIdentifiers.entries());this.pendingScopeMissingIdentifiers.clear();for(const[t,r]of e){const i=[];for(const n of r){if(!this.suppliedIdentifiers.has(n)||this.rowScopeIdentifiers.has(n))continue;const s=`${n}
4
- ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&m.warn("[Haori]",`Expression key(s) are missing from this scope but are provided in another scope: ${i.join(", ")}. A binding is visible only to the target element itself and its descendants, so bind the response to this element or one of its ancestors (data-fetch-bind / data-{event}-bind):`,t)}}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(c=>s[c]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const d=this.detectDisallowedKeywords(e);if(d.length>0){const p=d.some(g=>g==="function"||g==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+d.join(", ")+"."+p)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const d=r.join(",");this.loggedForbiddenKeySignatures.has(d)||(this.loggedForbiddenKeySignatures.add(d),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const d of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(d)||(a[d]=t[d]);s&&(this.BUILTIN_DATA_REFERENCE_PATTERN.test(n)?a[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...a}}:a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a),j.isEnabled()&&this.recordSuppliedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),c=this.extractFreeIdentifiers(e).filter(d=>!(d in a)&&!this.FORBIDDEN_NAMES.includes(d)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(d));if(j.isEnabled()){const d=this.extractBoundIdentifiers(e);this.recordScopeMissingIdentifiers(d.size===0?c:c.filter(p=>!d.has(p)),e)}o&&c.forEach(d=>{a[d]=void 0});const u=o?[]:c;for(let d=0;d<=this.MAX_IDENTIFIER_RECOVERY_COUNT;d+=1){const p=this.prepareEvaluator(e,a,u);if(p.compileFailed||p.evaluator===null)return{value:null,unresolvedReference:!1};try{const g=[],E=this.wrapBoundValues(a);p.bindKeys.forEach(D=>{g.push(E[D])});const v=this.withBlockedPropertyAccess(()=>p.evaluator(...g));return v===void 0&&this.warnBlockedIdentifiers(e),{value:v,unresolvedReference:v===void 0}}catch(g){if(o&&g instanceof ReferenceError){const E=this.extractMissingIdentifier(g);if(E!==null&&this.canRecoverMissingIdentifier(E,a)){a[E]=void 0;continue}}if(this.warnBlockedIdentifiers(e),g instanceof ReferenceError&&u.length>0){const E=this.evaluateAsCondition(e,a,u);return E!==void 0?{value:E,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(g,u),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,g),g instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(v=>!this.FORBIDDEN_BINDING_NAMES.has(v)),n=[],s=[];i.forEach(v=>{this.isUsableBindingKey(v)?n.push(v):s.push(v)}),n.sort(),this.reportUnusableBindingKeys(s);const a=new Set(n),o=r.filter(v=>!a.has(v)),c=`${e}:${n.join(",")}:${o.join(",")}`;let u=this.EXPRESSION_CACHE.get(c)||null;if(u!==null)return this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1};const d=this.buildAssignments(n),p=this.buildShadowDeclarations(o),g=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),E=d?`"use strict";
3
+ let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),m.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static toGuardedMemberExpression(e){const t=this.GUARDED_MEMBER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[],s=[];let a=null;for(const o of r){if(o.value==="["){const c=this.startsMemberAccess(a);s.push(c),c&&n.push({start:o.position+1,end:o.position+1,text:T.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&s.pop()===!0&&n.push({start:o.position,end:o.position,text:")"});a=o}for(let o=n.length-1;o>=0;o-=1){const c=n[o];i=i.slice(0,c.start)+c.text+i.slice(c.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(e.length!==0){if(l.strictBind){m.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}q.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,K.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),m.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static recordSuppliedIdentifiers(e){for(const t of Object.keys(e))this.suppliedIdentifiers.add(t)}static recordRowScopeIdentifiers(e){if(q.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,K.waitForIdle().then(()=>{this.scopeMissingReportScheduled=!1,this.reportScopeMissingIdentifiers()}))}static reportScopeMissingIdentifiers(){if(this.pendingScopeMissingIdentifiers.size===0)return;const e=Array.from(this.pendingScopeMissingIdentifiers.entries());this.pendingScopeMissingIdentifiers.clear();for(const[t,r]of e){const i=[];for(const n of r){if(!this.suppliedIdentifiers.has(n)||this.rowScopeIdentifiers.has(n))continue;const s=`${n}
4
+ ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&m.warn("[Haori]",`Expression key(s) are missing from this scope but are provided in another scope: ${i.join(", ")}. A binding is visible only to the target element itself and its descendants, so bind the response to this element or one of its ancestors (data-fetch-bind / data-{event}-bind):`,t)}}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(c=>s[c]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const d=this.detectDisallowedKeywords(e);if(d.length>0){const p=d.some(g=>g==="function"||g==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+d.join(", ")+"."+p)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const d=r.join(",");this.loggedForbiddenKeySignatures.has(d)||(this.loggedForbiddenKeySignatures.add(d),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const d of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(d)||(a[d]=t[d]);s&&(this.BUILTIN_DATA_REFERENCE_PATTERN.test(n)?a[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...a}}:a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a),q.isEnabled()&&this.recordSuppliedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),c=this.extractFreeIdentifiers(e).filter(d=>!(d in a)&&!this.FORBIDDEN_NAMES.includes(d)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(d));if(q.isEnabled()){const d=this.extractBoundIdentifiers(e);this.recordScopeMissingIdentifiers(d.size===0?c:c.filter(p=>!d.has(p)),e)}o&&c.forEach(d=>{a[d]=void 0});const u=o?[]:c;for(let d=0;d<=this.MAX_IDENTIFIER_RECOVERY_COUNT;d+=1){const p=this.prepareEvaluator(e,a,u);if(p.compileFailed||p.evaluator===null)return{value:null,unresolvedReference:!1};try{const g=[],E=this.wrapBoundValues(a);p.bindKeys.forEach(I=>{g.push(E[I])});const A=this.withBlockedPropertyAccess(()=>p.evaluator(...g));return A===void 0&&this.warnBlockedIdentifiers(e),{value:A,unresolvedReference:A===void 0}}catch(g){if(o&&g instanceof ReferenceError){const E=this.extractMissingIdentifier(g);if(E!==null&&this.canRecoverMissingIdentifier(E,a)){a[E]=void 0;continue}}if(this.warnBlockedIdentifiers(e),g instanceof ReferenceError&&u.length>0){const E=this.evaluateAsCondition(e,a,u);return E!==void 0?{value:E,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(g,u),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,g),g instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(A=>!this.FORBIDDEN_BINDING_NAMES.has(A)),n=[],s=[];i.forEach(A=>{this.isUsableBindingKey(A)?n.push(A):s.push(A)}),n.sort(),this.reportUnusableBindingKeys(s);const a=new Set(n),o=r.filter(A=>!a.has(A)),c=`${e}:${n.join(",")}:${o.join(",")}`;let u=this.EXPRESSION_CACHE.get(c)||null;if(u!==null)return this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1};const d=this.buildAssignments(n),p=this.buildShadowDeclarations(o),g=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),E=d?`"use strict";
5
5
  ${d};
6
6
  return (${g});${p}`:`"use strict";
7
- return (${g});${p}`;try{return u=new Function(...n,E),this.EXPRESSION_CACHE.set(c,u),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1}}catch(v){return o.length>0?(m.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(m.error("[Haori]","Failed to compile expression:",e,v),this.compileFailedExpressions.add(e),{bindKeys:n,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,c=t[n-2]||null,u=t[n-3]||null;if(this.startsObjectKey(o,i,c,u)&&(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 d=this.startsMemberAccess(i)?"member":"array";r.push(d);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 diagnoseStrictComparison(e,t={}){const r=T.splitStrictComparison(e);if(r===null)return null;const i=T.evaluateDetailed(r.left,t),n=T.evaluateDetailed(r.right,t);if(i.unresolvedReference||n.unresolvedReference)return null;const s=i.value,a=n.value;return typeof s==typeof a||!T.isLooselyEqual(s,a)?null:{left:typeof s,right:typeof a}}static isLooselyEqual(e,t){return e==t}static splitStrictComparison(e){const t=T.strictComparisonSplits.get(e);if(t!==void 0)return t;const r=T.computeStrictComparisonSplit(e);return T.strictComparisonSplits.set(e,r),r}static computeStrictComparisonSplit(e){const t=T.tokenizeExpression(e);if(t===null)return null;let r=0,i=null;for(const a of t)if(a.type==="operator"){if(a.value==="("||a.value==="["||a.value==="{"){r+=1;continue}if(a.value===")"||a.value==="]"||a.value==="}"){r-=1;continue}if(r===0){if(a.value==="&&")return T.splitStrictComparison(e.slice(0,a.position));if(a.value==="==="){if(i!==null)return null;i=a;continue}if(T.COMPOSING_OPERATORS.has(a.value))return null}}if(i===null)return null;const n=e.slice(0,i.position).trim(),s=e.slice(i.position+i.value.length).trim();return n===""||s===""?null:{left:n,right:s}}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==="/"&&this.startsRegexpLiteral(t)){const o=this.readRegexpToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}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 startsRegexpLiteral(e){const t=e[e.length-1];if(t===void 0)return!0;if(t.type!=="operator"||t.value===")"||t.value==="]"||t.value==="}")return!1;const r=e[e.length-2];return!((t.value==="+"||t.value==="-")&&r?.value===t.value)}static readRegexpToken(e,t){let r=t+1,i=!1;for(;r<e.length;){const n=e[r];if(n==="\\"){r+=2;continue}if(n==="[")i=!0;else if(n==="]")i=!1;else if(n==="/"&&!i){for(r+=1;r<e.length&&/[A-Za-z]/.test(e[r]);)r+=1;return{token:{type:"regexp",value:e.slice(t,r),position:t},nextIndex:r}}r+=1}return null}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"||e.type==="string"||e.type==="regexp"?!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`
8
- `;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;if(this.WRAPPED_VALUES.has(r))return r;const 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 c=Reflect.get(s,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,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 c=Reflect.apply(s,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return this.WRAPPED_VALUES.add(n),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){if(!e||typeof e!="object")return!1;const i=r??this.getForbiddenBindingValueSet(),n=this.forbiddenBindingValueCache.get(e);if(n!==void 0)return n;if(t.has(e))return!1;if(t.add(e),i.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(i.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,i))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};T.MAX_IDENTIFIER_RECOVERY_COUNT=8,T.BUILTIN_NAMESPACE="haori",T.BUILTIN_HELPERS={...Rt},T.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,T.BUILTIN_DATA_PROPERTY="data",T.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,T.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,T.usableBindingKeyCache=new Map,T.loggedUnusableBindingKeys=new Set,T.compileFailedExpressions=new Set,T.forbiddenBindingValueCache=new WeakMap,T.forbiddenBindingValueCacheResetScheduled=!1,T.loggedForbiddenKeySignatures=new Set,T.loggedForbiddenKeyResetScheduled=!1,T.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"],T.STRICT_FORBIDDEN_NAMES=["eval","arguments"],T.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),T.FORBIDDEN_BINDING_NAMES=new Set([...T.FORBIDDEN_NAMES.filter(e=>!T.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...T.STRICT_FORBIDDEN_NAMES]),T.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),T.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),T.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"]),T.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),T.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),T.EXPRESSION_CACHE=new Map,T.FREE_IDENTIFIER_CACHE=new Map,T.BOUND_IDENTIFIER_CACHE=new Map,T.OPTIONAL_CHAIN_CACHE=new Map,T.GUARDED_MEMBER_CACHE=new Map,T.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",T.FORBIDDEN_NAME_PATTERNS=T.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),T.FORBIDDEN_IDENTIFIER_CACHE=new Map,T.pendingUnresolvedIdentifiers=new Set,T.unresolvedReportScheduled=!1,T.suppliedIdentifiers=new Set,T.pendingScopeMissingIdentifiers=new Map,T.scopeMissingReportScheduled=!1,T.rowScopeIdentifiers=new Set,T.loggedScopeMissingIdentifiers=new Set,T.loggedBlockedIdentifierExpressions=new Set,T.COMPOSING_OPERATORS=new Set(["||","?",":","==","!=",">=","<=",">","<","=>",",","!","+","-","*","/","%","..."]),T.strictComparisonSplits=new Map,T.WRAPPED_VALUES=new WeakSet;let Q=T;const Ae="data-haori-if-disabled",Ge="input, select, textarea, button, fieldset",P=class P{static reset(){P.ELEMENT_STORES.clear(),P.ensureGlobalAccess()}static start(){P.collecting=!0}static stop(){P.collecting=!1}static isCollecting(){return P.collecting&&j.isEnabled()}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 report(e=P.DEFAULT_REPORT_LIMIT){const t=new Map;let r=0,i=0;const n=(c,u,d)=>{r+=d.totalDurationMs,i+=d.calls;const p=t.get(c);if(p===void 0){t.set(c,{where:u,template:d.template,elements:1,calls:d.calls,totalDurationMs:d.totalDurationMs,maxDurationMs:d.maxDurationMs,sharePercent:0,representativeDurationMs:d.totalDurationMs});return}p.elements+=1,p.calls+=d.calls,p.totalDurationMs+=d.totalDurationMs,p.maxDurationMs=Math.max(p.maxDurationMs,d.maxDurationMs),d.totalDurationMs>p.representativeDurationMs&&(p.where=u,p.representativeDurationMs=d.totalDurationMs)};P.snapshot().forEach(c=>{c.attributes.forEach(u=>{n(`@${u.name}
7
+ return (${g});${p}`;try{return u=new Function(...n,E),this.EXPRESSION_CACHE.set(c,u),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1}}catch(A){return o.length>0?(m.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(m.error("[Haori]","Failed to compile expression:",e,A),this.compileFailedExpressions.add(e),{bindKeys:n,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,c=t[n-2]||null,u=t[n-3]||null;if(this.startsObjectKey(o,i,c,u)&&(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 d=this.startsMemberAccess(i)?"member":"array";r.push(d);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 diagnoseStrictComparison(e,t={}){const r=T.splitStrictComparison(e);if(r===null)return null;const i=T.evaluateDetailed(r.left,t),n=T.evaluateDetailed(r.right,t);if(i.unresolvedReference||n.unresolvedReference)return null;const s=i.value,a=n.value;return typeof s==typeof a||!T.isLooselyEqual(s,a)?null:{left:typeof s,right:typeof a}}static isLooselyEqual(e,t){return e==t}static splitStrictComparison(e){const t=T.strictComparisonSplits.get(e);if(t!==void 0)return t;const r=T.computeStrictComparisonSplit(e);return T.strictComparisonSplits.set(e,r),r}static computeStrictComparisonSplit(e){const t=T.tokenizeExpression(e);if(t===null)return null;let r=0,i=null;for(const a of t)if(a.type==="operator"){if(a.value==="("||a.value==="["||a.value==="{"){r+=1;continue}if(a.value===")"||a.value==="]"||a.value==="}"){r-=1;continue}if(r===0){if(a.value==="&&")return T.splitStrictComparison(e.slice(0,a.position));if(a.value==="==="){if(i!==null)return null;i=a;continue}if(T.COMPOSING_OPERATORS.has(a.value))return null}}if(i===null)return null;const n=e.slice(0,i.position).trim(),s=e.slice(i.position+i.value.length).trim();return n===""||s===""?null:{left:n,right:s}}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==="/"&&this.startsRegexpLiteral(t)){const o=this.readRegexpToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}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 startsRegexpLiteral(e){const t=e[e.length-1];if(t===void 0)return!0;if(t.type!=="operator"||t.value===")"||t.value==="]"||t.value==="}")return!1;const r=e[e.length-2];return!((t.value==="+"||t.value==="-")&&r?.value===t.value)}static readRegexpToken(e,t){let r=t+1,i=!1;for(;r<e.length;){const n=e[r];if(n==="\\"){r+=2;continue}if(n==="[")i=!0;else if(n==="]")i=!1;else if(n==="/"&&!i){for(r+=1;r<e.length&&/[A-Za-z]/.test(e[r]);)r+=1;return{token:{type:"regexp",value:e.slice(t,r),position:t},nextIndex:r}}r+=1}return null}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"||e.type==="string"||e.type==="regexp"?!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`
8
+ `;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;if(this.WRAPPED_VALUES.has(r))return r;const 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 c=Reflect.get(s,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,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 c=Reflect.apply(s,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return this.WRAPPED_VALUES.add(n),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){if(!e||typeof e!="object")return!1;const i=r??this.getForbiddenBindingValueSet(),n=this.forbiddenBindingValueCache.get(e);if(n!==void 0)return n;if(t.has(e))return!1;if(t.add(e),i.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(i.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,i))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};T.MAX_IDENTIFIER_RECOVERY_COUNT=8,T.BUILTIN_NAMESPACE="haori",T.BUILTIN_HELPERS={...Rt},T.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,T.BUILTIN_DATA_PROPERTY="data",T.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,T.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,T.usableBindingKeyCache=new Map,T.loggedUnusableBindingKeys=new Set,T.compileFailedExpressions=new Set,T.forbiddenBindingValueCache=new WeakMap,T.forbiddenBindingValueCacheResetScheduled=!1,T.loggedForbiddenKeySignatures=new Set,T.loggedForbiddenKeyResetScheduled=!1,T.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"],T.STRICT_FORBIDDEN_NAMES=["eval","arguments"],T.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),T.FORBIDDEN_BINDING_NAMES=new Set([...T.FORBIDDEN_NAMES.filter(e=>!T.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...T.STRICT_FORBIDDEN_NAMES]),T.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),T.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),T.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"]),T.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),T.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),T.EXPRESSION_CACHE=new Map,T.FREE_IDENTIFIER_CACHE=new Map,T.BOUND_IDENTIFIER_CACHE=new Map,T.OPTIONAL_CHAIN_CACHE=new Map,T.GUARDED_MEMBER_CACHE=new Map,T.MEMBER_KEY_GUARD_OPEN="(_hk=>_hk==='constructor'||_hk==='__proto__'||_hk==='prototype'?undefined:_hk)(",T.FORBIDDEN_NAME_PATTERNS=T.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),T.FORBIDDEN_IDENTIFIER_CACHE=new Map,T.pendingUnresolvedIdentifiers=new Set,T.unresolvedReportScheduled=!1,T.suppliedIdentifiers=new Set,T.pendingScopeMissingIdentifiers=new Map,T.scopeMissingReportScheduled=!1,T.rowScopeIdentifiers=new Set,T.loggedScopeMissingIdentifiers=new Set,T.loggedBlockedIdentifierExpressions=new Set,T.COMPOSING_OPERATORS=new Set(["||","?",":","==","!=",">=","<=",">","<","=>",",","!","+","-","*","/","%","..."]),T.strictComparisonSplits=new Map,T.WRAPPED_VALUES=new WeakSet;let ee=T;const de="data-haori-if-disabled",ze="input, select, textarea, button, fieldset",k=class k{static reset(){k.ELEMENT_STORES.clear(),k.ensureGlobalAccess()}static start(){k.collecting=!0}static stop(){k.collecting=!1}static isCollecting(){return k.collecting&&q.isEnabled()}static snapshot(){return k.ensureGlobalAccess(),[...k.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:k.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:k.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 report(e=k.DEFAULT_REPORT_LIMIT){const t=new Map;let r=0,i=0;const n=(c,u,d)=>{r+=d.totalDurationMs,i+=d.calls;const p=t.get(c);if(p===void 0){t.set(c,{where:u,template:d.template,elements:1,calls:d.calls,totalDurationMs:d.totalDurationMs,maxDurationMs:d.maxDurationMs,sharePercent:0,representativeDurationMs:d.totalDurationMs});return}p.elements+=1,p.calls+=d.calls,p.totalDurationMs+=d.totalDurationMs,p.maxDurationMs=Math.max(p.maxDurationMs,d.maxDurationMs),d.totalDurationMs>p.representativeDurationMs&&(p.where=u,p.representativeDurationMs=d.totalDurationMs)};k.snapshot().forEach(c=>{c.attributes.forEach(u=>{n(`@${u.name}
9
9
  ${u.template}`,`${c.elementId} @${u.name}`,u)}),c.texts.forEach(u=>{n(`#${u.childIndex}
10
- ${u.template}`,`${c.elementId} #${u.childIndex}`,u)})});const s=[...t.values()].map(({representativeDurationMs:c,...u})=>u);s.sort((c,u)=>u.totalDurationMs-c.totalDurationMs);const a=s.slice(0,e).map(c=>({...c,sharePercent:r>0?Math.round(c.totalDurationMs/r*1e3)/10:0})),o={totalDurationMs:r,totalCalls:i,entryCount:s.length,top:a};return P.logReport(o),o}static logReport(e){const t=e.top.map((r,i)=>{const n=String(i+1).padStart(2),s=r.totalDurationMs.toFixed(1).padStart(9),a=`${r.sharePercent.toFixed(1)}%`.padStart(6),o=String(r.calls).padStart(6),c=String(r.elements).padStart(4),u=r.maxDurationMs.toFixed(1).padStart(8);return`${n}. ${s}ms ${a} calls=${o} elements=${c} max=${u}ms ${r.where} ${r.template}`});m.info("[Haori][evaluation-profile]",`total=${e.totalDurationMs.toFixed(1)}ms calls=${e.totalCalls} declarations=${e.entryCount}
10
+ ${u.template}`,`${c.elementId} #${u.childIndex}`,u)})});const s=[...t.values()].map(({representativeDurationMs:c,...u})=>u);s.sort((c,u)=>u.totalDurationMs-c.totalDurationMs);const a=s.slice(0,e).map(c=>({...c,sharePercent:r>0?Math.round(c.totalDurationMs/r*1e3)/10:0})),o={totalDurationMs:r,totalCalls:i,entryCount:s.length,top:a};return k.logReport(o),o}static logReport(e){const t=e.top.map((r,i)=>{const n=String(i+1).padStart(2),s=r.totalDurationMs.toFixed(1).padStart(9),a=`${r.sharePercent.toFixed(1)}%`.padStart(6),o=String(r.calls).padStart(6),c=String(r.elements).padStart(4),u=r.maxDurationMs.toFixed(1).padStart(8);return`${n}. ${s}ms ${a} calls=${o} elements=${c} max=${u}ms ${r.where} ${r.template}`});m.info("[Haori][evaluation-profile]",`total=${e.totalDurationMs.toFixed(1)}ms calls=${e.totalCalls} declarations=${e.entryCount}
11
11
  `+t.join(`
12
- `))}static record(e,t,r){if(!j.isEnabled()||!e||t.length===0||(P.ensureGlobalAccess(),!P.isCollecting()))return;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(!j.isEnabled())return;const e=globalThis;e[P.GLOBAL_KEY]===void 0&&(e[P.GLOBAL_KEY]={start:()=>P.start(),stop:()=>P.stop(),reset:()=>P.reset(),snapshot:()=>P.snapshot(),report:t=>P.report(t)})}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){if(!P.isCollecting())return{value:e(),durationMs:0};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(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.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,P.collecting=!1,P.DEFAULT_REPORT_LIMIT=20;let Ne=P;const ue=class ue{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,ue.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(ue.FRAGMENT_CACHE.has(e))return ue.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new I(e);break;case Node.TEXT_NODE:t=new ee(e);break;case Node.COMMENT_NODE:t=new Ve(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return 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),ue.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};ue.FRAGMENT_CACHE=new WeakMap;let x=ue;const R=class R extends x{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.lastSupplySequence=0,this.lastResetSequence=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.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.selfWritingAttributes=new Map,this.skipChangeValue=!1,this.valueWriteUnapplied=!1,this.pendingValueWrite=null,this.userEditSequence=0,this.authoritativeValueSequence=0,this.lastValueSequence=0,this.lastValueKind="nonSupply",this.selfWrittenBind=new Map,this.lastPathApplied=new Map,this.lastChangeSequence=0,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Fe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=x.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof R)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new R(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.rowLocalTemplate=this.rowLocalTemplate,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(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof R&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return e&&re.destroySubtree(this.getTarget()),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,this.clearUnappliedValueWrite(),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}static isExecutingAnyBindingWork(){return R.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,R.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,R.bindingWorkActiveCount--)}markSupplyApplied(e){e>this.lastSupplySequence&&(this.lastSupplySequence=e)}isSupplyStale(e){return this.lastSupplySequence>e}markResetAt(e){this.lastResetSequence=e}wasResetAfter(e){return this.lastResetSequence>e}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 R&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=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,t=null){return this.applyValue(e,!0,t)}syncBindingValue(e,t=null){return this.applyValue(e,!1,t)}applyValue(e,t,r=null){if(this.skipChangeValue)return(this.pendingValueWrite??Promise.resolve()).then(()=>this.applyValue(e,t,r));if(r&&!this.canApplyValue(r)||(r&&this.markValueApplied(r),this.value===e))return Promise.resolve();const i=this.getTarget();if(i instanceof HTMLInputElement&&i.type==="file")return e===null||e===""?(this.value=null,i.value===""?Promise.resolve():K.enqueue(()=>{i.value=""})):(m.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",i),Promise.resolve());if(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")){const n=this.hasAttribute("value")?this.getAttribute("value"):i.value,s=i.type==="checkbox"&&n==="true";let a;if(s?a=e===!0||e==="true":n==="false"?a=e===!1:Array.isArray(e)?a=e.map(String).includes(String(n)):a=n===String(e),s?this.value=a:a?Array.isArray(e)?this.value=String(n):this.value=e:this.value=null,i.checked===a)return Promise.resolve();const o=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(o)||r&&!this.canApplyValue(r)||(i.checked=a,t&&i.dispatchEvent(new Event("change",{bubbles:!0})))})}else if(i instanceof HTMLSelectElement&&i.multiple){const n=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.writeSelectedValues(n,t,r)}else return i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?this.writeScalarValue(Array.isArray(e)?e.join(","):e,t,r):(m.warn("[Haori]","setValue is not supported for this element type.",i),Promise.resolve())}writeScalarValue(e,t,r=null){const i=this.getTarget(),n=e===null?"":String(e);this.value=this.normalizeValueForElement(i,e);const s=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r)||(i.value=n,this.recordValueWriteResult(i.value===n),t&&((i instanceof HTMLInputElement&&R.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement)&&i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))))})}writeSelectedValues(e,t,r=null){const i=this.getTarget();this.value=e.slice();const n=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(n)||r&&!this.canApplyValue(r))return;let s=!1;const a=new Set;Array.from(i.options).forEach(o=>{const c=e.includes(o.value);o.selected!==c&&(o.selected=c,s=!0),c&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=K.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(R.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(R.UNAPPLIED_VALUE_WRITES)){const n=i.getTarget();if(i.wasResetAfter(t)){i.clearUnappliedValueWrite();continue}if(!n.isConnected){i.clearUnappliedValueWrite();continue}e.contains(n)&&r.push(i.retryValueWrite())}return Promise.all(r).then(()=>{})}retryValueWrite(){const e=this.getTarget();if(this.skipChangeValue||!(e instanceof HTMLSelectElement))return Promise.resolve();if(e.multiple){const r=Array.isArray(this.value)?this.value.slice():[];return r.every(i=>Array.from(e.options).some(n=>n.value===i))?this.writeSelectedValues(r,!1):Promise.resolve()}const t=this.value===null?"":String(this.value);return Array.from(e.options).some(r=>r.value===t)?this.writeScalarValue(this.value,!1):Promise.resolve()}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,R.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return R.sequenceCounter}static nextSequence(){return R.sequenceCounter+=1,R.sequenceCounter}static setPendingMutationFlusher(e){R.pendingMutationFlusher=e}static nextOperationSequence(){return R.pendingMutationFlusher&&!R.isExecutingAnyBindingWork()&&R.pendingMutationFlusher(),R.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:R.isApplicable({sequence:this.lastValueSequence,kind:this.lastValueKind},e)}static isApplicable(e,t){return e===null?!0:t.kind==="nonSupply"&&e.kind==="edit"?!1:t.sequence>e.sequence?!0:t.sequence===e.sequence?e.kind!=="edit"||t.kind==="edit":!1}canApplyPath(e,t){return R.isApplicable(this.lastPathApplied.get(e)??null,t)}markPathApplied(e,t){if(t.kind==="nonSupply")return;const r=this.lastPathApplied.get(e)??null;(r===null||t.sequence>r.sequence||t.sequence===r.sequence&&t.kind==="edit")&&this.lastPathApplied.set(e,{sequence:t.sequence,kind:t.kind})}markValueApplied(e){e.kind!=="nonSupply"&&(e.sequence>this.lastValueSequence||e.sequence===this.lastValueSequence&&e.kind==="edit")&&(this.lastValueSequence=e.sequence,this.lastValueKind=e.kind)}markUserEdit(){return this.userEditSequence=R.nextSequence(),this.markValueApplied({sequence:this.userEditSequence,kind:"edit"}),this.userEditSequence}markUserEditOnChange(){const t=this.userEditSequence>this.lastChangeSequence?this.userEditSequence:this.markUserEdit();return this.lastChangeSequence=t,t}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=R.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!j.isEnabled())return;const n=`${e} ${r}`;R.loggedUnresolvedAttributes.has(n)||(R.loggedUnresolvedAttributes.add(n),m.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}static warnTypeMismatchedComparison(e,t,r,i){const n=`${e} ${t}`;R.loggedTypeMismatchedComparisons.has(n)||(R.loggedTypeMismatchedComparisons.add(n),m.warn("[Haori]",`The strict comparison compares different types (${r.left} vs ${r.right}), so it is always false even though the values match. Align the types (for example with ${l.prefix}value-type) or compare converted values: ${e}="${t}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=x.get(t);return r instanceof R?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=R.resolveDeclaredValueType(e);return r==="boolean"?R.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?R.normalizeNumberValue(t):t}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!R.NUMBER_INPUT_PATTERN.test(e))return null;const t=Number(e);return Number.isFinite(t)?t:null}static normalizeBooleanValue(e){if(typeof e=="boolean")return e;if(typeof e!="string")return null;const t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:null}static resolveDeclaredValueType(e){const t=e.getAttribute(`${l.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return R.VALUE_TYPE_NAMES.has(r)?R.acceptsDeclaredValueType(e)?r:(R.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(R.warnValueTypeDeclaration(e,t,"boolean / number / string のいずれかを指定してください"),null)}static acceptsDeclaredValueType(e){return e instanceof HTMLInputElement?e.type!=="checkbox"&&e.type!=="radio"&&e.type!=="file":e instanceof HTMLSelectElement?!e.multiple:e instanceof HTMLTextAreaElement}static warnValueTypeDeclaration(e,t,r){if(!j.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;R.loggedValueTypeDeclarations.has(n)||(R.loggedValueTypeDeclarations.add(n),m.warn("Haori",`${l.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?R.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}static isUserEditableValue(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?!e.readOnly:!0}syncValue(){this.clearUnappliedValueWrite(),this.value=this.readValueFromDom()}readValueFromDom(){const e=this.getTarget();if(R.resolveDeclaredValueType(e),e instanceof HTMLInputElement){if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true",r=e.value;return e.checked?t?!0:r==="false"?!1:r:t?!1:r==="false"?!0:null}else if(e.type==="file"){const t=e.files;return t&&t.length>0?t[0].name:null}return this.normalizeValueForElement(e,e.value)}else{if(e instanceof HTMLTextAreaElement)return this.normalizeValueForElement(e,e.value);if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):this.normalizeValueForElement(e,e.value)}return this.value}recordValueWriteResult(e){if(!e&&this.value!==null&&this.value!==""){this.valueWriteUnapplied=!0,R.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:R.isValuePropertyTarget(this.getTarget())?this.readValueFromDom():this.value}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=x.get(t);r instanceof R&&r.syncValue()}getSelfWritingAttribute(e){for(const t of e){const r=this.selfWritingAttributes.get(t);if(r!==void 0)return r}return null}holdSelfWritingAttributes(e,t){for(const r of e)this.selfWritingAttributes.set(r,t)}releaseSelfWritingAttributes(e){for(const t of e)this.selfWritingAttributes.delete(t)}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,!0,i)}removeAliasedAttribute(e,t){const r=[e,t];if(this.getSelfWritingAttribute(r)!==null)return Promise.resolve();this.attributeMap.delete(e);const i=this.getTarget(),n=i.hasAttribute(e),s=t!==e&&i.hasAttribute(t);if(!n&&!s)return Promise.resolve();const a=K.enqueue(()=>{n&&i.removeAttribute(e),s&&i.removeAttribute(t)}).finally(()=>{this.releaseSelfWritingAttributes(r)});return this.holdSelfWritingAttributes(r,a),a}setAttributeInternal(e,t,r,i,n=!1){const s=[e,t],a=this.getSelfWritingAttribute(s);if(a!==null)return n||r===null?Promise.resolve():a.then(()=>this.setAttributeInternal(e,t,r,i,n));if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const o=new Fe(e,r);if(n){const fe=this.attributeMap.get(e);if(fe&&(fe.isEvaluate||fe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const Ee=K.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,Ee),Ee}}this.attributeMap.set(e,o);const c=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:c,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,p=e===t&&R.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),g=o.isSingleExpression(),E=se.joinEvaluateResults(u.results),v=u.results.length===1?u.results[0]:E,D=t==="value"&&R.resolveDeclaredValueType(c)==="boolean",M=v===!1&&!D,H=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||v===null||v===void 0||M:p?u.hasUnresolvedReference||v===null||v===void 0||v===!1:g?u.hasUnresolvedReference||v===null||v===void 0||M:d&&E==="");if(H&&u.hasUnresolvedReference&&R.warnUnresolvedAttribute(e,t,r,c),j.isEnabled()&&v===!1&&g){const fe=o.getSingleExpression(),Ee=fe===null?null:Q.diagnoseStrictComparison(fe,this.getBindingData());Ee!==null&&R.warnTypeMismatchedComparison(e,r,Ee,c)}const A=o.isForceEvaluation()?r:g?v:E,S=i&&o.isEvaluate&&t==="value"&&R.isValuePropertyTarget(c),C=c.getRootNode(),V=S&&R.isUserEditableValue(c)&&(c===C.activeElement||this.hasPendingUserEdit()),O=H||A===null||A===!1&&!D?null:String(A),_=e!==t&&c.getAttribute(e)!==r,k=O===null?c.hasAttribute(t):c.getAttribute(t)!==O,q=O===null?"":O,X=S&&!V&&c.value!==q,Y=t==="checked"&&c instanceof HTMLInputElement&&(c.type==="checkbox"||c.type==="radio"),te=t==="selected"&&c instanceof HTMLOptionElement,be=C.activeElement,de=be!==null&&(Y&&c===be||te&&c.closest("select")===be)||(Y||te)&&this.hasPendingCheckableUserEdit(te),we=O!==null,$e=Y&&!de&&c.checked!==we,Re=te&&!de&&c.selected!==we;if(!_&&!k&&!X&&!$e&&!Re)return S&&!V&&(this.value=this.normalizeValueForElement(c,q),this.clearUnappliedValueWrite()),(Y||te)&&!de&&this.syncCheckableValueFromDom(te),Promise.resolve();const We=K.enqueue(()=>{_&&c.setAttribute(e,r),O===null?c.removeAttribute(t):k&&(c.setAttribute(t,O),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(O)),S&&!V&&(this.value=this.normalizeValueForElement(c,q),X&&(c.value=q),this.recordValueWriteResult(c.value===q)),$e&&(c.checked=we),Re&&(c.selected=we),($e||Re)&&this.syncCheckableValueFromDom(Re)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,We),We}removeAttribute(e){if(this.getSelfWritingAttribute([e])!==null)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();if(!t.hasAttribute(e))return Promise.resolve();const r=K.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.releaseSelfWritingAttributes([e])});return this.holdSelfWritingAttributes([e],r),r}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:se.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=x.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let u=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const g=this.resolveInsertionPointFromDom(t,!1);g===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(g.index,0,e),u=g.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,K.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),R.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Ge)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(Ge)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){R.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(Ae,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){R.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(Ae)&&(e.removeAttribute(Ae),e.removeAttribute("disabled"))})}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(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};R.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,R.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),R.loggedValueTypeDeclarations=new Set,R.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"]),R.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],R.UNAPPLIED_VALUE_WRITES=new Set,R.sequenceCounter=0,R.bindingWorkActiveCount=0,R.pendingMutationFlusher=null,R.loggedUnresolvedAttributes=new Set,R.loggedTypeMismatchedComparisons=new Set;let I=R;class ee extends x{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new se(this.text)}clone(){const e=new ee(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}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new se(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=se.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 x{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,K.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Me=class Me{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(Me.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)}getSingleExpression(){return this.isSingleExpression()?this.contents[0].text:null}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const u=Ne.measure(()=>Q.evaluateDetailed(c.text,e)),d=u.value;a+=u.durationMs,s.push({expression:c.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(c.text)}catch(u){m.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,u),s.push({expression:c.text,durationMs:0}),n.push("")}}),Ne.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Me.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let se=Me;const Z=class Z extends se{constructor(e,t){super(t),this.forceEvaluation=Z.needsForceEvaluation(e)}static needsForceEvaluation(e){if(Z.forceEvaluationNames===null||Z.forceEvaluationPrefix!==l.prefix){const t=new Set;for(const r of[l.prefix,...Z.FORCE_EVALUATION_PREFIXES])for(const i of Z.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Z.forceEvaluationNames=t,Z.forceEvaluationPrefix=l.prefix}return Z.forceEvaluationNames.has(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Z.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Z.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Z.forceEvaluationNames=null,Z.forceEvaluationPrefix=null;let Fe=Z;const me=class me{static get runtime(){return l.runtime}static setRuntime(e){l.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?(me.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return me.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(()=>{me.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 Ce(e,t,r)}static now(e,t){return et(e,t)}static today(e,t,r){return tt(e,t,r)}static number(e,t){return rt(e,t)}static range(e,t,r){return it(e,t,r)}static pages(e,t,r){return nt(e,t,r)}static monthAdd(e,t){return ke(e,t)}static monthRange(e,t){return st(e,t)}static pageSummary(e,t){return at(e,t)}static findBy(e,t,r){return ot(e,t,r)}static sum(e,t){return lt(e,t)}static distinct(e,t){return ut(e,t)}static groupBy(e,t){return dt(e,t)}};me.enhancers={register(e,t){re.register(e,t)},has(e){return re.has(e)}};let ae=me;const Tt="入力内容を確認してください",Dt=["addErrorMessage","clearMessages"],ze="data-haori-group-name";function Ye(){const e=globalThis.window?.Haori;return Dt.every(r=>typeof e?.[r]=="function")?e:ae}const h=class h{static getValues(e){const t={},r=new Set;return h.getPartValues(e,t,null,r),h.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(h.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(h.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValueForCollection()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=h.getValues(e),i=new Set;for(const n of new Set([...Object.keys(r),...Object.keys(t)]))h.isSameCollectedValue(r[n],t[n])||i.add(n);i.size!==0&&h.clearUserEditMarksForKeys(e,e,i)}static isSameCollectedValue(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static clearUserEditMarksForKeys(e,t,r){const i=h.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(n=>{h.clearUserEditMarksForKeys(n,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const n=i.getAttribute(`${l.prefix}form-object`)||i.getAttribute(`${l.prefix}form-list`)||h.resolveFieldName(i);n!=null&&String(n)!==""&&(r=String(n)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){m.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(ze))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(ze,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=h.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(h.groupScopeSequence+=1,h.GROUP_SCOPE_IDS.set(e,h.groupScopeSequence),h.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!h.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return h.isDeclarationResolved(e,"checked");if(h.hasDeclarativeBinding(e,"value"))return h.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=x.get(r);if(i instanceof I&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${l.prefix}attr-${t}`,t]){const i=e.getAttributeEvaluation(r);if(i!==null)return!i.hasUnresolvedReference}return!1}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?h.hasDeclarativeBinding(e,"checked"):I.isValuePropertyTarget(t)?h.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?h.hasDeclarativeSelectedOption(t):!1:!1}static restoreDefaultValues(e){const t="input, textarea, select",r=[];e.matches(t)&&r.push(e),r.push(...e.querySelectorAll(t));for(const i of r)i instanceof HTMLInputElement?i.type==="checkbox"||i.type==="radio"?i.checked=i.defaultChecked:i.type==="file"?i.value="":i.value=i.defaultValue:i instanceof HTMLTextAreaElement?i.value=i.defaultValue:i instanceof HTMLSelectElement&&h.restoreDefaultSelection(i)}static restoreDefaultSelection(e){const t=Array.from(e.options);for(const r of t)r.selected=r.defaultSelected;if(!e.multiple&&e.selectedIndex<0){const r=t.find(i=>!i.disabled);r&&(r.selected=!0)}}static clearDeclarativeStateFromDom(e){if(h.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof I&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=x.get(t);if(r instanceof I&&h.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return h.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const n=new Map;for(const a of h.collectUserEditSequences(e)){const o=new Set;h.walkEditedPaths(h.getValuesEditedAfter(e,a-1),r,o);for(const c of o)n.has(c)||n.set(c,a)}const s=new Set;h.walkExcludedPaths(i??h.getValues(e),r,s);for(const a of s)n.has(a)||n.set(a,t);return n}static collectUserEditSequences(e){const t=new Set;return h.walkUserEditSequences(e,t),[...t].sort((r,i)=>i-r)}static walkUserEditSequences(e,t){const r=e.getUserEditSequence();r>0&&t.add(r);for(const i of e.getChildElementFragments())h.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i===null)return;const n=h.COLLECTED_EXCLUDED_KEYS.get(i);if(n)for(const s of n)s in i||r.add(t===""?s:`${t}.${s}`);for(const[s,a]of Object.entries(i))h.walkExcludedPaths(a,t===""?s:`${t}.${s}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i!==null){for(const[n,s]of Object.entries(i))h.walkEditedPaths(s,t===""?n:`${t}.${n}`,r);return}t!==""&&r.add(t)}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${l.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${l.prefix}if-false`)){if(i!==null)for(const u of h.collectDeclaredKeysInFragment(e))i.add(u);return t}const n=h.resolveFieldName(e),s=e.getAttribute(`${l.prefix}form-object`),a=e.getAttribute(`${l.prefix}form-list`),o=e.hasAttribute(`${l.prefix}form-list`),c=r!==null&&e.getUserEditSequence()<=r;if(n){if(r!==null&&h.isGroupedCheckable(e)){const u=h.collectGroupSelection(e,o,r);u.edited&&(t[String(n)]=u.value)}else if(o&&h.isGroupedCheckable(e)){const u=String(n),d=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!c&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&c)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!c)if(o){const u=h.resolveCollectedValue(e),d=h.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(n)])?t[String(n)].push(...d):t[String(n)]=d}else if(h.isGroupedCheckable(e)){const u=e.getTarget(),d=u instanceof HTMLInputElement?u.checked:!0,p=u instanceof HTMLInputElement?u.value:e.getValue(),g=d?p:null,E=String(n);g===null?E in t||(t[E]=null):t[E]===null||t[E]===void 0?t[E]=g:Array.isArray(t[E])?t[E].push(g):t[E]=[t[E],g]}else t[String(n)]=h.resolveCollectedValue(e);s&&m.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i)}else if(s){const u={},d=i===null?null:new Set;for(const p of e.getChildElementFragments())h.getPartValues(p,u,r,d);d!==null&&h.registerCollectedExcludedKeys(u,d),Object.keys(u).length>0?t[String(s)]=u:i!==null&&(d?.size??0)>0&&i.add(String(s)),a&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let p=!1;for(const g of e.getChildElementFragments()){const E={},v=i===null?null:new Set;h.getPartValues(g,E,r,v),v!==null&&h.registerCollectedExcludedKeys(E,v),Object.keys(E).length>0?(p=!0,u.push(E),d.push(g.getListKey())):r!==null&&(u.push({}),d.push(g.getListKey()))}if(r===null){const g=e.getAttribute(`${l.prefix}each-key`);h.registerCollectedRowIdentity(u,g==null?null:String(g),d,h.isCollectedListFromEachSource(e)),t[String(a)]=u}else p&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return h.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return h.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return h.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?h.asPlainRecord(t[i])??{}:h.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorArgOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t)){if(r.getListKey()!==null)return null;const n=h.asPlainRecord(i[t]);return n?{owner:r,value:n}:null}r=r.getParent()}return null}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:h.resolveFormArgKey(t)}:h.resolveConditionValueSource(e);if(!i)return r;const n=h.getValues(i.source),s=h.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of s)r[o]=n[o];return r}const a={...h.asPlainRecord(r[i.argKey])??{}};for(const o of s)a[o]=n[o];return r[i.argKey]=a,r}static resolveConditionValueSource(e){let t=e;for(;t;){const i=t.getParent();if(i&&i.hasAttribute(`${l.prefix}each`)&&i.hasAttribute(`${l.prefix}form-list`)){const n=i.getRawAttribute(`${l.prefix}each-arg`);return{source:t,argKey:typeof n=="string"&&n!==""?n:null}}t=i}const r=h.getFormFragment(e);return r?{source:r,argKey:h.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${l.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return h.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=h.resolveFieldName(e);i&&t.add(String(i));const n=`${l.prefix}form-object`,s=`${l.prefix}form-list`,a=r.getAttribute(n)??r.getAttribute(s);if(a)return t.add(a),t;const o=`input[name],select[name],textarea[name],[${l.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(c=>{if(!(c instanceof HTMLElement))return;let u=null,d=!1,p=c;for(;p&&p!==r;)p.hasAttribute(`${l.prefix}form-detach`)&&(d=!0),(p.hasAttribute(n)||p.hasAttribute(s))&&(u=p),p=p.parentElement;if(d)return;const g=u??c,E=g.getAttribute(n)||g.getAttribute(s)||g.getAttribute(`${l.prefix}form-name`)||g.getAttribute("name");E&&t.add(E)}),t}static applyCustomValidity(e){const t=`${l.prefix}validity`,r=i=>{i.hasAttribute(t)&&h.applyOneCustomValidity(i,t),i.getChildElementFragments().forEach(r)};r(e)}static applyOneCustomValidity(e,t){const r=e.getTarget();if(!(r instanceof HTMLInputElement)&&!(r instanceof HTMLSelectElement)&&!(r instanceof HTMLTextAreaElement)){m.warn("Haori",`${t} は入力要素にのみ指定できます: ${r.tagName}`);return}const i=e.getRawAttribute(t);if(typeof i!="string"||i.trim()===""){r.setCustomValidity("");return}const n=h.buildConditionScope(e),s=Q.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){m.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${l.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:Tt}static unwrapConditionExpression(e){const t=e.trim();return t.startsWith("{{{")&&t.endsWith("}}}")?t.slice(3,-3):t.startsWith("{{")&&t.endsWith("}}")?t.slice(2,-2):t}static warnUnvalidatedCustomValidity(e,t){if(!j.isEnabled()||!e)return;const r=`${l.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&m.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${l.prefix}{event}-validate を指定するか、${l.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){h.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&h.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(e);r&&h.COLLECTED_ROW_IDENTITY.set(t,r);const i=h.COLLECTED_EXCLUDED_KEYS.get(e);i&&h.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!j.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${l.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static mergeCollectedValues(e,t){const r={...e??{}};for(const[n,s]of Object.entries(t))h.UNSAFE_MERGE_KEYS.has(n)||(r[n]=h.overlayCollectedValue(e?.[n],s));const i=h.COLLECTED_EXCLUDED_KEYS.get(t);if(i)for(const n of i)n in t||delete r[n];return r}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const n=h.overlayIdentifiedRows(e,t);return n!==null?n:t.map((s,a)=>h.overlayCollectedValue(e[a],s))}const r=h.asPlainRecord(t),i=h.asPlainRecord(e);return r===null||i===null?t:h.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=h.LEADING_PATH_PATTERN.exec(e);if(!t)return null;const r=t[2].trim();return r!==""&&!r.startsWith("||")&&!r.startsWith("??")?null:t[1].replace(/\s+/g,"")}static isCollectedListFromEachSource(e){const t=e.getAttribute(`${l.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${l.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=h.resolveLeadingPath(r);if(i===null)return!0;const n=i.split(".");return n[n.length-1]===String(t)}static createRowKeyIndexes(e,t){const r=new Map;return e.forEach((i,n)=>{const s=L.createListKey(i,t,n),a=r.get(s);a?a.push(n):r.set(s,[n])}),r}static pairRowsWithItems(e,t,r){const i=e.map(s=>s.getListKey());if(i.some(s=>s===null))return null;const n=h.createRowKeyIndexes(t,r);return i.map(s=>{const a=n.get(s);return!a||a.length===0?null:t[a.shift()]})}static overlayIdentifiedRows(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(s=>h.asPlainRecord(s)!==null)&&h.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return h.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(s=>s===null))return null;const i=h.createRowKeyIndexes(e,r.keyArg),n=[];for(let s=0;s<t.length;s+=1){const a=r.keys[s],o=i.get(a);if(!o||o.length===0)continue;const c=o.shift();n.push(h.overlayCollectedValue(e[c],t[s]))}return n}static syncAncestorArgForms(e,t,r=null){const i=[];for(const{form:n,key:s}of h.collectArgForms(e)){if(n.wasResetAfter(t))continue;const a=h.resolveAncestorArgOwner(n,s);!a||a.owner!==e||i.push(h.pushAncestorArgValue(n,s,a.value,r))}return Promise.all(i).then(()=>{})}static collectArgForms(e){const t=`${l.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=x.get(n);if(!(s instanceof I))return;const a=s.getAttribute(t);a&&i.push({form:s,key:String(a)})}),i}static pushAncestorArgValue(e,t,r,i=null){const n=e.getTarget(),s=h.createArgValueSignature(r);if(s!==null){if(h.LAST_ANCESTOR_ARG_VALUES.get(n)===s)return Promise.resolve();h.LAST_ANCESTOR_ARG_VALUES.set(n,s)}else h.LAST_ANCESTOR_ARG_VALUES.delete(n);const a=e.getRawBindingData();if(a&&Object.prototype.hasOwnProperty.call(a,t)){const o={...a};return delete o[t],L.setBindingData(n,o,{kind:i?.kind??"supply",sequence:i?.sequence??I.nextSequence()})}return h.syncValues(e,r,!1,i)}static createArgValueSignature(e){try{return JSON.stringify(e)??null}catch{return null}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(h.INITIAL_RESTORED_FORMS.has(i))continue;const n=x.get(i);if(!(n instanceof I))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${l.prefix}form-arg`),o=a?String(a):null,c=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!c)){if(h.INITIAL_RESTORED_FORMS.add(i),c){r.push(h.pushAncestorArgValue(n,o,c.value));continue}r.push(h.syncValues(n,h.resolveSyncValues(n,s)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];h.collectGroupMembers(h.resolveCollectionScope(e),String(h.resolveFieldName(e)),i);let n=!1;const s=[];for(const a of i){a.getUserEditSequence()>r&&(n=!0);const o=a.getTarget();o instanceof HTMLInputElement&&o.checked&&s.push(o.value)}return t?{edited:n,value:h.markCompleteSet(s)}:s.length===0?{edited:n,value:null}:{edited:n,value:s.length===1?s[0]:h.markCompleteSet(s)}}static startsCollectionLevel(e){return h.resolveFieldName(e)?!1:!!(e.getAttribute(`${l.prefix}form-object`)||e.getAttribute(`${l.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${l.prefix}form-object`)?r:t;if(h.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${l.prefix}form`)}static collectGroupMembers(e,t,r){h.isGroupedCheckable(e)&&String(h.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())h.startsCollectionLevel(i)||i.hasAttribute(`${l.prefix}form-detach`)||i.getTarget().hasAttribute(`${l.prefix}if-false`)||h.collectGroupMembers(i,t,r)}static markCompleteSet(e){return h.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&h.COMPLETE_SET_VALUES.has(e)}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,i=null){return r?e.setValue(t,i):e.syncBindingValue(t,i)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map,a=null){const o=[];if(e.hasAttribute(`${l.prefix}form-detach`)&&!r)return Promise.resolve();const c=h.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),d=e.getAttribute(`${l.prefix}form-list`),p=e.hasAttribute(`${l.prefix}form-list`);if(c){const g=t[String(c)],E=n&&h.hasResolvedDeclarativeState(e),v=n&&typeof g>"u"&&!h.isDeclarativeStateBound(e);let D=g;if(E?D=void 0:v&&(D=null),h.isFileInput(e))return(D===null||D==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(p&&Array.isArray(D)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const M=String(c),H=s.get(M)??0;s.set(M,H+1),o.push(h.applyFragmentValue(e,D[H]??null,i,a))}else typeof D>"u"||(Array.isArray(D)&&h.isGroupedCheckable(e)||Array.isArray(D)&&h.isMultipleSelect(e)||typeof D=="string"||typeof D=="number"||typeof D=="boolean"||D===null?o.push(h.applyFragmentValue(e,D,i,a)):o.push(h.applyFragmentValue(e,String(D),i,a)))}else if(u){const g=t[String(u)];if(g&&typeof g=="object"){const E=new Map;for(const v of e.getChildElementFragments())o.push(h.setPartValues(v,g,r,i,n,E,a))}}else if(d){const g=t[String(d)];if(Array.isArray(g)){const E=e.getChildElementFragments(),v=e.getAttribute(`${l.prefix}each-key`),D=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(E,g,v==null?null:String(v)):null;for(let M=0;M<E.length;M++){const H=E[M],A=D?D[M]:g.length>M?g[M]:null;o.push(h.setPartValues(H,h.asPlainRecord(A)??{},r,i,n,new Map,a))}}}else for(const g of e.getChildElementFragments())o.push(h.setPartValues(g,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=I.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),L.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await K.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s)),h.clearDeclarativeStateFromDom(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await L.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await L.evaluateAll(e);for(const n of i)h.getInitialBindingData(n)!==null||n.getRawBindingData()!==null||await h.restoreAncestorArgValues(n,{sequence:t,kind:"supply"});for(const n of i){const s=h.getInitialBindingData(n);if(n.getRawBindingData()===null&&s===null)continue;const a=h.getValues(n),o=n.getAttribute(`${l.prefix}form-arg`);let c={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(c[u]=h.mergeCollectedValues(c[u]??null,a))}else c=h.mergeCollectedValues(c,a);await L.setBindingData(n.getTarget(),c,{sequence:t})}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:L.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())h.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=x.get(n);s instanceof I&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},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())h.clearValues(t)}static collectEditsAfter(e,t,r=[]){const i=e.getTarget();(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&e.getUserEditSequence()>t&&(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")?r.push({element:i,checked:i.checked}):i instanceof HTMLSelectElement&&i.multiple?r.push({element:i,selected:Array.from(i.selectedOptions).map(n=>n.value)}):r.push({element:i,value:i.value}));for(const n of e.getChildElementFragments())h.collectEditsAfter(n,t,r);return r}static restoreEdits(e){for(const t of e){const{element:r}=t;if(t.checked!==void 0&&r instanceof HTMLInputElement){r.checked=t.checked;continue}if(t.selected!==void 0&&r instanceof HTMLSelectElement){for(const i of Array.from(r.options))i.selected=t.selected.includes(i.value);continue}t.value!==void 0&&(r.value=t.value)}}static async restoreAncestorArgValues(e,t=null){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return;const i=String(r),n=h.resolveAncestorArgOwner(e,i);n&&(h.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await h.pushAncestorArgValue(e,i,n.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())h.markResetSubtree(r,t)}static clearMessages(e){return Ye().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ye(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),c=h.findFragmentsByKey(e,t);return c.forEach(u=>{n.push(o(u.getTarget()))}),c.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return h.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&h.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...h.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.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 c=i.substring(s+1,a),u=Number(c);if(isNaN(u))m.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));u<d.length&&r.push(...h.findFragmentByKeyParts(d[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...h.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};h.INITIAL_RESTORED_FORMS=new WeakSet,h.LAST_ANCESTOR_ARG_VALUES=new WeakMap,h.GROUP_SCOPE_IDS=new WeakMap,h.groupScopeSequence=0,h.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),h.COLLECTED_ROW_IDENTITY=new WeakMap,h.COMPLETE_SET_VALUES=new WeakSet,h.COLLECTED_EXCLUDED_KEYS=new WeakMap,h.warnedPositionalRowFallbacks=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let F=h;class U{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){U.dispatch(document,"ready",{version:e})}static importStart(e,t){U.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){U.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){U.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 c of o){const u=t?.[c],d=r[c];u!==d&&n.push(c)}U.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){U.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){U.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){U.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){U.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){U.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){U.dispatch(e,"show",{visible:!0})}static hide(e){U.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){U.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){U.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){U.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){U.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){U.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const It={401:"unauthorized-redirect",403:"forbidden-redirect"};function Nt(y,e){return y.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Q.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ft(y,e){const t=y.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=x.get(y),i=r instanceof I?r.getBindingData():{},n=Nt(t,i);return n===""?null:n}function xt(y,e,t){const r=y.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,s=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,a=t.indexOf("#"),o=a>=0?t.slice(a):"",c=a>=0?t.slice(0,a):t,u=c.includes("?")?"&":"?";return`${c}${u}${s}${o}`}function ft(y){const e=It[y];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ft(i,t);if(n===null)continue;const s=xt(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 z{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const N=class N{static resolveStorage(e){try{const t=e==="local"?window.localStorage:window.sessionStorage;if(!t)throw new Error("storage is not available");return t}catch(t){return N.WARNED_KINDS.has(e)||(N.WARNED_KINDS.add(e),m.warn("Haori",`${e}Storage が利用できないため ${l.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return e.startsWith("_")}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=N.WARNED_ELEMENTS.get(e);i||(i=new Set,N.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),m.warn("Haori",r))}static isInsideEachRow(e){let t=e;for(;t;){if(t.getListKey()!==null)return!0;t=t.getParent()}return!1}static readDeclaration(e){const t=e.getTarget(),r=e.getRawAttribute(`${l.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return N.warnOnce(t,"key",`${l.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return N.warnOnce(t,"expression",`${l.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${l.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:N.warnOnce(t,"type",`${l.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${l.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),c=e.getRawAttribute(`${l.prefix}store-params`);let u=null;if(c!==null){const d=c.split("&").map(g=>g.trim()).filter(g=>g!==""),p=d.filter(g=>!N.isReservedKey(g));p.length!==d.length&&N.warnOnce(t,"reserved",`${l.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=p.length>0?p:null}return u===null&&o===null?(N.warnOnce(t,"target",`${l.prefix}store には ${l.prefix}store-params または ${l.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=N.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return m.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return m.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return N.isPlainRecord(i)?i:(m.warn("Haori",`保存済みデータがオブジェクトではありません: ${e.key}`),null)}static extractFromRecord(e,t){let r=t;if(e.arg!==null){const s=t[e.arg];if(s===void 0)return{};if(!N.isPlainRecord(s))return m.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)N.isReservedKey(s)||Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s]);return n}static selectFromData(e,t){const r=e.params??Object.keys(t),i={};for(const n of r){if(N.isReservedKey(n)||!Object.prototype.hasOwnProperty.call(t,n))continue;const s=t[n];s!==void 0&&(i[n]=s)}return i}static stringify(e){try{return JSON.stringify(e)??null}catch{return null}}static createRefs(e){const t=new Map;for(const[r,i]of Object.entries(e))t.set(r,i);return t}static hasSameRefs(e,t){const r=Object.entries(t);if(e.refs.size!==r.length)return!1;for(const[i,n]of r)if(!e.refs.has(i)||e.refs.get(i)!==n)return!1;return!0}static seedSignature(e,t){const r=N.stringify(t);if(r===null){N.SIGNATURES.delete(e);return}N.SIGNATURES.set(e,{json:r,refs:N.createRefs(t)})}static writeRecord(e,t){const r=N.resolveStorage(e.kind);if(!r)return!1;const i=N.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=N.isPlainRecord(n)?{...n}:{};i[e.arg]={...s,...t}}else Object.assign(i,t);try{return r.setItem(e.key,JSON.stringify(i)),!0}catch(n){return m.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=N.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(N.isInsideEachRow(e))return N.warnOnce(r,"each-row",`${l.prefix}each の行の内側では ${l.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();N.RESTORED_ELEMENTS.add(r);const i=N.readRecord(t),n=i?N.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return N.seedSignature(r,N.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():L.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:I.nextSequence()})}static mirror(e){const t=N.readDeclaration(e);if(!t||N.isInsideEachRow(e))return;const r=e.getTarget();if(!N.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=N.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=N.SIGNATURES.get(r);if(s&&N.hasSameRefs(s,n))return;const a=N.stringify(n);if(a===null){m.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=N.createRefs(n);return}N.writeRecord(t,n)&&N.SIGNATURES.set(r,{json:a,refs:N.createRefs(n)})}static clear(e,t){const r=N.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){m.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}N.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${l.prefix}store]`).forEach(i=>{if(!N.RESTORED_ELEMENTS.has(i))return;const n=x.get(i);if(!(n instanceof I))return;const s=N.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();N.seedSignature(i,a?N.selectFromData(s,a):{})})}};N.SIGNATURES=new WeakMap,N.RESTORED_ELEMENTS=new WeakSet,N.WARNED_ELEMENTS=new WeakMap,N.WARNED_KINDS=new Set;let ve=N;class ht{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 Mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ct="__haoriHistoryState__",Pe="data-haori-click-lock";function De(){const e=globalThis.window?.Haori;return Mt.every(r=>typeof e?.[r]=="function")?e:ae}const kt=new Set(["GET","HEAD","OPTIONS"]);function Oe(y){return kt.has(y.toUpperCase())}function $t(y,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{y.append(t,he(i))}):y.append(t,he(r)))}function he(y){if(y==null)return"";if(typeof y=="object"||typeof y=="function")try{return JSON.stringify(y)??""}catch{return""}return String(y)}function pt(y,e){const t=new URL(y,window.location.href),r=new URLSearchParams(t.search);return $t(r,e),t.search=r.toString(),t.toString()}function Pt(y){if(y==null)return{payload:{},dropped:!1};if(typeof y=="string"){const e=y.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:Xe(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(y instanceof URLSearchParams)return{payload:Xe(y),dropped:!1};if(typeof FormData<"u"&&y instanceof FormData){const e={};let t=!1;for(const[r,i]of y.entries()){if(typeof i!="string"){t=!0;continue}gt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Xe(y){const e={};for(const[t,r]of y.entries())gt(e,t,r);return e}function gt(y,e,t){const r=y[e];r===void 0?y[e]=t:Array.isArray(r)?r.push(t):y[e]=[r,t]}function oe(y,e){if(F.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(y)?y.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=oe(t[n],i),r=!0))}),r?t:y}if(e!==null&&typeof e=="object"){const t=y!==null&&typeof y=="object"&&!Array.isArray(y)?{...y}:{};for(const[r,i]of Object.entries(e))t[r]=oe(t[r],i);return t}return e}function Lt(y){const e=y?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Ot(y,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||Oe(r))return{url:y,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Pt(t.body);let s=y;Object.keys(i).length>0&&(s=pt(s,i)),n&&m.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function Bt(y){return y==null?null:typeof y=="string"?y:y instanceof URLSearchParams?y.toString():y instanceof FormData?Array.from(y.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(y)}function Se(y){return y instanceof Blob?!0:Array.isArray(y)?y.some(Se):y!==null&&typeof y=="object"?Object.values(y).some(Se):!1}function Ut(y){return Object.values(y).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Se(t)):Se(e))}function Ie(y){return Be(F.getValues(y))}function Be(y){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r)){const i=r.map(e);return F.carryCollectedRowIdentity(r,i),i}if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return F.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(y))t[r]=e(i);return F.carryCollectedRowIdentity(y,t),t}function Ht(y,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:y,method:String(e.method||"GET").toUpperCase(),headers:r,body:Bt(e.body||null)})}const b=class b{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,this.operationSequence=r!=null?I.nextOperationSequence():I.nextSequence(),b.isElementFragment(e)?(this.options=b.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static readLateAttribute(e,t,r,i){const n=e.getAttributeEvaluation(i);return t.lateAttributes||(t.lateAttributes=new Map),t.lateAttributes.set(r,{attributeName:i,hasUnresolvedReference:n?.hasUnresolvedReference??!1}),n?.value??null}static normalizeMessage(e){return e?String(e):null}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
13
- `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(b.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=Q.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"?b.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(b.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const c=Q.evaluateDetailed(s??a??"",t);return r=r||c.unresolvedReference,b.isJsonStringContext(e,o)?b.stringifyJsonTemplateStringContent(c.value):b.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return b.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(b.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:L.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const c=b.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:L.parseDataBind(c.value),hasUnresolvedReference:s||c.hasUnresolvedReference}}const o=b.resolveDataParamStringDetailed(r,e.getBindingData());return{value:L.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?b.attrName(t,"if"):b.attrName(null,"if",!0);if(e.hasAttribute(i)){const A=e.getRawAttribute(i);typeof A=="string"&&A.trim()!==""?(r.conditionExpression=F.unwrapConditionExpression(A),r.conditionAttributeName=i):m.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(b.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(b.attrName(t,"confirm"))&&(r.confirmMessage=b.unescapeNewlines(b.normalizeMessage(e.getAttribute(b.attrName(t,"confirm"))))),e.hasAttribute(b.attrName(t,"data"))&&(r.dataAttrName=b.attrName(t,"data")),e.hasAttribute(b.attrName(t,"form"))){const S=z.read(e,b.attrName(t,"form"));if(S){const C=z.query(S,b.attrName(t,"form"));C!==null?r.formFragment=F.getFormFragment(x.get(C)):m.error("Haori",`Form element not found: ${S} (${b.attrName(t,"form")})`)}else r.formFragment=F.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=F.getFormFragment(e),r.formFragment===null&&b.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const S=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
12
+ `))}static record(e,t,r){if(!q.isEnabled()||!e||t.length===0||(k.ensureGlobalAccess(),!k.isCollecting()))return;const i=k.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=k.getOrCreateCounter(i.attributes,e.rawName,e.template);k.updateCounter(s,t,r);return}const n=k.getOrCreateCounter(i.texts,String(e.childIndex),e.template);k.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!q.isEnabled())return;const e=globalThis;e[k.GLOBAL_KEY]===void 0&&(e[k.GLOBAL_KEY]={start:()=>k.start(),stop:()=>k.stop(),reset:()=>k.reset(),snapshot:()=>k.snapshot(),report:t=>k.report(t)})}static getOrCreateElementStore(e){const t=k.createElementId(e),r=k.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return k.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=k.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){if(!k.isCollecting())return{value:e(),durationMs:0};const t=k.now();return{value:e(),durationMs:k.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(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.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(" > ")}};k.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",k.ELEMENT_STORES=new Map,k.collecting=!1,k.DEFAULT_REPORT_LIMIT=20;let Fe=k;const ge=class ge{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,ge.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(ge.FRAGMENT_CACHE.has(e))return ge.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new D(e);break;case Node.TEXT_NODE:t=new re(e);break;case Node.COMMENT_NODE:t=new Ve(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return 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),ge.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};ge.FRAGMENT_CACHE=new WeakMap;let M=ge;const w=class w extends M{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.lastSupplySequence=0,this.lastResetSequence=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.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.selfWritingAttributes=new Map,this.skipChangeValue=!1,this.valueWriteUnapplied=!1,this.pendingValueWrite=null,this.userEditSequence=0,this.authoritativeValueSequence=0,this.lastValueSequence=0,this.lastValueKind="nonSupply",this.selfWrittenBind=new Map,this.lastPathApplied=new Map,this.lastChangeSequence=0,w.dropIfVisibilityArtifacts(e),this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Ne(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=M.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof w)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new w(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.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}static dropIfVisibilityArtifacts(e){e.hasAttribute(`${l.prefix}if-false`)&&(e.style.removeProperty("display"),e.getAttribute("style")?.trim()===""&&e.removeAttribute("style"),e.removeAttribute(`${l.prefix}if-false`),w.forEachFormControlInBranch(e,t=>{t.hasAttribute(de)&&(t.removeAttribute(de),t.removeAttribute("disabled"))}))}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof w&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return e&&ne.destroySubtree(this.getTarget()),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,this.clearUnappliedValueWrite(),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}static isExecutingAnyBindingWork(){return w.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,w.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,w.bindingWorkActiveCount--)}markSupplyApplied(e){e>this.lastSupplySequence&&(this.lastSupplySequence=e)}isSupplyStale(e){return this.lastSupplySequence>e}markResetAt(e){this.lastResetSequence=e}wasResetAfter(e){return this.lastResetSequence>e}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 w&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=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,t=null){return this.applyValue(e,!0,t)}syncBindingValue(e,t=null){return this.applyValue(e,!1,t)}applyValue(e,t,r=null){if(this.skipChangeValue)return(this.pendingValueWrite??Promise.resolve()).then(()=>this.applyValue(e,t,r));if(r&&!this.canApplyValue(r)||(r&&this.markValueApplied(r),this.value===e))return Promise.resolve();const i=this.getTarget();if(i instanceof HTMLInputElement&&i.type==="file")return e===null||e===""?(this.value=null,i.value===""?Promise.resolve():K.enqueue(()=>{i.value=""})):(m.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",i),Promise.resolve());if(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")){const n=this.hasAttribute("value")?this.getAttribute("value"):i.value,s=i.type==="checkbox"&&n==="true";let a;if(s?a=e===!0||e==="true":n==="false"?a=e===!1:Array.isArray(e)?a=e.map(String).includes(String(n)):a=n===String(e),s?this.value=a:a?Array.isArray(e)?this.value=String(n):this.value=e:this.value=null,i.checked===a)return Promise.resolve();const o=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(o)||r&&!this.canApplyValue(r)||(i.checked=a,t&&i.dispatchEvent(new Event("change",{bubbles:!0})))})}else if(i instanceof HTMLSelectElement&&i.multiple){const n=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.writeSelectedValues(n,t,r)}else return i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?this.writeScalarValue(Array.isArray(e)?e.join(","):e,t,r):(m.warn("[Haori]","setValue is not supported for this element type.",i),Promise.resolve())}writeScalarValue(e,t,r=null){const i=this.getTarget(),n=e===null?"":String(e);this.value=this.normalizeValueForElement(i,e);const s=this.userEditSequence;return this.enqueueValueWrite(()=>{this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r)||(i.value=n,this.recordValueWriteResult(i.value===n),t&&((i instanceof HTMLInputElement&&w.INPUT_EVENT_TYPES.includes(i.type)||i instanceof HTMLTextAreaElement)&&i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))))})}writeSelectedValues(e,t,r=null){const i=this.getTarget();this.value=e.slice();const n=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(n)||r&&!this.canApplyValue(r))return;let s=!1;const a=new Set;Array.from(i.options).forEach(o=>{const c=e.includes(o.value);o.selected!==c&&(o.selected=c,s=!0),c&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=K.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(w.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(w.UNAPPLIED_VALUE_WRITES)){const n=i.getTarget();if(i.wasResetAfter(t)){i.clearUnappliedValueWrite();continue}if(!n.isConnected){i.clearUnappliedValueWrite();continue}e.contains(n)&&r.push(i.retryValueWrite())}return Promise.all(r).then(()=>{})}retryValueWrite(){const e=this.getTarget();if(this.skipChangeValue||!(e instanceof HTMLSelectElement))return Promise.resolve();if(e.multiple){const r=Array.isArray(this.value)?this.value.slice():[];return r.every(i=>Array.from(e.options).some(n=>n.value===i))?this.writeSelectedValues(r,!1):Promise.resolve()}const t=this.value===null?"":String(this.value);return Array.from(e.options).some(r=>r.value===t)?this.writeScalarValue(this.value,!1):Promise.resolve()}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,w.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return w.sequenceCounter}static nextSequence(){return w.sequenceCounter+=1,w.sequenceCounter}static setPendingMutationFlusher(e){w.pendingMutationFlusher=e}static nextOperationSequence(){return w.pendingMutationFlusher&&!w.isExecutingAnyBindingWork()&&w.pendingMutationFlusher(),w.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:w.isApplicable({sequence:this.lastValueSequence,kind:this.lastValueKind},e)}static isApplicable(e,t){return e===null?!0:t.kind==="nonSupply"&&e.kind==="edit"?!1:t.sequence>e.sequence?!0:t.sequence===e.sequence?e.kind!=="edit"||t.kind==="edit":!1}canApplyPath(e,t){return w.isApplicable(this.lastPathApplied.get(e)??null,t)}markPathApplied(e,t){if(t.kind==="nonSupply")return;const r=this.lastPathApplied.get(e)??null;(r===null||t.sequence>r.sequence||t.sequence===r.sequence&&t.kind==="edit")&&this.lastPathApplied.set(e,{sequence:t.sequence,kind:t.kind})}markValueApplied(e){e.kind!=="nonSupply"&&(e.sequence>this.lastValueSequence||e.sequence===this.lastValueSequence&&e.kind==="edit")&&(this.lastValueSequence=e.sequence,this.lastValueKind=e.kind)}markUserEdit(){return this.userEditSequence=w.nextSequence(),this.markValueApplied({sequence:this.userEditSequence,kind:"edit"}),this.userEditSequence}markUserEditOnChange(){const t=this.userEditSequence>this.lastChangeSequence?this.userEditSequence:this.markUserEdit();return this.lastChangeSequence=t,t}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=w.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!q.isEnabled())return;const n=`${e} ${r}`;w.loggedUnresolvedAttributes.has(n)||(w.loggedUnresolvedAttributes.add(n),m.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}static warnTypeMismatchedComparison(e,t,r,i){const n=`${e} ${t}`;w.loggedTypeMismatchedComparisons.has(n)||(w.loggedTypeMismatchedComparisons.add(n),m.warn("[Haori]",`The strict comparison compares different types (${r.left} vs ${r.right}), so it is always false even though the values match. Align the types (for example with ${l.prefix}value-type) or compare converted values: ${e}="${t}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=M.get(t);return r instanceof w?r.hasPendingUserEdit():!1}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=w.resolveDeclaredValueType(e);return r==="boolean"?w.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?w.normalizeNumberValue(t):t}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!w.NUMBER_INPUT_PATTERN.test(e))return null;const t=Number(e);return Number.isFinite(t)?t:null}static normalizeBooleanValue(e){if(typeof e=="boolean")return e;if(typeof e!="string")return null;const t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:null}static resolveDeclaredValueType(e){const t=e.getAttribute(`${l.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return w.VALUE_TYPE_NAMES.has(r)?w.acceptsDeclaredValueType(e)?r:(w.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(w.warnValueTypeDeclaration(e,t,"boolean / number / string のいずれかを指定してください"),null)}static acceptsDeclaredValueType(e){return e instanceof HTMLInputElement?e.type!=="checkbox"&&e.type!=="radio"&&e.type!=="file":e instanceof HTMLSelectElement?!e.multiple:e instanceof HTMLTextAreaElement}static warnValueTypeDeclaration(e,t,r){if(!q.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",n=`${e.tagName}${i} ${t} ${r}`;w.loggedValueTypeDeclarations.has(n)||(w.loggedValueTypeDeclarations.add(n),m.warn("Haori",`${l.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?w.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}static isUserEditableValue(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?!e.readOnly:!0}syncValue(){this.clearUnappliedValueWrite(),this.value=this.readValueFromDom()}readValueFromDom(){const e=this.getTarget();if(w.resolveDeclaredValueType(e),e instanceof HTMLInputElement){if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true",r=e.value;return e.checked?t?!0:r==="false"?!1:r:t?!1:r==="false"?!0:null}else if(e.type==="file"){const t=e.files;return t&&t.length>0?t[0].name:null}return this.normalizeValueForElement(e,e.value)}else{if(e instanceof HTMLTextAreaElement)return this.normalizeValueForElement(e,e.value);if(e instanceof HTMLSelectElement)return e.multiple?Array.from(e.selectedOptions).map(t=>t.value):this.normalizeValueForElement(e,e.value)}return this.value}recordValueWriteResult(e){if(!e&&this.value!==null&&this.value!==""){this.valueWriteUnapplied=!0,w.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:w.isValuePropertyTarget(this.getTarget())?this.readValueFromDom():this.value}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=M.get(t);r instanceof w&&r.syncValue()}getSelfWritingAttribute(e){for(const t of e){const r=this.selfWritingAttributes.get(t);if(r!==void 0)return r}return null}holdSelfWritingAttributes(e,t){for(const r of e)this.selfWritingAttributes.set(r,t)}releaseSelfWritingAttributes(e){for(const t of e)this.selfWritingAttributes.delete(t)}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,!0,i)}removeAliasedAttribute(e,t){const r=[e,t];if(this.getSelfWritingAttribute(r)!==null)return Promise.resolve();this.attributeMap.delete(e);const i=this.getTarget(),n=i.hasAttribute(e),s=t!==e&&i.hasAttribute(t);if(!n&&!s)return Promise.resolve();const a=K.enqueue(()=>{n&&i.removeAttribute(e),s&&i.removeAttribute(t)}).finally(()=>{this.releaseSelfWritingAttributes(r)});return this.holdSelfWritingAttributes(r,a),a}setAttributeInternal(e,t,r,i,n=!1){const s=[e,t],a=this.getSelfWritingAttribute(s);if(a!==null)return n||r===null?Promise.resolve():a.then(()=>this.setAttributeInternal(e,t,r,i,n));if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const o=new Ne(e,r);if(n){const me=this.attributeMap.get(e);if(me&&(me.isEvaluate||me.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const we=K.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,we),we}}this.attributeMap.set(e,o);const c=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:c,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,p=e===t&&w.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),g=o.isSingleExpression(),E=le.joinEvaluateResults(u.results),A=u.results.length===1?u.results[0]:E,I=t==="value"&&w.resolveDeclaredValueType(c)==="boolean",C=A===!1&&!I,W=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||A===null||A===void 0||C:p?u.hasUnresolvedReference||A===null||A===void 0||A===!1:g?u.hasUnresolvedReference||A===null||A===void 0||C:d&&E==="");if(W&&u.hasUnresolvedReference&&w.warnUnresolvedAttribute(e,t,r,c),q.isEnabled()&&A===!1&&g){const me=o.getSingleExpression(),we=me===null?null:ee.diagnoseStrictComparison(me,this.getBindingData());we!==null&&w.warnTypeMismatchedComparison(e,r,we,c)}const x=o.isForceEvaluation()?r:g?A:E,U=i&&o.isEvaluate&&t==="value"&&w.isValuePropertyTarget(c),z=c.getRootNode(),R=U&&w.isUserEditableValue(c)&&(c===z.activeElement||this.hasPendingUserEdit()),S=W||x===null||x===!1&&!I?null:String(x),H=e!==t&&c.getAttribute(e)!==r,B=S===null?c.hasAttribute(t):c.getAttribute(t)!==S,te=S===null?"":S,ie=U&&!R&&c.value!==te,V=t==="checked"&&c instanceof HTMLInputElement&&(c.type==="checkbox"||c.type==="radio"),G=t==="selected"&&c instanceof HTMLOptionElement,Z=z.activeElement,J=Z!==null&&(V&&c===Z||G&&c.closest("select")===Z)||(V||G)&&this.hasPendingCheckableUserEdit(G),ae=S!==null,Se=V&&!J&&c.checked!==ae,ue=G&&!J&&c.selected!==ae;if(!H&&!B&&!ie&&!Se&&!ue)return U&&!R&&(this.value=this.normalizeValueForElement(c,te),this.clearUnappliedValueWrite()),(V||G)&&!J&&this.syncCheckableValueFromDom(G),Promise.resolve();const We=K.enqueue(()=>{H&&c.setAttribute(e,r),S===null?c.removeAttribute(t):B&&(c.setAttribute(t,S),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(S)),U&&!R&&(this.value=this.normalizeValueForElement(c,te),ie&&(c.value=te),this.recordValueWriteResult(c.value===te)),Se&&(c.checked=ae),ue&&(c.selected=ae),(Se||ue)&&this.syncCheckableValueFromDom(ue)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,We),We}removeAttribute(e){if(this.getSelfWritingAttribute([e])!==null)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();if(!t.hasAttribute(e))return Promise.resolve();const r=K.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.releaseSelfWritingAttributes([e])});return this.holdSelfWritingAttributes([e],r),r}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:le.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=M.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let u=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const g=this.resolveInsertionPointFromDom(t,!1);g===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(g.index,0,e),u=g.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const d=this.skipMutationNodes;return this.skipMutationNodes=!0,K.enqueue(()=>{this.target.insertBefore(e.getTarget(),u)}).finally(()=>{this.skipMutationNodes=d})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),w.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(ze)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(ze)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){w.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(de,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){w.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(de)&&(e.removeAttribute(de),e.removeAttribute("disabled"))})}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(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};w.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,w.VALUE_TYPE_NAMES=new Set(["boolean","number","string"]),w.loggedValueTypeDeclarations=new Set,w.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),w.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],w.UNAPPLIED_VALUE_WRITES=new Set,w.sequenceCounter=0,w.bindingWorkActiveCount=0,w.pendingMutationFlusher=null,w.loggedUnresolvedAttributes=new Set,w.loggedTypeMismatchedComparisons=new Set;let D=w;class re extends M{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new le(this.text)}clone(){const e=new re(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}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new le(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=le.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 M{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,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)}getSingleExpression(){return this.isSingleExpression()?this.contents[0].text:null}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const u=Fe.measure(()=>ee.evaluateDetailed(c.text,e)),d=u.value;a+=u.durationMs,s.push({expression:c.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,n.push(d.value)}else n.push(c.text)}catch(u){m.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,u),s.push({expression:c.text,durationMs:0}),n.push("")}}),Fe.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Ce.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let le=Ce;const _=class _ extends le{constructor(e,t){super(t),this.forceEvaluation=_.needsForceEvaluation(e)}static needsForceEvaluation(e){if(_.forceEvaluationNames===null||_.forceEvaluationPrefix!==l.prefix){const t=new Set;for(const r of[l.prefix,..._.FORCE_EVALUATION_PREFIXES])for(const i of _.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);_.forceEvaluationNames=t,_.forceEvaluationPrefix=l.prefix}return _.forceEvaluationNames.has(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};_.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],_.FORCE_EVALUATION_PREFIXES=["data-","hor-"],_.forceEvaluationNames=null,_.forceEvaluationPrefix=null;let Ne=_;const Ae=class Ae{static get runtime(){return l.runtime}static setRuntime(e){l.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?(Ae.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Ae.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(()=>{Ae.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 $e(e,t,r)}static now(e,t){return et(e,t)}static today(e,t,r){return tt(e,t,r)}static number(e,t){return rt(e,t)}static range(e,t,r){return it(e,t,r)}static pages(e,t,r){return nt(e,t,r)}static monthAdd(e,t){return ke(e,t)}static monthRange(e,t){return st(e,t)}static pageSummary(e,t){return at(e,t)}static findBy(e,t,r){return ot(e,t,r)}static sum(e,t){return lt(e,t)}static distinct(e,t){return ut(e,t)}static groupBy(e,t){return dt(e,t)}};Ae.enhancers={register(e,t){ne.register(e,t)},has(e){return ne.has(e)}};let ce=Ae;const Tt="入力内容を確認してください",Dt=["addErrorMessage","clearMessages"],Ge="data-haori-group-name";function Ye(){const e=globalThis.window?.Haori;return Dt.every(r=>typeof e?.[r]=="function")?e:ce}const h=class h{static getValues(e){const t={},r=new Set;return h.getPartValues(e,t,null,r),h.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(h.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(h.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValueForCollection()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=h.getValues(e),i=new Set;for(const n of new Set([...Object.keys(r),...Object.keys(t)]))h.isSameCollectedValue(r[n],t[n])||i.add(n);i.size!==0&&h.clearUserEditMarksForKeys(e,e,i)}static isSameCollectedValue(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static clearUserEditMarksForKeys(e,t,r){const i=h.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(n=>{h.clearUserEditMarksForKeys(n,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const n=i.getAttribute(`${l.prefix}form-object`)||i.getAttribute(`${l.prefix}form-list`)||h.resolveFieldName(i);n!=null&&String(n)!==""&&(r=String(n)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){m.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Ge))return;const i=h.resolveGroupScope(e),n=`${String(t)}--haori${h.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Ge,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=h.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(h.groupScopeSequence+=1,h.GROUP_SCOPE_IDS.set(e,h.groupScopeSequence),h.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!h.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return h.isDeclarationResolved(e,"checked");if(h.hasDeclarativeBinding(e,"value"))return h.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=M.get(r);if(i instanceof D&&h.hasDeclarativeBinding(i,"selected")&&!h.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${l.prefix}attr-${t}`,t]){const i=e.getAttributeEvaluation(r);if(i!==null)return!i.hasUnresolvedReference}return!1}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?h.hasDeclarativeBinding(e,"checked"):D.isValuePropertyTarget(t)?h.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?h.hasDeclarativeSelectedOption(t):!1:!1}static restoreDefaultValues(e){const t="input, textarea, select",r=[];e.matches(t)&&r.push(e),r.push(...e.querySelectorAll(t));for(const i of r)i instanceof HTMLInputElement?i.type==="checkbox"||i.type==="radio"?i.checked=i.defaultChecked:i.type==="file"?i.value="":i.value=i.defaultValue:i instanceof HTMLTextAreaElement?i.value=i.defaultValue:i instanceof HTMLSelectElement&&h.restoreDefaultSelection(i)}static restoreDefaultSelection(e){const t=Array.from(e.options);for(const r of t)r.selected=r.defaultSelected;if(!e.multiple&&e.selectedIndex<0){const r=t.find(i=>!i.disabled);r&&(r.selected=!0)}}static clearDeclarativeStateFromDom(e){if(h.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof D&&h.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=M.get(t);if(r instanceof D&&h.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return h.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const n=new Map;for(const a of h.collectUserEditSequences(e)){const o=new Set;h.walkEditedPaths(h.getValuesEditedAfter(e,a-1),r,o);for(const c of o)n.has(c)||n.set(c,a)}const s=new Set;h.walkExcludedPaths(i??h.getValues(e),r,s);for(const a of s)n.has(a)||n.set(a,t);return n}static collectUserEditSequences(e){const t=new Set;return h.walkUserEditSequences(e,t),[...t].sort((r,i)=>i-r)}static walkUserEditSequences(e,t){const r=e.getUserEditSequence();r>0&&t.add(r);for(const i of e.getChildElementFragments())h.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i===null)return;const n=h.COLLECTED_EXCLUDED_KEYS.get(i);if(n)for(const s of n)s in i||r.add(t===""?s:`${t}.${s}`);for(const[s,a]of Object.entries(i))h.walkExcludedPaths(a,t===""?s:`${t}.${s}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=h.asPlainRecord(e);if(i!==null){for(const[n,s]of Object.entries(i))h.walkEditedPaths(s,t===""?n:`${t}.${n}`,r);return}t!==""&&r.add(t)}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${l.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${l.prefix}if-false`)){if(i!==null)for(const u of h.collectDeclaredKeysInFragment(e))i.add(u);return t}const n=h.resolveFieldName(e),s=e.getAttribute(`${l.prefix}form-object`),a=e.getAttribute(`${l.prefix}form-list`),o=e.hasAttribute(`${l.prefix}form-list`),c=r!==null&&e.getUserEditSequence()<=r;if(n){if(r!==null&&h.isGroupedCheckable(e)){const u=h.collectGroupSelection(e,o,r);u.edited&&(t[String(n)]=u.value)}else if(o&&h.isGroupedCheckable(e)){const u=String(n),d=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!c&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&c)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!c)if(o){const u=h.resolveCollectedValue(e),d=h.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(n)])?t[String(n)].push(...d):t[String(n)]=d}else if(h.isGroupedCheckable(e)){const u=e.getTarget(),d=u instanceof HTMLInputElement?u.checked:!0,p=u instanceof HTMLInputElement?u.value:e.getValue(),g=d?p:null,E=String(n);g===null?E in t||(t[E]=null):t[E]===null||t[E]===void 0?t[E]=g:Array.isArray(t[E])?t[E].push(g):t[E]=[t[E],g]}else t[String(n)]=h.resolveCollectedValue(e);s&&m.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i)}else if(s){const u={},d=i===null?null:new Set;for(const p of e.getChildElementFragments())h.getPartValues(p,u,r,d);d!==null&&h.registerCollectedExcludedKeys(u,d),Object.keys(u).length>0?t[String(s)]=u:i!==null&&(d?.size??0)>0&&i.add(String(s)),a&&m.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let p=!1;for(const g of e.getChildElementFragments()){const E={},A=i===null?null:new Set;h.getPartValues(g,E,r,A),A!==null&&h.registerCollectedExcludedKeys(E,A),Object.keys(E).length>0?(p=!0,u.push(E),d.push(g.getListKey())):r!==null&&(u.push({}),d.push(g.getListKey()))}if(r===null){const g=e.getAttribute(`${l.prefix}each-key`);h.registerCollectedRowIdentity(u,g==null?null:String(g),d,h.isCollectedListFromEachSource(e)),h.warnDerivedRowsWithoutKey(e),t[String(a)]=u}else p&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())h.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return h.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return h.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return h.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?h.asPlainRecord(t[i])??{}:h.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorArgOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t)){if(r.getListKey()!==null)return null;const n=h.asPlainRecord(i[t]);return n?{owner:r,value:n}:null}r=r.getParent()}return null}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:h.resolveFormArgKey(t)}:h.resolveConditionValueSource(e);if(!i)return r;const n=h.getValues(i.source),s=h.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of s)r[o]=n[o];return r}const a={...h.asPlainRecord(r[i.argKey])??{}};for(const o of s)a[o]=n[o];return r[i.argKey]=a,r}static resolveConditionValueSource(e){let t=e;for(;t;){const i=t.getParent();if(i&&i.hasAttribute(`${l.prefix}each`)&&i.hasAttribute(`${l.prefix}form-list`)){const n=i.getRawAttribute(`${l.prefix}each-arg`);return{source:t,argKey:typeof n=="string"&&n!==""?n:null}}t=i}const r=h.getFormFragment(e);return r?{source:r,argKey:h.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${l.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return h.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=h.resolveFieldName(e);i&&t.add(String(i));const n=`${l.prefix}form-object`,s=`${l.prefix}form-list`,a=r.getAttribute(n)??r.getAttribute(s);if(a)return t.add(a),t;const o=`input[name],select[name],textarea[name],[${l.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(c=>{if(!(c instanceof HTMLElement))return;let u=null,d=!1,p=c;for(;p&&p!==r;)p.hasAttribute(`${l.prefix}form-detach`)&&(d=!0),(p.hasAttribute(n)||p.hasAttribute(s))&&(u=p),p=p.parentElement;if(d)return;const g=u??c,E=g.getAttribute(n)||g.getAttribute(s)||g.getAttribute(`${l.prefix}form-name`)||g.getAttribute("name");E&&t.add(E)}),t}static applyCustomValidity(e){const t=`${l.prefix}validity`,r=i=>{i.hasAttribute(t)&&h.applyOneCustomValidity(i,t),i.getChildElementFragments().forEach(r)};r(e)}static applyOneCustomValidity(e,t){const r=e.getTarget();if(!(r instanceof HTMLInputElement)&&!(r instanceof HTMLSelectElement)&&!(r instanceof HTMLTextAreaElement)){m.warn("Haori",`${t} は入力要素にのみ指定できます: ${r.tagName}`);return}const i=e.getRawAttribute(t);if(typeof i!="string"||i.trim()===""){r.setCustomValidity("");return}const n=h.buildConditionScope(e),s=ee.evaluateDetailed(h.unwrapConditionExpression(i),n);if(s.unresolvedReference){m.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(h.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":h.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${l.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:Tt}static unwrapConditionExpression(e){const t=e.trim();return t.startsWith("{{{")&&t.endsWith("}}}")?t.slice(3,-3):t.startsWith("{{")&&t.endsWith("}}")?t.slice(2,-2):t}static warnUnvalidatedCustomValidity(e,t){if(!q.isEnabled()||!e)return;const r=`${l.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&m.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${l.prefix}{event}-validate を指定するか、${l.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){h.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&h.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(e);r&&h.COLLECTED_ROW_IDENTITY.set(t,r);const i=h.COLLECTED_EXCLUDED_KEYS.get(e);i&&h.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!q.isEnabled()||h.warnedPositionalRowFallbacks.has(e)||(h.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${l.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!q.isEnabled()||e.getRawAttribute(`${l.prefix}each-key`)!==null)return;const t=e.getRawAttribute(`${l.prefix}each`);t===null||h.resolveLeadingPath(t)!==null||h.warnedDerivedRowsWithoutKey.has(t)||(h.warnedDerivedRowsWithoutKey.add(t),m.warn("[Haori]",`${l.prefix}each="${t}" の一覧を ${l.prefix}form-list で収集していますが、${l.prefix}each-key がありません。行と配列要素を出現順で対応付けるため、画面に出ていない要素があると行の値を取り違えます。${l.prefix}each-key を宣言してください。`))}static mergeCollectedValues(e,t){const r={...e??{}};for(const[n,s]of Object.entries(t))h.UNSAFE_MERGE_KEYS.has(n)||(r[n]=h.overlayCollectedValue(e?.[n],s));const i=h.COLLECTED_EXCLUDED_KEYS.get(t);if(i)for(const n of i)n in t||delete r[n];return r}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const n=h.overlayIdentifiedRows(e,t);return n!==null?n:t.map((s,a)=>h.overlayCollectedValue(e[a],s))}const r=h.asPlainRecord(t),i=h.asPlainRecord(e);return r===null||i===null?t:h.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=h.LEADING_PATH_PATTERN.exec(e);if(!t)return null;const r=t[2].trim();return r!==""&&!r.startsWith("||")&&!r.startsWith("??")?null:t[1].replace(/\s+/g,"")}static isCollectedListFromEachSource(e){const t=e.getAttribute(`${l.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${l.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=h.resolveLeadingPath(r);if(i===null)return!0;const n=i.split(".");return n[n.length-1]===String(t)}static createRowKeyIndexes(e,t){const r=new Map;return e.forEach((i,n)=>{const s=P.createListKey(i,t,n),a=r.get(s);a?a.push(n):r.set(s,[n])}),r}static pairRowsWithItems(e,t,r){const i=e.map(s=>s.getListKey());if(i.some(s=>s===null))return null;const n=h.createRowKeyIndexes(t,r);return i.map(s=>{const a=n.get(s);return!a||a.length===0?null:t[a.shift()]})}static overlayIdentifiedRows(e,t){const r=h.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(s=>h.asPlainRecord(s)!==null)&&h.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return h.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(s=>s===null))return null;const i=h.createRowKeyIndexes(e,r.keyArg),n=e.slice();for(let s=0;s<t.length;s+=1){const a=r.keys[s],o=i.get(a);if(!o||o.length===0)continue;const c=o.shift();n[c]=h.overlayCollectedValue(e[c],t[s])}return n}static syncAncestorArgForms(e,t,r=null){const i=[];for(const{form:n,key:s}of h.collectArgForms(e)){if(n.wasResetAfter(t))continue;const a=h.resolveAncestorArgOwner(n,s);!a||a.owner!==e||i.push(h.pushAncestorArgValue(n,s,a.value,r))}return Promise.all(i).then(()=>{})}static collectArgForms(e){const t=`${l.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=M.get(n);if(!(s instanceof D))return;const a=s.getAttribute(t);a&&i.push({form:s,key:String(a)})}),i}static pushAncestorArgValue(e,t,r,i=null){const n=e.getTarget(),s=h.createArgValueSignature(r);if(s!==null){if(h.LAST_ANCESTOR_ARG_VALUES.get(n)===s)return Promise.resolve();h.LAST_ANCESTOR_ARG_VALUES.set(n,s)}else h.LAST_ANCESTOR_ARG_VALUES.delete(n);const a=e.getRawBindingData();if(a&&Object.prototype.hasOwnProperty.call(a,t)){const o={...a};return delete o[t],P.setBindingData(n,o,{kind:i?.kind??"supply",sequence:i?.sequence??D.nextSequence()})}return h.syncValues(e,r,!1,i)}static createArgValueSignature(e){try{return JSON.stringify(e)??null}catch{return null}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(h.INITIAL_RESTORED_FORMS.has(i))continue;const n=M.get(i);if(!(n instanceof D))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${l.prefix}form-arg`),o=a?String(a):null,c=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?h.resolveAncestorArgOwner(n,o):null;if(!(!s&&!c)){if(h.INITIAL_RESTORED_FORMS.add(i),c){r.push(h.pushAncestorArgValue(n,o,c.value));continue}r.push(h.syncValues(n,h.resolveSyncValues(n,s)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];h.collectGroupMembers(h.resolveCollectionScope(e),String(h.resolveFieldName(e)),i);let n=!1;const s=[];for(const a of i){a.getUserEditSequence()>r&&(n=!0);const o=a.getTarget();o instanceof HTMLInputElement&&o.checked&&s.push(o.value)}return t?{edited:n,value:h.markCompleteSet(s)}:s.length===0?{edited:n,value:null}:{edited:n,value:s.length===1?s[0]:h.markCompleteSet(s)}}static startsCollectionLevel(e){return h.resolveFieldName(e)?!1:!!(e.getAttribute(`${l.prefix}form-object`)||e.getAttribute(`${l.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(h.startsCollectionLevel(r))return r.getAttribute(`${l.prefix}form-object`)?r:t;if(h.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${l.prefix}form`)}static collectGroupMembers(e,t,r){h.isGroupedCheckable(e)&&String(h.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())h.startsCollectionLevel(i)||i.hasAttribute(`${l.prefix}form-detach`)||i.getTarget().hasAttribute(`${l.prefix}if-false`)||h.collectGroupMembers(i,t,r)}static markCompleteSet(e){return h.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&h.COMPLETE_SET_VALUES.has(e)}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,i=null){return r?e.setValue(t,i):e.syncBindingValue(t,i)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map,a=null){const o=[];if(e.hasAttribute(`${l.prefix}form-detach`)&&!r)return Promise.resolve();const c=h.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),d=e.getAttribute(`${l.prefix}form-list`),p=e.hasAttribute(`${l.prefix}form-list`);if(c){const g=t[String(c)],E=n&&h.hasResolvedDeclarativeState(e),A=n&&typeof g>"u"&&!h.isDeclarativeStateBound(e);let I=g;if(E?I=void 0:A&&(I=null),h.isFileInput(e))return(I===null||I==="")&&o.push(h.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(p&&Array.isArray(I)&&!h.isGroupedCheckable(e)&&!h.isMultipleSelect(e)){const C=String(c),W=s.get(C)??0;s.set(C,W+1),o.push(h.applyFragmentValue(e,I[W]??null,i,a))}else typeof I>"u"||(Array.isArray(I)&&h.isGroupedCheckable(e)||Array.isArray(I)&&h.isMultipleSelect(e)||typeof I=="string"||typeof I=="number"||typeof I=="boolean"||I===null?o.push(h.applyFragmentValue(e,I,i,a)):o.push(h.applyFragmentValue(e,String(I),i,a)))}else if(u){const g=t[String(u)];if(g&&typeof g=="object"){const E=new Map;for(const A of e.getChildElementFragments())o.push(h.setPartValues(A,g,r,i,n,E,a))}}else if(d){const g=t[String(d)];if(Array.isArray(g)){const E=e.getChildElementFragments(),A=e.getAttribute(`${l.prefix}each-key`),I=h.isCollectedListFromEachSource(e)?h.pairRowsWithItems(E,g,A==null?null:String(A)):null;for(let C=0;C<E.length;C++){const W=E[C],x=I?I[C]:g.length>C?g[C]:null;o.push(h.setPartValues(W,h.asPlainRecord(x)??{},r,i,n,new Map,a))}}}else for(const g of e.getChildElementFragments())o.push(h.setPartValues(g,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=D.nextSequence()){const r=h.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;h.markResetSubtree(e,t),P.clearUserEditMarks(e,t),h.clearValues(e),await Promise.all([h.clearMessages(e),h.clearEachClones(e)]),await K.enqueue(()=>{const n=h.collectEditsAfter(e,t),s=e.getTarget();s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),h.restoreDefaultValues(s)),h.clearDeclarativeStateFromDom(e),h.restoreEdits(n)});const i=r;for(const n of i){const s=h.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await P.setBindingData(n.getTarget(),s??{},{sequence:t})}h.syncValuesFromDom(e),await P.evaluateAll(e);for(const n of i)h.getInitialBindingData(n)!==null||n.getRawBindingData()!==null||await h.restoreAncestorArgValues(n,{sequence:t,kind:"supply"});for(const n of i){const s=h.getInitialBindingData(n);if(n.getRawBindingData()===null&&s===null)continue;const a=h.getValues(n),o=n.getAttribute(`${l.prefix}form-arg`);let c={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&h.resolveAncestorArgOwner(n,u)!==null||(c[u]=h.mergeCollectedValues(c[u]??null,a))}else c=h.mergeCollectedValues(c,a);await P.setBindingData(n.getTarget(),c,{sequence:t})}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:P.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())h.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=M.get(n);s instanceof D&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},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())h.clearValues(t)}static collectEditsAfter(e,t,r=[]){const i=e.getTarget();(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement)&&e.getUserEditSequence()>t&&(i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio")?r.push({element:i,checked:i.checked}):i instanceof HTMLSelectElement&&i.multiple?r.push({element:i,selected:Array.from(i.selectedOptions).map(n=>n.value)}):r.push({element:i,value:i.value}));for(const n of e.getChildElementFragments())h.collectEditsAfter(n,t,r);return r}static restoreEdits(e){for(const t of e){const{element:r}=t;if(t.checked!==void 0&&r instanceof HTMLInputElement){r.checked=t.checked;continue}if(t.selected!==void 0&&r instanceof HTMLSelectElement){for(const i of Array.from(r.options))i.selected=t.selected.includes(i.value);continue}t.value!==void 0&&(r.value=t.value)}}static async restoreAncestorArgValues(e,t=null){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return;const i=String(r),n=h.resolveAncestorArgOwner(e,i);n&&(h.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await h.pushAncestorArgValue(e,i,n.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())h.markResetSubtree(r,t)}static clearMessages(e){return Ye().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return h.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ye(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),c=h.findFragmentsByKey(e,t);return c.forEach(u=>{n.push(o(u.getTarget()))}),c.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return h.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&h.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...h.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.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 c=i.substring(s+1,a),u=Number(c);if(isNaN(u))m.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));u<d.length&&r.push(...h.findFragmentByKeyParts(d[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...h.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};h.INITIAL_RESTORED_FORMS=new WeakSet,h.LAST_ANCESTOR_ARG_VALUES=new WeakMap,h.GROUP_SCOPE_IDS=new WeakMap,h.groupScopeSequence=0,h.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),h.COLLECTED_ROW_IDENTITY=new WeakMap,h.COMPLETE_SET_VALUES=new WeakSet,h.COLLECTED_EXCLUDED_KEYS=new WeakMap,h.warnedPositionalRowFallbacks=new Set,h.warnedDerivedRowsWithoutKey=new Set,h.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let N=h;class O{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){O.dispatch(document,"ready",{version:e})}static importStart(e,t){O.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){O.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){O.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 c of o){const u=t?.[c],d=r[c];u!==d&&n.push(c)}O.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){O.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){O.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){O.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){O.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){O.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){O.dispatch(e,"show",{visible:!0})}static hide(e){O.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){O.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){O.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){O.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){O.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){O.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const It={401:"unauthorized-redirect",403:"forbidden-redirect"};function xt(y,e){return y.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=ee.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ft(y,e){const t=y.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=M.get(y),i=r instanceof D?r.getBindingData():{},n=xt(t,i);return n===""?null:n}function Nt(y,e,t){const r=y.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,s=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,a=t.indexOf("#"),o=a>=0?t.slice(a):"",c=a>=0?t.slice(0,a):t,u=c.includes("?")?"&":"?";return`${c}${u}${s}${o}`}function ft(y){const e=It[y];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ft(i,t);if(n===null)continue;const s=Nt(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 X{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const F=class F{static resolveStorage(e){try{const t=e==="local"?window.localStorage:window.sessionStorage;if(!t)throw new Error("storage is not available");return t}catch(t){return F.WARNED_KINDS.has(e)||(F.WARNED_KINDS.add(e),m.warn("Haori",`${e}Storage が利用できないため ${l.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return e.startsWith("_")}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=F.WARNED_ELEMENTS.get(e);i||(i=new Set,F.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),m.warn("Haori",r))}static isInsideEachRow(e){let t=e;for(;t;){if(t.getListKey()!==null)return!0;t=t.getParent()}return!1}static readDeclaration(e){const t=e.getTarget(),r=e.getRawAttribute(`${l.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return F.warnOnce(t,"key",`${l.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return F.warnOnce(t,"expression",`${l.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${l.prefix}store-type`);let s="session";if(n!==null){const d=n.trim();d==="local"||d==="session"?s=d:F.warnOnce(t,"type",`${l.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${l.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),c=e.getRawAttribute(`${l.prefix}store-params`);let u=null;if(c!==null){const d=c.split("&").map(g=>g.trim()).filter(g=>g!==""),p=d.filter(g=>!F.isReservedKey(g));p.length!==d.length&&F.warnOnce(t,"reserved",`${l.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=p.length>0?p:null}return u===null&&o===null?(F.warnOnce(t,"target",`${l.prefix}store には ${l.prefix}store-params または ${l.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=F.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return m.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return m.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return F.isPlainRecord(i)?i:(m.warn("Haori",`保存済みデータがオブジェクトではありません: ${e.key}`),null)}static extractFromRecord(e,t){let r=t;if(e.arg!==null){const s=t[e.arg];if(s===void 0)return{};if(!F.isPlainRecord(s))return m.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)F.isReservedKey(s)||Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s]);return n}static selectFromData(e,t){const r=e.params??Object.keys(t),i={};for(const n of r){if(F.isReservedKey(n)||!Object.prototype.hasOwnProperty.call(t,n))continue;const s=t[n];s!==void 0&&(i[n]=s)}return i}static stringify(e){try{return JSON.stringify(e)??null}catch{return null}}static createRefs(e){const t=new Map;for(const[r,i]of Object.entries(e))t.set(r,i);return t}static hasSameRefs(e,t){const r=Object.entries(t);if(e.refs.size!==r.length)return!1;for(const[i,n]of r)if(!e.refs.has(i)||e.refs.get(i)!==n)return!1;return!0}static seedSignature(e,t){const r=F.stringify(t);if(r===null){F.SIGNATURES.delete(e);return}F.SIGNATURES.set(e,{json:r,refs:F.createRefs(t)})}static writeRecord(e,t){const r=F.resolveStorage(e.kind);if(!r)return!1;const i=F.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=F.isPlainRecord(n)?{...n}:{};i[e.arg]={...s,...t}}else Object.assign(i,t);try{return r.setItem(e.key,JSON.stringify(i)),!0}catch(n){return m.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=F.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(F.isInsideEachRow(e))return F.warnOnce(r,"each-row",`${l.prefix}each の行の内側では ${l.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();F.RESTORED_ELEMENTS.add(r);const i=F.readRecord(t),n=i?F.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return F.seedSignature(r,F.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():P.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:D.nextSequence()})}static mirror(e){const t=F.readDeclaration(e);if(!t||F.isInsideEachRow(e))return;const r=e.getTarget();if(!F.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=F.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=F.SIGNATURES.get(r);if(s&&F.hasSameRefs(s,n))return;const a=F.stringify(n);if(a===null){m.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=F.createRefs(n);return}F.writeRecord(t,n)&&F.SIGNATURES.set(r,{json:a,refs:F.createRefs(n)})}static clear(e,t){const r=F.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){m.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}F.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${l.prefix}store]`).forEach(i=>{if(!F.RESTORED_ELEMENTS.has(i))return;const n=M.get(i);if(!(n instanceof D))return;const s=F.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();F.seedSignature(i,a?F.selectFromData(s,a):{})})}};F.SIGNATURES=new WeakMap,F.RESTORED_ELEMENTS=new WeakSet,F.WARNED_ELEMENTS=new WeakMap,F.WARNED_KINDS=new Set;let Re=F;class ht{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 Mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ct="__haoriHistoryState__",Pe="data-haori-click-lock";function Ie(){const e=globalThis.window?.Haori;return Mt.every(r=>typeof e?.[r]=="function")?e:ce}const $t=new Set(["GET","HEAD","OPTIONS"]);function Oe(y){return $t.has(y.toUpperCase())}function kt(y,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{y.append(t,ye(i))}):y.append(t,ye(r)))}function ye(y){if(y==null)return"";if(typeof y=="object"||typeof y=="function")try{return JSON.stringify(y)??""}catch{return""}return String(y)}function pt(y,e){const t=new URL(y,window.location.href),r=new URLSearchParams(t.search);return kt(r,e),t.search=r.toString(),t.toString()}function Pt(y){if(y==null)return{payload:{},dropped:!1};if(typeof y=="string"){const e=y.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:Xe(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(y instanceof URLSearchParams)return{payload:Xe(y),dropped:!1};if(typeof FormData<"u"&&y instanceof FormData){const e={};let t=!1;for(const[r,i]of y.entries()){if(typeof i!="string"){t=!0;continue}gt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Xe(y){const e={};for(const[t,r]of y.entries())gt(e,t,r);return e}function gt(y,e,t){const r=y[e];r===void 0?y[e]=t:Array.isArray(r)?r.push(t):y[e]=[r,t]}function fe(y,e){if(N.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(y)?y.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=fe(t[n],i),r=!0))}),r?t:y}if(e!==null&&typeof e=="object"){const t=y!==null&&typeof y=="object"&&!Array.isArray(y)?{...y}:{};for(const[r,i]of Object.entries(e))t[r]=fe(t[r],i);return t}return e}function Lt(y){const e=y?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Ot(y,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||Oe(r))return{url:y,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Pt(t.body);let s=y;Object.keys(i).length>0&&(s=pt(s,i)),n&&m.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function Bt(y){return y==null?null:typeof y=="string"?y:y instanceof URLSearchParams?y.toString():y instanceof FormData?Array.from(y.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(y)}function Te(y){return y instanceof Blob?!0:Array.isArray(y)?y.some(Te):y!==null&&typeof y=="object"?Object.values(y).some(Te):!1}function Ut(y){return Object.values(y).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Te(t)):Te(e))}function xe(y){return Be(N.getValues(y))}function Be(y){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r)){const i=r.map(e);return N.carryCollectedRowIdentity(r,i),i}if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return N.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(y))t[r]=e(i);return N.carryCollectedRowIdentity(y,t),t}function Ht(y,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:y,method:String(e.method||"GET").toUpperCase(),headers:r,body:Bt(e.body||null)})}const b=class b{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,this.operationSequence=r!=null?D.nextOperationSequence():D.nextSequence(),b.isElementFragment(e)?(this.options=b.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static readLateAttribute(e,t,r,i){const n=e.getAttributeEvaluation(i);return t.lateAttributes||(t.lateAttributes=new Map),t.lateAttributes.set(r,{attributeName:i,hasUnresolvedReference:n?.hasUnresolvedReference??!1}),n?.value??null}static normalizeAttributeText(e){return e?String(e):null}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
13
+ `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(b.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=ee.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"?b.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(b.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const c=ee.evaluateDetailed(s??a??"",t);return r=r||c.unresolvedReference,b.isJsonStringContext(e,o)?b.stringifyJsonTemplateStringContent(c.value):b.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return b.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(b.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const c=b.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:s||c.hasUnresolvedReference}}const o=b.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?b.attrName(t,"if"):b.attrName(null,"if",!0);if(e.hasAttribute(i)){const R=e.getRawAttribute(i);typeof R=="string"&&R.trim()!==""?(r.conditionExpression=N.unwrapConditionExpression(R),r.conditionAttributeName=i):m.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(b.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(b.attrName(t,"confirm"))&&(r.confirmMessage=b.unescapeNewlines(b.normalizeAttributeText(e.getAttribute(b.attrName(t,"confirm"))))),e.hasAttribute(b.attrName(t,"data"))&&(r.dataAttrName=b.attrName(t,"data")),e.hasAttribute(b.attrName(t,"form"))){const S=X.read(e,b.attrName(t,"form"));if(S){const H=X.query(S,b.attrName(t,"form"));H!==null?r.formFragment=N.getFormFragment(M.get(H)):m.error("Haori",`Form element not found: ${S} (${b.attrName(t,"form")})`)}else r.formFragment=N.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=N.getFormFragment(e),r.formFragment===null&&b.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const S=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
14
14
  "use strict";
15
15
  ${S}
16
- `)}catch(C){m.error("Haori",`Invalid before script: ${C}`)}}const A=b.attrName(t,"run");if(e.hasAttribute(A)){const S=String(e.getAttribute(A)??"");let C=null;try{C=new Function("event",`"use strict"; return (
16
+ `)}catch(H){m.error("Haori",`Invalid before script: ${H}`)}}const R=b.attrName(t,"run");if(e.hasAttribute(R)){const S=String(e.getAttribute(R)??"");let H=null;try{H=new Function("event",`"use strict"; return (
17
17
  ${S}
18
- );`)}catch{try{C=new Function("event",`"use strict";
18
+ );`)}catch{try{H=new Function("event",`"use strict";
19
19
  ${S}
20
- `)}catch(V){m.error("Haori",`Invalid run script: ${V}`)}}C&&(r.runScript=C)}}const n=b.attrName(t,"fetch"),s=e.hasAttribute(n);if(s){const A=e.getAttributeEvaluation(n);A&&(r.fetchHasUnresolvedReference=A.hasUnresolvedReference,r.fetchUrl=A.hasUnresolvedReference?null:A.value)}const a={};if(t){const A=b.attrName(t,"fetch-method");if(e.hasAttribute(A)){const S=e.getAttributeEvaluation(A);S?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=S?.value}}else{const A=b.attrName(null,"method",!0);if(e.hasAttribute(A)){const S=e.getAttributeEvaluation(A);S?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=S?.value}}if(t){const A=b.attrName(t,"fetch-headers");if(e.hasAttribute(A)){const S=e.getRawAttribute(A);try{a.headers=L.parseDataBind(S)}catch(C){m.error("Haori",`Invalid fetch headers: ${C}`)}}}else{const A=b.attrName(null,"headers",!0);if(e.hasAttribute(A)){const S=e.getRawAttribute(A);try{a.headers=L.parseDataBind(S)}catch(C){m.error("Haori",`Invalid fetch headers: ${C}`)}}}if(t){const A=b.attrName(t,"fetch-content-type");if(e.hasAttribute(A)){const S=e.getAttributeEvaluation(A);S?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),a.headers={...a.headers,"Content-Type":S?.value}}else if(a.method&&a.method!=="GET"&&a.method!=="HEAD"&&a.method!=="OPTIONS"){let S=!1;a.headers&&typeof a.headers=="object"&&(S="Content-Type"in a.headers),S||(a.headers={...a.headers,"Content-Type":"application/json"})}else a.method&&(a.method==="GET"||a.method==="HEAD"||a.method==="OPTIONS")&&(a.headers={...a.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const A=b.attrName(null,"content-type",!0);if(e.hasAttribute(A)){const S=e.getAttributeEvaluation(A);S?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),a.headers={...a.headers,"Content-Type":S?.value}}else if(a.method&&a.method!=="GET"&&a.method!=="HEAD"&&a.method!=="OPTIONS"){let S=!1;a.headers&&typeof a.headers=="object"&&(S="Content-Type"in a.headers),S||(a.headers={...a.headers,"Content-Type":"application/json"})}else a.method&&(a.method==="GET"||a.method==="HEAD"||a.method==="OPTIONS")&&(a.headers={...a.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(a).length>0&&(r.fetchOptions=a);const o=t?b.attrName(t,"bind"):b.attrName(null,"bind",!0);if(e.hasAttribute(o)){const A=z.read(e,o);if(A){const S=z.queryAll(A,o);S.length>0?(r.bindFragments=[],S.forEach(C=>{const V=x.get(C);V&&r.bindFragments.push(V)})):m.error("Haori",`Bind element not found: ${A} (${o})`)}}const c=b.attrName(t,"bind-arg"),u=b.attrName(null,"arg",!0),d=b.attrName(null,"bind-arg",!0);t?e.hasAttribute(c)&&(r.bindArg=e.getRawAttribute(c)):e.hasAttribute(u)?r.bindArg=e.getRawAttribute(u):e.hasAttribute(d)&&(r.bindArg=e.getRawAttribute(d));const p=t?b.attrName(t,"bind-params"):b.attrName(null,"bind-params",!0);if(e.hasAttribute(p)){const A=e.getRawAttribute(p);r.bindParams=A.split("&").map(S=>S.trim())}const g=t?b.attrName(t,"bind-append"):b.attrName(null,"bind-append",!0);if(e.hasAttribute(g)){const A=e.getRawAttribute(g);r.bindAppendParams=A.split("&").map(S=>S.trim()).filter(Boolean)}const E=t?b.attrName(t,"bind-merge"):b.attrName(null,"bind-merge",!0);e.hasAttribute(E)&&(r.bindMerge=!0);const v=t?b.attrName(t,"bind-transform"):b.attrName(null,"bind-transform",!0);e.hasAttribute(v)&&(r.bindTransform=e.getRawAttribute(v));const D=t?b.attrName(t,"copy-params"):null;if(D&&e.hasAttribute(D)){const A=e.getRawAttribute(D);r.copyParams=A.split("&").map(S=>S.trim()).filter(Boolean)}if(t){if(e.hasAttribute(b.attrName(t,"adjust"))){const k=z.read(e,b.attrName(t,"adjust"));if(k){const q=z.queryAll(k,b.attrName(t,"adjust"));q.length>0?(r.adjustFragments=[],q.forEach(X=>{const Y=x.get(X);Y&&r.adjustFragments.push(Y)})):m.error("Haori",`Adjust element not found: ${k} (${b.attrName(t,"adjust")})`)}if(e.hasAttribute(b.attrName(t,"adjust-value"))){const q=e.getRawAttribute(b.attrName(t,"adjust-value")),X=Number(q);isNaN(X)||(r.adjustValue=X)}}if(e.hasAttribute(b.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(b.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(b.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(b.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const k=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
20
+ `)}catch(B){m.error("Haori",`Invalid run script: ${B}`)}}H&&(r.runScript=H)}}const n=b.attrName(t,"fetch"),s=e.hasAttribute(n);if(s){const R=e.getAttributeEvaluation(n);R&&(r.fetchHasUnresolvedReference=R.hasUnresolvedReference,r.fetchUrl=R.hasUnresolvedReference?null:R.value)}const a={},o=t?b.attrName(t,"fetch-method"):b.attrName(null,"method",!0);if(e.hasAttribute(o)){const R=e.getAttributeEvaluation(o);R?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=b.normalizeAttributeText(R?.value)??void 0}if(t){const R=b.attrName(t,"fetch-headers");if(e.hasAttribute(R)){const S=e.getRawAttribute(R);try{a.headers=P.parseDataBind(S)}catch(H){m.error("Haori",`Invalid fetch headers: ${H}`)}}}else{const R=b.attrName(null,"headers",!0);if(e.hasAttribute(R)){const S=e.getRawAttribute(R);try{a.headers=P.parseDataBind(S)}catch(H){m.error("Haori",`Invalid fetch headers: ${H}`)}}}const c=t?b.attrName(t,"fetch-content-type"):b.attrName(null,"content-type",!0);let u=null;if(e.hasAttribute(c)){const R=e.getAttributeEvaluation(c);R?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),u=b.normalizeAttributeText(R?.value)}if(u!==null)a.headers={...a.headers,"Content-Type":u};else if(a.method){const R=a.method.toUpperCase();if(R==="GET"||R==="HEAD"||R==="OPTIONS")a.headers={...a.headers,"Content-Type":"application/x-www-form-urlencoded"};else{let S=!1;a.headers&&typeof a.headers=="object"&&(S="Content-Type"in a.headers),S||(a.headers={...a.headers,"Content-Type":"application/json"})}}Object.keys(a).length>0&&(r.fetchOptions=a);const d=t?b.attrName(t,"bind"):b.attrName(null,"bind",!0);if(e.hasAttribute(d)){const R=X.read(e,d);if(R){const S=X.queryAll(R,d);S.length>0?(r.bindFragments=[],S.forEach(H=>{const B=M.get(H);B&&r.bindFragments.push(B)})):m.error("Haori",`Bind element not found: ${R} (${d})`)}}const p=b.attrName(t,"bind-arg"),g=b.attrName(null,"arg",!0),E=b.attrName(null,"bind-arg",!0);t?e.hasAttribute(p)&&(r.bindArg=e.getRawAttribute(p)):e.hasAttribute(g)?r.bindArg=e.getRawAttribute(g):e.hasAttribute(E)&&(r.bindArg=e.getRawAttribute(E));const A=t?b.attrName(t,"bind-params"):b.attrName(null,"bind-params",!0);if(e.hasAttribute(A)){const R=e.getRawAttribute(A);r.bindParams=R.split("&").map(S=>S.trim())}const I=t?b.attrName(t,"bind-append"):b.attrName(null,"bind-append",!0);if(e.hasAttribute(I)){const R=e.getRawAttribute(I);r.bindAppendParams=R.split("&").map(S=>S.trim()).filter(Boolean)}const C=t?b.attrName(t,"bind-merge"):b.attrName(null,"bind-merge",!0);e.hasAttribute(C)&&(r.bindMerge=!0);const W=t?b.attrName(t,"bind-transform"):b.attrName(null,"bind-transform",!0);e.hasAttribute(W)&&(r.bindTransform=e.getRawAttribute(W));const x=t?b.attrName(t,"copy-params"):null;if(x&&e.hasAttribute(x)){const R=e.getRawAttribute(x);r.copyParams=R.split("&").map(S=>S.trim()).filter(Boolean)}if(t){if(e.hasAttribute(b.attrName(t,"adjust"))){const V=X.read(e,b.attrName(t,"adjust"));if(V){const G=X.queryAll(V,b.attrName(t,"adjust"));G.length>0?(r.adjustFragments=[],G.forEach(Z=>{const J=M.get(Z);J&&r.adjustFragments.push(J)})):m.error("Haori",`Adjust element not found: ${V} (${b.attrName(t,"adjust")})`)}if(e.hasAttribute(b.attrName(t,"adjust-value"))){const G=e.getRawAttribute(b.attrName(t,"adjust-value")),Z=Number(G);isNaN(Z)||(r.adjustValue=Z)}}if(e.hasAttribute(b.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(b.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(b.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(b.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const V=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
21
21
  "use strict";
22
- ${k}
23
- `)}catch(q){m.error("Haori",`Invalid after script: ${q}`)}}if(e.hasAttribute(b.attrName(t,"dialog"))&&(r.dialogMessage=b.unescapeNewlines(b.readLateAttribute(e,r,"dialog",b.attrName(t,"dialog")))),e.hasAttribute(b.attrName(t,"toast"))){r.toastMessage=b.readLateAttribute(e,r,"toast",b.attrName(t,"toast"));const k=e.getRawAttribute(b.attrName(t,"toast-level")),X=["info","warning","error","success"].includes(k);r.toastLevel=X?k:null}const A=b.attrName(t,"redirect"),S=b.attrName(t,"redirect-replace"),C=e.hasAttribute(A),V=e.hasAttribute(S);if(C&&(r.redirectUrl=b.readLateAttribute(e,r,"redirect",A)),V&&(r.redirectReplaceUrl=b.readLateAttribute(e,r,"redirect-replace",S)),C||V){const k=b.attrName(t,"redirect-return-param");e.hasAttribute(k)&&(r.redirectReturnParam=b.readLateAttribute(e,r,"redirect-return-param",k))}if(e.hasAttribute(b.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(b.attrName(t,"scroll"))&&(r.scrollTarget=b.readLateAttribute(e,r,"scroll",b.attrName(t,"scroll"))),e.hasAttribute(b.attrName(t,"history"))&&(r.historyUrl=b.readLateAttribute(e,r,"history",b.attrName(t,"history"))),e.hasAttribute(b.attrName(t,"history-data"))&&(r.historyDataAttrName=b.attrName(t,"history-data")),e.hasAttribute(b.attrName(t,"history-form"))){const k=z.read(e,b.attrName(t,"history-form"));if(k){const q=z.query(k,b.attrName(t,"history-form"));q!==null?r.historyFormFragment=F.getFormFragment(x.get(q)):m.error("Haori",`Form element not found: ${k} (${b.attrName(t,"history-form")})`)}else r.historyFormFragment=F.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(k=>{const q=b.attrName(t,k);if(!e.hasAttribute(q))return;const X=z.read(e,q),Y=[];if(X)z.queryAll(X,q).forEach(be=>{const de=x.get(be);de&&Y.push(de)}),Y.length===0&&m.error("Haori",`Element not found: ${X} (${q})`);else if(k==="open"||k==="close"){const te=e.getTarget().closest("dialog");te?Y.push(x.get(te)):m.error("Haori",`Ancestor <dialog> not found (${q})`)}else Y.push(e);if(Y.length>0)switch(k){case"reset-before":r.resetBeforeFragments=Y;break;case"reset":r.resetFragments=Y;break;case"refetch":r.refetchFragments=Y;break;case"click":r.clickFragments=Y;break;case"copy":r.copyFragments=Y;break;case"open":r.openFragments=Y;break;case"close":r.closeFragments=Y;break}});const _=b.attrName(t,"copy-source");if(e.hasAttribute(_)){const k=z.read(e,_);if(k){const q=z.query(k,_);if(q!==null){const X=x.get(q);X?r.copySourceFragment=X:m.error("Haori",`Element is not managed by Haori: ${k} (${_})`)}else m.error("Haori",`Element not found: ${k} (${_})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(b.attrName(null,"data",!0))&&(r.dataAttrName=b.attrName(null,"data",!0)),e.hasAttribute(b.attrName(null,"form",!0)))){const A=z.read(e,b.attrName(null,"form",!0));if(A){const S=z.query(A,b.attrName(null,"form",!0));S!==null?r.formFragment=F.getFormFragment(x.get(S)):m.error("Haori",`Form element not found: ${A} (${b.attrName(null,"fetch-form",!0)})`)}else r.formFragment=F.getFormFragment(e)}const M=t?b.attrName(t,"fetch-state"):b.attrName(null,"state",!0);if(e.hasAttribute(M)){const A=z.read(e,M),S=[];A?(z.queryAll(A,M).forEach(V=>{const O=x.get(V);O&&S.push(O)}),S.length===0&&m.error("Haori",`Element not found: ${A} (${M})`)):S.push(e),S.length>0&&(r.fetchStateFragments=S)}const H=t?b.attrName(t,"store-clear"):b.attrName(null,"store-clear",!0);if(e.hasAttribute(H)){const A=e.getRawAttribute(H),S=A===null?"":A.trim();if(S==="")m.error("Haori",`ストレージキーが指定されていません (${H})`);else{r.storeClearKey=S;const C=e.getRawAttribute(`${H}-type`),V=C===null?"session":C.trim();V==="local"||V==="session"?r.storeClearKind=V:(m.warn("Haori",`${H}-type は session または local を指定してください(session として扱います): ${V}`),r.storeClearKind="session")}}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),b.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const n=i.getParent();!n||!n.hasAttribute(`${l.prefix}each`)||!n.hasAttribute(`${l.prefix}form-list`)||t.set(i,b.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!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 b(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||(!this.options.formFragment&&this.options.targetFragment&&F.warnUnvalidatedCustomValidity(F.getFormFragment(this.options.targetFragment),`${l.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition()))return!1;if(this.options.runScript){const p=this.options.targetFragment?.getTarget()??null;try{const g=this.options.runScript.call(p,this.domEvent);g===!1&&this.domEvent&&this.domEvent.preventDefault(),g!=null&&typeof g.then=="function"&&await g}catch(g){m.error("Haori",`Run script execution error: ${g}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(p=>F.reset(p,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=I.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const p=this.options.beforeCallback(n||null,s||null);if(p!=null){if(p===!1||typeof p=="object"&&p.stop)return!1;typeof p=="object"&&(a="fetchUrl"in p,o="fetchOptions"in p,n=a?p.fetchUrl:n,s=o?p.fetchOptions:s)}}const c=Object.keys(i).length>0;if(n){const p=(s?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&Lt(s)&&!Oe(p)?r.baseUrl??n:n,v=Ot(E,s);n=v.url;const D={...v.options},M=v.normalized?v.requestedMethod:r.requestedMethod,H=v.effectiveMethod,A=r.transportMode==="query-get"||v.normalized,S=v.queryString??r.queryString;if(A&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:M,effectiveMethod:H,transportMode:"query-get",url:n,payload:c?i:void 0,queryString:S}),this.options.targetFragment&&n){const C=performance.now(),V={runtime:l.runtime,requestedMethod:M,effectiveMethod:H,transportMode:A?"query-get":"http",...A?{queryString:S}:{}};return U.fetchStart(this.options.targetFragment.getTarget(),n,D,c?i:void 0,V),await this.injectFetchState("loading"),await fetch(n,D).then(O=>this.handleFetchResult(O,n||void 0,C)).catch(async O=>{throw n&&U.fetchError(this.options.targetFragment.getTarget(),n,O),await this.injectFetchState("error",null,O instanceof Error?O.message:String(O)),O})}return await fetch(n,D).then(C=>this.handleFetchResult(C,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&c){const p=this.options.formFragment,g=p.getTarget(),E=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&E.add(this.options.targetFragment);const v=p.getRawBindingData(),D=Be(i),M=p.getAttribute(`${l.prefix}form-arg`);let H;if(M){H={...v??{}};const A=String(M),S=F.resolveAncestorArgOwner(p,A);H[A]=F.mergeCollectedValues((S?S.value:H[A])??null,D)}else H=F.mergeCollectedValues(v,D);await L.setBindingData(g,H,{skipFragments:E,kind:"nonSupply",sequence:this.operationSequence,editedPaths:F.collectEditedPaths(p,this.operationSequence,M?String(M):"",D)})}this.suppressEmptyReplaceBind=!c&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=c?Be(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(b.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Pe))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return b.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Pe,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(b.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(Pe),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=De();if(!e.ok)return ft(e.status)||(this.options.targetFragment&&t&&U.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&&U.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const g=this.options.afterCallback(e);if(g!=null){if(g===!1||typeof g=="object"&&g.stop)return!1;typeof g=="object"&&"response"in g&&(e="response"in g?g.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(g=>F.reset(g,this.operationSequence))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(g=>{s.push(new b(g,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const g of this.options.clickFragments){await L.evaluateAll(g);const E=g.getTarget();typeof E.click=="function"?E.click():E.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(g=>{const E=g.getTarget();E instanceof HTMLElement?s.push(i.openDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(g=>{const E=g.getTarget();E instanceof HTMLElement?s.push(i.closeDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),await Promise.all(s);const a=b.unescapeNewlines(b.normalizeMessage(this.resolveLateAttribute("dialog",this.options.dialogMessage)));a&&await i.dialog(a);const o=b.normalizeMessage(this.resolveLateAttribute("toast",this.options.toastMessage));o&&await i.toast(o,this.options.toastLevel??"info"),this.clearStore(),this.pushHistory();const c=this.resolveLateAttribute("scroll",this.options.scrollTarget);c&&z.query(c,b.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const u=this.resolveLateAttribute("redirect",this.options.redirectUrl),d=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);u&&d&&m.warn("Haori",`${b.attrName(this.eventType,"redirect")} と ${b.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const p=d||u;if(p){let g=p;const E=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(E){const D=new URLSearchParams(window.location.search).get(E);if(D!==null){const M=D.trim();ht.isSafeLocalPath(M)?g=M:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${D}`)}}d?window.location.replace(g):window.location.href=g}return!0}clearStore(){const e=this.options.storeClearKey;e&&ve.clear(e,this.options.storeClearKind??"session")}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(j.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",u);return}const c=u=>{for(const[d,p]of Object.entries(u))p!=null&&(Array.isArray(p)?p.forEach(g=>o.searchParams.append(d,String(g))):typeof p=="object"?o.searchParams.set(d,JSON.stringify(p)):o.searchParams.set(d,String(p)))};n&&c(r),s&&c(i),history.pushState({[Ct]:!0},"",o.toString())}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=F.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await De().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await De().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 c=new Map,u=[];for(const d of a)if(d&&typeof d=="object"&&!Array.isArray(d)){const p=d.key,g=d.message,E=typeof p=="string"&&p.length>0?p:null,v=typeof g=="string"?g:g!=null?String(g):"";if(v.length===0)continue;if(E!==null){const D=c.get(E)??[];D.push(v),c.set(E,D)}else u.push(v)}else typeof d=="string"&&d.length>0&&u.push(d);for(const[d,p]of c)o.push({key:d,message:p.join(`
22
+ ${V}
23
+ `)}catch(G){m.error("Haori",`Invalid after script: ${G}`)}}if(e.hasAttribute(b.attrName(t,"dialog"))&&(r.dialogMessage=b.unescapeNewlines(b.readLateAttribute(e,r,"dialog",b.attrName(t,"dialog")))),e.hasAttribute(b.attrName(t,"toast"))){r.toastMessage=b.readLateAttribute(e,r,"toast",b.attrName(t,"toast"));const V=e.getRawAttribute(b.attrName(t,"toast-level")),Z=["info","warning","error","success"].includes(V);r.toastLevel=Z?V:null}const R=b.attrName(t,"redirect"),S=b.attrName(t,"redirect-replace"),H=e.hasAttribute(R),B=e.hasAttribute(S);if(H&&(r.redirectUrl=b.readLateAttribute(e,r,"redirect",R)),B&&(r.redirectReplaceUrl=b.readLateAttribute(e,r,"redirect-replace",S)),H||B){const V=b.attrName(t,"redirect-return-param");e.hasAttribute(V)&&(r.redirectReturnParam=b.readLateAttribute(e,r,"redirect-return-param",V))}if(e.hasAttribute(b.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(b.attrName(t,"scroll"))&&(r.scrollTarget=b.readLateAttribute(e,r,"scroll",b.attrName(t,"scroll"))),e.hasAttribute(b.attrName(t,"history"))&&(r.historyUrl=b.readLateAttribute(e,r,"history",b.attrName(t,"history"))),e.hasAttribute(b.attrName(t,"history-data"))&&(r.historyDataAttrName=b.attrName(t,"history-data")),e.hasAttribute(b.attrName(t,"history-form"))){const V=X.read(e,b.attrName(t,"history-form"));if(V){const G=X.query(V,b.attrName(t,"history-form"));G!==null?r.historyFormFragment=N.getFormFragment(M.get(G)):m.error("Haori",`Form element not found: ${V} (${b.attrName(t,"history-form")})`)}else r.historyFormFragment=N.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(V=>{const G=b.attrName(t,V);if(!e.hasAttribute(G))return;const Z=X.read(e,G),J=[];if(Z)X.queryAll(Z,G).forEach(Se=>{const ue=M.get(Se);ue&&J.push(ue)}),J.length===0&&m.error("Haori",`Element not found: ${Z} (${G})`);else if(V==="open"||V==="close"){const ae=e.getTarget().closest("dialog");ae?J.push(M.get(ae)):m.error("Haori",`Ancestor <dialog> not found (${G})`)}else J.push(e);if(J.length>0)switch(V){case"reset-before":r.resetBeforeFragments=J;break;case"reset":r.resetFragments=J;break;case"refetch":r.refetchFragments=J;break;case"click":r.clickFragments=J;break;case"copy":r.copyFragments=J;break;case"open":r.openFragments=J;break;case"close":r.closeFragments=J;break}});const ie=b.attrName(t,"copy-source");if(e.hasAttribute(ie)){const V=X.read(e,ie);if(V){const G=X.query(V,ie);if(G!==null){const Z=M.get(G);Z?r.copySourceFragment=Z:m.error("Haori",`Element is not managed by Haori: ${V} (${ie})`)}else m.error("Haori",`Element not found: ${V} (${ie})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(b.attrName(null,"data",!0))&&(r.dataAttrName=b.attrName(null,"data",!0)),e.hasAttribute(b.attrName(null,"form",!0)))){const R=X.read(e,b.attrName(null,"form",!0));if(R){const S=X.query(R,b.attrName(null,"form",!0));S!==null?r.formFragment=N.getFormFragment(M.get(S)):m.error("Haori",`Form element not found: ${R} (${b.attrName(null,"fetch-form",!0)})`)}else r.formFragment=N.getFormFragment(e)}const U=t?b.attrName(t,"fetch-state"):b.attrName(null,"state",!0);if(e.hasAttribute(U)){const R=X.read(e,U),S=[];R?(X.queryAll(R,U).forEach(B=>{const te=M.get(B);te&&S.push(te)}),S.length===0&&m.error("Haori",`Element not found: ${R} (${U})`)):S.push(e),S.length>0&&(r.fetchStateFragments=S)}const z=t?b.attrName(t,"store-clear"):b.attrName(null,"store-clear",!0);if(e.hasAttribute(z)){const R=e.getRawAttribute(z),S=R===null?"":R.trim();if(S==="")m.error("Haori",`ストレージキーが指定されていません (${z})`);else{r.storeClearKey=S;const H=e.getRawAttribute(`${z}-type`),B=H===null?"session":H.trim();B==="local"||B==="session"?r.storeClearKind=B:(m.warn("Haori",`${z}-type は session または local を指定してください(session として扱います): ${B}`),r.storeClearKind="session")}}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),b.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const n=i.getParent();!n||!n.hasAttribute(`${l.prefix}each`)||!n.hasAttribute(`${l.prefix}form-list`)||t.set(i,b.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!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 b(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||(!this.options.formFragment&&this.options.targetFragment&&N.warnUnvalidatedCustomValidity(N.getFormFragment(this.options.targetFragment),`${l.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition()))return!1;if(this.options.runScript){const p=this.options.targetFragment?.getTarget()??null;try{const g=this.options.runScript.call(p,this.domEvent);g===!1&&this.domEvent&&this.domEvent.preventDefault(),g!=null&&typeof g.then=="function"&&await g}catch(g){m.error("Haori",`Run script execution error: ${g}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(p=>N.reset(p,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=D.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const p=this.options.beforeCallback(n||null,s||null);if(p!=null){if(p===!1||typeof p=="object"&&p.stop)return!1;typeof p=="object"&&(a="fetchUrl"in p,o="fetchOptions"in p,n=a?p.fetchUrl:n,s=o?p.fetchOptions:s)}}const c=Object.keys(i).length>0;if(n){const p=(s?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&Lt(s)&&!Oe(p)?r.baseUrl??n:n,A=Ot(E,s);n=A.url;const I={...A.options},C=A.normalized?A.requestedMethod:r.requestedMethod,W=A.effectiveMethod,x=r.transportMode==="query-get"||A.normalized,U=A.queryString??r.queryString;if(x&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:C,effectiveMethod:W,transportMode:"query-get",url:n,payload:c?i:void 0,queryString:U}),this.options.targetFragment&&n){const z=performance.now(),R={runtime:l.runtime,requestedMethod:C,effectiveMethod:W,transportMode:x?"query-get":"http",...x?{queryString:U}:{}};return O.fetchStart(this.options.targetFragment.getTarget(),n,I,c?i:void 0,R),await this.injectFetchState("loading"),await fetch(n,I).then(S=>this.handleFetchResult(S,n||void 0,z)).catch(async S=>{throw n&&O.fetchError(this.options.targetFragment.getTarget(),n,S),await this.injectFetchState("error",null,S instanceof Error?S.message:String(S)),S})}return await fetch(n,I).then(z=>this.handleFetchResult(z,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&c){const p=this.options.formFragment,g=p.getTarget(),E=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&E.add(this.options.targetFragment);const A=p.getRawBindingData(),I=Be(i),C=p.getAttribute(`${l.prefix}form-arg`);let W;if(C){W={...A??{}};const x=String(C),U=N.resolveAncestorArgOwner(p,x);W[x]=N.mergeCollectedValues((U?U.value:W[x])??null,I)}else W=N.mergeCollectedValues(A,I);await P.setBindingData(g,W,{skipFragments:E,kind:"nonSupply",sequence:this.operationSequence,editedPaths:N.collectEditedPaths(p,this.operationSequence,C?String(C):"",I)})}this.suppressEmptyReplaceBind=!c&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=c?Be(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(b.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Pe))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return b.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Pe,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(b.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(Pe),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=Ie();if(!e.ok)return ft(e.status)||(this.options.targetFragment&&t&&O.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&&O.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const g=this.options.afterCallback(e);if(g!=null){if(g===!1||typeof g=="object"&&g.stop)return!1;typeof g=="object"&&"response"in g&&(e="response"in g?g.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(g=>N.reset(g,this.operationSequence))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(g=>{s.push(new b(g,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const g of this.options.clickFragments){await P.evaluateAll(g);const E=g.getTarget();typeof E.click=="function"?E.click():E.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(g=>{const E=g.getTarget();E instanceof HTMLElement?s.push(i.openDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(g=>{const E=g.getTarget();E instanceof HTMLElement?s.push(i.closeDialog(E)):m.error("Haori","Element is not an HTML element: ",E)}),await Promise.all(s);const a=b.unescapeNewlines(b.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));a&&await i.dialog(a);const o=b.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));o&&await i.toast(o,this.options.toastLevel??"info"),this.clearStore(),this.pushHistory();const c=this.resolveLateAttribute("scroll",this.options.scrollTarget);c&&X.query(c,b.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const u=this.resolveLateAttribute("redirect",this.options.redirectUrl),d=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);u&&d&&m.warn("Haori",`${b.attrName(this.eventType,"redirect")} と ${b.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const p=d||u;if(p){let g=p;const E=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(E){const I=new URLSearchParams(window.location.search).get(E);if(I!==null){const C=I.trim();ht.isSafeLocalPath(C)?g=C:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${I}`)}}d?window.location.replace(g):window.location.href=g}return!0}clearStore(){const e=this.options.storeClearKey;e&&Re.clear(e,this.options.storeClearKind??"session")}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(q.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",u);return}const c=u=>{for(const[d,p]of Object.entries(u))p!=null&&(Array.isArray(p)?p.forEach(g=>o.searchParams.append(d,String(g))):typeof p=="object"?o.searchParams.set(d,JSON.stringify(p)):o.searchParams.set(d,String(p)))};n&&c(r),s&&c(i),history.pushState({[Ct]:!0},"",o.toString())}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=N.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await Ie().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await Ie().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const c=new Map,u=[];for(const d of a)if(d&&typeof d=="object"&&!Array.isArray(d)){const p=d.key,g=d.message,E=typeof p=="string"&&p.length>0?p:null,A=typeof g=="string"?g:g!=null?String(g):"";if(A.length===0)continue;if(E!==null){const I=c.get(E)??[];I.push(A),c.set(E,I)}else u.push(A)}else typeof d=="string"&&d.length>0&&u.push(d);for(const[d,p]of c)o.push({key:d,message:p.join(`
24
24
  `)});for(const d of u)o.push({message:d})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const c of a.messages)typeof c=="string"&&o.push({message:c});if(a.errors&&typeof a.errors=="object")for(const[c,u]of Object.entries(a.errors))Array.isArray(u)?o.push({key:c,message:u.join(`
25
25
  `)}):typeof u=="string"?o.push({key:c,message:u}):u!=null&&o.push({key:c,message:String(u)});if(o.length===0)for(const[c,u]of Object.entries(a))c==="message"||c==="messages"||c==="errors"||(Array.isArray(u)?o.push({key:c,message:u.join(`
26
- `)}):typeof u=="string"&&o.push({key:c,message:u}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const c of o)c.key&&t?await F.addErrorMessage(t,c.key,c.message):await i(c.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 F.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return b.isRectFullyVisible(t.getBoundingClientRect())?(r.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1):(t.focus({preventScroll:!0}),t.scrollIntoView({behavior:"smooth",block:"nearest"}),b.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++b.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==b.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=b.VALIDATION_SCROLL_STABLE_FRAMES&&b.isRectPartlyVisible(a)||performance.now()-r>=b.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top<r&&e.bottom>0&&e.left<t&&e.right>0}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${l.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=Q.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&j.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;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):De().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=Q.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.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 ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?b.attrName(this.eventType,"bind"):b.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const p=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:g=>{const E=this.resolveCurrentRowItem(o,g),v={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const D=E[p],M=D!==null&&typeof D=="object"&&!Array.isArray(D)?D:{};v[p]=this.mergeAppendBindingData(o,i,M)}else v[p]=i;return this.reconcileRowUserEdits(o,v)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const p=u[d],g=p&&typeof p=="object"&&!Array.isArray(p)?p:{};u[d]=this.mergeAppendBindingData(o,i,g)}else u[d]=i;n.push(L.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:p=>{const g=this.options.bindMerge?this.resolveCurrentRowItem(o,p):p,E=this.mergeAppendBindingData(o,i,g),v=this.options.bindMerge?{...g,...E}:E;return this.reconcileRowUserEdits(o,v)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push(L.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{U.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&L.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=F.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:oe(c,n)}}return oe(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&L.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:oe(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of F.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=F.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:oe(c,a)}}return i}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=b.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(L.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=F.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:oe(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Ie(this.options.copySourceFragment):{...this.options.copySourceFragment.getRawBindingData()??{}}:this.options.formFragment?Ie(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getRawBindingData()??{}}:{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=F.getValues(r);Object.assign(e,i),F.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=b.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 e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,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,baseUrl: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=l.runtime==="demo"&&!Oe(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Se(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Ut(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=pt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const p=new FormData;for(const[g,E]of Object.entries(t))E==null?p.append(g,""):E instanceof Blob?p.append(g,E):Array.isArray(E)?E.forEach(v=>{v instanceof Blob?p.append(g,v):p.append(g,he(v))}):p.append(g,he(E));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(d)){const p=new URLSearchParams;for(const[g,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(v=>p.append(g,he(v))):p.append(g,he(E)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:Ht(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Ie(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return Ie(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=b.attrName(this.eventType,e),i=z.read(t,r);if(i!==null&&i.trim()!==""){const s=z.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=x.get(s);return a instanceof I?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(v=>/^[A-Za-z_$][\w$]*$/.test(v))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=b.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,p,g;if(u)d=u.owner,p=u.ownerData,g=[...u.path,...o.slice(1)];else{for(d=e,p=null;d;){const v=d.getRawBindingData();if(v&&o[0]in v&&!b.isRowScopeKey(d,o[0])){p=v;break}d=d.getParent()}g=o}if(!d||!p)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=b.readPathValue(p,g);return Array.isArray(E)?{owner:d,ownerData:p,array:E,path:g,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=b.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=b.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):b.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=b.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=b.resolveRowArrayIndex(u,a);if(d===null)continue;const p=a[d];if(p===null||typeof p!="object"||Array.isArray(p)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const g=u.apply(p);if(b.isSameRowItem(p,g)){u.syncWhenUnchanged&&r.push(b.syncUnchangedRowValues(u.row,g,u.syncWhenUnchanged));continue}a[d]=g,o=!0,u.syncWhenUnchanged==="supply"&&F.clearRowUserEditMarksForChangedKeys(u.row,g)}if(!o)return;const c=L.setBindingData(s.owner.getTarget(),b.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(L.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&F.clearRowUserEditMarksForChangedKeys(e,t),F.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){return b.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const n=b.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((p,g)=>{L.createListKey(p,String(a),g)===o&&c.push(g)});const u=n.slice(0,s).filter(p=>p.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(b.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t,r)=>{const i=r();if(i===null||t<=0||t>=e.length)return!1;const[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=b.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=b.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=g=>g<0||g>=a.length?null:i.mapped?b.resolveRowIndex(r,a[g],i.array,b.attrName(this.eventType,e)):g,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const p=new Map;return a.forEach(g=>{const E=g.getListKey();E!==null&&!p.has(String(E))&&p.set(String(E),g)}),d.forEach((g,E)=>{if(b.isSameRowItem(i.array[E],g))return;const v=p.get(L.createListKey(g,null,E));v&&L.clearUserEditMarks(v)}),L.setBindingData(i.owner.getTarget(),b.withPathValue(i.ownerData,i.path,d),{kind:"nonSupply",sequence:this.operationSequence})}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 L.setBindingData(a,o,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};b.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,b.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,b.RUNNING_CLICK_TARGETS=new WeakSet,b.validationReportGeneration=0,b.VALIDATION_SCROLL_TIMEOUT_MS=1e3,b.VALIDATION_SCROLL_STABLE_FRAMES=2;let ie=b;class Vt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ft(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=x.get(e);return r instanceof I?r.hasAttribute(`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof I?t.push(f.evaluateAll(r)):r instanceof ee&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=I.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof I&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.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(`${l.prefix}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(f.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof I&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=f.getReactiveFetchState(t),i=ie.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 ie(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.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(`${l.prefix}importing`,""),U.importStart(t,n),Vt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),U.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof I?c.push(f.scan(u.getTarget())):u instanceof ee&&c.push(f.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),U.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=x.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){const t=x.get(e);return t?f.initializeElementFragment(t,!1).then(()=>F.restoreInitialValues(e)).then(()=>{re.applySubtree(e)}):Promise.resolve()}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),re.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof I?r.push(f.initializeElementFragment(i,t)):i instanceof ee&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.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 f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>f.setAttribute(e.getTarget(),i,n)))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>F.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=x.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof I&&s.consumeSelfWrittenBind(r))break;const p=r===null?{}:f.parseDataBind(r);if(i){const g=n??I.nextSequence();return r===null?(o.push(f.setBindingData(e,p,{reflectToAttribute:!1,sequence:g})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,p,{sequence:g})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(p);break}case`${l.prefix}derive`:u=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=f.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=f.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=f.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:o.push(f.evaluateIf(s));break;case`${l.prefix}each`:o.push(f.evaluateEach(s));break;case`${l.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(ve.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const p=s.getAttribute(`${l.prefix}url-arg`),g=ht.readParams();p===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:I.nextSequence()};if(p===null)o.push(f.setBindingData(e,g,E));else{const v=s.getRawBindingData()||{};v[String(p)]=g,o.push(f.setBindingData(e,v,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(p=>{if(p)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=x.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??I.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const p=I.currentSequence(),g=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,c);const E=a?f.resolveByPathAuthority(i,g,t,u):t;i.setBindingData(E),a&&(U.bindChange(e,g,E,"manual"),ve.mirror(i));const v=()=>{i.markBindingWorkStart();const D=i.getRawBindingData()??E;let M=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(D)):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(p))return;const H=i.getRawBindingData()??E;return F.syncValues(i,F.resolveSyncValues(i,H),!1,u)})),M=M.then(()=>F.syncAncestorArgForms(i,p,u)),M=M.then(()=>f.evaluateAll(i,n)),M=M.then(()=>I.retryUnappliedValueWrites(e,p)),M=M.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),M.then(()=>i.markBindingWorkEnd(),H=>{throw i.markBindingWorkEnd(),H})};return s?v():i.enqueueBindingWork(v)}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const u=t,d=r,p={};let g=Object.keys(u).some(v=>!Object.prototype.hasOwnProperty.call(d,v));const E=new Set([...Object.keys(u),...Object.keys(d)]);for(const v of E){const D=n===""?v:`${n}.${v}`,M=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,v)?u[v]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,v)?d[v]:f.ABSENT_PATH,i,D);M!==f.ABSENT_PATH&&(p[v]=M),M!==(Object.prototype.hasOwnProperty.call(d,v)?d[v]:f.ABSENT_PATH)&&(g=!0)}return g?p:d}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,p=d.map((g,E)=>f.mergePathAuthority(e,u[E],g,i,`${n}[${s[E]}]`));return p.some((g,E)=>g!==d[E])?p:d}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>f.createListKey(o,n,c)),a=r.map((o,c)=>f.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=x.get(e);return r instanceof I?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=f.collectScope(e);return j.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=x.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=f.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,p)=>{if(c)for(const g of Object.keys(c))g in i||(i[g]={value:c[g],source:n(u),kind:d,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=x.get(e);if(r.isSkipMutationNodes())return;const i=x.get(t.nextSibling),n=x.get(t);if(n){if(n.getParent()===r)return;r.insertBefore(n,i),n instanceof I?f.scan(n.getTarget()):n instanceof ee&&f.evaluateText(n)}}static removeNode(e){const t=x.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=x.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=x.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=F.resolveAncestorArgOwner(n,u);c[u]=F.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=F.mergeCollectedValues(o,s);i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:I.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=f.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>f.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const p=[];return e.getChildren().forEach(g=>{if(g instanceof I){if(f.canSkipUnchangedNestedEach(g))return;p.push(f.evaluateAll(g,t))}else g instanceof ee&&p.push(f.evaluateText(g))}),Promise.all(p).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.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=Q.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 f.createBindingSignature(i)===f.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(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(Q.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.collectScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(f.isHiddenIfCondition(r))j.isEnabled()&&e.isVisible()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{U.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof I?n.push(s.isMounted()?f.evaluateAll(s):f.scan(s.getTarget())):s instanceof ee&&n.push(f.evaluateText(s))}),t.push(e.show().then(()=>{U.show(e.getTarget()),i||(f.triggerLoadOnShow(e),re.refreshSubtree(e.getTarget()))})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new ie(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(j.isEnabled()&&Q.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),e.isMounted()||f.syncMountedState(e),!e.isVisible()||!e.isMounted())return Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${l.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),re.refreshSubtree(i),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${l.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 (
26
+ `)}):typeof u=="string"&&o.push({key:c,message:u}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const c of o)c.key&&t?await N.addErrorMessage(t,c.key,c.message):await i(c.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 N.warnUnvalidatedCustomValidity(e,`${l.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;N.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return b.isRectFullyVisible(t.getBoundingClientRect())?(r.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1):(t.focus({preventScroll:!0}),t.scrollIntoView({behavior:"smooth",block:"nearest"}),b.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++b.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==b.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=b.VALIDATION_SCROLL_STABLE_FRAMES&&b.isRectPartlyVisible(a)||performance.now()-r>=b.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=b.getViewportSize();return e.top<r&&e.bottom>0&&e.left<t&&e.right>0}evaluateExecutionCondition(e=!1){const t=this.options.conditionExpression;if(!t)return!0;const r=this.options.targetFragment;if(!r)return!0;const i=this.options.conditionAttributeName??`${l.prefix}if`,n=N.buildConditionScope(r,this.options.formFragment??null),s=ee.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&q.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):Ie().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=ee.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.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 ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?b.attrName(this.eventType,"bind"):b.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const p=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:g=>{const E=this.resolveCurrentRowItem(o,g),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const I=E[p],C=I!==null&&typeof I=="object"&&!Array.isArray(I)?I:{};A[p]=this.mergeAppendBindingData(o,i,C)}else A[p]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const p=u[d],g=p&&typeof p=="object"&&!Array.isArray(p)?p:{};u[d]=this.mergeAppendBindingData(o,i,g)}else u[d]=i;n.push(P.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:p=>{const g=this.options.bindMerge?this.resolveCurrentRowItem(o,p):p,E=this.mergeAppendBindingData(o,i,g),A=this.options.bindMerge?{...g,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push(P.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{O.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&P.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=N.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:fe(c,n)}}return fe(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&P.clearUserEditMarks(e,r);const n=N.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:fe(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of N.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=N.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:fe(c,a)}}return i}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=b.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(P.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=N.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:fe(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?xe(this.options.copySourceFragment):{...this.options.copySourceFragment.getRawBindingData()??{}}:this.options.formFragment?xe(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getRawBindingData()??{}}:{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=N.getValues(r);Object.assign(e,i),N.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=b.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 e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,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,baseUrl: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=l.runtime==="demo"&&!Oe(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Te(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Ut(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=pt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const p=new FormData;for(const[g,E]of Object.entries(t))E==null?p.append(g,""):E instanceof Blob?p.append(g,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?p.append(g,A):p.append(g,ye(A))}):p.append(g,ye(E));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(d)){const p=new URLSearchParams;for(const[g,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>p.append(g,ye(A))):p.append(g,ye(E)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:Ht(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?xe(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?b.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return xe(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=b.attrName(this.eventType,e),i=X.read(t,r);if(i!==null&&i.trim()!==""){const s=X.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=M.get(s);return a instanceof D?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(A=>/^[A-Za-z_$][\w$]*$/.test(A))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=b.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,p,g;if(u)d=u.owner,p=u.ownerData,g=[...u.path,...o.slice(1)];else{for(d=e,p=null;d;){const A=d.getRawBindingData();if(A&&o[0]in A&&!b.isRowScopeKey(d,o[0])){p=A;break}d=d.getParent()}g=o}if(!d||!p)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=b.readPathValue(p,g);return Array.isArray(E)?{owner:d,ownerData:p,array:E,path:g,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=b.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=b.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):b.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=b.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=b.resolveRowArrayIndex(u,a);if(d===null)continue;const p=a[d];if(p===null||typeof p!="object"||Array.isArray(p)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const g=u.apply(p);if(b.isSameRowItem(p,g)){u.syncWhenUnchanged&&r.push(b.syncUnchangedRowValues(u.row,g,u.syncWhenUnchanged));continue}a[d]=g,o=!0,u.syncWhenUnchanged==="supply"&&N.clearRowUserEditMarksForChangedKeys(u.row,g)}if(!o)return;const c=P.setBindingData(s.owner.getTarget(),b.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(P.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&N.clearRowUserEditMarksForChangedKeys(e,t),N.syncRowValues(e,t)}static isSameRowItem(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static resolveRowArrayIndex(e,t){return b.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const n=b.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((p,g)=>{P.createListKey(p,String(a),g)===o&&c.push(g)});const u=n.slice(0,s).filter(p=>p.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(b.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t,r)=>{const i=r();if(i===null||t<=0||t>=e.length)return!1;const[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=b.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=b.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=g=>g<0||g>=a.length?null:i.mapped?b.resolveRowIndex(r,a[g],i.array,b.attrName(this.eventType,e)):g,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const p=new Map;return a.forEach(g=>{const E=g.getListKey();E!==null&&!p.has(String(E))&&p.set(String(E),g)}),d.forEach((g,E)=>{if(b.isSameRowItem(i.array[E],g))return;const A=p.get(P.createListKey(g,null,E));A&&P.clearUserEditMarks(A)}),P.setBindingData(i.owner.getTarget(),b.withPathValue(i.ownerData,i.path,d),{kind:"nonSupply",sequence:this.operationSequence})}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 P.setBindingData(a,o,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};b.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,b.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,b.RUNNING_CLICK_TARGETS=new WeakSet,b.validationReportGeneration=0,b.VALIDATION_SCROLL_TIMEOUT_MS=1e3,b.VALIDATION_SCROLL_STABLE_FRAMES=2;let se=b;class Vt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ft(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const f=class f{static isDeferredAttributeName(e){return f.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!f.isEvaluateAllExcludedAttributeName(e)&&f.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=M.get(e);return r instanceof D?r.hasAttribute(`${l.prefix}${f.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);f.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>f.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof D?t.push(f.evaluateAll(r)):r instanceof re&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=D.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof D&&f.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=f.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return f.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=f.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return f.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(`${l.prefix}validity`)&&N.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(f.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(f.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof D&&r.push(f.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=f.getReactiveFetchState(t),i=se.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 se(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=f.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.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(`${l.prefix}importing`,""),O.importStart(t,n),Vt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),O.importEnd(t,n,o,s),f.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof D?c.push(f.scan(u.getTarget())):u instanceof re&&c.push(f.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),O.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,f.executeManagedImport(e)})}static adoptImportedChildren(e){const t=e.getTarget();e.getChildren().filter(r=>r.getTarget().parentNode!==t).forEach(r=>{r.remove(!1)}),t.childNodes.forEach(r=>{const i=M.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){const t=M.get(e);return t?f.initializeElementFragment(t,!1).then(()=>N.restoreInitialValues(e)).then(()=>{ne.applySubtree(e)}):Promise.resolve()}static initializeFreshEachRow(e){return f.initializeElementFragment(e,!0).then(()=>{f.needsScheduledEvaluateAll(e)&&f.scheduleEvaluateAll(e),ne.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return f.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():f.initializeElementAttributes(e).then(()=>{if(f.shouldSkipChildInitialization(e,t)){f.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof D?r.push(f.initializeElementFragment(i,t)):i instanceof re&&r.push(f.evaluateText(i))}),Promise.all(r).then(()=>{f.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 f.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||f.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>f.setAttribute(e.getTarget(),i,n)))}for(const i of f.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>f.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>N.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&f.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=M.get(e),a=f.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof D&&s.consumeSelfWrittenBind(r))break;const p=r===null?{}:f.parseDataBind(r);if(i){const g=n??D.nextSequence();return r===null?(o.push(f.setBindingData(e,p,{reflectToAttribute:!1,sequence:g})),o.push(s.removeAttribute(t))):o.push(f.setBindingData(e,p,{sequence:g})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(p);break}case`${l.prefix}derive`:u=f.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=f.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=f.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=f.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:d=()=>f.evaluateIf(s);break;case`${l.prefix}each`:d=()=>f.evaluateEach(s);break;case`${l.prefix}fetch`:d=()=>f.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>f.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(Re.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&N.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const p=s.getAttribute(`${l.prefix}url-arg`),g=ht.readParams();p===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:D.nextSequence()};if(p===null)o.push(f.setBindingData(e,g,E));else{const A=s.getRawBindingData()||{};A[String(p)]=g,o.push(f.setBindingData(e,A,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(p=>{if(p)return f.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=M.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??D.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const p=D.currentSequence(),g=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&f.clearUserEditMarks(i,c);const E=a?f.resolveByPathAuthority(i,g,t,u):t;i.setBindingData(E),a&&(O.bindChange(e,g,E,"manual"),Re.mirror(i));const A=()=>{i.markBindingWorkStart();const I=i.getRawBindingData()??E;let C=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(I)):Promise.resolve();return e.tagName==="FORM"&&(C=C.then(()=>{if(i.wasResetAfter(p))return;const W=i.getRawBindingData()??E;return N.syncValues(i,N.resolveSyncValues(i,W),!1,u)})),C=C.then(()=>N.syncAncestorArgForms(i,p,u)),C=C.then(()=>f.evaluateAll(i,n)),C=C.then(()=>D.retryUnappliedValueWrites(e,p)),C=C.then(()=>f.reevaluateReactiveSpecialAttributes(i,n)),C.then(()=>i.markBindingWorkEnd(),W=>{throw i.markBindingWorkEnd(),W})};return s?A():i.enqueueBindingWork(A)}static resolveByPathAuthority(e,t,r,i){const n=f.mergePathAuthority(e,t??{},r,i,"");return n===f.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(f.isPlainRecord(t)&&f.isPlainRecord(r)){const u=t,d=r,p={};let g=Object.keys(u).some(A=>!Object.prototype.hasOwnProperty.call(d,A));const E=new Set([...Object.keys(u),...Object.keys(d)]);for(const A of E){const I=n===""?A:`${n}.${A}`,C=f.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,A)?u[A]:f.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,A)?d[A]:f.ABSENT_PATH,i,I);C!==f.ABSENT_PATH&&(p[A]=C),C!==(Object.prototype.hasOwnProperty.call(d,A)?d[A]:f.ABSENT_PATH)&&(g=!0)}return g?p:d}const s=f.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,p=d.map((g,E)=>f.mergePathAuthority(e,u[E],g,i,`${n}[${s[E]}]`));return p.some((g,E)=>g!==d[E])?p:d}if(f.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>f.isPlainRecord(o))?f.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>f.createListKey(o,n,c)),a=r.map((o,c)=>f.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=f.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===f.ABSENT_PATH||t===f.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=M.get(e);return r instanceof D?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=f.collectScope(e);return q.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=M.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=f.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,p)=>{if(c)for(const g of Object.keys(c))g in i||(i[g]={value:c[g],source:n(u),kind:d,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=M.get(e);if(r.isSkipMutationNodes())return;const i=M.get(t.nextSibling),n=M.get(t);if(n){if(n.getParent()===r)return;r.insertBefore(n,i),n instanceof D?f.scan(n.getTarget()):n instanceof re&&f.evaluateText(n)}}static removeNode(e){const t=M.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=M.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=M.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=f.getFormFragment(r);if(n){const s=N.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=N.resolveAncestorArgOwner(n,u);c[u]=N.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=N.mergeCollectedValues(o,s);i.push(f.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:D.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?f.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=f.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=f.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>f.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>f.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>f.evaluateEachFixedChildren(e)).then(()=>f.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=f.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,f.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const p=[];return e.getChildren().forEach(g=>{if(g instanceof D){if(f.canSkipUnchangedNestedEach(g))return;p.push(f.evaluateAll(g,t))}else g instanceof re&&p.push(f.evaluateText(g))}),Promise.all(p).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.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=ee.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 f.createBindingSignature(i)===f.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(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(ee.hasCompileFailure(t)){m.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=f.collectScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${l.prefix}each-before`)||e.hasAttribute(`${l.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof D&&f.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof D?f.isEachFixedChild(r)&&t.push(f.evaluateAll(r)):r instanceof re&&t.push(f.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(f.isHiddenIfCondition(r))q.isEnabled()&&e.isVisible()&&f.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{O.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=[],s=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(a=>{if(a instanceof D){if(s&&!f.isEachFixedChild(a))return;n.push(a.isMounted()?f.evaluateAll(a):f.scan(a.getTarget()))}else a instanceof re&&n.push(f.evaluateText(a))}),t.push(e.show().then(()=>{O.show(e.getTarget()),i||(f.triggerLoadOnShow(e),ne.refreshSubtree(e.getTarget()))})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new se(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=f.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},f.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(q.isEnabled()&&ee.recordRowScopeIdentifiers([f.getRowScopeName(e,"each-arg"),f.getRowScopeName(e,"each-index")]),e.isMounted()||f.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${l.prefix}each-done`),Promise.resolve();const t=f.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):f.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${l.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return f.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await f.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),ne.refreshSubtree(i),f.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}f.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${l.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 (
27
27
  ${r}
28
28
  );`)}catch{try{i=new Function(`"use strict";
29
29
  ${r}
30
- `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.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"&&(f.EACH_RENDERED_CHANGE_WARNED.has(r)||(f.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),f.countEachRenderedRows(e)!==0){if(!n){if(f.EACH_RENDERED_CHANGE_FIRED.has(r))return;f.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){m.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=f.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${l.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof I){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),s&&f.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!s){const d=x.get(c);d instanceof I&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=x.get(c);u instanceof I&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?f.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(f.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>f.evaluateAll(r))).then(()=>{})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.prefix}each-index`);s&&n.add(String(s));const a=f.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!f.areExpressionsRowLocal(f.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(f.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!f.areExpressionsRowLocal([s],t))return!1;continue}if(f.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&f.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof I){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof ee){const n=i.getRawText();if(n.includes("{{")&&!f.areExpressionsRowLocal(f.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=Q.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof I?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:f.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return f.recordDerivedSubtreeSignatureComputation(e,t),f.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:f.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(f.createDescendantBindingSignature(e,"refresh")),f.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!j.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=f.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:f.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return f.DERIVE_SUBTREE_PROFILES.set(e,r),r}static resolveElementId(e){return e.getAttribute("id")??""}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();const s=f.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const c=o.getChildren().filter(u=>u instanceof I).findIndex(u=>u===r);n+=`:nth-child(${c+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof ee&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof I?!f.markFreshInitializationSkippable(n):n instanceof ee?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=t.map((A,S)=>f.createListKey(A,n?String(n):null,S)),o=new Set(a),c=new Map;a.forEach(A=>{c.set(A,(c.get(A)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(A=>A instanceof I).filter(A=>!A.hasAttribute(`${l.prefix}each-before`)&&!A.hasAttribute(`${l.prefix}each-after`));const p=d.map(A=>A.getListKey()),g=new Set;d=d.filter((A,S)=>{const C=String(A.getListKey()),V=c.get(C)??0;if(V===0){g.add(A);const O=A.getListKey();return O!==null&&U.rowRemove(A.getTarget(),O,S),u.push(A.remove()),!1}return c.set(C,V-1),!0});const E=d.map(A=>A.getListKey()),v=new Map;d.forEach(A=>{const S=A.getListKey();if(S===null)return;const C=v.get(S);C?C.push(A):v.set(S,[A])});const D=e.getChildElementFragments().filter(A=>!g.has(A)),M=D.filter(A=>A.hasAttribute(`${l.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((A,S)=>{const C=t[S],V=S;let O;const _=v.get(A)?.shift();if(_){O=_;const k=M+S;H=H.then(()=>f.updateRowFragment(O,C,i,V,s?String(s):null,A).then(q=>f.repositionEachRow(e,O,D,k).then(X=>{if(X!==null&&U.rowMove(O.getTarget(),A,X-M,S),!(!q&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(O).then(()=>f.applyRowFormValues(e,O,C))})))}else{O=r.clone();const k=M+S;H=H.then(()=>f.updateRowFragment(O,C,i,V,s?String(s):null,A).then(()=>{const q=D[k]??null;return e.insertBefore(O,q).then(()=>{D.splice(k,0,O)}).then(()=>f.initializeFreshEachRow(O)).then(()=>f.applyRowFormValues(e,O,C)).then(()=>{U.rowAdd(O.getTarget(),A,V,C)})}))}}),Promise.all(u).then(()=>H).then(()=>{const A=a.filter(k=>k!==null),S=E.filter(k=>k!==null),C=new Set(S),V=A.filter(k=>!C.has(k)),_=p.filter(k=>k!==null).filter(k=>!o.has(k));U.eachUpdate(e.getTarget(),V,_,A)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof I).filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!j.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${l.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve(null);r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s).then(()=>n)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||!F.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():F.syncRowValues(t,r)}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;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,c=f.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.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()&&f.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${l.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=>f.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)}:${f.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{f.evaluateAll(e)},100)}};f.ATTRIBUTE_ALIAS_SUFFIX="attr-",f.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],f.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],f.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,f.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),f.ROW_LOCAL_STATIC_ATTRIBUTES=new Set(["each-arg","each-key","each-index","each-before","each-after","derive-name","row","form","form-arg","form-list","form-object","form-detach","value-type","store","store-params","store-arg","store-type","enhance","enhance-new"]),f.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),f.REACTIVE_FETCH_STATES=new WeakMap,f.REACTIVE_IMPORT_STATES=new WeakMap,f.DERIVE_SUBTREE_PROFILES=new WeakMap,f.EACH_UPDATE_STATES=new WeakMap,f.EACH_RENDERED_CHANGE_FIRED=new WeakSet,f.EACH_RENDERED_CHANGE_WARNED=new WeakSet,f.WARNED_DUPLICATE_EACH_KEYS=new Set,f.ABSENT_PATH=Symbol("absent");let L=f;const ye=class ye{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[ye.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=x.get(e);t&&new ie(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){m.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`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ye.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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=x.get(i);n instanceof I&&new ie(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${l.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=x.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{new ie(i,t,r).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=x.get(e);t instanceof I&&t.markUserEdit()}syncUserEdit(e,t){const r=x.get(e);if(r instanceof I&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const i=document.getElementsByName(e.name);for(const n of Array.from(i)){if(n===e||!(n instanceof HTMLInputElement)||n.type!=="radio"||n.form!==e.form)continue;const s=x.get(n);s instanceof I&&(s.syncValue(),s.markUserEdit())}}}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=`${l.prefix}click-`,r=`${l.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}};ye.HISTORY_STATE_KEY="__haoriHistoryState__",ye.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ue=ye;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=x.get(e);if(!r||!W.shouldObserve(r)){t&&(t.observer.disconnect(),W.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=W.resolveRoot(r),n=W.resolveRootMargin(r),s=W.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&W.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),W.registrations.delete(e));const o=new IntersectionObserver(c=>{const u=W.registrations.get(e);u&&c.forEach(d=>{!d.isIntersecting||u.running||W.isDisabled(u.fragment)||(u.running=!0,new ie(u.fragment,"intersect").runWithResult().then(p=>{p&&u.once&&(u.observer.disconnect(),W.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=W.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),W.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}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.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!W.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${l.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=z.query(r,t,document);return W.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.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=`${l.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}};W.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),W.registrations=new Map;let pe=W;const w=class w{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);if(!t&&!w.hasPollAttribute(e))return;const r=x.get(e);if(!(r instanceof I)||!w.shouldObserve(r)){t&&w.teardown(e,t);return}const i=w.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}w.teardown(e,t)}w.startPolling(e,r,i)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&w.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&w.teardown(t,r)})}static disconnectAll(){w.registrations.forEach(e=>{w.clearTimers(e)}),w.registrations.clear(),w.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",w.visibilityListener),w.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${l.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!w.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
31
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:w.resolveInterval(t),timeoutMs:w.resolveTimeout(t),errorLimit:w.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};w.registrations.set(e,i),w.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{w.handleTimeout(e)},i.timeoutMs)),w.injectState(i),w.tick(e)}static async tick(e){const t=w.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await w.stop(e,t,"detached");return}const r=w.isHidden(e)||w.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await w.injectState(t)),r){w.schedule(e,t);return}if(w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ie(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(w.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await w.stop(e,t,"error");return}if(await w.restoreStateIfCleared(t),i&&w.isUntilSatisfied(t.fragment)){await w.stop(e,t,"until");return}w.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{w.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=w.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&U.pollTimeout(e,t.count,w.elapsed(t)),await w.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,w.clearTimers(t),r==="detached"){w.registrations.delete(e);return}await w.injectState(t),e.isConnected&&U.pollStop(e,r,t.count,w.elapsed(t))}}static teardown(e,t){w.clearTimers(t),w.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(w.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(w.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),w.tick(t))})};w.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=w.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:w.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return L.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:I.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){w.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await w.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=z.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=x.get(a);o instanceof I&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return w.DEFAULT_INTERVAL_MS;const r=w.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${w.DEFAULT_INTERVAL_MS}ms を使用します。`),w.DEFAULT_INTERVAL_MS):r<w.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${w.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),w.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=w.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?w.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):w.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};w.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),w.DEFAULT_INTERVAL_MS=5e3,w.MIN_INTERVAL_MS=100,w.registrations=new Map,w.visibilityListener=null;let ge=w;const mt="0.46.2";function qt(y){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>y()):Promise.resolve().then(y)}const B=class B{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)&&(B.isHtmlElement(e)&&B.syncElement(e),e.querySelectorAll("*").forEach(t=>{B.syncElement(t)}))}static syncElement(e){const t=B.registrations.get(e),r=x.get(e);if(!(r instanceof I)||!B.shouldObserve(r)){t&&(t.observer.disconnect(),B.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=B.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),B.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=B.resolveRoot(r),s=B.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,B.refreshRows(t);return}t&&(t.observer.disconnect(),B.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=B.registrations.get(e);if(!u)return;let d=!1;c.forEach(p=>{const g=p.target;u.observedRows.has(g)&&(p.isIntersecting?u.visibleRows.has(g)||(u.visibleRows.add(g),d=!0):u.visibleRows.delete(g)&&(d=!0))}),d&&B.scheduleCompute(u)},{root:n,rootMargin:s,threshold:B.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};B.registrations.set(e,o),B.refreshRows(o)}static cleanupTree(e){if(B.isHtmlElement(e)){const t=B.registrations.get(e);t&&(t.observer.disconnect(),B.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=B.registrations.get(t);r&&(r.observer.disconnect(),B.registrations.delete(t))})}static disconnectAll(){B.registrations.forEach(e=>{e.observer.disconnect()}),B.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.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=z.query(r,t,document);return B.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?B.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof I&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=B.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));B.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,qt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();B.registrations.get(t)===e&&B.computeAndPublish(e)}))}static computeAndPublish(e){const t=B.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 c of i)c<a&&(a=c),c>o&&(o=c);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,B.publish(e,n))}static publish(e,t){const r=B.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);L.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:I.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};B.THRESHOLD=0,B.DEFAULT_ROOT_MARGIN="0px",B.registrations=new Map;let le=B;const G=class G{static disconnectMutationObservers(){G._mutationObservers.forEach(e=>{e.disconnect()}),G._mutationObservers.length=0}static async init(){if(G._initialized)return;G._initialized=!0,G.disconnectMutationObservers(),I.setPendingMutationFlusher(()=>{G.flushPendingMutations()});const e=new Ue;G._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([L.scan(document.head),L.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await K.wait(),document.body.setAttribute("data-haori-ready",""),G.observe(document.head),G.observe(document.body),pe.syncTree(document.body),ge.syncTree(document.body),le.syncTree(document.body)}finally{e.release()}U.ready(mt)}static getDispatcher(){return G._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{G.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),G._mutationObservers.push(t)}static flushPendingMutations(){for(const e of G._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(G.isBindAttributeRecord),i=t.filter(n=>!G.isBindAttributeRecord(n));r.length>0&&G.processMutations(r,I.nextSequence()),i.length>0&&Promise.resolve().then(()=>{G.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(G.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(Ae)&&(r.attributeName==="disabled"||r.attributeName===Ae)||r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))||r.attributeName&&L.isAliasedAttributeReflection(i,r.attributeName))break;L.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),pe.syncElement(i),ge.syncElement(i),le.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{pe.cleanupTree(i),ge.cleanupTree(i),le.cleanupTree(i),L.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(L.addNode(i.parentElement,i),pe.syncTree(i),ge.syncTree(i),le.syncTree(i))}),r.target instanceof Element&&le.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?L.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};G._initialized=!1,G._mutationObservers=[],G._dispatcher=null;let xe=G;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",xe.init):xe.init();const Wt=()=>ae.waitForRenders(),jt=ae.enhancers;exports.Core=L;exports.Enhance=re;exports.Env=l;exports.Form=F;exports.Fragment=x;exports.Haori=ae;exports.Log=m;exports.Queue=K;exports.default=ae;exports.enhancers=jt;exports.version=mt;exports.waitForRenders=Wt;
30
+ `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.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"&&(f.EACH_RENDERED_CHANGE_WARNED.has(r)||(f.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),f.countEachRenderedRows(e)!==0){if(!n){if(f.EACH_RENDERED_CHANGE_FIRED.has(r))return;f.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){m.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=f.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${l.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof D){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),s&&f.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!s){const d=M.get(c);d instanceof D&&(r=d.clone(),f.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=M.get(c);u instanceof D&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?f.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(f.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>f.evaluateAll(r))).then(()=>{})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||f.hasNonEachDynamicElementState(e)||!f.isRowLocalEachTemplate(e)||f.hasEachFixedChildren(e))return!1;const r=f.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),n=f.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.prefix}each-index`);s&&n.add(String(s));const a=f.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!f.areExpressionsRowLocal(f.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(f.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!f.areExpressionsRowLocal([s],t))return!1;continue}if(f.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&f.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof D){if(!f.isRowLocalSubtree(i,r))return!1}else if(i instanceof re){const n=i.getRawText();if(n.includes("{{")&&!f.areExpressionsRowLocal(f.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=ee.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!f.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof D?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:f.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return f.recordDerivedSubtreeSignatureComputation(e,t),f.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:f.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!f.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),f.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(f.createDescendantBindingSignature(e,"refresh")),f.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!q.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=f.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:f.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return f.DERIVE_SUBTREE_PROFILES.set(e,r),r}static resolveElementId(e){return e.getAttribute("id")??""}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();const s=f.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const c=o.getChildren().filter(u=>u instanceof D).findIndex(u=>u===r);n+=`:nth-child(${c+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=f.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof re&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>f.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof D?!f.markFreshInitializationSkippable(n):n instanceof re?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=t.map((x,U)=>f.createListKey(x,n?String(n):null,U)),o=new Set(a),c=new Map;a.forEach(x=>{c.set(x,(c.get(x)??0)+1)}),n&&o.size!==a.length&&f.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(x=>x instanceof D).filter(x=>!x.hasAttribute(`${l.prefix}each-before`)&&!x.hasAttribute(`${l.prefix}each-after`));const p=d.map(x=>x.getListKey()),g=new Set;d=d.filter((x,U)=>{const z=String(x.getListKey()),R=c.get(z)??0;if(R===0){g.add(x);const S=x.getListKey();return S!==null&&O.rowRemove(x.getTarget(),S,U),u.push(x.remove()),!1}return c.set(z,R-1),!0});const E=d.map(x=>x.getListKey()),A=new Map;d.forEach(x=>{const U=x.getListKey();if(U===null)return;const z=A.get(U);z?z.push(x):A.set(U,[x])});const I=e.getChildElementFragments().filter(x=>!g.has(x)),C=I.filter(x=>x.hasAttribute(`${l.prefix}each-before`)).length;let W=Promise.resolve();return a.forEach((x,U)=>{const z=t[U],R=U;let S;const H=A.get(x)?.shift();if(H){S=H;const B=C+U;W=W.then(()=>f.updateRowFragment(S,z,i,R,s?String(s):null,x).then(te=>f.repositionEachRow(e,S,I,B).then(ie=>{if(ie!==null&&O.rowMove(S.getTarget(),x,ie-C,U),!(!te&&f.isRowLocalEachTemplate(e)))return f.evaluateAll(S).then(()=>f.applyRowFormValues(e,S,z))})))}else{S=r.clone();const B=C+U;W=W.then(()=>f.updateRowFragment(S,z,i,R,s?String(s):null,x).then(()=>{const te=I[B]??null;return e.insertBefore(S,te).then(()=>{I.splice(B,0,S)}).then(()=>f.initializeFreshEachRow(S)).then(()=>f.applyRowFormValues(e,S,z)).then(()=>{O.rowAdd(S.getTarget(),x,R,z)})}))}}),Promise.all(u).then(()=>W).then(()=>{const x=a.filter(B=>B!==null),U=E.filter(B=>B!==null),z=new Set(U),R=x.filter(B=>!z.has(B)),H=p.filter(B=>B!==null).filter(B=>!o.has(B));O.eachUpdate(e.getTarget(),R,H,x)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof D).filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!q.isEnabled()||f.WARNED_DUPLICATE_EACH_KEYS.has(e)||(f.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${l.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve(null);r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s).then(()=>n)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||!N.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():N.syncRowValues(t,r)}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;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,c=f.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.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()&&f.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${l.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=>f.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)}:${f.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{f.evaluateAll(e)},100)}};f.ATTRIBUTE_ALIAS_SUFFIX="attr-",f.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],f.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],f.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],f.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,f.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),f.ROW_LOCAL_STATIC_ATTRIBUTES=new Set(["each-arg","each-key","each-index","each-before","each-after","derive-name","row","form","form-arg","form-list","form-object","form-detach","value-type","store","store-params","store-arg","store-type","enhance","enhance-new"]),f.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),f.REACTIVE_FETCH_STATES=new WeakMap,f.REACTIVE_IMPORT_STATES=new WeakMap,f.DERIVE_SUBTREE_PROFILES=new WeakMap,f.EACH_UPDATE_STATES=new WeakMap,f.EACH_RENDERED_CHANGE_FIRED=new WeakSet,f.EACH_RENDERED_CHANGE_WARNED=new WeakSet,f.WARNED_DUPLICATE_EACH_KEYS=new Set,f.ABSENT_PATH=Symbol("absent");let P=f;const ve=class ve{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[ve.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=M.get(e);t&&new se(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){m.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`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ve.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){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=M.get(i);n instanceof D&&new se(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${l.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=M.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{new se(i,t,r).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=M.get(e);t instanceof D&&t.markUserEdit()}syncUserEdit(e,t){const r=M.get(e);if(r instanceof D&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const i=document.getElementsByName(e.name);for(const n of Array.from(i)){if(n===e||!(n instanceof HTMLInputElement)||n.type!=="radio"||n.form!==e.form)continue;const s=M.get(n);s instanceof D&&(s.syncValue(),s.markUserEdit())}}}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=`${l.prefix}click-`,r=`${l.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}};ve.HISTORY_STATE_KEY="__haoriHistoryState__",ve.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ue=ve;const j=class j{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)&&(j.isHtmlElement(e)&&j.syncElement(e),e.querySelectorAll("*").forEach(t=>{j.syncElement(t)}))}static syncElement(e){const t=j.registrations.get(e),r=M.get(e);if(!r||!j.shouldObserve(r)){t&&(t.observer.disconnect(),j.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=j.resolveRoot(r),n=j.resolveRootMargin(r),s=j.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&j.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),j.registrations.delete(e));const o=new IntersectionObserver(c=>{const u=j.registrations.get(e);u&&c.forEach(d=>{!d.isIntersecting||u.running||j.isDisabled(u.fragment)||(u.running=!0,new se(u.fragment,"intersect").runWithResult().then(p=>{p&&u.once&&(u.observer.disconnect(),j.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=j.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),j.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(j.isHtmlElement(e)){const t=j.registrations.get(e);t&&(t.observer.disconnect(),j.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=j.registrations.get(t);r&&(r.observer.disconnect(),j.registrations.delete(t))})}static disconnectAll(){j.registrations.forEach(e=>{e.observer.disconnect()}),j.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!j.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${l.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=X.query(r,t,document);return j.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.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=`${l.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}};j.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),j.registrations=new Map;let be=j;const v=class v{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(v.isHtmlElement(e)&&v.syncElement(e),e.querySelectorAll("*").forEach(t=>{v.syncElement(t)}))}static syncElement(e){const t=v.registrations.get(e);if(!t&&!v.hasPollAttribute(e))return;const r=M.get(e);if(!(r instanceof D)||!v.shouldObserve(r)){t&&v.teardown(e,t);return}const i=v.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}v.teardown(e,t)}v.startPolling(e,r,i)}static cleanupTree(e){if(v.isHtmlElement(e)){const t=v.registrations.get(e);t&&v.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=v.registrations.get(t);r&&v.teardown(t,r)})}static disconnectAll(){v.registrations.forEach(e=>{v.clearTimers(e)}),v.registrations.clear(),v.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",v.visibilityListener),v.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${l.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!v.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
31
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new se(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(await v.restoreStateIfCleared(t),i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&O.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&O.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return P.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()})})).then(()=>{})}static async restoreStateIfCleared(e){v.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await v.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=X.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=M.get(a);o instanceof D&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let Ee=v;const mt="0.47.2";function qt(y){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>y()):Promise.resolve().then(y)}const L=class L{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)&&(L.isHtmlElement(e)&&L.syncElement(e),e.querySelectorAll("*").forEach(t=>{L.syncElement(t)}))}static syncElement(e){const t=L.registrations.get(e),r=M.get(e);if(!(r instanceof D)||!L.shouldObserve(r)){t&&(t.observer.disconnect(),L.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=L.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),L.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=L.resolveRoot(r),s=L.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=L.registrations.get(e);if(!u)return;let d=!1;c.forEach(p=>{const g=p.target;u.observedRows.has(g)&&(p.isIntersecting?u.visibleRows.has(g)||(u.visibleRows.add(g),d=!0):u.visibleRows.delete(g)&&(d=!0))}),d&&L.scheduleCompute(u)},{root:n,rootMargin:s,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};L.registrations.set(e,o),L.refreshRows(o)}static cleanupTree(e){if(L.isHtmlElement(e)){const t=L.registrations.get(e);t&&(t.observer.disconnect(),L.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=L.registrations.get(t);r&&(r.observer.disconnect(),L.registrations.delete(t))})}static disconnectAll(){L.registrations.forEach(e=>{e.observer.disconnect()}),L.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.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=X.query(r,t,document);return L.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?L.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof D&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=L.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));L.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,qt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();L.registrations.get(t)===e&&L.computeAndPublish(e)}))}static computeAndPublish(e){const t=L.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 c of i)c<a&&(a=c),c>o&&(o=c);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,L.publish(e,n))}static publish(e,t){const r=L.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);P.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:D.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let he=L;const Y=class Y{static disconnectMutationObservers(){Y._mutationObservers.forEach(e=>{e.disconnect()}),Y._mutationObservers.length=0}static async init(){if(Y._initialized)return;Y._initialized=!0,Y.disconnectMutationObservers(),D.setPendingMutationFlusher(()=>{Y.flushPendingMutations()});const e=new Ue;Y._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",i.reason),await K.wait(),document.body.setAttribute("data-haori-ready",""),Y.observe(document.head),Y.observe(document.body),be.syncTree(document.body),Ee.syncTree(document.body),he.syncTree(document.body)}finally{e.release()}O.ready(mt)}static getDispatcher(){return Y._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{Y.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),Y._mutationObservers.push(t)}static flushPendingMutations(){for(const e of Y._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(Y.isBindAttributeRecord),i=t.filter(n=>!Y.isBindAttributeRecord(n));r.length>0&&Y.processMutations(r,D.nextSequence()),i.length>0&&Promise.resolve().then(()=>{Y.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(Y.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(de)&&(r.attributeName==="disabled"||r.attributeName===de)||r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))||r.attributeName&&P.isAliasedAttributeReflection(i,r.attributeName))break;P.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t),be.syncElement(i),Ee.syncElement(i),he.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{be.cleanupTree(i),Ee.cleanupTree(i),he.cleanupTree(i),P.removeNode(i)}),Array.from(r.addedNodes).forEach(i=>{i.parentElement instanceof Element&&(P.addNode(i.parentElement,i),be.syncTree(i),Ee.syncTree(i),he.syncTree(i))}),r.target instanceof Element&&he.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?P.changeText(r.target,r.target.textContent):m.warn("[Haori]","Unsupported character data type:",r.target);break}default:m.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){m.error("[Haori]","Error processing mutation:",i)}}};Y._initialized=!1,Y._mutationObservers=[],Y._dispatcher=null;let Me=Y;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Me.init):Me.init();const Wt=()=>ce.waitForRenders(),jt=ce.enhancers;exports.Core=P;exports.Enhance=ne;exports.Env=l;exports.Form=N;exports.Fragment=M;exports.Haori=ce;exports.Log=m;exports.Queue=K;exports.default=ce;exports.enhancers=jt;exports.version=mt;exports.waitForRenders=Wt;
32
32
  //# sourceMappingURL=haori.cjs.js.map