haori 0.62.3 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +1,41 @@
1
- var Haori=function(){"use strict";const ye=class ye{static isEnabled(){return ye.devMode}static enable(){ye.devMode=!0}static disable(){ye.devMode=!1}static set(e){ye.devMode=e}};ye.devMode=!1;let q=ye;const Ve="embedded";function Je(b){return b==="embedded"||b==="demo"}function Tt(b){return b===null?null:Je(b)?b:Ve}const re=class re{static get strictBind(){return re._strictBind}static setStrictBind(e){re._strictBind=e}static get runtime(){return re._runtime}static setRuntime(e){re._runtime=Je(e)?e:Ve}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||re._prefix;re._prefix=r.endsWith("-")?r:r+"-";const i=Tt(e.getAttribute("data-runtime"));i!==null&&(re._runtime=i),re._strictBind=e.hasAttribute(`${re._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${re._prefix}dev`)){const r=(e.getAttribute(`${re._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 re._prefix}};re._prefix="data-",re._runtime=Ve,re._strictBind=!1;let c=re;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c.detect):c.detect());class g{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 Dt=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,Ze="new:",I=class I{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){g.error("[Haori]","Enhancer name is required.");return}if(!t||typeof t.init!="function"){g.error("[Haori]",`Enhancer "${r}" must have an init function.`);return}I.enhancers.set(r,t),I.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&I.forEachTarget(document.body,i=>{I.visited.has(i)&&I.applyElement(i)})}static setMutationCapture(e){I.mutationCapture=e}static has(e){return I.enhancers.has(e)}static applySubtree(e){I.forEachTarget(e,t=>{I.visited.add(t),I.applyElement(t)})}static isApplied(e){return(I.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){I.forEachTarget(e,r=>{I.refreshElement(r,t)})}static destroySubtree(e){I.forEachTarget(e,t=>{I.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${c.prefix}enhance],[${c.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){if(e.closest(`[${c.prefix}if-false]`))return;const t=I.instances.get(e)??null;I.names(e,`${c.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=I.enhancers.get(r);if(!i){I.warnUnknownName(r);return}I.run(`enhance "${r}"`,()=>{const n=i.init(e);I.appliedKeys(e).set(r,n)})}),I.names(e,`${c.prefix}enhance-new`).forEach(r=>{const i=`${Ze}${r}`;if(I.instances.get(e)?.has(i))return;const n=I.resolveGlobal(r);n!==null&&I.run(`enhance-new "${r}"`,()=>{const s=new n(e);I.appliedKeys(e).set(i,s)})})}static refreshElement(e,t){const r=I.instances.get(e);I.names(e,`${c.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const n=I.enhancers.get(i);!n||typeof n.refresh!="function"||I.run(`enhance "${i}" refresh`,()=>{n.refresh(e,r.get(i))})}),t&&I.applyElement(e)}static destroyElement(e){const t=I.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(Ze))return;const n=I.enhancers.get(i);!n||typeof n.destroy!="function"||I.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),I.instances.delete(e))}static appliedKeys(e){const t=I.instances.get(e);if(t)return t;const r=new Map;return I.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(!Dt.test(e))return g.error("[Haori]",`${c.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()&&!I.warnedMissingGlobals.has(e)&&(I.warnedMissingGlobals.add(e),g.warn("[Haori]",`${c.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!q.isEnabled()||I.warnedUnknownNames.has(e)||(I.warnedUnknownNames.add(e),g.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){const r=()=>{try{t()}catch(i){g.error("[Haori]",`${e} failed:`,i)}};I.mutationCapture?I.mutationCapture(r):r()}};I.enhancers=new Map,I.instances=new WeakMap,I.warnedUnknownNames=new Set,I.warnedMissingGlobals=new Set,I.visited=new WeakSet,I.mutationCapture=null;let te=I;const Qe="yyyy/MM/dd HH:mm",Nt="en-US",_e=1e4;function ue(b){return String(b).padStart(2,"0")}function et(b,e,t,r,i,n){return{yyyy:String(b).padStart(4,"0"),yy:ue(b%100),MM:ue(e),M:String(e),dd:ue(t),d:String(t),HH:ue(r),H:String(r),mm:ue(i),ss:ue(n)}}function tt(b,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(b)}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),l=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(l)?null:et(i,n,s,a,o,l)}function Ie(b,e=Qe,t){if(b==null||b==="")return"";const r=b instanceof Date?b:new Date(b);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=tt(r,t.trim()),i===null)return""}else i=et(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 Ft="yyyy-MM-dd";function rt(b=Qe,e){return Ie(new Date,b,e)}function it(b=0,e=Ft,t){const r=Number.isFinite(b)?Math.trunc(b):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const l=tt(new Date,i);if(l===null)return"";n=Number(l.yyyy),s=Number(l.MM),a=Number(l.dd)}else{const l=new Date;n=l.getFullYear(),s=l.getMonth()+1,a=l.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return Ie(o,e,"UTC")}function nt(b,e){if(b==null)return"";let t;if(typeof b=="number")t=b;else{const i=String(b).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(Nt,r).format(t)}function st(b,e,t){let r,i,n;if(e===void 0?(r=0,i=b,n=1):(r=b,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<_e;a+=n)s.push(a);else for(let a=r;a>i&&s.length<_e;a+=n)s.push(a);return s}function at(b,e,t={}){const r=Math.trunc(Number(b));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 h=0;h<s&&h<r;h+=1)a.add(h);for(let h=Math.max(0,r-s);h<r;h+=1)a.add(h);for(let h=Math.max(0,i-n);h<=Math.min(r-1,i+n);h+=1)a.add(h);const o=Array.from(a).sort((h,m)=>h-m),l=[];let u=null;for(const h of o){if(u!==null&&h-u>1)if(h-u===2){const m=u+1;l.push({page:m,label:m+1,active:m===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:h,label:h+1,active:h===i,ellipsis:!1}),u=h}return l}const kt=/^(\d{4})-(\d{1,2})$/,It=1200;function xe(b,e){const t=Number(b);return Number.isFinite(t)?Math.trunc(t):e}function Ce(b,e){if(typeof b!="string")return"";const t=kt.exec(b.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")}-${ue(o)}`}function xt(b){if(typeof b=="string"&&b.trim()!=="")return Ce(b,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${ue(e.getMonth()+1)}`}function ot(b,e){const t=Math.trunc(Number(b));if(!Number.isFinite(t)||t<0)return[];const r=xt(e);if(r==="")return[];const i=Math.min(t,It),n=[];for(let s=0;s<=i;s+=1){const a=Ce(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function lt(b,e){const t={start:0,end:0,total:0,empty:!0};if(!b||typeof b!="object")return t;const r=b,i=xe(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,xe(r.number,0)),s=Math.max(0,xe(r.size,0)),a=n*s,o=Math.min(a+1,i);let l;if(e!==void 0&&Number.isFinite(e))l=Math.max(0,Math.trunc(e));else{const h=xe(r.numberOfElements,NaN);l=Number.isFinite(h)?h:Math.min(s,i-a)}const u=Math.min(a+l,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function ct(b,e,t){if(!Array.isArray(b)||b.length===0)return null;const r=String(t),i=b.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function ut(b,e){if(!Array.isArray(b))return 0;let t=0;for(const r of b){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 dt(b,e){return e==null||b==null?String(b):String(b[e])}function ft(b,e){if(!Array.isArray(b))return[];const t=new Set,r=[];for(const i of b){const n=dt(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function ht(b,e){if(!Array.isArray(b))return[];const t=new Map,r=[];for(const i of b){const n=dt(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 Ct=Object.freeze({date:Ie,now:rt,today:it,number:nt,pages:at,range:st,monthAdd:Ce,monthRange:ot,pageSummary:lt,findBy:ct,sum:ut,distinct:ft,groupBy:ht});class qe{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1,this.channel=null}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),g.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){g.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){if(this.processing)return;const e=this.getChannel();e!==null?e.port2.postMessage(null):setTimeout(()=>{this.processQueue()},0)}getChannel(){return this.channel===null&&typeof MessageChannel<"u"&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>{this.processQueue()}),this.channel}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 qe.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const Ye=class Ye{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)}};Ye.ASYNC_QUEUE=new qe;let K=Ye;const T=class T{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,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 isForbiddenStorage(e){const t=globalThis.Storage;return t!==void 0&&e instanceof t}static getForbiddenBindingValueSet(){return this.forbiddenBindingValueSet===null&&(this.forbiddenBindingValueSet=new Set(this.getForbiddenBindingValues())),this.forbiddenBindingValueSet}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueSet=null,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,'"use strict"')}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0)return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),g.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 ${c.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
+ var Haori=function(){"use strict";const we=class we{static isEnabled(){return we.devMode}static enable(){we.devMode=!0}static disable(){we.devMode=!1}static set(e){we.devMode=e}};we.devMode=!1;let U=we;const Qe="embedded";function ut(f){return f==="embedded"||f==="demo"}function er(f){return f===null?null:ut(f)?f:Qe}function dt(f){const e=f.trim().toLowerCase();return e!=="false"&&e!=="off"&&e!=="0"}const ee=class ee{static get csp(){return ee._csp}static setCsp(e){ee._csp=e}static get strictBind(){return ee._strictBind}static setStrictBind(e){ee._strictBind=e}static get runtime(){return ee._runtime}static setRuntime(e){ee._runtime=ut(e)?e:Qe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||ee._prefix;ee._prefix=r.endsWith("-")?r:r+"-";const i=er(e.getAttribute("data-runtime"));i!==null&&(ee._runtime=i),ee._strictBind=e.hasAttribute(`${ee._prefix}strict-bind`);const s=e.getAttribute(`${ee._prefix}csp`);s!==null&&(ee._csp=dt(s))}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${ee._prefix}dev`)){U.set(dt(e.getAttribute(`${ee._prefix}dev`)??""));return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){U.set(!0);return}U.set(!1)}catch{}}static get prefix(){return ee._prefix}};ee._prefix="data-",ee._runtime=Qe,ee._strictBind=!1,ee._csp=!1;let c=ee;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c.detect):c.detect());class m{static info(e,...t){U.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){U.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const tr=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,ht="new:",I=class I{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}I.enhancers.set(r,t),I.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&I.forEachTarget(document.body,i=>{I.visited.has(i)&&I.applyElement(i)})}static setMutationCapture(e){I.mutationCapture=e}static has(e){return I.enhancers.has(e)}static applySubtree(e){I.forEachTarget(e,t=>{I.visited.add(t),I.applyElement(t)})}static isApplied(e){return(I.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){I.forEachTarget(e,r=>{I.refreshElement(r,t)})}static destroySubtree(e){I.forEachTarget(e,t=>{I.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${c.prefix}enhance],[${c.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){if(e.closest(`[${c.prefix}if-false]`))return;const t=I.instances.get(e)??null;I.names(e,`${c.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=I.enhancers.get(r);if(!i){I.warnUnknownName(r);return}I.run(`enhance "${r}"`,()=>{const s=i.init(e);I.appliedKeys(e).set(r,s)})}),I.names(e,`${c.prefix}enhance-new`).forEach(r=>{const i=`${ht}${r}`;if(I.instances.get(e)?.has(i))return;const s=I.resolveGlobal(r);s!==null&&I.run(`enhance-new "${r}"`,()=>{const n=new s(e);I.appliedKeys(e).set(i,n)})})}static refreshElement(e,t){const r=I.instances.get(e);I.names(e,`${c.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const s=I.enhancers.get(i);!s||typeof s.refresh!="function"||I.run(`enhance "${i}" refresh`,()=>{s.refresh(e,r.get(i))})}),t&&I.applyElement(e)}static destroyElement(e){const t=I.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(ht))return;const s=I.enhancers.get(i);!s||typeof s.destroy!="function"||I.run(`enhance "${i}" destroy`,()=>{s.destroy(e,r)})}),I.instances.delete(e))}static appliedKeys(e){const t=I.instances.get(e);if(t)return t;const r=new Map;return I.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(!tr.test(e))return m.error("[Haori]",`${c.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"?(U.isEnabled()&&!I.warnedMissingGlobals.has(e)&&(I.warnedMissingGlobals.add(e),m.warn("[Haori]",`${c.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!U.isEnabled()||I.warnedUnknownNames.has(e)||(I.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){const r=()=>{try{t()}catch(i){m.error("[Haori]",`${e} failed:`,i)}};I.mutationCapture?I.mutationCapture(r):r()}};I.enhancers=new Map,I.instances=new WeakMap,I.warnedUnknownNames=new Set,I.warnedMissingGlobals=new Set,I.visited=new WeakSet,I.mutationCapture=null;let se=I;const ft="yyyy/MM/dd HH:mm",rr="en-US",pt=1e4;function pe(f){return String(f).padStart(2,"0")}function gt(f,e,t,r,i,s){return{yyyy:String(f).padStart(4,"0"),yy:pe(f%100),MM:pe(e),M:String(e),dd:pe(t),d:String(t),HH:pe(r),H:String(r),mm:pe(i),ss:pe(s)}}function mt(f,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(f)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),s=Number(r.month),n=Number(r.day),a=Number(r.hour),o=Number(r.minute),l=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(l)?null:gt(i,s,n,a,o,l)}function He(f,e=ft,t){if(f==null||f==="")return"";const r=f instanceof Date?f:new Date(f);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=mt(r,t.trim()),i===null)return""}else i=gt(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const s=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(n,a)=>a!==void 0?a===""?"'":a:s[n])}const ir="yyyy-MM-dd";function yt(f=ft,e){return He(new Date,f,e)}function bt(f=0,e=ir,t){const r=Number.isFinite(f)?Math.trunc(f):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let s,n,a;if(i!==""){const l=mt(new Date,i);if(l===null)return"";s=Number(l.yyyy),n=Number(l.MM),a=Number(l.dd)}else{const l=new Date;s=l.getFullYear(),n=l.getMonth()+1,a=l.getDate()}const o=new Date(Date.UTC(s,n-1,a+r));return He(o,e,"UTC")}function Et(f,e){if(f==null)return"";let t;if(typeof f=="number")t=f;else{const i=String(f).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(rr,r).format(t)}function At(f,e,t){let r,i,s;if(e===void 0?(r=0,i=f,s=1):(r=f,i=e,s=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(s)||s===0)return[];r=Math.trunc(r),i=Math.trunc(i),s=Math.trunc(s);const n=[];if(s>0)for(let a=r;a<i&&n.length<pt;a+=s)n.push(a);else for(let a=r;a>i&&n.length<pt;a+=s)n.push(a);return n}function vt(f,e,t={}){const r=Math.trunc(Number(f));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),s=Math.max(0,Math.trunc(t.window??2)),n=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let d=0;d<n&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-n);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-s);d<=Math.min(r-1,i+s);d+=1)a.add(d);const o=Array.from(a).sort((d,y)=>d-y),l=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const y=u+1;l.push({page:y,label:y+1,active:y===i,ellipsis:!1})}else l.push({page:null,label:"…",active:!1,ellipsis:!0});l.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return l}const sr=/^(\d{4})-(\d{1,2})$/,nr=1200;function Ve(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function qe(f,e){if(typeof f!="string")return"";const t=sr.exec(f.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const s=Number.isFinite(e)?Math.trunc(e):0,n=r*12+(i-1)+s,a=Math.floor(n/12),o=n-a*12+1;return`${String(a).padStart(4,"0")}-${pe(o)}`}function ar(f){if(typeof f=="string"&&f.trim()!=="")return qe(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${pe(e.getMonth()+1)}`}function wt(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=ar(e);if(r==="")return[];const i=Math.min(t,nr),s=[];for(let n=0;n<=i;n+=1){const a=qe(r,-n);s.push({targetMonth:a,label:a.replace(/-/g,"/")})}return s}function St(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=Ve(r.totalElements??r.totalCount,0);if(i<=0)return t;const s=Math.max(0,Ve(r.number,0)),n=Math.max(0,Ve(r.size,0)),a=s*n,o=Math.min(a+1,i);let l;if(e!==void 0&&Number.isFinite(e))l=Math.max(0,Math.trunc(e));else{const d=Ve(r.numberOfElements,NaN);l=Number.isFinite(d)?d:Math.min(n,i-a)}const u=Math.min(a+l,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function Rt(f,e,t){if(!Array.isArray(f)||f.length===0)return null;const r=String(t),i=f.find(s=>s!=null&&String(s[e])===r);return i===void 0?null:i}function Tt(f,e){if(!Array.isArray(f))return 0;let t=0;for(const r of f){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const s=typeof i=="number"?i:Number(i);Number.isNaN(s)||(t+=s)}return t}function kt(f,e){return e==null||f==null?String(f):String(f[e])}function Dt(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const s=kt(i,e);t.has(s)||(t.add(s),r.push(i))}return r}function xt(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const s=kt(i,e),n=t.get(s);if(n===void 0){const a=i==null?i:i[e];t.set(s,r.length),r.push({key:a,items:[i]})}else r[n].items.push(i)}return r}const or=Object.freeze({date:He,now:yt,today:bt,number:Et,pages:vt,range:At,monthAdd:qe,monthRange:wt,pageSummary:St,findBy:Rt,sum:Tt,distinct:Dt,groupBy:xt});class _e{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1,this.channel=null}enqueue(e,t=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:e,timestamp:performance.now(),promise:s,resolve:r,reject:i};return t?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}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(){if(this.processing)return;const e=this.getChannel();e!==null?e.port2.postMessage(null):setTimeout(()=>{this.processQueue()},0)}getChannel(){return this.channel===null&&typeof MessageChannel<"u"&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>{this.processQueue()}),this.channel}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 _e.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const ot=class ot{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)}};ot.ASYNC_QUEUE=new _e;let Y=ot;const Nt=new Set(["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"]),We=new Set(["eval","arguments"]),It=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),je=new Set(["constructor","__proto__","prototype"]),Ke=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"]),et=new Set(["enum","implements","interface","package","private","protected","public","static","super"]),Ft=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"]),lr=[">>>","===","!==","...","**","?.","??","&&","||","==","!=","<=",">=","<<",">>","=>","++","--","(",")","[","]","{","}",".",",","?",":","+","-","*","/","%","!","<",">"],cr={"==":1,"!=":1,"===":1,"!==":1,"<":2,">":2,"<=":2,">=":2,"<<":3,">>":3,">>>":3,"+":4,"-":4,"*":5,"/":5,"%":5},ur=new Set(["undefined","NaN","Infinity"]);function tt(f){return f===`
2
+ `||f==="\r"||f==="\u2028"||f==="\u2029"}function dr(f){return f!==void 0&&/[A-Za-z_$]/.test(f)}function Ct(f){return f!==void 0&&/[A-Za-z0-9_$]/.test(f)}function X(f,e){return new SyntaxError(`${f} (at position ${e})`)}const J={comment:"Comments are not allowed in expressions",unexpectedCharacter:f=>`Unexpected character '${f}'`,unterminatedRegExp:"Unterminated regular expression",invalidRegExp:f=>`Invalid regular expression: ${f}`,numericSeparator:"Numeric separators are not allowed here",invalidToken:"Invalid or unexpected token",octalLiteral:"Octal literals are not allowed in strict mode",unterminatedString:"Unterminated string literal",octalEscape:"Octal escape sequences are not allowed in strict mode",invalidHex:"Invalid hexadecimal escape sequence",invalidUnicode:"Invalid Unicode escape sequence",unexpectedEnd:"Unexpected end of expression",unexpectedToken:f=>`Unexpected token '${f}'`,notInExpressions:f=>`'${f}' cannot be used in expressions`,notParameter:f=>`'${f}' cannot be used as a parameter`,notProperty:f=>`'${f}' cannot be used as a property`,duplicateParameter:"Duplicate parameter name",blockBody:"Arrow functions with a block body are not supported",mixNullish:"Cannot mix ?? with || or &&",unaryExponent:"Unary operator used immediately before exponentiation expression",invalidUpdate:"Invalid left-hand side expression in update operation"};class hr{constructor(e){this.source=e,this.position=0}lex(){const e=this.source;let t=!1;for(;this.position<e.length;){const n=e[this.position];if(tt(n))t=!0;else if(!/\s/.test(n))break;this.position+=1}const r=this.position;if(r>=e.length)return{type:"eof",value:"",start:r,end:r,newlineBefore:t};const i=e[r],s=e[r+1];if(/[0-9]/.test(i))return this.readNumber(r,t);if(i==='"'||i==="'")return this.readString(r,t);if(dr(i)){let n=r+1;for(;Ct(e[n]);)n+=1;return this.position=n,{type:"identifier",value:e.slice(r,n),start:r,end:n,newlineBefore:t}}if(i==="/"&&(s==="/"||s==="*"))throw X(J.comment,r);for(const n of lr)if(e.startsWith(n,r))return this.position=r+n.length,{type:"punct",value:n,start:r,end:this.position,newlineBefore:t};throw X(J.unexpectedCharacter(i),r)}readRegExp(e,t){const r=this.source;let i=e+1,s=!1;for(;;){const l=r[i];if(l===void 0||tt(l))throw X(J.unterminatedRegExp,e);if(l==="\\"){const u=r[i+1];if(tt(u))throw X(J.unterminatedRegExp,e);i+=2;continue}if(l==="[")s=!0;else if(l==="]")s=!1;else if(l==="/"&&!s)break;i+=1}const n=r.slice(e+1,i);i+=1;const a=i;for(;Ct(r[i]);)i+=1;const o=r.slice(a,i);try{new RegExp(n,o)}catch(l){throw X(J.invalidRegExp(l.message),e)}return this.position=i,{type:"regexp",value:r.slice(e,i),literal:{pattern:n,flags:o},start:e,end:i,newlineBefore:t}}readDigits(e,t){const r=this.source;let i=e;for(;;){const s=r[i];if(s!==void 0&&t.test(s)){i+=1;continue}if(s==="_"){const n=r[i-1],a=r[i+1];if(!t.test(n)||a===void 0||!t.test(a))throw X(J.numericSeparator,i);i+=1;continue}return i}}readNumber(e,t){const r=this.source;let i=e,s=!1;const n=r[e+1];if(r[e]==="0"&&/[xXoObB]/.test(n)){const o=/[xX]/.test(n)?/[0-9a-fA-F]/:/[oO]/.test(n)?/[0-7]/:/[01]/;if(i=this.readDigits(e+2,o),i===e+2)throw X(J.invalidToken,e);r[i]==="n"&&(s=!0,i+=1)}else{if(r[e]==="0"&&/[0-9_]/.test(r[e+1]))throw X(J.octalLiteral,e);if(i=this.readDigits(e,/[0-9]/),r[i]==="."&&(i+=1,/[0-9]/.test(r[i])&&(i=this.readDigits(i,/[0-9]/))),r[i]==="e"||r[i]==="E"){if(i+=1,(r[i]==="+"||r[i]==="-")&&(i+=1),!/[0-9]/.test(r[i]))throw X(J.invalidToken,e);i=this.readDigits(i,/[0-9]/)}r[i]==="n"&&(s=!0,i+=1)}const a=r.slice(e,i).replace(/_/g,"");return this.position=i,{type:"number",value:r.slice(e,i),literal:s?BigInt(a.slice(0,-1)):Number(a),start:e,end:i,newlineBefore:t}}readHex(e,t){const r=this.source.slice(e,e+t);return/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):null}readString(e,t){const r=this.source,i=r[e];let s=e+1,n="";for(;;){const a=r[s];if(a===void 0||a===`
3
+ `||a==="\r")throw X(J.unterminatedString,e);if(a===i){s+=1;break}if(a!=="\\"){n+=a,s+=1;continue}const o=r[s+1],l=s;switch(s+=2,o){case void 0:throw X(J.unterminatedString,e);case"n":n+=`
4
+ `;break;case"t":n+=" ";break;case"r":n+="\r";break;case"b":n+="\b";break;case"f":n+="\f";break;case"v":n+="\v";break;case"0":if(/[0-9]/.test(r[s]))throw X(J.octalEscape,l);n+="\0";break;case"x":{const u=this.readHex(s,2);if(u===null)throw X(J.invalidHex,l);n+=String.fromCharCode(u),s+=2;break}case"u":{if(r[s]==="{"){const d=r.indexOf("}",s),y=d<0?s:d,b=r.slice(s+1,y),E=/^[0-9a-fA-F]+$/.test(b)?parseInt(b,16):NaN;if(!(E<=1114111))throw X(J.invalidUnicode,l);n+=String.fromCodePoint(E),s=d+1;break}const u=this.readHex(s,4);if(u===null)throw X(J.invalidUnicode,l);n+=String.fromCharCode(u),s+=4;break}case"\r":r[s]===`
5
+ `&&(s+=1);break;case`
6
+ `:case"\u2028":case"\u2029":break;default:if(/[1-9]/.test(o))throw X(J.octalEscape,l);n+=o}}return this.position=s,{type:"string",value:r.slice(e,s),literal:n,start:e,end:s,newlineBefore:t}}}class fr{constructor(e){this.lastEnd=0,this.lexer=new hr(e),this.token=this.lexer.lex()}parseProgram(){const e=this.parseExpression();if(this.token.type!=="eof")throw this.unexpected();return e}unexpected(){const e=this.token;return e.type==="eof"?X(J.unexpectedEnd,e.start):X(J.unexpectedToken(e.value),e.start)}advance(){const e=this.token;return this.lastEnd=e.end,this.token=this.lexer.lex(),e}is(e){return this.token.type!=="punct"?!1:this.token.value===e}eat(e){return this.is(e)?(this.advance(),!0):!1}expect(e){if(!this.eat(e))throw this.unexpected()}save(){return{position:this.lexer.position,token:this.token,lastEnd:this.lastEnd}}restore(e){this.lexer.position=e.position,this.token=e.token,this.lastEnd=e.lastEnd}finish(e,t){return{...e,start:t,end:this.lastEnd}}checkReferenceName(e,t){if(Ke.has(e)||We.has(e)||et.has(e))throw X(J.notInExpressions(e),t)}checkBindingName(e,t){if(this.checkReferenceName(e,t),e==="true"||e==="false"||e==="null")throw X(J.notParameter(e),t)}checkPropertyName(e,t){if(Ke.has(e)||We.has(e)||je.has(e))throw X(J.notProperty(e),t)}parseExpression(){const e=this.token.start,t=this.parseAssignment();if(!this.is(","))return t;const r=[t];for(;this.eat(",");)r.push(this.parseAssignment());return this.finish({type:"Sequence",expressions:r},e)}parseAssignment(){return this.tryParseArrow()??this.parseConditional()}tryParseArrow(){const e=this.token,t=e.start;if(e.type==="identifier"){const r=this.save();if(this.advance(),this.is("=>")&&!this.token.newlineBefore){this.checkBindingName(e.value,e.start);const i=[{type:"BindingIdentifier",name:e.value}];return this.parseArrowBody(i,null,!1,t)}if(e.value==="async"&&!this.token.newlineBefore){const i=this.token;if(i.type==="identifier"){if(this.advance(),this.is("=>")&&!this.token.newlineBefore){this.checkBindingName(i.value,i.start);const s=[{type:"BindingIdentifier",name:i.value}];return this.parseArrowBody(s,null,!0,t)}}else{const s=this.tryParseParenthesizedArrow(!0,t);if(s!==null)return s}}return this.restore(r),null}return this.is("(")?this.tryParseParenthesizedArrow(!1,t):null}tryParseParenthesizedArrow(e,t){const r=this.save();let i;try{i=this.parseParameters()}catch{return this.restore(r),null}return!this.is("=>")||this.token.newlineBefore?(this.restore(r),null):this.parseArrowBody(i.params,i.rest,e,t)}parseParameters(){this.expect("(");const e=[];let t=null;for(;!this.is(")");){if(this.eat("...")){t=this.parseBindingTarget();break}if(e.push(this.parseBindingTarget()),!this.eat(","))break}return this.expect(")"),{params:e,rest:t}}parseBindingTarget(){const e=this.token;if(e.type==="identifier")return this.checkBindingName(e.value,e.start),this.advance(),{type:"BindingIdentifier",name:e.value};if(this.eat("{")){const t=[];let r=null;for(;!this.is("}");){if(this.eat("...")){const n=this.token;if(n.type!=="identifier")throw this.unexpected();this.checkBindingName(n.value,n.start),this.advance(),r=n.value;break}const i=this.token,s=this.parsePropertyKey();if(this.eat(":"))t.push({key:s,value:this.parseBindingTarget()});else{if(i.type!=="identifier")throw this.unexpected();this.checkBindingName(s,i.start),t.push({key:s,value:{type:"BindingIdentifier",name:s}})}if(!this.eat(","))break}return this.expect("}"),{type:"ObjectPattern",properties:t,rest:r}}if(this.eat("[")){const t=[];let r=null;for(;!this.is("]");){if(this.eat(",")){t.push(null);continue}if(this.eat("...")){r=this.parseBindingTarget();break}t.push(this.parseBindingTarget()),this.is("]")||this.expect(",")}return this.expect("]"),{type:"ArrayPattern",elements:t,rest:r}}throw this.unexpected()}collectBoundNames(e,t){switch(e.type){case"BindingIdentifier":t.push(e.name);return;case"ObjectPattern":e.properties.forEach(r=>this.collectBoundNames(r.value,t)),e.rest!==null&&t.push(e.rest);return;case"ArrayPattern":e.elements.forEach(r=>{r!==null&&this.collectBoundNames(r,t)}),e.rest!==null&&this.collectBoundNames(e.rest,t);return}}parseArrowBody(e,t,r,i){const s=[];if(e.forEach(a=>this.collectBoundNames(a,s)),t!==null&&this.collectBoundNames(t,s),new Set(s).size!==s.length)throw X(J.duplicateParameter,i);if(this.expect("=>"),this.is("{"))throw X(J.blockBody,this.token.start);const n=this.parseAssignment();return this.finish({type:"Arrow",params:e,rest:t,body:n,async:r},i)}parseConditional(){const e=this.token.start,t=this.parseShortCircuit();if(!this.eat("?"))return t;const r=this.parseAssignment();this.expect(":");const i=this.parseAssignment();return this.finish({type:"Conditional",test:t,consequent:r,alternate:i},e)}parseShortCircuit(){const e=this.token.start;let t=this.parseLogical("||");if(!this.is("??"))return t;if(t.type==="Logical"&&!t.paren)throw X(J.mixNullish,this.token.start);for(;this.eat("??");){const r=this.parseBinary(1);t=this.finish({type:"Logical",operator:"??",left:t,right:r},e)}return t}parseLogical(e){const t=this.token.start,r=()=>e==="||"?this.parseLogical("&&"):this.parseBinary(1);let i=r();for(;this.eat(e);){const s=r();i=this.finish({type:"Logical",operator:e,left:i,right:s},t)}return i}parseBinary(e){const t=this.token.start;let r=this.parseExponent();for(;;){const i=this.token,s=i.type==="punct"?cr[i.value]:void 0;if(s===void 0||s<e)return r;this.advance();const n=this.parseBinary(s+1);r=this.finish({type:"Binary",operator:i.value,left:r,right:n},t)}}parseExponent(){const e=this.token.start,t=this.parseUnary();if(!this.is("**"))return t;if(t.type==="Unary"&&!t.paren)throw X(J.unaryExponent,this.token.start);this.advance();const r=this.parseExponent();return this.finish({type:"Binary",operator:"**",left:t,right:r},e)}toUpdateTarget(e){if(e.type!=="Identifier")throw X(J.invalidUpdate,e.start);return e}parseUnary(){const e=this.token.start;if(this.is("!")||this.is("-")||this.is("+")){const t=this.advance().value,r=this.parseUnary();return this.finish({type:"Unary",operator:t,argument:r},e)}if(this.is("++")||this.is("--")){const t=this.advance().value,r=this.toUpdateTarget(this.parseUnary());return this.finish({type:"Update",operator:t,prefix:!0,argument:r},e)}return this.parsePostfix()}parsePostfix(){const e=this.token.start,t=this.parseCallOrMember();if((this.is("++")||this.is("--"))&&!this.token.newlineBefore){const r=this.toUpdateTarget(t),i=this.advance().value;return this.finish({type:"Update",operator:i,prefix:!1,argument:r},e)}return t}isImplicitlyOptionalCall(e){if(e.paren)return!0;switch(e.type){case"Identifier":return!ur.has(e.name);case"Member":case"Call":return!0;default:return!1}}parseArguments(){this.expect("(");const e=[];for(;!this.is(")")&&(e.push(this.parseElement()),!!this.eat(",")););return this.expect(")"),e}parseElement(){const e=this.token.start;return this.eat("...")?{type:"Spread",argument:this.parseAssignment(),start:e,end:this.lastEnd}:this.parseAssignment()}parseMemberName(){const e=this.token;if(e.type!=="identifier")throw this.unexpected();return this.checkPropertyName(e.value,e.start),this.advance(),e.value}parseCallOrMember(){const e=this.token.start;let t=this.parsePrimary();for(;;)if(this.eat(".")){const r=this.parseMemberName();t=this.finish({type:"Member",object:t,property:r,computed:!1},e)}else if(this.eat("?."))if(this.is("(")){const r=this.parseArguments();t=this.finish({type:"Call",callee:t,args:r,optional:!0},e)}else if(this.eat("[")){const r=this.parseExpression();this.expect("]"),t=this.finish({type:"Member",object:t,property:r,computed:!0},e)}else{const r=this.parseMemberName();t=this.finish({type:"Member",object:t,property:r,computed:!1},e)}else if(this.eat("[")){const r=this.parseExpression();this.expect("]"),t=this.finish({type:"Member",object:t,property:r,computed:!0},e)}else if(this.is("(")){const r=this.isImplicitlyOptionalCall(t),i=this.parseArguments();t=this.finish({type:"Call",callee:t,args:i,optional:r},e)}else return t}parsePropertyKey(){const e=this.token;if(e.type==="identifier")return this.checkPropertyName(e.value,e.start),this.advance(),e.value;if(e.type==="string"){const t=e.literal;if(je.has(t))throw X(J.notProperty(t),e.start);return this.advance(),t}if(e.type==="number")return this.advance(),String(e.literal);throw this.unexpected()}parseObject(){const e=this.token.start;this.expect("{");const t=[];for(;!this.is("}");){if(this.eat("..."))t.push({kind:"spread",argument:this.parseAssignment()});else{const r=this.token,i=this.parsePropertyKey();if(this.eat(":"))t.push({kind:"init",key:i,value:this.parseAssignment()});else{if(r.type!=="identifier"||i==="true"||i==="false"||i==="null")throw this.unexpected();this.checkReferenceName(i,r.start),t.push({kind:"init",key:i,value:{type:"Identifier",name:i,start:r.start,end:r.end}})}}if(!this.eat(","))break}return this.expect("}"),this.finish({type:"Object",properties:t},e)}parseArray(){const e=this.token.start;this.expect("[");const t=[];for(;!this.is("]");){if(this.eat(",")){t.push(null);continue}t.push(this.parseElement()),this.is("]")||this.expect(",")}return this.expect("]"),this.finish({type:"Array",elements:t},e)}parsePrimary(){const e=this.token,t=e.start;switch(e.type){case"number":case"string":return this.advance(),this.finish({type:"Literal",value:e.literal},t);case"identifier":return this.advance(),e.value==="true"||e.value==="false"?this.finish({type:"Literal",value:e.value==="true"},t):e.value==="null"?this.finish({type:"Literal",value:null},t):(this.checkReferenceName(e.value,e.start),this.finish({type:"Identifier",name:e.value},t));case"punct":break;default:throw this.unexpected()}if(this.is("/")){this.token=this.lexer.readRegExp(e.start,e.newlineBefore);const r=this.advance().literal;return this.finish({type:"RegExp",pattern:r.pattern,flags:r.flags},t)}if(this.eat("(")){const r=this.parseExpression();return this.expect(")"),{...r,paren:!0}}if(this.is("["))return this.parseArray();if(this.is("{"))return this.parseObject();throw this.unexpected()}}function pr(f){return new fr(f).parseProgram()}class Mt extends ReferenceError{constructor(e){super(`${e} is not defined`),this.identifier=e}}const $t=new Map([["undefined",void 0],["NaN",NaN],["Infinity",1/0]]);function Pt(f,e){return Object.prototype.propertyIsEnumerable.call(f,e)}function Lt(f){const e=typeof f=="symbol"?f:String(f);return je.has(e)?"undefined":e}function gr(f){return typeof f=="bigint"?f:Number(f)}function Ot(f){return f[Symbol.iterator]()}function Bt(f,e,t){const r=Object(e);for(const i of Reflect.ownKeys(r)){if(t?.has(i))continue;Reflect.getOwnPropertyDescriptor(r,i)?.enumerable&&Object.defineProperty(f,i,{value:r[i],writable:!0,enumerable:!0,configurable:!0})}}const lt=class lt{static compile(e){const t=this.COMPILE_CACHE.get(e);if(typeof t=="string")throw new SyntaxError(t);if(t!==void 0)return t;let r;try{const i=pr(e);r={expression:e,evaluator:this.compileNode(i,null)}}catch(i){throw i instanceof SyntaxError&&this.COMPILE_CACHE.set(e,i.message),i}return this.COMPILE_CACHE.set(e,r),r}static run(e,t,r={}){const i={slots:[],parent:null,run:{bindings:t,overlay:null,missingIdentifier:r.missingIdentifier??"throw"}};return e.evaluator(i)}static evaluate(e,t={},r={}){return this.run(this.compile(e),t,r)}static compileNode(e,t){switch(e.type){case"Literal":{const r=e.value;return()=>r}case"RegExp":{const{pattern:r,flags:i}=e;return()=>new RegExp(r,i)}case"Identifier":return this.compileIdentifier(e.name,t);case"Array":return this.compileArray(e,t);case"Object":return this.compileObject(e,t);case"Member":return this.compileMember(e,t);case"Call":return this.compileCall(e,t);case"Unary":{const r=this.compileNode(e.argument,t);switch(e.operator){case"!":return i=>!r(i);case"-":return i=>-r(i);default:return i=>+r(i)}}case"Update":return this.compileUpdate(e,t);case"Binary":return this.compileBinary(e.operator,this.compileNode(e.left,t),this.compileNode(e.right,t));case"Logical":{const r=this.compileNode(e.left,t),i=this.compileNode(e.right,t);switch(e.operator){case"&&":return s=>{const n=r(s);return n&&i(s)};case"||":return s=>{const n=r(s);return n||i(s)};default:return s=>{const n=r(s);return n??i(s)}}}case"Conditional":{const r=this.compileNode(e.test,t),i=this.compileNode(e.consequent,t),s=this.compileNode(e.alternate,t);return n=>r(n)?i(n):s(n)}case"Sequence":{const r=e.expressions.map(i=>this.compileNode(i,t));return i=>{let s;for(const n of r)s=n(i);return s}}case"Arrow":return this.compileArrow(e,t)}}static findSlot(e,t){let r=0;for(let i=t;i!==null;i=i.parent){const s=i.names.get(e);if(s!==void 0)return{depth:r,slot:s};r+=1}return null}static outerFrame(e,t){let r=e;for(let i=0;i<t;i+=1)r=r.parent;return r}static classify(e){return It.has(e)?"rebindable":Nt.has(e)?"forbidden":$t.has(e)?"constant":Ft.has(e)?"builtin":"free"}static missing(e,t){if(e.missingIdentifier==="throw")throw new Mt(t)}static compileIdentifier(e,t){const r=this.findSlot(e,t);if(r!==null){const{depth:s,slot:n}=r;return s===0?a=>a.slots[n]:a=>this.outerFrame(a,s).slots[n]}const i=this.classify(e);return i==="forbidden"?()=>{}:s=>{const n=s.run;if(n.overlay!==null&&n.overlay.has(e))return n.overlay.get(e);if(Pt(n.bindings,e))return n.bindings[e];switch(i){case"rebindable":case"constant":return $t.get(e);case"builtin":return globalThis[e];default:return this.missing(n,e)}}}static compileUpdate(e,t){const r=e.argument.name,i=e.operator==="++"?1:-1,s=e.prefix,n=u=>{const d=gr(u),y=typeof d=="bigint"?d+BigInt(i):d+i;return[d,y]},a=this.findSlot(r,t);if(a!==null){const{depth:u,slot:d}=a;return y=>{const b=this.outerFrame(y,u),[E,A]=n(b.slots[d]);return b.slots[d]=A,s?A:E}}const o=this.classify(r),l=this.compileIdentifier(r,null);return u=>{const d=u.run;if(!(o!=="forbidden"&&Pt(d.bindings,r))&&o!=="free")throw new TypeError(`Assignment to constant variable '${r}'.`);const[b,E]=n(l(u));return d.overlay===null&&(d.overlay=new Map),d.overlay.set(r,E),s?E:b}}static compileBinary(e,t,r){const i=t,s=r;switch(e){case"+":return n=>i(n)+s(n);case"-":return n=>i(n)-s(n);case"*":return n=>i(n)*s(n);case"/":return n=>i(n)/s(n);case"%":return n=>i(n)%s(n);case"**":return n=>i(n)**s(n);case"<<":return n=>i(n)<<s(n);case">>":return n=>i(n)>>s(n);case">>>":return n=>i(n)>>>s(n);case"<":return n=>i(n)<s(n);case">":return n=>i(n)>s(n);case"<=":return n=>i(n)<=s(n);case">=":return n=>i(n)>=s(n);case"==":return n=>t(n)==r(n);case"!=":return n=>t(n)!=r(n);case"===":return n=>t(n)===r(n);default:return n=>t(n)!==r(n)}}static compileMember(e,t){const r=this.compileNode(e.object,t);if(!e.computed){const s=e.property;return n=>{const a=r(n);return a?.[s]}}const i=this.compileNode(e.property,t);return s=>{const n=r(s);if(n!=null)return n[Lt(i(s))]}}static compileElements(e,t){const r=e.map(i=>i===null?null:i.type==="Spread"?{spread:!0,evaluate:this.compileNode(i.argument,t)}:{spread:!1,evaluate:this.compileNode(i,t)});return i=>{const s=[];let n=0;for(const a of r)if(a===null)n+=1;else if(a.spread){const o=Ot(a.evaluate(i));for(;;){const l=o.next();if(l.done)break;s[n]=l.value,n+=1}}else s[n]=a.evaluate(i),n+=1;return s.length=n,s}}static compileArray(e,t){return this.compileElements(e.elements,t)}static compileObject(e,t){const r=e.properties.map(i=>i.kind==="init"?{key:i.key,evaluate:this.compileNode(i.value,t)}:{key:null,evaluate:this.compileNode(i.argument,t)});return i=>{const s={};for(const n of r)n.key===null?Bt(s,n.evaluate(i),null):s[n.key]=n.evaluate(i);return s}}static compileCall(e,t){const r=this.compileElements(e.args,t),i=e.optional,s=(o,l,u)=>{if(!(i&&o==null))return Reflect.apply(o,l,r(u))},n=e.callee;if(n.type==="Member"){const o=this.compileNode(n.object,t),l=n.computed?null:n.property,u=n.computed?this.compileNode(n.property,t):null;return d=>{const y=o(d);if(y==null)return;const b=u===null?l:Lt(u(d));return s(y[b],y,d)}}const a=this.compileNode(n,t);return o=>s(a(o),void 0,o)}static compilePattern(e,t){switch(e.type){case"BindingIdentifier":{const r=t.names.get(e.name);return(i,s)=>{i.slots[r]=s}}case"ObjectPattern":{const r=e.properties.map(n=>({key:n.key,bind:this.compilePattern(n.value,t)})),i=e.rest===null?null:t.names.get(e.rest),s=new Set(r.map(n=>n.key));return(n,a)=>{if(a==null){const o=String(a);throw new TypeError(`Cannot destructure '${o}' as it is ${o}.`)}for(const o of r)o.bind(n,a[o.key]);if(i!==null){const o={};Bt(o,a,s),n.slots[i]=o}}}case"ArrayPattern":{const r=e.elements.map(s=>s===null?null:this.compilePattern(s,t)),i=e.rest===null?null:this.compilePattern(e.rest,t);return(s,n)=>{const a=Ot(n);let o=!1;try{for(const l of r){let u;if(!o){const d=a.next();o=d.done===!0,u=o?void 0:d.value}l?.(s,u)}if(i!==null){const l=[];for(;!o;){const u=a.next();o=u.done===!0,o||l.push(u.value)}i(s,l)}}finally{o||a.return?.()}}}}}static assignSlots(e,t){switch(e.type){case"BindingIdentifier":t.set(e.name,t.size);return;case"ObjectPattern":e.properties.forEach(r=>this.assignSlots(r.value,t)),e.rest!==null&&t.set(e.rest,t.size);return;case"ArrayPattern":e.elements.forEach(r=>{r!==null&&this.assignSlots(r,t)}),e.rest!==null&&this.assignSlots(e.rest,t);return}}static compileArrow(e,t){const r={names:new Map,parent:t};e.params.forEach(l=>this.assignSlots(l,r.names)),e.rest!==null&&this.assignSlots(e.rest,r.names);const i=e.params.map(l=>this.compilePattern(l,r)),s=e.rest===null?null:this.compilePattern(e.rest,r),n=this.compileNode(e.body,r),a=i.length,o=e.async;return l=>{const u=y=>{const b={slots:[],parent:l,run:l.run};for(let E=0;E<a;E+=1)i[E](b,y[E]);return s!==null&&s(b,y.slice(a)),n(b)},d=o?async(...y)=>u(y):(...y)=>u(y);return Object.defineProperty(d,"length",{value:a}),d}}};lt.COMPILE_CACHE=new Map;let Me=lt;const T=class T{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,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 isForbiddenStorage(e){const t=globalThis.Storage;return t!==void 0&&e instanceof t}static getForbiddenBindingValueSet(){return this.forbiddenBindingValueSet===null&&(this.forbiddenBindingValueSet=new Set(this.getForbiddenBindingValues())),this.forbiddenBindingValueSet}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueSet=null,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&&c.csp)r=!this.STRICT_PARAMETER_RESERVED_WORDS.has(e);else if(r)try{new Function(e,'"use strict"')}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0)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 ${c.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
7
  `)}static buildBuiltinConstants(e,t){const r=this.extractFreeIdentifiers(e).filter(i=>this.ALLOWED_GLOBAL_IDENTIFIERS.has(i)&&!t.has(i));return r.length===0?"":`const ${r.map(i=>`${i} = this.${i}`).join(", ")};
3
- `}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,l=0;for(let u=s-1;u>=0;u-=1){const h=i[u].value;if(h===")"||h==="]"||h==="}"){o+=1,h===")"&&(l+=1);continue}if(h==="("||h==="["||h==="{"){if(o-=1,h==="("&&(l-=1),o===0)break;continue}l===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?"":`
4
- let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),g.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 startsArrowParameters(e,t){const r=e.findIndex((i,n)=>n>t&&i.value===")");return e[r+1]?.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(let a=0;a<r.length;a+=1){const o=r[a];o.type==="operator"&&s?.value!=="?."&&(o.value==="."?n.push({start:o.position,end:o.position+1,text:"?."}):(o.value==="["&&this.startsMemberAccess(s)||o.value==="("&&this.startsCall(s)&&!this.startsArrowParameters(r,a))&&n.push({start:o.position,end:o.position,text:"?."})),s=o}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 l=this.startsMemberAccess(a);s.push(l),l&&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 l=n[o];i=i.slice(0,l.start)+l.text+i.slice(l.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||this.evaluatingForDiagnosis)){if(c.strictBind){g.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(),g.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(!this.evaluatingForDiagnosis){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}
5
- ${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&g.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 isReservedBindingKey(e){return e.startsWith("_")}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.runEvaluator(e,n,i);return typeof s=="boolean"?s: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 g.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};const r=this.getExpressionProfile(e);if(r.dangerous){const y=this.detectDisallowedKeywords(e);if(y.length>0){const E=y.some(A=>A==="function"||A==="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.";g.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+y.join(", ")+"."+E)}else g.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const i=this.collectForbiddenKeys(t);if(i.length>0){const y=i.join(",");this.loggedForbiddenKeySignatures.has(y)||(this.loggedForbiddenKeySignatures.add(y),this.scheduleForbiddenKeyLogReset(),g.error("[Haori]","Binding keys are reserved and ignored: "+i.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const n=r.referencesBuiltinData,s=n?null:this.getReferencedNames(e);if(this.containsForbiddenReferencedValues(t,s))return g.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const a=r.referencesBuiltins;a&&this.BUILTIN_NAMESPACE in t&&g.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const o={};for(const y of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(y)||(o[y]=t[y]);a&&(n?o[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...o}}:o[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(o),q.isEnabled()&&this.recordSuppliedIdentifiers(o);const l=r.allowMissingIdentifierRecovery,u=this.extractFreeIdentifiers(e).filter(y=>!(y in o)&&!this.FORBIDDEN_NAMES.includes(y)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(y));let h=null;if(q.isEnabled()){const y=this.extractBoundIdentifiers(e);h=y.size===0?u:u.filter(E=>!y.has(E))}const m=this.evaluateWithShadowing(e,o,u,l);return h!==null&&this.recordScopeMissingIdentifiers(typeof m.value=="boolean"?h.filter(y=>!this.isReservedBindingKey(y)):h,e),m}static evaluateWithShadowing(e,t,r,i){i&&r.forEach(s=>{t[s]=void 0});const n=i?[]:r;for(let s=0;s<=this.MAX_IDENTIFIER_RECOVERY_COUNT;s+=1){const a=this.prepareEvaluator(e,t,n);if(a.compileFailed||a.evaluator===null)return{value:null,unresolvedReference:!1};try{const o=this.runEvaluator(e,a,t);return o===void 0&&this.warnBlockedIdentifiers(e),{value:o,unresolvedReference:o===void 0}}catch(o){if(i&&o instanceof ReferenceError){const l=this.extractMissingIdentifier(o);if(l!==null&&this.canRecoverMissingIdentifier(l,t)){t[l]=void 0;continue}}if(this.warnBlockedIdentifiers(e),o instanceof ReferenceError&&n.length>0){const l=this.evaluateAsCondition(e,t,n);return l!==void 0?{value:l,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(o,n),e),{value:void 0,unresolvedReference:!0})}return g.error("[Haori]","Expression evaluation error:",e,o),o instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return g.error("[Haori]","Failed to recover missing identifiers:",e,t),{value:void 0,unresolvedReference:!0}}static getExpressionProfile(e){const t=this.PROFILE_CACHE.get(e);if(t!==void 0)return t;const r=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),i={dangerous:this.containsDangerousPatterns(e),referencesBuiltins:this.BUILTIN_REFERENCE_PATTERN.test(r),referencesBuiltinData:this.BUILTIN_DATA_REFERENCE_PATTERN.test(r),allowMissingIdentifierRecovery:this.canAttemptMissingIdentifierRecovery(e),needsPropertyBlocking:this.needsPropertyBlocking(e),parameterCandidates:[...new Set(this.getReferencedNames(e))]};return this.PROFILE_CACHE.set(e,i),i}static needsPropertyBlocking(e){let t=null;for(const r of this.tokenizeExpression(e)??[]){if(r.value==="..."||r.value==="("&&t!==null&&(t.type==="identifier"||[")","]","?."].includes(t.value)))return!0;t=r}return!1}static runEvaluator(e,t,r){const i=new WeakMap,n=t.bindKeys.map(a=>this.wrapBoundValue(r[a],i)),s=()=>t.evaluator.call(this.BUILTIN_HOLDER,...n);return this.getExpressionProfile(e).needsPropertyBlocking?this.withBlockedPropertyAccess(s):s()}static prepareEvaluator(e,t,r=[]){const i=this.getExpressionProfile(e).parameterCandidates.filter(E=>Object.prototype.propertyIsEnumerable.call(t,E)&&!this.FORBIDDEN_BINDING_NAMES.has(E));q.isEnabled()&&this.reportUnusableBindingKeys(Object.keys(t).filter(E=>!this.isUsableBindingKey(E)));const n=new Set(i),s=r.filter(E=>!n.has(E)),a=`${e}:${i.join(",")}:${s.join(",")}`;let o=this.EXPRESSION_CACHE.get(a)||null;if(o!==null)return this.compileFailedExpressions.delete(e),{bindKeys:i,evaluator:o,compileFailed:!1};const l=this.buildAssignments(i),u=this.buildBuiltinConstants(e,n),h=this.buildShadowDeclarations(s),m=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),y=`"use strict";
8
+ `}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 s=null;for(const n of r){const a=s?.value==="."||s?.value==="?.";n.type==="identifier"&&!a&&!this.NON_SHADOWABLE_IDENTIFIERS.has(n.value)&&!this.DISALLOWED_KEYWORDS.has(n.value)&&!this.STRICT_FORBIDDEN_NAMES.includes(n.value)&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n.value)&&!i.includes(n.value)&&i.push(n.value),s=n}}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 s=new Set(["(",",","{","["]);for(let n=0;n<i.length;n+=1){if(i[n].value!=="=>")continue;const a=i[n-1];if(a===void 0)continue;if(a.type==="identifier"){r.add(a.value);continue}if(a.value!==")")continue;let o=0,l=0;for(let u=n-1;u>=0;u-=1){const d=i[u].value;if(d===")"||d==="]"||d==="}"){o+=1,d===")"&&(l+=1);continue}if(d==="("||d==="["||d==="{"){if(o-=1,d==="("&&(l-=1),o===0)break;continue}l===1&&i[u].type==="identifier"&&s.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?"":`
9
+ 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 startsArrowParameters(e,t){const r=e.findIndex((i,s)=>s>t&&i.value===")");return e[r+1]?.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 s=[];let n=null;for(let a=0;a<r.length;a+=1){const o=r[a];o.type==="operator"&&n?.value!=="?."&&(o.value==="."?s.push({start:o.position,end:o.position+1,text:"?."}):(o.value==="["&&this.startsMemberAccess(n)||o.value==="("&&this.startsCall(n)&&!this.startsArrowParameters(r,a))&&s.push({start:o.position,end:o.position,text:"?."})),n=o}for(let a=s.length-1;a>=0;a-=1){const o=s[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 s=[],n=[];let a=null;for(const o of r){if(o.value==="["){const l=this.startsMemberAccess(a);n.push(l),l&&s.push({start:o.position+1,end:o.position+1,text:T.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&n.pop()===!0&&s.push({start:o.position,end:o.position,text:")"});a=o}for(let o=s.length-1;o>=0;o-=1){const l=s[o];i=i.slice(0,l.start)+l.text+i.slice(l.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){if(e instanceof Mt)return[e.identifier];const r=String(e.message||""),i=t.filter(s=>["'",'"',"`"].some(n=>r.includes(`${n}${s}${n}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(!(e.length===0||this.evaluatingForDiagnosis)){if(c.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}U.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,Y.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(U.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(!this.evaluatingForDiagnosis){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,Y.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 s of r){if(!this.suppliedIdentifiers.has(s)||this.rowScopeIdentifiers.has(s))continue;const n=`${s}
10
+ ${t}`;this.loggedScopeMissingIdentifiers.has(n)||(this.loggedScopeMissingIdentifiers.add(n),i.push(s))}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 isReservedBindingKey(e){return e.startsWith("_")}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(n=>{i[n]=void 0});const s=this.prepareEvaluator(e,i);if(!s.compileFailed)try{const n=this.runEvaluator(e,s,i);return typeof n=="boolean"?n: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};const r=this.getExpressionProfile(e);if(r.dangerous){const b=this.detectDisallowedKeywords(e);if(b.length>0){const E=b.some(A=>A==="function"||A==="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): "+b.join(", ")+"."+E)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const i=this.collectForbiddenKeys(t);if(i.length>0){const b=i.join(",");this.loggedForbiddenKeySignatures.has(b)||(this.loggedForbiddenKeySignatures.add(b),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+i.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const s=r.referencesBuiltinData,n=s?null:this.getReferencedNames(e);if(this.containsForbiddenReferencedValues(t,n))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const a=r.referencesBuiltins;a&&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 o={};for(const b of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(b)||(o[b]=t[b]);a&&(s?o[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...o}}:o[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(o),U.isEnabled()&&this.recordSuppliedIdentifiers(o);const l=r.allowMissingIdentifierRecovery,u=this.extractFreeIdentifiers(e).filter(b=>!(b in o)&&!this.FORBIDDEN_NAMES.includes(b)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(b));let d=null;if(U.isEnabled()){const b=this.extractBoundIdentifiers(e);d=b.size===0?u:u.filter(E=>!b.has(E))}const y=this.evaluateWithShadowing(e,o,u,l);return d!==null&&this.recordScopeMissingIdentifiers(typeof y.value=="boolean"?d.filter(b=>!this.isReservedBindingKey(b)):d,e),y}static evaluateWithShadowing(e,t,r,i){i&&r.forEach(n=>{t[n]=void 0});const s=i?[]:r;for(let n=0;n<=this.MAX_IDENTIFIER_RECOVERY_COUNT;n+=1){const a=this.prepareEvaluator(e,t,s);if(a.compileFailed)return{value:null,unresolvedReference:!1};try{const o=this.runEvaluator(e,a,t);return o===void 0&&this.warnBlockedIdentifiers(e),{value:o,unresolvedReference:o===void 0}}catch(o){if(i&&o instanceof ReferenceError){const l=this.extractMissingIdentifier(o);if(l!==null&&this.canRecoverMissingIdentifier(l,t)){t[l]=void 0;continue}}if(this.warnBlockedIdentifiers(e),o instanceof ReferenceError&&s.length>0){const l=this.evaluateAsCondition(e,t,s);return l!==void 0?{value:l,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(o,s),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,o),o instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,t),{value:void 0,unresolvedReference:!0}}static getExpressionProfile(e){const t=this.PROFILE_CACHE.get(e);if(t!==void 0)return t;const r=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),i={dangerous:this.containsDangerousPatterns(e),referencesBuiltins:this.BUILTIN_REFERENCE_PATTERN.test(r),referencesBuiltinData:this.BUILTIN_DATA_REFERENCE_PATTERN.test(r),allowMissingIdentifierRecovery:this.canAttemptMissingIdentifierRecovery(e),needsPropertyBlocking:this.needsPropertyBlocking(e),parameterCandidates:[...new Set(this.getReferencedNames(e))]};return this.PROFILE_CACHE.set(e,i),i}static needsPropertyBlocking(e){let t=null;for(const r of this.tokenizeExpression(e)??[]){if(r.value==="..."||r.value==="("&&t!==null&&(t.type==="identifier"||[")","]","?."].includes(t.value)))return!0;t=r}return!1}static runEvaluator(e,t,r){const i=new WeakMap,s=t.bindKeys.map(o=>this.wrapBoundValue(r[o],i));let n;const a=t.compiled;if(a!==void 0){const o={};t.bindKeys.forEach((l,u)=>{o[l]=s[u]}),n=()=>Me.run(a,o)}else n=()=>t.evaluator.call(this.BUILTIN_HOLDER,...s);return this.getExpressionProfile(e).needsPropertyBlocking?this.withBlockedPropertyAccess(n):n()}static prepareEvaluator(e,t,r=[]){const i=this.getExpressionProfile(e).parameterCandidates.filter(E=>Object.prototype.propertyIsEnumerable.call(t,E)&&!this.FORBIDDEN_BINDING_NAMES.has(E));if(U.isEnabled()&&this.reportUnusableBindingKeys(Object.keys(t).filter(E=>!this.isUsableBindingKey(E))),c.csp)return this.prepareInterpretedEvaluator(e,i);const s=new Set(i),n=r.filter(E=>!s.has(E)),a=`${e}:${i.join(",")}:${n.join(",")}`;let o=this.EXPRESSION_CACHE.get(a)||null;if(o!==null)return this.compileFailedExpressions.delete(e),{bindKeys:i,evaluator:o,compileFailed:!1};const l=this.buildAssignments(i),u=this.buildBuiltinConstants(e,s),d=this.buildShadowDeclarations(n),y=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),b=`"use strict";
6
11
  ${l};
7
- ${u}return (${m});`+h;try{return o=new Function(...i,y),this.EXPRESSION_CACHE.set(a,o),this.compileFailedExpressions.delete(e),{bindKeys:i,evaluator:o,compileFailed:!1}}catch(E){return s.length>0?(g.warn("[Haori]","Failed to shadow undeclared identifier(s): "+s.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(g.error("[Haori]","Failed to compile expression:",e,E),this.compileFailedExpressions.add(e),{bindKeys:i,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.ALLOWED_SYNTAX_CACHE.get(e);if(t!==void 0)return t;const r=this.checkAllowedSyntax(e);return this.ALLOWED_SYNTAX_CACHE.set(e,r),r}static checkAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,l=t[n-2]||null,u=t[n-3]||null;if(this.startsObjectKey(o,i,l,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 h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static diagnoseStrictComparison(e,t={}){const r=T.splitStrictComparison(e);if(r===null)return null;T.evaluatingForDiagnosis=!0;let i,n;try{i=T.evaluateDetailed(r.left,t),n=T.evaluateDetailed(r.right,t)}finally{T.evaluatingForDiagnosis=!1}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 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 l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return 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 getReferencedNames(e){const t=this.REFERENCED_NAME_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];let n=null;for(const s of r??[]){const a=n?.value==="."||n?.value==="?.";s.type==="identifier"&&!a&&i.push(s.value),n=s}return this.REFERENCED_NAME_CACHE.set(e,i),i}static containsForbiddenReferencedValues(e,t){const r=this.getForbiddenBindingValueSet(),i=new WeakSet;if(t===null)return this.containsForbiddenBindingValues(e,i,r);for(const n of t){const s=e[n];if(typeof s=="function"){if(r.has(s))return!0;continue}if(this.containsForbiddenBindingValues(s,i,r))return!0}return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r,i){if(!e||typeof e!="object")return!1;const n=r??this.getForbiddenBindingValueSet(),s=this.forbiddenBindingValueCache.get(e);if(s!==void 0)return s;if(t.has(e))return i&&(i.cut=!0),!1;if(t.add(e),n.has(e)||this.isForbiddenStorage(e))return this.forbiddenBindingValueCache.set(e,!0),!0;const a={cut:!1};for(const o of Object.values(e)){if(typeof o=="function"){if(n.has(o))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(o,t,n,a))return this.forbiddenBindingValueCache.set(e,!0),!0}return a.cut?(i&&(i.cut=!0),!1):(this.forbiddenBindingValueCache.set(e,!1),!1)}};T.MAX_IDENTIFIER_RECOVERY_COUNT=8,T.BUILTIN_NAMESPACE="haori",T.BUILTIN_HELPERS={...Ct},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.forbiddenBindingValueSet=null,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.BUILTIN_HOLDER=Object.freeze(Object.defineProperties({},Object.fromEntries([...T.ALLOWED_GLOBAL_IDENTIFIERS].map(e=>[e,{get:()=>globalThis[e],enumerable:!0}])))),T.EXPRESSION_CACHE=new Map,T.FREE_IDENTIFIER_CACHE=new Map,T.ALLOWED_SYNTAX_CACHE=new Map,T.REFERENCED_NAME_CACHE=new Map,T.PROFILE_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=typeof _hk==='symbol'?_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.evaluatingForDiagnosis=!1,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 ie=T;class Te{static readParams(){const e={},t=new URLSearchParams(window.location.search);for(const r of new Set(t.keys())){if(r==="__proto__")continue;const i=t.getAll(r);e[r]=i.length===1?i[0]:i}return 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}}static isNavigableUrl(e){try{const t=new URL(window.location.href).protocol,{protocol:r}=new URL(e,window.location.href);return r==="http:"||r==="https:"||r===t}catch{return!1}}static hasScriptScheme(e){const t=e.replace(/^[\u0000- ]+/,"").replace(/[\t\n\r]/g,"");return/^(?:javascript|vbscript):/i.test(t)}}const he="data-haori-if-disabled",pt="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&&q.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=(l,u,h)=>{r+=h.totalDurationMs,i+=h.calls;const m=t.get(l);if(m===void 0){t.set(l,{where:u,template:h.template,elements:1,calls:h.calls,totalDurationMs:h.totalDurationMs,maxDurationMs:h.maxDurationMs,sharePercent:0,representativeDurationMs:h.totalDurationMs});return}m.elements+=1,m.calls+=h.calls,m.totalDurationMs+=h.totalDurationMs,m.maxDurationMs=Math.max(m.maxDurationMs,h.maxDurationMs),h.totalDurationMs>m.representativeDurationMs&&(m.where=u,m.representativeDurationMs=h.totalDurationMs)};P.snapshot().forEach(l=>{l.attributes.forEach(u=>{n(`@${u.name}
9
- ${u.template}`,`${l.elementId} @${u.name}`,u)}),l.texts.forEach(u=>{n(`#${u.childIndex}
10
- ${u.template}`,`${l.elementId} #${u.childIndex}`,u)})});const s=[...t.values()].map(({representativeDurationMs:l,...u})=>u);s.sort((l,u)=>u.totalDurationMs-l.totalDurationMs);const a=s.slice(0,e).map(l=>({...l,sharePercent:r>0?Math.round(l.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),l=String(r.elements).padStart(4),u=r.maxDurationMs.toFixed(1).padStart(8);return`${n}. ${s}ms ${a} calls=${o} elements=${l} max=${u}ms ${r.where} ${r.template}`});g.info("[Haori][evaluation-profile]",`total=${e.totalDurationMs.toFixed(1)}ms calls=${e.totalCalls} declarations=${e.entryCount}
12
+ ${u}return (${y});`+d;try{return o=new Function(...i,b),this.EXPRESSION_CACHE.set(a,o),this.compileFailedExpressions.delete(e),{bindKeys:i,evaluator:o,compileFailed:!1}}catch(E){return n.length>0?(m.warn("[Haori]","Failed to shadow undeclared identifier(s): "+n.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(E instanceof EvalError&&this.reportEvalBlocked(),m.error("[Haori]","Failed to compile expression:",e,E),this.compileFailedExpressions.add(e),{bindKeys:i,evaluator:null,compileFailed:!0})}}static reportEvalBlocked(){this.evalBlockedReported||(this.evalBlockedReported=!0,m.error("[Haori]",`Expressions cannot be compiled because the Content Security Policy does not allow 'unsafe-eval'. Enable the CSP mode with <script src="haori.js" data-csp> or Haori.setCsp(true).`))}static prepareInterpretedEvaluator(e,t){try{const r=Me.compile(e);return{bindKeys:t,evaluator:null,compileFailed:!1,compiled:r}}catch(r){return m.error("[Haori]","Failed to compile expression:",e,r),this.compileFailedExpressions.add(e),{bindKeys:t,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.ALLOWED_SYNTAX_CACHE.get(e);if(t!==void 0)return t;const r=this.checkAllowedSyntax(e);return this.ALLOWED_SYNTAX_CACHE.set(e,r),r}static checkAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let s=0;s<t.length;s++){const n=t[s],a=t[s+1]||null,o=r[r.length-1]||null,l=t[s-2]||null,u=t[s-3]||null;if(this.startsObjectKey(o,i,l,u)&&(n.value==="["||n.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value)||n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value)))||n.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(n.value)||this.STRICT_FORBIDDEN_NAMES.includes(n.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value))||o==="member"&&n.value!=="]"&&n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value))||n.value==="."&&a?.type!=="identifier"||n.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(n.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=n}return r.length===0}static diagnoseStrictComparison(e,t={}){const r=T.splitStrictComparison(e);if(r===null)return null;T.evaluatingForDiagnosis=!0;let i,s;try{i=T.evaluateDetailed(r.left,t),s=T.evaluateDetailed(r.right,t)}finally{T.evaluatingForDiagnosis=!1}if(i.unresolvedReference||s.unresolvedReference)return null;const n=i.value,a=s.value;return typeof n==typeof a||!T.isLooselyEqual(n,a)?null:{left:typeof n,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 s=e.slice(0,i.position).trim(),n=e.slice(i.position+i.value.length).trim();return s===""||n===""?null:{left:s,right:n}}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<e.length;){const n=e[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return null;if(n==="/"&&this.startsRegexpLiteral(t)){const o=this.readRegexpToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}if(n==='"'||n==="'"){const o=this.readStringToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,s));if(a){t.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(i.has(n)){t.push({type:"operator",value:n,position:s}),s+=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 s=e[r];if(s==="\\"){r+=2;continue}if(s==="[")i=!0;else if(s==="]")i=!1;else if(s==="/"&&!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 s=e[i];if(s==="\\"){i+=2;continue}if(s===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`
13
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return 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 s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(n,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const l=Reflect.apply(n,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return this.WRAPPED_VALUES.add(s),t.set(r,s),s}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:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}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 getReferencedNames(e){const t=this.REFERENCED_NAME_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];let s=null;for(const n of r??[]){const a=s?.value==="."||s?.value==="?.";n.type==="identifier"&&!a&&i.push(n.value),s=n}return this.REFERENCED_NAME_CACHE.set(e,i),i}static containsForbiddenReferencedValues(e,t){const r=this.getForbiddenBindingValueSet(),i=new WeakSet;if(t===null)return this.containsForbiddenBindingValues(e,i,r);for(const s of t){const n=e[s];if(typeof n=="function"){if(r.has(n))return!0;continue}if(this.containsForbiddenBindingValues(n,i,r))return!0}return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r,i){if(!e||typeof e!="object")return!1;const s=r??this.getForbiddenBindingValueSet(),n=this.forbiddenBindingValueCache.get(e);if(n!==void 0)return n;if(t.has(e))return i&&(i.cut=!0),!1;if(t.add(e),s.has(e)||this.isForbiddenStorage(e))return this.forbiddenBindingValueCache.set(e,!0),!0;const a={cut:!1};for(const o of Object.values(e)){if(typeof o=="function"){if(s.has(o))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(o,t,s,a))return this.forbiddenBindingValueCache.set(e,!0),!0}return a.cut?(i&&(i.cut=!0),!1):(this.forbiddenBindingValueCache.set(e,!1),!1)}};T.MAX_IDENTIFIER_RECOVERY_COUNT=8,T.BUILTIN_NAMESPACE="haori",T.BUILTIN_HELPERS={...or},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.STRICT_PARAMETER_RESERVED_WORDS=new Set([...[...Ke].filter(e=>e!=="await"),...et,...We,"extends","true","false","null"]),T.evalBlockedReported=!1,T.usableBindingKeyCache=new Map,T.loggedUnusableBindingKeys=new Set,T.compileFailedExpressions=new Set,T.forbiddenBindingValueCache=new WeakMap,T.forbiddenBindingValueSet=null,T.forbiddenBindingValueCacheResetScheduled=!1,T.loggedForbiddenKeySignatures=new Set,T.loggedForbiddenKeyResetScheduled=!1,T.FORBIDDEN_NAMES=[...Nt],T.STRICT_FORBIDDEN_NAMES=[...We],T.REBINDABLE_FORBIDDEN_NAMES=It,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=je,T.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),T.DISALLOWED_KEYWORDS=Ke,T.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity",...et]),T.ALLOWED_GLOBAL_IDENTIFIERS=Ft,T.BUILTIN_HOLDER=Object.freeze(Object.defineProperties({},Object.fromEntries([...T.ALLOWED_GLOBAL_IDENTIFIERS].map(e=>[e,{get:()=>globalThis[e],enumerable:!0}])))),T.EXPRESSION_CACHE=new Map,T.FREE_IDENTIFIER_CACHE=new Map,T.ALLOWED_SYNTAX_CACHE=new Map,T.REFERENCED_NAME_CACHE=new Map,T.PROFILE_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=typeof _hk==='symbol'?_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.evaluatingForDiagnosis=!1,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 ne=T;class $e{static readParams(){const e={},t=new URLSearchParams(window.location.search);for(const r of new Set(t.keys())){if(r==="__proto__")continue;const i=t.getAll(r);e[r]=i.length===1?i[0]:i}return 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}}static isNavigableUrl(e){try{const t=new URL(window.location.href).protocol,{protocol:r}=new URL(e,window.location.href);return r==="http:"||r==="https:"||r===t}catch{return!1}}static hasScriptScheme(e){const t=e.replace(/^[\u0000- ]+/,"").replace(/[\t\n\r]/g,"");return/^(?:javascript|vbscript):/i.test(t)}}const ye="data-haori-if-disabled",Ut="input, select, textarea, button, fieldset",$=class ${static reset(){$.ELEMENT_STORES.clear(),$.ensureGlobalAccess()}static start(){$.collecting=!0}static stop(){$.collecting=!1}static isCollecting(){return $.collecting&&U.isEnabled()}static snapshot(){return $.ensureGlobalAccess(),[...$.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:$.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:$.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((s,n)=>s+n.calls,0)+e.texts.reduce((s,n)=>s+n.calls,0);return t.attributes.reduce((s,n)=>s+n.calls,0)+t.texts.reduce((s,n)=>s+n.calls,0)-r})}static report(e=$.DEFAULT_REPORT_LIMIT){const t=new Map;let r=0,i=0;const s=(l,u,d)=>{r+=d.totalDurationMs,i+=d.calls;const y=t.get(l);if(y===void 0){t.set(l,{where:u,template:d.template,elements:1,calls:d.calls,totalDurationMs:d.totalDurationMs,maxDurationMs:d.maxDurationMs,sharePercent:0,representativeDurationMs:d.totalDurationMs});return}y.elements+=1,y.calls+=d.calls,y.totalDurationMs+=d.totalDurationMs,y.maxDurationMs=Math.max(y.maxDurationMs,d.maxDurationMs),d.totalDurationMs>y.representativeDurationMs&&(y.where=u,y.representativeDurationMs=d.totalDurationMs)};$.snapshot().forEach(l=>{l.attributes.forEach(u=>{s(`@${u.name}
14
+ ${u.template}`,`${l.elementId} @${u.name}`,u)}),l.texts.forEach(u=>{s(`#${u.childIndex}
15
+ ${u.template}`,`${l.elementId} #${u.childIndex}`,u)})});const n=[...t.values()].map(({representativeDurationMs:l,...u})=>u);n.sort((l,u)=>u.totalDurationMs-l.totalDurationMs);const a=n.slice(0,e).map(l=>({...l,sharePercent:r>0?Math.round(l.totalDurationMs/r*1e3)/10:0})),o={totalDurationMs:r,totalCalls:i,entryCount:n.length,top:a};return $.logReport(o),o}static logReport(e){const t=e.top.map((r,i)=>{const s=String(i+1).padStart(2),n=r.totalDurationMs.toFixed(1).padStart(9),a=`${r.sharePercent.toFixed(1)}%`.padStart(6),o=String(r.calls).padStart(6),l=String(r.elements).padStart(4),u=r.maxDurationMs.toFixed(1).padStart(8);return`${s}. ${n}ms ${a} calls=${o} elements=${l} 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
16
  `+t.join(`
12
- `))}static record(e,t,r){if(!q.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(!q.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(`${c.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${c.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};P.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",P.ELEMENT_STORES=new Map,P.collecting=!1,P.DEFAULT_REPORT_LIMIT=20;let Me=P;const fe=class fe{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,fe.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(fe.FRAGMENT_CACHE.has(e))return fe.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new w(e);break;case Node.TEXT_NODE:t=new ne(e);break;case Node.COMMENT_NODE:t=new We(e);break;default:return g.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return fe.FRAGMENT_CACHE.get(e)??null}isSkipMutationNode(e){return this.skipMutationNodeSet.has(e)}holdSkipMutationNode(e){this.skipMutationNodeSet.add(e)}releaseSkipMutationNode(e){this.skipMutationNodeSet.delete(e)}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}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 e.holdSkipMutationNode(this.target),K.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),fe.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};fe.FRAGMENT_CACHE=new WeakMap;let N=fe;const v=class v extends N{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.initialized=!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,v.dropFollowUpArtifacts(e),this.syncValue(),this.initialBindAttribute=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(i=>{const n=e.getAttribute(i);if(n!==null&&!this.attributeMap.has(i)){const s=new $e(i,n);this.attributeMap.set(i,s)}});let t=null;const r=[];e.childNodes.forEach(i=>{if(v.isOwnedWithinExternal(i))return;const n=N.peek(i)?.getParent()??null,s=N.get(i);n!==null&&n!==this&&(t=t??n,n===t&&r.push(s)),s.setParent(this),this.children.push(s)}),t!==null&&this.takeOverPlaceOf(t,r)}takeOverPlaceOf(e,t){const r=e.children,i=t.map(s=>r.indexOf(s)).filter(s=>s>=0).sort((s,a)=>s-a);if(i.length===0)return;const n=i[0];i.slice().reverse().forEach(s=>r.splice(s,1)),r.splice(n,0,this),this.setParent(e)}static isOwnedWithinExternal(e){const r=N.peek(e)?.getParent()??null;if(r===null)return!1;const i=r.getTarget().closest(`[${c.prefix}external]`);return i!==null&&i.contains(e)}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof v)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){g.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new v(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.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}static dropFollowUpArtifacts(e){v.dropIfVisibilityArtifacts(e),e.removeAttribute(`${c.prefix}each-done`),e.removeAttribute(`${c.prefix}importing`)}static dropIfVisibilityArtifacts(e){e.hasAttribute(`${c.prefix}if-false`)&&(e.style.removeProperty("display"),e.getAttribute("style")?.trim()===""&&e.removeAttribute("style"),e.removeAttribute(`${c.prefix}if-false`),v.forEachFormControlInBranch(e,t=>{t.hasAttribute(he)&&(t.removeAttribute(he),t.removeAttribute("disabled"))}))}remove(e=!0){const t=[];return e&&te.destroySubtree(this.getTarget()),this.getTarget().hasAttribute(`${c.prefix}external`)?this.detachPreservingSubtree(e):(this.children.slice().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(()=>{}))}detachObserved(){te.destroySubtree(this.getTarget());const e=this.getParent();e&&e.removeChild(this)}detachPreservingSubtree(e){const t=this.getParent();return t&&t.removeChild(this),e?this.unmount():Promise.resolve()}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=this.withRetainedReservedKeys(e),this.clearBindingDataCache()}withRetainedReservedKeys(e){const t=this.bindingData;if(t===null)return e;const r={};for(const i of Object.keys(t))v.isReservedBindingKey(i)&&(r[i]=t[i]);return{...r,...e}}static isReservedBindingKey(e){return ie.isReservedBindingKey(e)}isExecutingBindingWork(){return this.bindingWorkActive>0}static isExecutingAnyBindingWork(){return v.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,v.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,v.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 v&&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}isInitialized(){return this.initialized}markInitialized(){this.initialized=!0}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=""})):(g.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 this.collectsLines()?this.writeLinesValue(e,t,r):i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement||i instanceof HTMLSelectElement?this.writeScalarValue(Array.isArray(e)?e.join(","):e,t,r):(g.warn("[Haori]","setValue is not supported for this element type.",i),Promise.resolve())}collectsLines(){const e=this.getTarget();return e instanceof HTMLTextAreaElement&&v.resolveDeclaredValueType(e)==="lines"}writeLinesValue(e,t,r){const i=this.getTarget(),n=v.normalizeLinesValue(e),s=n.join(`
17
+ `))}static record(e,t,r){if(!U.isEnabled()||!e||t.length===0||($.ensureGlobalAccess(),!$.isCollecting()))return;const i=$.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=$.getOrCreateCounter(i.attributes,e.rawName,e.template);$.updateCounter(n,t,r);return}const s=$.getOrCreateCounter(i.texts,String(e.childIndex),e.template);$.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!U.isEnabled())return;const e=globalThis;e[$.GLOBAL_KEY]===void 0&&(e[$.GLOBAL_KEY]={start:()=>$.start(),stop:()=>$.stop(),reset:()=>$.reset(),snapshot:()=>$.snapshot(),report:t=>$.report(t)})}static getOrCreateElementStore(e){const t=$.createElementId(e),r=$.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return $.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const s={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,s),s}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 s=$.getOrCreatePlaceholder(e.placeholders,i.expression);s.calls+=1,s.totalDurationMs+=i.durationMs,s.maxDurationMs=Math.max(s.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(!$.isCollecting())return{value:e(),durationMs:0};const t=$.now();return{value:e(),durationMs:$.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const s=r.getAttribute("id")||"";if(s.trim()!==""){i+=`#${s.trim()}`,t.unshift(i);break}const n=r.getAttribute(`${c.prefix}derive-name`);n&&n.trim()!==""&&(i+=`[${c.prefix}derive-name="${n.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};$.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",$.ELEMENT_STORES=new Map,$.collecting=!1,$.DEFAULT_REPORT_LIMIT=20;let ze=$;const me=class me{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,me.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(me.FRAGMENT_CACHE.has(e))return me.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new R(e);break;case Node.TEXT_NODE:t=new le(e);break;case Node.COMMENT_NODE:t=new rt(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return me.FRAGMENT_CACHE.get(e)??null}isSkipMutationNode(e){return this.skipMutationNodeSet.has(e)}holdSkipMutationNode(e){this.skipMutationNodeSet.add(e)}releaseSkipMutationNode(e){this.skipMutationNodeSet.delete(e)}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return e.holdSkipMutationNode(this.target),Y.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}else{const e=this.target.parentNode;if(e)return Y.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 e.holdSkipMutationNode(this.target),Y.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t,e.releaseSkipMutationNode(this.target)})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),me.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};me.FRAGMENT_CACHE=new WeakMap;let D=me;const v=class v extends D{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.initialized=!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,v.dropFollowUpArtifacts(e),this.syncValue(),this.initialBindAttribute=e.getAttribute(`${c.prefix}bind`),e.getAttributeNames().forEach(i=>{const s=e.getAttribute(i);if(s!==null&&!this.attributeMap.has(i)){const n=new Ge(i,s);this.attributeMap.set(i,n)}});let t=null;const r=[];e.childNodes.forEach(i=>{if(v.isOwnedWithinExternal(i))return;const s=D.peek(i)?.getParent()??null,n=D.get(i);s!==null&&s!==this&&(t=t??s,s===t&&r.push(n)),n.setParent(this),this.children.push(n)}),t!==null&&this.takeOverPlaceOf(t,r)}takeOverPlaceOf(e,t){const r=e.children,i=t.map(n=>r.indexOf(n)).filter(n=>n>=0).sort((n,a)=>n-a);if(i.length===0)return;const s=i[0];i.slice().reverse().forEach(n=>r.splice(n,1)),r.splice(s,0,this),this.setParent(e)}static isOwnedWithinExternal(e){const r=D.peek(e)?.getParent()??null;if(r===null)return!1;const i=r.getTarget().closest(`[${c.prefix}external]`);return i!==null&&i.contains(e)}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof v)}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 v(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.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}static dropFollowUpArtifacts(e){v.dropIfVisibilityArtifacts(e),e.removeAttribute(`${c.prefix}each-done`),e.removeAttribute(`${c.prefix}importing`)}static dropIfVisibilityArtifacts(e){e.hasAttribute(`${c.prefix}if-false`)&&(e.style.removeProperty("display"),e.getAttribute("style")?.trim()===""&&e.removeAttribute("style"),e.removeAttribute(`${c.prefix}if-false`),v.forEachFormControlInBranch(e,t=>{t.hasAttribute(ye)&&(t.removeAttribute(ye),t.removeAttribute("disabled"))}))}remove(e=!0){const t=[];return e&&se.destroySubtree(this.getTarget()),this.getTarget().hasAttribute(`${c.prefix}external`)?this.detachPreservingSubtree(e):(this.children.slice().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(()=>{}))}detachObserved(){se.destroySubtree(this.getTarget());const e=this.getParent();e&&e.removeChild(this)}detachPreservingSubtree(e){const t=this.getParent();return t&&t.removeChild(this),e?this.unmount():Promise.resolve()}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=this.withRetainedReservedKeys(e),this.clearBindingDataCache()}withRetainedReservedKeys(e){const t=this.bindingData;if(t===null)return e;const r={};for(const i of Object.keys(t))v.isReservedBindingKey(i)&&(r[i]=t[i]);return{...r,...e}}static isReservedBindingKey(e){return ne.isReservedBindingKey(e)}isExecutingBindingWork(){return this.bindingWorkActive>0}static isExecutingAnyBindingWork(){return v.bindingWorkActiveCount>0}markBindingWorkStart(){this.bindingWorkActive++,v.bindingWorkActiveCount++}markBindingWorkEnd(){this.bindingWorkActive>0&&(this.bindingWorkActive--,v.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 v&&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}isInitialized(){return this.initialized}markInitialized(){this.initialized=!0}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():Y.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 s=this.hasAttribute("value")?this.getAttribute("value"):i.value,n=i.type==="checkbox"&&s==="true";let a;if(n?a=e===!0||e==="true":s==="false"?a=e===!1:Array.isArray(e)?a=e.map(String).includes(String(s)):a=s===String(e),n?this.value=a:a?Array.isArray(e)?this.value=String(s):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 s=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.writeSelectedValues(s,t,r)}else return this.collectsLines()?this.writeLinesValue(e,t,r):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())}collectsLines(){const e=this.getTarget();return e instanceof HTMLTextAreaElement&&v.resolveDeclaredValueType(e)==="lines"}writeLinesValue(e,t,r){const i=this.getTarget(),s=v.normalizeLinesValue(e),n=s.join(`
13
18
  `);return v.normalizeLinesValue(i.value).join(`
14
- `)===s?(this.value=n,Promise.resolve()):this.writeScalarValue(s,t,r)}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(()=>{if(this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r))return;const a=i.value;i.value=n,this.recordValueWriteResult(i.value===n),i.value!==a&&v.notifyValueToEnhancers(i),t&&((i instanceof HTMLInputElement&&v.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 l=e.includes(o.value);o.selected!==l&&(o.selected=l,s=!0),l&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),s&&v.notifyValueToEnhancers(i),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(v.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(v.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()}static notifyValueToEnhancers(e){te.isApplied(e)&&te.refreshSubtree(e)}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,v.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return v.sequenceCounter}static nextSequence(){return v.sequenceCounter+=1,v.sequenceCounter}static setPendingMutationFlusher(e){v.pendingMutationFlusher=e}static nextOperationSequence(){return v.pendingMutationFlusher&&!v.isExecutingAnyBindingWork()&&v.pendingMutationFlusher(),v.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:v.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 v.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=v.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=v.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}`;v.loggedUnresolvedAttributes.has(n)||(v.loggedUnresolvedAttributes.add(n),g.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}`;v.loggedTypeMismatchedComparisons.has(n)||(v.loggedTypeMismatchedComparisons.add(n),g.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 ${c.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=N.get(t);return r instanceof v?r.hasPendingUserEdit():!1}static captureSelection(e){const t=Array.from(e.options),r=t.map(i=>i.selected);return()=>{t.forEach((i,n)=>{i.selected=r[n]})}}getCheckableUserEditSequence(e){if(!e)return this.userEditSequence;const t=N.get(this.getTarget().closest("select"));return t instanceof v?t.userEditSequence:null}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=v.resolveDeclaredValueType(e);return r==="lines"?v.normalizeLinesValue(t):r==="boolean"?v.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?v.normalizeNumberValue(t):t}static normalizeLinesValue(e){return(Array.isArray(e)?e.filter(r=>r!==null).map(String):e===null?[]:String(e).split(`
15
- `)).map(r=>r.trim()).filter(r=>r!=="")}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!v.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(`${c.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return v.VALUE_TYPE_NAMES.has(r)?r==="lines"&&!(e instanceof HTMLTextAreaElement)?(v.warnValueTypeDeclaration(e,t,"lines は <textarea> にのみ指定できます"),null):v.acceptsDeclaredValueType(e)?r:(v.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(v.warnValueTypeDeclaration(e,t,"boolean / number / string / lines のいずれかを指定してください"),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}`;v.loggedValueTypeDeclarations.has(n)||(v.loggedValueTypeDeclarations.add(n),g.warn("Haori",`${c.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?v.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(v.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,v.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:v.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=N.get(t);r instanceof v&&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 $e(e,r);if(n){const le=this.attributeMap.get(e);if(le&&(le.isEvaluate||le.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const be=K.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,be),be}}this.attributeMap.set(e,o);const l=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),h=o.isEvaluate||o.isRawEvaluate,m=e===t&&v.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),y=o.isSingleExpression(),E=de.joinEvaluateResults(u.results),A=u.results.length===1?u.results[0]:E,D=t==="value"&&v.resolveDeclaredValueType(l)==="boolean",M=A===!1&&!D,L=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||A===null||A===void 0||M:m?u.hasUnresolvedReference||A===null||A===void 0||A===!1:y?u.hasUnresolvedReference||A===null||A===void 0||M:h&&E==="");if(L&&u.hasUnresolvedReference&&v.warnUnresolvedAttribute(e,t,r,l),q.isEnabled()&&A===!1&&y){const le=o.getSingleExpression(),be=le===null?null:ie.diagnoseStrictComparison(le,this.getBindingData());be!==null&&v.warnTypeMismatchedComparison(e,r,be,l)}const ee=o.isForceEvaluation()?r:y?A:E,x=i&&o.isEvaluate&&t==="value"&&v.isValuePropertyTarget(l),X=l.getRootNode(),Q=this.userEditSequence,J=x&&v.isUserEditableValue(l)&&(l===X.activeElement||this.hasPendingUserEdit()),j=L||ee===null||ee===!1&&!D?null:String(ee),se=o.isEvaluate&&j!==null&&v.URL_ATTRIBUTES.has(t)&&Te.hasScriptScheme(j);se&&g.warn("[Haori]",`Attribute "${t}" was removed because the evaluated URL uses a script scheme: ${e}="${r}" -> ${j}`,l);const R=se?null:j,$=e!==t&&l.getAttribute(e)!==r,z=R===null?l.hasAttribute(t):l.getAttribute(t)!==R,_=R===null?"":R,Re=x&&!J&&l.value!==_,oe=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),U=t==="selected"&&l instanceof HTMLOptionElement,G=X.activeElement,Z=G!==null&&(oe&&l===G||U&&l.closest("select")===G)||(oe||U)&&this.hasPendingCheckableUserEdit(U),Be=this.getCheckableUserEditSequence(U),He=R!==null,Xe=oe&&o.isEvaluate&&!Z&&l.checked!==He,Ue=U&&o.isEvaluate&&!Z&&l.selected!==He;if(!$&&!z&&!Re&&!Xe&&!Ue)return x&&!J&&(this.value=this.normalizeValueForElement(l,_),this.clearUnappliedValueWrite()),(oe||U)&&!Z&&this.syncCheckableValueFromDom(U),Promise.resolve();const Rt=K.enqueue(()=>{const le=this.getCheckableUserEditSequence(U)!==Be,be=U&&(Z||le)?v.captureSelection(l.closest("select")):null;$&&l.setAttribute(e,r),R===null?l.removeAttribute(t):z&&(l.setAttribute(t,R),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(R)),t==="style"&&this.captureAndHideDisplay(),be?.(),x&&!J&&!(v.isUserEditableValue(l)&&this.isSupersededByUserEdit(Q))&&(this.value=this.normalizeValueForElement(l,_),Re&&(l.value=_),this.recordValueWriteResult(l.value===_));const rr=Xe&&!le,ir=Ue&&!le;rr&&(l.checked=He),ir&&(l.selected=He),(Xe||Ue)&&this.syncCheckableValueFromDom(Ue)}).finally(()=>{this.releaseSelfWritingAttributes(s)});return this.holdSelfWritingAttributes(s,Rt),Rt}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:de.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=N.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}}replaceChildNodesWithHtml(e){const t=Array.from(this.target.childNodes);t.forEach(i=>this.holdSkipMutationNode(i)),this.target.innerHTML=e;const r=Array.from(this.target.childNodes);return r.forEach(i=>this.holdSkipMutationNode(i)),()=>{t.forEach(i=>this.releaseSkipMutationNode(i)),r.forEach(i=>this.releaseSkipMutationNode(i))}}insertBefore(e,t,r){if(this.isSkipMutationNode(e.getTarget()))return Promise.resolve();if(e===this)return g.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 g.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=this.linkChild(e,t,r),a=this.skipMutationNodes;return this.skipMutationNodes=!0,this.holdSkipMutationNode(e.getTarget()),K.enqueue(()=>{this.target.insertBefore(e.getTarget(),s)}).finally(()=>{this.skipMutationNodes=a,this.releaseSkipMutationNode(e.getTarget())})}attachObserved(e,t){this.linkChild(e,t)}linkChild(e,t,r){const i=e.getParent()===this;let n=-1,s=-1;i&&(n=this.children.indexOf(e),t!==null&&(s=this.children.indexOf(t)));const a=e.getParent();a!==null&&a.removeChild(e);let o=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let l;if(i?n!==-1&&n<s?l=s-1:l=s:l=this.children.indexOf(t),l===-1){const u=this.resolveInsertionPointFromDom(t,!1);u===null?(g.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(u.index,0,e),o=u.referenceNode)}else this.children.splice(l,0,e)}return e.setParent(this),e.setMounted(this.mounted),o}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?(g.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}captureAndHideDisplay(){if(this.visible)return;const e=this.getTarget().style;this.display=e.getPropertyValue("display"),this.displayPriority=e.getPropertyPriority("display"),e.setProperty("display","none","important")}hideDisplayWithoutCapture(){if(this.visible)return;const e=this.getTarget().style;e.getPropertyValue("display")==="none"&&e.getPropertyPriority("display")==="important"||e.setProperty("display","none","important")}static reassertHiddenDisplay(e){const t=N.get(e);t instanceof v&&t.hideDisplayWithoutCapture()}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.captureAndHideDisplay(),e.setAttribute(`${c.prefix}if-false`,""),v.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(pt)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${c.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(pt)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){v.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(he,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){v.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(he)&&(e.removeAttribute(he),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(`${c.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)}};v.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,v.VALUE_TYPE_NAMES=new Set(["boolean","number","string","lines"]),v.loggedValueTypeDeclarations=new Set,v.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"]),v.URL_ATTRIBUTES=new Set(["href","src","action","formaction","xlink:href","poster","data","cite","background"]),v.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],v.UNAPPLIED_VALUE_WRITES=new Set,v.sequenceCounter=0,v.bindingWorkActiveCount=0,v.pendingMutationFlusher=null,v.loggedUnresolvedAttributes=new Set,v.loggedTypeMismatchedComparisons=new Set;let w=v;class ne extends N{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new de(this.text)}clone(){const e=new ne(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 de(e),this.evaluate())}evaluate(){if(this.contents.isRawEvaluate&&this.parent===null)return Promise.reject(new Error("Parent fragment is required for raw evaluation"));let e=null;return K.enqueue(()=>{this.skipMutation=!0;let t=this.text;this.contents.isEvaluate&&(t=de.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const r=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===t&&r===t||(this.contents.isRawEvaluate?e=this.parent.replaceChildNodesWithHtml(t):this.target.textContent=t,this.renderedText=t)}).finally(()=>{this.skipMutation=!1,e?.()})}}class We extends N{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new We(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 Oe=class Oe{constructor(e,t=!1){if(this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e,t){this.contents.push({text:e,type:0});return}const r=[...e.matchAll(Oe.PLACEHOLDER_REGEX)];let i=0,n=!1,s=!1;for(const a of r){a.index>i&&this.contents.push({text:e.slice(i,a.index),type:0});const o={text:a[1]??a[2],type:a[1]?2:1};n=!0,s=s||o.type===2,this.contents.push(o),i=a.index+a[0].length}i<e.length&&this.contents.push({text:e.slice(i),type:0}),this.isEvaluate=n,this.isRawEvaluate=s,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&&(g.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const u=Me.measure(()=>ie.evaluateDetailed(l.text,e)),h=u.value;a+=u.durationMs,s.push({expression:l.text,durationMs:u.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(l.text)}catch(u){g.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,u),s.push({expression:l.text,durationMs:0}),n.push("")}}),Me.record(t,s,a),{results:n,hasUnresolvedReference:o}}};Oe.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let de=Oe;const Y=class Y extends de{constructor(e,t){const r=Y.isEventHandlerAttribute(e);super(t,e===`${c.prefix}bind`||r),this.name=e,this.forceEvaluation=Y.needsForceEvaluation(e),this.checksUrlPath=Y.isRequestUrlAttribute(e),r&&q.isEnabled()&&t.includes("{{")&&Y.warnEventHandlerPlaceholder(e,t)}static isEventHandlerAttribute(e){const t=`${c.prefix}attr-`;return(e.startsWith(t)?e.slice(t.length):e).startsWith("on")}static isRequestUrlAttribute(e){return e===`${c.prefix}import`||e.startsWith(c.prefix)&&e.endsWith("fetch")}static warnEventHandlerPlaceholder(e,t){const r=`${e}\0${t}`;Y.WARNED_EVENT_HANDLER_PLACEHOLDERS.has(r)||(Y.WARNED_EVENT_HANDLER_PLACEHOLDERS.add(r),g.warn("[Haori]",`Placeholders in event handler attributes are not evaluated: ${e}="${t}". Use ${c.prefix}{event}-run, or read the bound value inside the called function.`))}diagnoseUrlPathValues(e){let t=!1,r="";this.contents.forEach((i,n)=>{const s=String(e[n]);if(i.type===0)t=!0;else if(t&&!/[?#]/.test(r)&&Y.changesUrlPath(s)){const a=`${this.name}\0${this.getValue()}\0${s}`;Y.WARNED_URL_PATH_VALUES.has(a)||(Y.WARNED_URL_PATH_VALUES.add(a),g.warn("[Haori]",`A value embedded in the URL path is not URL-encoded and changes the request path: ${this.name}="${this.getValue()}", value: ${s}. Encode it with encodeURIComponent, or send it as a query.`))}r+=s})}static changesUrlPath(e){return/[/\\?#]/.test(e)||/^(?:\.|%2e){1,2}$/i.test(e)}static needsForceEvaluation(e){if(Y.forceEvaluationNames===null||Y.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Y.FORCE_EVALUATION_PREFIXES])for(const i of Y.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Y.forceEvaluationNames=t,Y.forceEvaluationPrefix=c.prefix}return Y.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.checksUrlPath&&q.isEnabled()&&this.diagnoseUrlPathValues(r.results),this.forceEvaluation&&r.results.length>1?(g.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Y.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Y.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Y.forceEvaluationNames=null,Y.forceEvaluationPrefix=null,Y.WARNED_EVENT_HANDLER_PLACEHOLDERS=new Set,Y.WARNED_URL_PATH_VALUES=new Set;let $e=Y;const Se=class Se{static get runtime(){return c.runtime}static setRuntime(e){c.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?(Se.clearMessagesSync(e),e.showModal()):g.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return K.enqueue(()=>{e instanceof HTMLDialogElement?e.close():g.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Se.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(()=>{!(e instanceof HTMLFormElement)&&e.parentElement&&(e.parentElement.removeAttribute("data-message"),e.parentElement.removeAttribute("data-message-level")),Se.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 Ie(e,t,r)}static now(e,t){return rt(e,t)}static today(e,t,r){return it(e,t,r)}static number(e,t){return nt(e,t)}static range(e,t,r){return st(e,t,r)}static pages(e,t,r){return at(e,t,r)}static monthAdd(e,t){return Ce(e,t)}static monthRange(e,t){return ot(e,t)}static pageSummary(e,t){return lt(e,t)}static findBy(e,t,r){return ct(e,t,r)}static sum(e,t){return ut(e,t)}static distinct(e,t){return ft(e,t)}static groupBy(e,t){return ht(e,t)}};Se.enhancers={register(e,t){te.register(e,t)},has(e){return te.has(e)}};let ce=Se;const Mt="入力内容を確認してください",$t=["addErrorMessage","clearMessages"],gt="data-haori-group-name";function mt(){const e=globalThis.window?.Haori;return $t.every(r=>typeof e?.[r]=="function")?e:ce}const f=class f{static getValues(e){const t={},r=new Set;return f.getPartValues(e,t,null,r),f.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(f.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(f.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(`${c.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=f.getValues(e),i=new Set;for(const n of new Set([...Object.keys(r),...Object.keys(t)]))f.isSameCollectedValue(r[n],t[n])||i.add(n);i.size!==0&&f.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=f.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(n=>{f.clearUserEditMarksForKeys(n,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const n=i.getAttribute(`${c.prefix}form-object`)||i.getAttribute(`${c.prefix}form-list`)||f.resolveFieldName(i);n!=null&&String(n)!==""&&(r=String(n)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${c.prefix}form-name`))return;const t=e.getAttribute(`${c.prefix}form-name`);if(!t){g.warn("Haori",`${c.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(gt))return;const i=f.resolveGroupScope(e),n=`${String(t)}--haori${f.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(gt,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${c.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${c.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=f.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(f.groupScopeSequence+=1,f.GROUP_SCOPE_IDS.set(e,f.groupScopeSequence),f.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!f.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return f.isDeclarationResolved(e,"checked");if(f.hasDeclarativeBinding(e,"value"))return f.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=N.get(r);if(i instanceof w&&f.hasDeclarativeBinding(i,"selected")&&!f.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${c.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")?f.hasDeclarativeBinding(e,"checked"):w.isValuePropertyTarget(t)?f.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?f.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&&f.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(f.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 w&&f.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${c.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=N.get(t);if(r instanceof w&&f.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 f.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const n=new Map;for(const a of f.collectUserEditSequences(e)){const o=new Set;f.walkEditedPaths(f.getValuesEditedAfter(e,a-1),r,o);for(const l of o)n.has(l)||n.set(l,a)}const s=new Set;f.walkExcludedPaths(i??f.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 f.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())f.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=f.asPlainRecord(e);if(i===null)return;const n=f.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))f.walkExcludedPaths(a,t===""?s:`${t}.${s}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=f.asPlainRecord(e);if(i!==null){for(const[n,s]of Object.entries(i))f.walkEditedPaths(s,t===""?n:`${t}.${n}`,r);return}t!==""&&r.add(t)}static isResettingInternally(){return f.internalResetDepth>0}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${c.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${c.prefix}if-false`)){if(i!==null)for(const u of f.collectDeclaredKeysInFragment(e))i.add(u);return t}const n=f.resolveFieldName(e),s=e.getAttribute(`${c.prefix}form-object`),a=e.getAttribute(`${c.prefix}form-list`),o=e.hasAttribute(`${c.prefix}form-list`),l=r!==null&&e.getUserEditSequence()<=r;if(n){if(r!==null&&f.isGroupedCheckable(e)){const u=f.collectGroupSelection(e,o,r);u.edited&&(t[String(n)]=u.value)}else if(o&&f.isGroupedCheckable(e)){const u=String(n),h=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!l&&h.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(h.value))}else if(o&&l)Array.isArray(t[String(n)])?t[String(n)].push(null):t[String(n)]=[null];else if(!l)if(o){const u=f.resolveCollectedValue(e),h=f.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(n)])?t[String(n)].push(...h):t[String(n)]=h}else if(f.isGroupedCheckable(e)){const u=e.getTarget(),h=u instanceof HTMLInputElement?u.checked:!0,m=u instanceof HTMLInputElement?u.value:e.getValue(),y=h?m:null,E=String(n);y===null?E in t||(t[E]=null):t[E]===null||t[E]===void 0?t[E]=y:Array.isArray(t[E])?t[E].push(y):t[E]=[t[E],y]}else t[String(n)]=f.resolveCollectedValue(e);s&&g.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())f.getPartValues(u,t,r,i)}else if(s){const u={},h=i===null?null:new Set;for(const m of e.getChildElementFragments())f.getPartValues(m,u,r,h);h!==null&&f.registerCollectedExcludedKeys(u,h),Object.keys(u).length>0?t[String(s)]=u:i!==null&&(h?.size??0)>0&&i.add(String(s)),a&&g.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(a){const u=[],h=[];let m=!1;for(const y of e.getChildElementFragments()){const E={},A=i===null?null:new Set;f.getPartValues(y,E,r,A),A!==null&&f.registerCollectedExcludedKeys(E,A),Object.keys(E).length>0?(m=!0,u.push(E),h.push(y.getListKey())):r!==null&&(u.push({}),h.push(y.getListKey()))}if(r===null){const y=e.getAttribute(`${c.prefix}each-key`);f.registerCollectedRowIdentity(u,y==null?null:String(y),h,f.isCollectedListFromEachSource(e)),f.warnDerivedRowsWithoutKey(e),t[String(a)]=u}else m&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())f.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return f.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return f.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return f.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?f.asPlainRecord(t[i])??{}:f.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorKeyOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t))return r.getListKey()!==null?null:{owner:r,value:i[t]};r=r.getParent()}return null}static resolveAncestorArgOwner(e,t){const r=f.resolveAncestorKeyOwner(e,t);if(r===null)return null;const i=f.asPlainRecord(r.value);return i===null?(f.warnArgOwnerIsNotRecord(e,t,r.value),null):{owner:r.owner,value:i}}static ancestorBaseResolver(e){return t=>f.resolveAncestorKeyOwner(e,t)?.value}static warnArgOwnerIsNotRecord(e,t,r){if(!q.isEnabled()||r==null)return;const i=e.getTarget(),n=f.warnedArgOwnerNotRecord.get(i);n?.has(t)||(n?n.add(t):f.warnedArgOwnerNotRecord.set(i,new Set([t])),g.warn("[Haori]",`${c.prefix}form-arg="${t}" のキーを祖先が${Array.isArray(r)?"配列":`${typeof r} 型の値`}で持っています。${c.prefix}form-arg はそのキーの配下に入力欄が対応することを宣言するため、値はレコード(オブジェクト)である必要があります。このままでは収集値がそのキーへ直接入り、値の型が変わります。`))}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:f.resolveFormArgKey(t)}:f.resolveConditionValueSource(e);if(!i)return r;const n=f.getValues(i.source),s=f.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of s)r[o]=n[o];return r}const a={...f.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(`${c.prefix}each`)&&i.hasAttribute(`${c.prefix}form-list`)){const n=i.getRawAttribute(`${c.prefix}each-arg`);return{source:t,argKey:typeof n=="string"&&n!==""?n:null}}t=i}const r=f.getFormFragment(e);return r?{source:r,argKey:f.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${c.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return f.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=f.resolveFieldName(e);i&&t.add(String(i));const n=`${c.prefix}form-object`,s=`${c.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],[${c.prefix}form-name],[${n}],[${s}]`;return r.querySelectorAll(o).forEach(l=>{if(!(l instanceof HTMLElement))return;let u=null,h=!1,m=l;for(;m&&m!==r;)m.hasAttribute(`${c.prefix}form-detach`)&&(h=!0),(m.hasAttribute(n)||m.hasAttribute(s))&&(u=m),m=m.parentElement;if(h)return;const y=u??l,E=y.getAttribute(n)||y.getAttribute(s)||y.getAttribute(`${c.prefix}form-name`)||y.getAttribute("name");E&&t.add(E)}),t}static applyCustomValidity(e){const t=`${c.prefix}validity`,r=i=>{i.hasAttribute(t)&&f.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)){g.warn("Haori",`${t} は入力要素にのみ指定できます: ${r.tagName}`);return}const i=e.getRawAttribute(t);if(typeof i!="string"||i.trim()===""){r.setCustomValidity("");return}const n=f.buildConditionScope(e),s=ie.evaluateDetailed(f.unwrapConditionExpression(i),n);if(s.unresolvedReference){g.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(f.resolveValidityMessage(e));return}r.setCustomValidity(s.value?"":f.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${c.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:Mt}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=`${c.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&g.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${c.prefix}{event}-validate を指定するか、${c.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){f.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&f.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=f.COLLECTED_ROW_IDENTITY.get(e);r&&f.COLLECTED_ROW_IDENTITY.set(t,r);const i=f.COLLECTED_EXCLUDED_KEYS.get(e);i&&f.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!q.isEnabled()||f.warnedPositionalRowFallbacks.has(e)||(f.warnedPositionalRowFallbacks.add(e),g.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!q.isEnabled()||e.getRawAttribute(`${c.prefix}each-key`)!==null)return;const t=e.getRawAttribute(`${c.prefix}each`);t===null||f.resolveLeadingPath(t)!==null||f.warnedDerivedRowsWithoutKey.has(t)||(f.warnedDerivedRowsWithoutKey.add(t),g.warn("[Haori]",`${c.prefix}each="${t}" の一覧を ${c.prefix}form-list で収集していますが、${c.prefix}each-key がありません。行と配列要素を出現順で対応付けるため、画面に出ていない要素があると行の値を取り違えます。${c.prefix}each-key を宣言してください。`))}static mergeCollectedValues(e,t,r=null){const i={...e??{}};for(const[s,a]of Object.entries(t)){if(f.UNSAFE_MERGE_KEYS.has(s))continue;const o=e&&Object.prototype.hasOwnProperty.call(e,s)?e[s]:r?.(s);i[s]=f.overlayCollectedValue(o,a)}const n=f.COLLECTED_EXCLUDED_KEYS.get(t);if(n)for(const s of n)s in t||delete i[s];return i}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const n=f.overlayIdentifiedRows(e,t);return n!==null?n:t.map((s,a)=>f.overlayCollectedValue(e[a],s))}const r=f.asPlainRecord(t),i=f.asPlainRecord(e);return r===null||i===null?t:f.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=f.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(`${c.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${c.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=f.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=C.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=f.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=f.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(s=>f.asPlainRecord(s)!==null)&&f.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return f.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(s=>s===null))return null;const i=f.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 l=o.shift();n[l]=f.overlayCollectedValue(e[l],t[s])}return n}static syncAncestorArgForms(e,t,r=null,i=null){const n=[];for(const{form:a,key:o}of f.collectArgForms(e)){if(a.wasResetAfter(t))continue;const l=f.resolveAncestorArgOwner(a,o);!l||l.owner!==e||n.push(f.pushAncestorArgValue(a,o,l.value,r))}const s=e.getRawBindingData();for(const{form:a,keys:o}of f.collectShadowingContainers(e)){if(a.wasResetAfter(t))continue;const l=o.filter(u=>f.createArgValueSignature(i?.[u])!==f.createArgValueSignature(s?.[u]));l.length!==0&&n.push(f.releaseOwnCopy(a,l,r))}return Promise.all(n).then(()=>{})}static collectShadowingContainers(e){const t=`${c.prefix}form-arg`,r=[];return e.getTarget().querySelectorAll(`form:not([${t}]), [${c.prefix}form]`).forEach(i=>{const n=N.get(i);if(!(n instanceof w))return;const s=n.getRawBindingData();if(s===null)return;const a=f.getInitialBindingData(n),o=Object.keys(s).filter(l=>Object.prototype.hasOwnProperty.call(a??{},l)?!1:f.resolveAncestorKeyOwner(n,l)?.owner===e);o.length>0&&r.push({form:n,keys:o})}),r}static releaseOwnCopy(e,t,r=null){const i=e.getRawBindingData();if(i===null)return Promise.resolve();const n={...i};for(const s of t)delete n[s];return C.setBindingData(e.getTarget(),n,{kind:r?.kind??"supply",sequence:r?.sequence??w.nextSequence()})}static collectArgForms(e){const t=`${c.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(n=>{const s=N.get(n);if(!(s instanceof w))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=f.createArgValueSignature(r);if(s!==null){if(f.LAST_ANCESTOR_ARG_VALUES.get(n)===s)return Promise.resolve();f.LAST_ANCESTOR_ARG_VALUES.set(n,s)}else f.LAST_ANCESTOR_ARG_VALUES.delete(n);const a=e.getRawBindingData();return a&&Object.prototype.hasOwnProperty.call(a,t)?f.releaseOwnCopy(e,[t],i):f.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(f.INITIAL_RESTORED_FORMS.has(i))continue;const n=N.get(i);if(!(n instanceof w))continue;const s=n.getRawBindingData(),a=n.getAttribute(`${c.prefix}form-arg`),o=a?String(a):null,l=o!==null&&!(s&&Object.prototype.hasOwnProperty.call(s,o))?f.resolveAncestorArgOwner(n,o):null;if(!(!s&&!l)){if(f.INITIAL_RESTORED_FORMS.add(i),l){r.push(f.pushAncestorArgValue(n,o,l.value));continue}r.push(f.syncValues(n,f.resolveSyncValues(n,s)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];f.collectGroupMembers(f.resolveCollectionScope(e),String(f.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:f.markCompleteSet(s)}:s.length===0?{edited:n,value:null}:{edited:n,value:s.length===1?s[0]:f.markCompleteSet(s)}}static startsCollectionLevel(e){return f.resolveFieldName(e)?!1:!!(e.getAttribute(`${c.prefix}form-object`)||e.getAttribute(`${c.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(f.startsCollectionLevel(r))return r.getAttribute(`${c.prefix}form-object`)?r:t;if(f.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${c.prefix}form`)}static collectGroupMembers(e,t,r){f.isGroupedCheckable(e)&&String(f.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())f.startsCollectionLevel(i)||i.hasAttribute(`${c.prefix}form-detach`)||i.getTarget().hasAttribute(`${c.prefix}if-false`)||f.collectGroupMembers(i,t,r)}static markCompleteSet(e){return f.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&f.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(`${c.prefix}form-detach`)&&!r)return Promise.resolve();const l=f.resolveFieldName(e),u=e.getAttribute(`${c.prefix}form-object`),h=e.getAttribute(`${c.prefix}form-list`),m=e.hasAttribute(`${c.prefix}form-list`);if(l){const y=t[String(l)],E=n&&f.hasResolvedDeclarativeState(e),A=n&&typeof y>"u"&&!f.isDeclarativeStateBound(e);let D=y;if(E?D=void 0:A&&(D=null),f.isFileInput(e))return(D===null||D==="")&&o.push(f.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(m&&Array.isArray(D)&&!f.isGroupedCheckable(e)&&!f.isMultipleSelect(e)){const M=String(l),L=s.get(M)??0;s.set(M,L+1),o.push(f.applyFragmentValue(e,D[L]??null,i,a))}else typeof D>"u"||(Array.isArray(D)&&f.isGroupedCheckable(e)||Array.isArray(D)&&f.isMultipleSelect(e)||typeof D=="string"||typeof D=="number"||typeof D=="boolean"||D===null||Array.isArray(D)&&e.collectsLines()?o.push(f.applyFragmentValue(e,D,i,a)):o.push(f.applyFragmentValue(e,String(D),i,a)))}else if(u){const y=t[String(u)],E=y&&typeof y=="object"?y:{},A=new Map;for(const D of e.getChildElementFragments())o.push(f.setPartValues(D,E,r,i,n,A,a))}else if(h){const y=t[String(h)],E=Array.isArray(y)?y:[],A=e.getChildElementFragments(),D=e.getAttribute(`${c.prefix}each-key`),M=f.isCollectedListFromEachSource(e)?f.pairRowsWithItems(A,E,D==null?null:String(D)):null;for(let L=0;L<A.length;L++){const ee=A[L],x=M?M[L]:E.length>L?E[L]:null;o.push(f.setPartValues(ee,f.asPlainRecord(x)??{},r,i,n,new Map,a))}}else for(const y of e.getChildElementFragments())o.push(f.setPartValues(y,t,r,i,n,s,a));return Promise.all(o).then(()=>{})}static async reset(e,t=w.nextSequence()){const r=f.collectBindingTargetForms(e);if(r.length>0&&r.every(n=>n.isSupplyStale(t)))return;f.markResetSubtree(e,t),C.clearUserEditMarks(e,t),f.clearValues(e),await Promise.all([f.clearMessages(e),f.clearEachClones(e)]),await K.enqueue(()=>{const n=f.collectEditsAfter(e,t),s=e.getTarget();f.internalResetDepth+=1;try{s instanceof HTMLFormElement?s.reset():(s.querySelectorAll("form").forEach(a=>a.reset()),f.restoreDefaultValues(s))}finally{f.internalResetDepth-=1}f.clearDeclarativeStateFromDom(e),C.invalidateDerivedSubtreeSignatures(e),f.restoreEdits(n)});const i=r;for(const n of i){const s=f.getInitialBindingData(n);s===null&&n.getRawBindingData()===null||await C.setBindingData(n.getTarget(),s??{},{sequence:t})}f.syncValuesFromDom(e),await C.evaluateAll(e);for(const n of i)f.getInitialBindingData(n)!==null||n.getRawBindingData()!==null||await f.restoreAncestorArgValues(n,{sequence:t,kind:"supply"});for(const n of i){const s=f.getInitialBindingData(n);if(n.getRawBindingData()===null&&s===null)continue;const a=f.getValues(n),o=n.getAttribute(`${c.prefix}form-arg`);let l={...s||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(s??{},u)&&f.resolveAncestorArgOwner(n,u)!==null||(l[u]=f.mergeCollectedValues(l[u]??null,a))}else l=f.mergeCollectedValues(l,a),f.deleteAncestorOwnedKeys(n,s,l);await C.setBindingData(n.getTarget(),l,{sequence:t})}te.refreshSubtree(e.getTarget())}static deleteAncestorOwnedKeys(e,t,r){for(const i of Object.keys(r))Object.prototype.hasOwnProperty.call(t??{},i)||f.resolveAncestorKeyOwner(e,i)!==null&&delete r[i]}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:C.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())f.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=N.get(n);s instanceof w&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${c.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${c.prefix}each-before`),o=s.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(s.remove())}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())f.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())f.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(`${c.prefix}form-arg`);if(!r)return;const i=String(r),n=f.resolveAncestorArgOwner(e,i);n&&(f.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await f.pushAncestorArgValue(e,i,n.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())f.markResetSubtree(r,t)}static clearMessages(e){return mt().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return f.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=mt(),a=s.addMessage,o=u=>typeof a=="function"?a.call(s,u,r,i):s.addErrorMessage(u,r),l=f.keepFirstRadio(f.findFragmentsByKey(e,t));return l.forEach(u=>{n.push(o(u.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static keepFirstRadio(e){let t=!1;return e.filter(r=>{const i=r.getTarget();return!(i instanceof HTMLInputElement)||i.type!=="radio"?!0:t?!1:(t=!0,!0)})}static findFragmentsByKey(e,t){return f.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&f.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...f.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${c.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),u=Number(l);if(isNaN(u))g.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(m=>m.hasAttribute(`${c.prefix}row`));u<h.length&&r.push(...f.findFragmentByKeyParts(h[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...f.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};f.INITIAL_RESTORED_FORMS=new WeakSet,f.LAST_ANCESTOR_ARG_VALUES=new WeakMap,f.GROUP_SCOPE_IDS=new WeakMap,f.groupScopeSequence=0,f.internalResetDepth=0,f.warnedArgOwnerNotRecord=new WeakMap,f.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),f.COLLECTED_ROW_IDENTITY=new WeakMap,f.COMPLETE_SET_VALUES=new WeakSet,f.COLLECTED_EXCLUDED_KEYS=new WeakMap,f.warnedPositionalRowFallbacks=new Set,f.warnedDerivedRowsWithoutKey=new Set,f.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let F=f;class B{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){B.dispatch(document,"ready",{version:e})}static importStart(e,t){B.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){B.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){B.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const u=t?.[l],h=r[l];u!==h&&n.push(l)}B.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){B.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){B.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){B.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){B.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){B.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){B.dispatch(e,"show",{visible:!0})}static hide(e){B.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){B.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){B.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){B.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){B.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){B.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const Pt={401:"unauthorized-redirect",403:"forbidden-redirect"};function Lt(b,e){return b.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=ie.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Ot(b,e){const t=b.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=N.get(b),i=r instanceof w?r.getBindingData():{},n=Lt(t,i);return n===""?null:n}function Bt(b,e,t){const r=b.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):"",l=a>=0?t.slice(0,a):t,u=l.includes("?")?"&":"?";return`${l}${u}${s}${o}`}function yt(b){const e=Pt[b];if(e===void 0||typeof document>"u")return!1;const t=`${c.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=Ot(i,t);if(n===null)continue;const s=Bt(i,t,n);if(!Te.isNavigableUrl(s))return g.error("Haori",`遷移先が http: / https: / 現在ページと同じスキームの URL ではないため遷移しません: ${s}`),!1;try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class W{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 g.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static queryAllInListOrder(e,t){if(W.queryAll(e,t).length===0)return[];const r=new Set;return W.splitList(e).forEach(i=>{W.queryAll(i,t).forEach(n=>r.add(n))}),Array.from(r)}static splitList(e){const t=[];let r=0,i=null,n=0;for(let s=0;s<e.length;s++){const a=e[s];a==="\\"?s++:i!==null?a===i&&(i=null):a==='"'||a==="'"?i=a:a==="("||a==="["?r++:a===")"||a==="]"?r--:a===","&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t}static query(e,t,r=document.body){try{return r.querySelector(e)}catch(i){return g.error("Haori",`Invalid selector: ${e} (${t})`,i),null}}}const k=class k{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 k.WARNED_KINDS.has(e)||(k.WARNED_KINDS.add(e),g.warn("Haori",`${e}Storage が利用できないため ${c.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return w.isReservedBindingKey(e)}static isPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}static warnOnce(e,t,r){let i=k.WARNED_ELEMENTS.get(e);i||(i=new Set,k.WARNED_ELEMENTS.set(e,i)),!i.has(t)&&(i.add(t),g.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(`${c.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return k.warnOnce(t,"key",`${c.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return k.warnOnce(t,"expression",`${c.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const n=e.getRawAttribute(`${c.prefix}store-type`);let s="session";if(n!==null){const h=n.trim();h==="local"||h==="session"?s=h:k.warnOnce(t,"type",`${c.prefix}store-type は session または local を指定してください(session として扱います): ${h}`)}const a=e.getRawAttribute(`${c.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),l=e.getRawAttribute(`${c.prefix}store-params`);let u=null;if(l!==null){const h=l.split("&").map(y=>y.trim()).filter(y=>y!==""),m=h.filter(y=>!k.isReservedKey(y));m.length!==h.length&&k.warnOnce(t,"reserved",`${c.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=m.length>0?m:null}return u===null&&o===null?(k.warnOnce(t,"target",`${c.prefix}store には ${c.prefix}store-params または ${c.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:s,params:u,arg:o}}static readRecord(e){const t=k.resolveStorage(e.kind);if(!t)return null;let r;try{r=t.getItem(e.key)}catch(n){return g.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,n),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(n){return g.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,n),null}return k.isPlainRecord(i)?i:(g.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(!k.isPlainRecord(s))return g.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=s}const i=e.params??Object.keys(r),n={};for(const s of i)k.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(k.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=k.stringify(t);if(r===null){k.SIGNATURES.delete(e);return}k.SIGNATURES.set(e,{json:r,refs:k.createRefs(t)})}static writeRecord(e,t){const r=k.resolveStorage(e.kind);if(!r)return!1;const i=k.readRecord(e)??{};if(e.arg!==null){const n=i[e.arg],s=k.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 g.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,n),!1}}static restore(e){const t=k.readDeclaration(e);if(!t)return Promise.resolve();const r=e.getTarget();if(k.isInsideEachRow(e))return k.warnOnce(r,"each-row",`${c.prefix}each の行の内側では ${c.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();k.RESTORED_ELEMENTS.add(r);const i=k.readRecord(t),n=i?k.extractFromRecord(t,i):{},s={...e.getRawBindingData()??{},...n};return k.seedSignature(r,k.selectFromData(t,s)),Object.keys(n).length===0?Promise.resolve():C.setBindingData(r,s,{reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()})}static mirror(e){const t=k.readDeclaration(e);if(!t||k.isInsideEachRow(e))return;const r=e.getTarget();if(!k.RESTORED_ELEMENTS.has(r))return;const i=e.getRawBindingData();if(!i)return;const n=k.selectFromData(t,i);if(Object.keys(n).length===0)return;const s=k.SIGNATURES.get(r);if(s&&k.hasSameRefs(s,n))return;const a=k.stringify(n);if(a===null){g.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(s&&s.json===a){s.refs=k.createRefs(n);return}k.writeRecord(t,n)&&k.SIGNATURES.set(r,{json:a,refs:k.createRefs(n)})}static clear(e,t){const r=k.resolveStorage(t);if(r){try{r.removeItem(e)}catch(i){g.warn("Haori",`ストレージの破棄に失敗しました: ${e}`,i);return}k.reseedDeclaringElements(e,t)}}static reseedDeclaringElements(e,t){document.querySelectorAll(`[${c.prefix}store]`).forEach(i=>{if(!k.RESTORED_ELEMENTS.has(i))return;const n=N.get(i);if(!(n instanceof w))return;const s=k.readDeclaration(n);if(!s||s.key!==e||s.kind!==t)return;const a=n.getRawBindingData();k.seedSignature(i,a?k.selectFromData(s,a):{})})}};k.SIGNATURES=new WeakMap,k.RESTORED_ELEMENTS=new WeakSet,k.WARNED_ELEMENTS=new WeakMap,k.WARNED_KINDS=new Set;let De=k;const Ht=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Ut="__haoriHistoryState__",je="data-haori-click-lock",bt="ファイルを保存できませんでした",Vt=100;let Ne=null;const qt=["info","warning","error","success"],Et=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message|bind)$/;function pe(){const e=globalThis.window?.Haori;return Ht.every(r=>typeof e?.[r]=="function")?e:ce}const Wt=new Set(["GET","HEAD","OPTIONS"]);function Pe(b){return Wt.has(b.toUpperCase())}function jt(b,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{b.append(t,Ee(i))}):b.append(t,Ee(r)))}function Ee(b){if(b==null)return"";if(typeof b=="object"||typeof b=="function")try{return JSON.stringify(b)??""}catch{return""}return String(b)}function At(b,e){const t=new URL(b,window.location.href),r=new URLSearchParams(t.search);return jt(r,e),t.search=r.toString(),t.toString()}function Kt(b){if(b==null)return{payload:{},dropped:!1};if(typeof b=="string"){const e=b.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:vt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(b instanceof URLSearchParams)return{payload:vt(b),dropped:!1};if(typeof FormData<"u"&&b instanceof FormData){const e={};let t=!1;for(const[r,i]of b.entries()){if(typeof i!="string"){t=!0;continue}St(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function vt(b){const e={};for(const[t,r]of b.entries())St(e,t,r);return e}function St(b,e,t){const r=b[e];r===void 0?b[e]=t:Array.isArray(r)?r.push(t):b[e]=[r,t]}function ge(b,e){if(F.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(b)?b.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=ge(t[n],i),r=!0))}),r?t:b}if(e!==null&&typeof e=="object"){const t=b!==null&&typeof b=="object"&&!Array.isArray(b)?{...b}:{};for(const[r,i]of Object.entries(e))t[r]=ge(t[r],i);return t}return e}function zt(b){const e=b?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Gt(b,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Pe(r))return{url:b,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Kt(t.body);let s=b;Object.keys(i).length>0&&(s=At(s,i)),n&&g.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${c.prefix}{event}-data / ${c.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 Yt(b){return b==null?null:typeof b=="string"?b:b instanceof URLSearchParams?b.toString():b instanceof FormData?Array.from(b.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(b)}function Fe(b){return b instanceof Blob?!0:Array.isArray(b)?b.some(Fe):b!==null&&typeof b=="object"?Object.values(b).some(Fe):!1}function Xt(b){return Object.values(b).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Fe(t)):Fe(e))}function Le(b){return Ke(F.getValues(b))}function Ke(b){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(b))t[r]=e(i);return F.carryCollectedRowIdentity(b,t),t}function Jt(b,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:b,method:String(e.method||"GET").toUpperCase(),headers:r,body:Yt(e.body||null)})}const p=class p{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.downloadReceivedBytes=0,this.downloadTotalBytes=null,this.downloadFolder=null,this.twoWayCommitBind=!1,this.skipped=!1,this.operationSequence=r!=null?w.nextOperationSequence():w.nextSequence(),p.isElementFragment(e)?(this.options=p.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static recordClickOutcome(e,t){p.CLICK_OUTCOMES.set(e,t)}static takeClickOutcome(e){const t=p.CLICK_OUTCOMES.get(e);return t?(p.CLICK_OUTCOMES.delete(e),t):null}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static resolveSelectorTargets(e,t,r){const i=W.read(e,t),n=[];if(i)(r==="click"||r==="error-click"?W.queryAllInListOrder(i,t):W.queryAll(i,t)).forEach(a=>{const o=N.get(a);o&&n.push(o)}),n.length===0&&g.error("Haori",`Element not found: ${i} (${t})`);else if(r==="error-click")g.error("Haori",`${t} にはクリックする要素のセレクタが必要です。`);else if(r==="open"||r==="close"||r==="error-close"){const s=e.getTarget().closest("dialog");s?n.push(N.get(s)):g.error("Haori",`Ancestor <dialog> not found (${t})`)}else n.push(e);return n}static readToastLevel(e,t,r,i){return p.toToastLevel(p.readLateAttribute(e,t,r,i))}static readNoMessageDeclarations(e,t,r){const i=p.attrName(r,"error-status");e.hasAttribute(i)&&(t.errorStatuses=p.parseErrorStatuses(e.getRawAttribute(i),i)),t.errorNoMessage=e.hasAttribute(p.attrName(r,"error-no-message"));const n=p.attrName(r,"error-"),s=new Map;for(const a of e.getAttributeNames()){const o=a.startsWith(n)?Et.exec(a.slice(n.length)):null;o&&o[2]==="no-message"&&s.set(Number(o[1]),{key:`error-${o[1]}`,clickFragments:null,clickAwait:!1,closeFragments:null,toastMessage:null,toastLevel:null,noMessage:!0,bind:!1})}t.errorStatusActions=s}static readErrorStatusActions(e,t,r){const i=p.attrName(r,"error-"),n=new Set;for(const a of e.getAttributeNames()){if(!a.startsWith(i))continue;const o=Et.exec(a.slice(i.length));o&&n.add(o[1])}const s=new Map;return n.forEach(a=>{const o=`error-${a}`,l=u=>p.attrName(r,`${o}-${u}`);s.set(Number(a),{key:o,clickFragments:e.hasAttribute(l("click"))?p.resolveSelectorTargets(e,l("click"),"error-click"):null,clickAwait:e.hasAttribute(l("click-await")),closeFragments:e.hasAttribute(l("close"))?p.resolveSelectorTargets(e,l("close"),"error-close"):null,toastMessage:p.readLateAttribute(e,t,`${o}-toast`,l("toast")),toastLevel:p.readToastLevel(e,t,`${o}-toast-level`,l("toast-level")),noMessage:e.hasAttribute(l("no-message")),bind:e.hasAttribute(l("bind"))})}),s}static toToastLevel(e){return qt.includes(e)?e:null}static parseErrorStatuses(e,t){const r=[];for(const i of(e??"").split("&")){const n=i.trim();/^\d{3}$/.test(n)?r.push(Number(n)):g.warn("Haori",`${t} の "${n}" は 3 桁のステータスではないため無視します。`)}return r}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 readFetchHeaders(e,t){if(!e.hasAttribute(t))return null;const r=e.getRawAttribute(t);let i;try{i=C.parseDataBind(r)}catch(n){return g.error("Haori",`Invalid fetch headers: ${n}`),null}return i===null||typeof i!="object"||Array.isArray(i)?(g.warn("Haori",`${t} はヘッダー名と値のオブジェクトで指定してください(${Array.isArray(i)?"配列":`${typeof i} 型の値`}が指定されたため、ヘッダーは設定しません)。`),null):i}static hasDeclaredContentType(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>t.toLowerCase()==="content-type")}static withContentType(e,t){const r={};return e&&typeof e=="object"&&Object.entries(e).forEach(([i,n])=>{i.toLowerCase()!=="content-type"&&(r[i]=n)}),r["Content-Type"]=t,r}static invokeFetch(e,t){try{return fetch(e,t)}catch(r){return Promise.reject(r)}}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
16
- `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(p.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=ie.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"?p.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(p.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=ie.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,p.isJsonStringContext(e,o)?p.stringifyJsonTemplateStringContent(l.value):p.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return p.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(p.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:C.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=p.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:C.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=p.resolveDataParamStringDetailed(r,e.getBindingData());return{value:C.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?p.attrName(t,"if"):p.attrName(null,"if",!0);if(e.hasAttribute(i)){const R=e.getRawAttribute(i);typeof R=="string"&&R.trim()!==""?(r.conditionExpression=F.unwrapConditionExpression(R),r.conditionAttributeName=i):g.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(p.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(p.attrName(t,"confirm"))&&(r.confirmMessage=p.unescapeNewlines(p.normalizeAttributeText(e.getAttribute(p.attrName(t,"confirm"))))),e.hasAttribute(p.attrName(t,"data"))&&(r.dataAttrName=p.attrName(t,"data")),e.hasAttribute(p.attrName(t,"form"))){const $=W.read(e,p.attrName(t,"form"));if($){const z=W.query($,p.attrName(t,"form"));z!==null?r.formFragment=F.getFormFragment(N.get(z)):g.error("Haori",`Form element not found: ${$} (${p.attrName(t,"form")})`)}else r.formFragment=F.getFormFragment(e)}else if(t==="change"||t==="input"){r.formFragment=F.getFormFragment(e);const $=`${c.prefix}${t}-`;r.implicitFormFragment=!e.getAttributeNames().some(z=>z.startsWith($)),r.formFragment===null&&p.isNamedInputFragment(e)&&(r.selfValueFragment=e)}if(e.hasAttribute(`${c.prefix}${t}-before-run`)){const $=e.getRawAttribute(`${c.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
19
+ `)===n?(this.value=s,Promise.resolve()):this.writeScalarValue(n,t,r)}writeScalarValue(e,t,r=null){const i=this.getTarget(),s=e===null?"":String(e);this.value=this.normalizeValueForElement(i,e);const n=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(n)||r&&!this.canApplyValue(r))return;const a=i.value;i.value=s,this.recordValueWriteResult(i.value===s),i.value!==a&&v.notifyValueToEnhancers(i),t&&((i instanceof HTMLInputElement&&v.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 s=this.userEditSequence;return this.enqueueValueWrite(()=>{if(this.isSupersededByUserEdit(s)||r&&!this.canApplyValue(r))return;let n=!1;const a=new Set;Array.from(i.options).forEach(o=>{const l=e.includes(o.value);o.selected!==l&&(o.selected=l,n=!0),l&&a.add(o.value)}),this.recordValueWriteResult(e.every(o=>a.has(o))),n&&v.notifyValueToEnhancers(i),n&&t&&i.dispatchEvent(new Event("change",{bubbles:!0}))})}enqueueValueWrite(e){this.skipChangeValue=!0;const t=Y.enqueue(e).finally(()=>{this.skipChangeValue=!1});return this.pendingValueWrite=t,t}isSupersededByUserEdit(e){return this.userEditSequence!==e}static retryUnappliedValueWrites(e,t){if(v.UNAPPLIED_VALUE_WRITES.size===0)return Promise.resolve();const r=[];for(const i of Array.from(v.UNAPPLIED_VALUE_WRITES)){const s=i.getTarget();if(i.wasResetAfter(t)){i.clearUnappliedValueWrite();continue}if(!s.isConnected){i.clearUnappliedValueWrite();continue}e.contains(s)&&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(s=>s.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()}static notifyValueToEnhancers(e){se.isApplied(e)&&se.refreshSubtree(e)}clearUnappliedValueWrite(){this.valueWriteUnapplied=!1,v.UNAPPLIED_VALUE_WRITES.delete(this)}getValue(){return this.value}static currentSequence(){return v.sequenceCounter}static nextSequence(){return v.sequenceCounter+=1,v.sequenceCounter}static setPendingMutationFlusher(e){v.pendingMutationFlusher=e}static nextOperationSequence(){return v.pendingMutationFlusher&&!v.isExecutingAnyBindingWork()&&v.pendingMutationFlusher(),v.nextSequence()}canApplyValue(e){return e.kind==="nonSupply"&&e.editedPaths!==void 0&&this.userEditSequence>0&&this.wasResetAfter(this.userEditSequence)?!1:v.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 v.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=v.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=v.currentSequence()){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e),this.lastValueKind==="edit"&&this.lastValueSequence<=e&&(this.lastValueKind="supply")}static warnUnresolvedAttribute(e,t,r,i){if(!U.isEnabled())return;const s=`${e} ${r}`;v.loggedUnresolvedAttributes.has(s)||(v.loggedUnresolvedAttributes.add(s),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 s=`${e} ${t}`;v.loggedTypeMismatchedComparisons.has(s)||(v.loggedTypeMismatchedComparisons.add(s),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 ${c.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=D.get(t);return r instanceof v?r.hasPendingUserEdit():!1}static captureSelection(e){const t=Array.from(e.options),r=t.map(i=>i.selected);return()=>{t.forEach((i,s)=>{i.selected=r[s]})}}getCheckableUserEditSequence(e){if(!e)return this.userEditSequence;const t=D.get(this.getTarget().closest("select"));return t instanceof v?t.userEditSequence:null}clearValue(){this.value=null,this.clearUnappliedValueWrite()}normalizeValueForElement(e,t){const r=v.resolveDeclaredValueType(e);return r==="lines"?v.normalizeLinesValue(t):r==="boolean"?v.normalizeBooleanValue(t):r==="string"?t===null?null:String(t):r==="number"||r===null&&e instanceof HTMLInputElement&&e.type==="number"?v.normalizeNumberValue(t):t}static normalizeLinesValue(e){return(Array.isArray(e)?e.filter(r=>r!==null).map(String):e===null?[]:String(e).split(`
20
+ `)).map(r=>r.trim()).filter(r=>r!=="")}static normalizeNumberValue(e){if(e===null||e==="")return null;if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||!v.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(`${c.prefix}value-type`);if(t===null)return null;const r=t.trim().toLowerCase();return v.VALUE_TYPE_NAMES.has(r)?r==="lines"&&!(e instanceof HTMLTextAreaElement)?(v.warnValueTypeDeclaration(e,t,"lines は <textarea> にのみ指定できます"),null):v.acceptsDeclaredValueType(e)?r:(v.warnValueTypeDeclaration(e,t,"値を持つ入力(checkbox / radio / file と複数選択の select を除く)にのみ指定できます"),null):(v.warnValueTypeDeclaration(e,t,"boolean / number / string / lines のいずれかを指定してください"),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(!U.isEnabled())return;const i=e instanceof HTMLInputElement?`[type=${e.type}]`:"",s=`${e.tagName}${i} ${t} ${r}`;v.loggedValueTypeDeclarations.has(s)||(v.loggedValueTypeDeclarations.add(s),m.warn("Haori",`${c.prefix}value-type="${t}" を無視しました(${r}):`,e))}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?v.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(v.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,v.UNAPPLIED_VALUE_WRITES.add(this);return}this.clearUnappliedValueWrite()}getValueForCollection(){return this.skipChangeValue||this.valueWriteUnapplied?this.value:v.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=D.get(t);r instanceof v&&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(),s=i.hasAttribute(e),n=t!==e&&i.hasAttribute(t);if(!s&&!n)return Promise.resolve();const a=Y.enqueue(()=>{s&&i.removeAttribute(e),n&&i.removeAttribute(t)}).finally(()=>{this.releaseSelfWritingAttributes(r)});return this.holdSelfWritingAttributes(r,a),a}setAttributeInternal(e,t,r,i,s=!1){const n=[e,t],a=this.getSelfWritingAttribute(n);if(a!==null)return s||r===null?Promise.resolve():a.then(()=>this.setAttributeInternal(e,t,r,i,s));if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const o=new Ge(e,r);if(s){const fe=this.attributeMap.get(e);if(fe&&(fe.isEvaluate||fe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const ke=Y.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,ke),ke}}this.attributeMap.set(e,o);const l=this.getTarget(),u=o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),d=o.isEvaluate||o.isRawEvaluate,y=e===t&&v.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),b=o.isSingleExpression(),E=ge.joinEvaluateResults(u.results),A=u.results.length===1?u.results[0]:E,k=t==="value"&&v.resolveDeclaredValueType(l)==="boolean",M=A===!1&&!k,P=!o.isForceEvaluation()&&(t!==e?u.hasUnresolvedReference||A===null||A===void 0||M:y?u.hasUnresolvedReference||A===null||A===void 0||A===!1:b?u.hasUnresolvedReference||A===null||A===void 0||M:d&&E==="");if(P&&u.hasUnresolvedReference&&v.warnUnresolvedAttribute(e,t,r,l),U.isEnabled()&&A===!1&&b){const fe=o.getSingleExpression(),ke=fe===null?null:ne.diagnoseStrictComparison(fe,this.getBindingData());ke!==null&&v.warnTypeMismatchedComparison(e,r,ke,l)}const ie=o.isForceEvaluation()?r:b?A:E,F=i&&o.isEvaluate&&t==="value"&&v.isValuePropertyTarget(l),Q=l.getRootNode(),te=this.userEditSequence,_=F&&v.isUserEditableValue(l)&&(l===Q.activeElement||this.hasPendingUserEdit()),z=P||ie===null||ie===!1&&!k?null:String(ie),ce=o.isEvaluate&&z!==null&&v.URL_ATTRIBUTES.has(t)&&$e.hasScriptScheme(z);ce&&m.warn("[Haori]",`Attribute "${t}" was removed because the evaluated URL uses a script scheme: ${e}="${r}" -> ${z}`,l);const w=ce?null:z,O=e!==t&&l.getAttribute(e)!==r,j=w===null?l.hasAttribute(t):l.getAttribute(t)!==w,V=w===null?"":w,de=F&&!_&&l.value!==V,Ue=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),oe=t==="selected"&&l instanceof HTMLOptionElement,W=Q.activeElement,G=W!==null&&(Ue&&l===W||oe&&l.closest("select")===W)||(Ue||oe)&&this.hasPendingCheckableUserEdit(oe),re=this.getCheckableUserEditSequence(oe),Te=w!==null,ct=Ue&&o.isEvaluate&&!G&&l.checked!==Te,Ze=oe&&o.isEvaluate&&!G&&l.selected!==Te;if(!O&&!j&&!de&&!ct&&!Ze)return F&&!_&&(this.value=this.normalizeValueForElement(l,V),this.clearUnappliedValueWrite()),(Ue||oe)&&!G&&this.syncCheckableValueFromDom(oe),Promise.resolve();const _t=Y.enqueue(()=>{const fe=this.getCheckableUserEditSequence(oe)!==re,ke=oe&&(G||fe)?v.captureSelection(l.closest("select")):null;O&&l.setAttribute(e,r),w===null?l.removeAttribute(t):j&&(l.setAttribute(t,w),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(w)),t==="style"&&this.captureAndHideDisplay(),ke?.(),F&&!_&&!(v.isUserEditableValue(l)&&this.isSupersededByUserEdit(te))&&(this.value=this.normalizeValueForElement(l,V),de&&(l.value=V),this.recordValueWriteResult(l.value===V));const Ur=ct&&!fe,Hr=Ze&&!fe;Ur&&(l.checked=Te),Hr&&(l.selected=Te),(ct||Ze)&&this.syncCheckableValueFromDom(Ze)}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,_t),_t}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=Y.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:ge.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 s=t?r.nextSibling:r;for(;s!==null;){const n=D.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}replaceChildNodesWithHtml(e){const t=Array.from(this.target.childNodes);t.forEach(i=>this.holdSkipMutationNode(i)),this.target.innerHTML=e;const r=Array.from(this.target.childNodes);return r.forEach(i=>this.holdSkipMutationNode(i)),()=>{t.forEach(i=>this.releaseSkipMutationNode(i)),r.forEach(i=>this.releaseSkipMutationNode(i))}}insertBefore(e,t,r){if(this.isSkipMutationNode(e.getTarget()))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 s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=this.linkChild(e,t,r),a=this.skipMutationNodes;return this.skipMutationNodes=!0,this.holdSkipMutationNode(e.getTarget()),Y.enqueue(()=>{this.target.insertBefore(e.getTarget(),n)}).finally(()=>{this.skipMutationNodes=a,this.releaseSkipMutationNode(e.getTarget())})}attachObserved(e,t){this.linkChild(e,t)}linkChild(e,t,r){const i=e.getParent()===this;let s=-1,n=-1;i&&(s=this.children.indexOf(e),t!==null&&(n=this.children.indexOf(t)));const a=e.getParent();a!==null&&a.removeChild(e);let o=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let l;if(i?s!==-1&&s<n?l=n-1:l=n:l=this.children.indexOf(t),l===-1){const u=this.resolveInsertionPointFromDom(t,!1);u===null?(m.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(u.index,0,e),o=u.referenceNode)}else this.children.splice(l,0,e)}return e.setParent(this),e.setMounted(this.mounted),o}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}captureAndHideDisplay(){if(this.visible)return;const e=this.getTarget().style;this.display=e.getPropertyValue("display"),this.displayPriority=e.getPropertyPriority("display"),e.setProperty("display","none","important")}hideDisplayWithoutCapture(){if(this.visible)return;const e=this.getTarget().style;e.getPropertyValue("display")==="none"&&e.getPropertyPriority("display")==="important"||e.setProperty("display","none","important")}static reassertHiddenDisplay(e){const t=D.get(e);t instanceof v&&t.hideDisplayWithoutCapture()}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.captureAndHideDisplay(),e.setAttribute(`${c.prefix}if-false`,""),v.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Ut)&&t(e);const r=i=>{Array.from(i.children).forEach(s=>{s.hasAttribute(`${c.prefix}if-false`)||(s instanceof HTMLElement&&s.matches(Ut)&&t(s),r(s))})};r(e)}static disableFormControlsInBranch(e){v.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(ye,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){v.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(ye)&&(e.removeAttribute(ye),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(`${c.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)}};v.NUMBER_INPUT_PATTERN=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/,v.VALUE_TYPE_NAMES=new Set(["boolean","number","string","lines"]),v.loggedValueTypeDeclarations=new Set,v.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"]),v.URL_ATTRIBUTES=new Set(["href","src","action","formaction","xlink:href","poster","data","cite","background"]),v.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],v.UNAPPLIED_VALUE_WRITES=new Set,v.sequenceCounter=0,v.bindingWorkActiveCount=0,v.pendingMutationFlusher=null,v.loggedUnresolvedAttributes=new Set,v.loggedTypeMismatchedComparisons=new Set;let R=v;class le extends D{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new ge(this.text)}clone(){const e=new le(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 ge(e),this.evaluate())}evaluate(){if(this.contents.isRawEvaluate&&this.parent===null)return Promise.reject(new Error("Parent fragment is required for raw evaluation"));let e=null;return Y.enqueue(()=>{this.skipMutation=!0;let t=this.text;this.contents.isEvaluate&&(t=ge.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const r=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===t&&r===t||(this.contents.isRawEvaluate?e=this.parent.replaceChildNodesWithHtml(t):this.target.textContent=t,this.renderedText=t)}).finally(()=>{this.skipMutation=!1,e?.()})}}class rt extends D{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new rt(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,Y.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const Je=class Je{constructor(e,t=!1){if(this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e,t){this.contents.push({text:e,type:0});return}const r=[...e.matchAll(Je.PLACEHOLDER_REGEX)];let i=0,s=!1,n=!1;for(const a of r){a.index>i&&this.contents.push({text:e.slice(i,a.index),type:0});const o={text:a[1]??a[2],type:a[1]?2:1};s=!0,n=n||o.type===2,this.contents.push(o),i=a.index+a[0].length}i<e.length&&this.contents.push({text:e.slice(i),type:0}),this.isEvaluate=s,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 s=[],n=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const u=ze.measure(()=>ne.evaluateDetailed(l.text,e)),d=u.value;a+=u.durationMs,n.push({expression:l.text,durationMs:u.durationMs}),o=o||d.unresolvedReference,s.push(d.value)}else s.push(l.text)}catch(u){m.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,u),n.push({expression:l.text,durationMs:0}),s.push("")}}),ze.record(t,n,a),{results:s,hasUnresolvedReference:o}}};Je.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let ge=Je;const Z=class Z extends ge{constructor(e,t){const r=Z.isEventHandlerAttribute(e);super(t,e===`${c.prefix}bind`||r),this.name=e,this.forceEvaluation=Z.needsForceEvaluation(e),this.checksUrlPath=Z.isRequestUrlAttribute(e),r&&U.isEnabled()&&t.includes("{{")&&Z.warnEventHandlerPlaceholder(e,t)}static isEventHandlerAttribute(e){const t=`${c.prefix}attr-`;return(e.startsWith(t)?e.slice(t.length):e).startsWith("on")}static isRequestUrlAttribute(e){return e===`${c.prefix}import`||e.startsWith(c.prefix)&&e.endsWith("fetch")}static warnEventHandlerPlaceholder(e,t){const r=`${e}\0${t}`;Z.WARNED_EVENT_HANDLER_PLACEHOLDERS.has(r)||(Z.WARNED_EVENT_HANDLER_PLACEHOLDERS.add(r),m.warn("[Haori]",`Placeholders in event handler attributes are not evaluated: ${e}="${t}". Use ${c.prefix}{event}-run, or read the bound value inside the called function.`))}diagnoseUrlPathValues(e){let t=!1,r="";this.contents.forEach((i,s)=>{const n=String(e[s]);if(i.type===0)t=!0;else if(t&&!/[?#]/.test(r)&&Z.changesUrlPath(n)){const a=`${this.name}\0${this.getValue()}\0${n}`;Z.WARNED_URL_PATH_VALUES.has(a)||(Z.WARNED_URL_PATH_VALUES.add(a),m.warn("[Haori]",`A value embedded in the URL path is not URL-encoded and changes the request path: ${this.name}="${this.getValue()}", value: ${n}. Encode it with encodeURIComponent, or send it as a query.`))}r+=n})}static changesUrlPath(e){return/[/\\?#]/.test(e)||/^(?:\.|%2e){1,2}$/i.test(e)}static needsForceEvaluation(e){if(Z.forceEvaluationNames===null||Z.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Z.FORCE_EVALUATION_PREFIXES])for(const i of Z.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Z.forceEvaluationNames=t,Z.forceEvaluationPrefix=c.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.checksUrlPath&&U.isEnabled()&&this.diagnoseUrlPathValues(r.results),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,Z.WARNED_EVENT_HANDLER_PLACEHOLDERS=new Set,Z.WARNED_URL_PATH_VALUES=new Set;let Ge=Z;const Ht="[Haori]",Vt={nameRequired:"Handler name is required.",notFunction:f=>`Handler "${f}" must be a function.`},Se=class Se{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error(Ht,Vt.nameRequired);return}if(typeof t!="function"){m.error(Ht,Vt.notFunction(r));return}Se.handlers.set(r,t)}static has(e){return Se.handlers.has(e)}static get(e){return Se.handlers.get(e)}static entries(){return Object.fromEntries(Se.handlers)}};Se.handlers=new Map;let be=Se;const Re=class Re{static get runtime(){return c.runtime}static setRuntime(e){c.setRuntime(e)}static get csp(){return c.csp}static setCsp(e){c.setCsp(e)}static waitForRenders(){return Y.waitForIdle()}static dialog(e){return Y.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 Y.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return Y.enqueue(()=>{e instanceof HTMLDialogElement?(Re.clearMessagesSync(e),e.showModal()):m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return Y.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Re.addMessage(e,t,"error")}static addMessage(e,t,r){return Y.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 Y.enqueue(()=>{!(e instanceof HTMLFormElement)&&e.parentElement&&(e.parentElement.removeAttribute("data-message"),e.parentElement.removeAttribute("data-message-level")),Re.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 He(e,t,r)}static now(e,t){return yt(e,t)}static today(e,t,r){return bt(e,t,r)}static number(e,t){return Et(e,t)}static range(e,t,r){return At(e,t,r)}static pages(e,t,r){return vt(e,t,r)}static monthAdd(e,t){return qe(e,t)}static monthRange(e,t){return wt(e,t)}static pageSummary(e,t){return St(e,t)}static findBy(e,t,r){return Rt(e,t,r)}static sum(e,t){return Tt(e,t)}static distinct(e,t){return Dt(e,t)}static groupBy(e,t){return xt(e,t)}};Re.handlers={register(e,t){be.register(e,t)},has(e){return be.has(e)}},Re.enhancers={register(e,t){se.register(e,t)},has(e){return se.has(e)}};let he=Re;const mr="入力内容を確認してください",yr=["addErrorMessage","clearMessages"],qt="data-haori-group-name";function Wt(){const e=globalThis.window?.Haori;return yr.every(r=>typeof e?.[r]=="function")?e:he}const p=class p{static getValues(e){const t={},r=new Set;return p.getPartValues(e,t,null,r),p.registerCollectedExcludedKeys(t,r),t}static resolveCollectedValue(e){const t=e.getTarget();if(p.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(p.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(`${c.prefix}form-name`);return t||e.getAttribute("name")}static clearRowUserEditMarksForChangedKeys(e,t){const r=p.getValues(e),i=new Set;for(const s of new Set([...Object.keys(r),...Object.keys(t)]))p.isSameCollectedValue(r[s],t[s])||i.add(s);i.size!==0&&p.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=p.resolveRowTopLevelKey(e,t);i!==null&&r.has(i)&&e.clearUserEditMark(),e.getChildElementFragments().forEach(s=>{p.clearUserEditMarksForKeys(s,t,r)})}static resolveRowTopLevelKey(e,t){let r=null,i=e;for(;i!==null&&i!==t;){const s=i.getAttribute(`${c.prefix}form-object`)||i.getAttribute(`${c.prefix}form-list`)||p.resolveFieldName(i);s!=null&&String(s)!==""&&(r=String(s)),i=i.getParent()}return r}static prepareFormName(e){if(!e.hasAttribute(`${c.prefix}form-name`))return;const t=e.getAttribute(`${c.prefix}form-name`);if(!t){m.warn("Haori",`${c.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(qt))return;const i=p.resolveGroupScope(e),s=`${String(t)}--haori${p.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==s)return e.setAttribute(qt,"").then(()=>e.setAttribute("name",s))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${c.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${c.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=p.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(p.groupScopeSequence+=1,p.GROUP_SCOPE_IDS.set(e,p.groupScopeSequence),p.groupScopeSequence)}static hasResolvedDeclarativeState(e){if(!p.isDeclarativeStateBound(e))return!1;const t=e.getTarget();if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))return p.isDeclarationResolved(e,"checked");if(p.hasDeclarativeBinding(e,"value"))return p.isDeclarationResolved(e,"value");if(t instanceof HTMLSelectElement){for(const r of Array.from(t.options)){const i=D.get(r);if(i instanceof R&&p.hasDeclarativeBinding(i,"selected")&&!p.isDeclarationResolved(i,"selected"))return!1}return!0}return!1}static isDeclarationResolved(e,t){for(const r of[`${c.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")?p.hasDeclarativeBinding(e,"checked"):R.isValuePropertyTarget(t)?p.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?p.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&&p.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(p.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 R&&p.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${c.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=D.get(t);if(r instanceof R&&p.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 p.getPartValues(e,{},t)}static collectEditedPaths(e,t,r="",i=null){const s=new Map;for(const a of p.collectUserEditSequences(e)){const o=new Set;p.walkEditedPaths(p.getValuesEditedAfter(e,a-1),r,o);for(const l of o)s.has(l)||s.set(l,a)}const n=new Set;p.walkExcludedPaths(i??p.getValues(e),r,n);for(const a of n)s.has(a)||s.set(a,t);return s}static collectUserEditSequences(e){const t=new Set;return p.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())p.walkUserEditSequences(i,t)}static walkExcludedPaths(e,t,r){if(Array.isArray(e))return;const i=p.asPlainRecord(e);if(i===null)return;const s=p.COLLECTED_EXCLUDED_KEYS.get(i);if(s)for(const n of s)n in i||r.add(t===""?n:`${t}.${n}`);for(const[n,a]of Object.entries(i))p.walkExcludedPaths(a,t===""?n:`${t}.${n}`,r)}static walkEditedPaths(e,t,r){if(Array.isArray(e))return;const i=p.asPlainRecord(e);if(i!==null){for(const[s,n]of Object.entries(i))p.walkEditedPaths(n,t===""?s:`${t}.${s}`,r);return}t!==""&&r.add(t)}static isResettingInternally(){return p.internalResetDepth>0}static getPartValues(e,t,r=null,i=null){if(e.hasAttribute(`${c.prefix}form-detach`))return t;if(e.getTarget().hasAttribute(`${c.prefix}if-false`)){if(i!==null)for(const u of p.collectDeclaredKeysInFragment(e))i.add(u);return t}const s=p.resolveFieldName(e),n=e.getAttribute(`${c.prefix}form-object`),a=e.getAttribute(`${c.prefix}form-list`),o=e.hasAttribute(`${c.prefix}form-list`),l=r!==null&&e.getUserEditSequence()<=r;if(s){if(r!==null&&p.isGroupedCheckable(e)){const u=p.collectGroupSelection(e,o,r);u.edited&&(t[String(s)]=u.value)}else if(o&&p.isGroupedCheckable(e)){const u=String(s),d=e.getTarget();r===null&&!Array.isArray(t[u])&&(t[u]=[]),!l&&d.checked&&(Array.isArray(t[u])||(t[u]=[]),t[u].push(d.value))}else if(o&&l)Array.isArray(t[String(s)])?t[String(s)].push(null):t[String(s)]=[null];else if(!l)if(o){const u=p.resolveCollectedValue(e),d=p.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(s)])?t[String(s)].push(...d):t[String(s)]=d}else if(p.isGroupedCheckable(e)){const u=e.getTarget(),d=u instanceof HTMLInputElement?u.checked:!0,y=u instanceof HTMLInputElement?u.value:e.getValue(),b=d?y:null,E=String(s);b===null?E in t||(t[E]=null):t[E]===null||t[E]===void 0?t[E]=b:Array.isArray(t[E])?t[E].push(b):t[E]=[t[E],b]}else t[String(s)]=p.resolveCollectedValue(e);n&&m.warn("Haori",`Element cannot have both ${c.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())p.getPartValues(u,t,r,i)}else if(n){const u={},d=i===null?null:new Set;for(const y of e.getChildElementFragments())p.getPartValues(y,u,r,d);d!==null&&p.registerCollectedExcludedKeys(u,d),Object.keys(u).length>0?t[String(n)]=u:i!==null&&(d?.size??0)>0&&i.add(String(n)),a&&m.warn("Haori",`Element cannot have both ${c.prefix}form-list and ${c.prefix}form-object attributes.`)}else if(a){const u=[],d=[];let y=!1;for(const b of e.getChildElementFragments()){const E={},A=i===null?null:new Set;p.getPartValues(b,E,r,A),A!==null&&p.registerCollectedExcludedKeys(E,A),Object.keys(E).length>0?(y=!0,u.push(E),d.push(b.getListKey())):r!==null&&(u.push({}),d.push(b.getListKey()))}if(r===null){const b=e.getAttribute(`${c.prefix}each-key`);p.registerCollectedRowIdentity(u,b==null?null:String(b),d,p.isCollectedListFromEachSource(e)),p.warnDerivedRowsWithoutKey(e),t[String(a)]=u}else y&&(t[String(a)]=u)}else for(const u of e.getChildElementFragments())p.getPartValues(u,t,r,i);return t}static setValues(e,t,r=!1){return p.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1,i=null){return p.setPartValues(e,t,r,!1,!1,new Map,i)}static syncRowValues(e,t,r=null){return p.setPartValues(e,t,!1,!1,!0,new Map,r)}static resolveSyncValues(e,t){const r=e.getAttribute(`${c.prefix}form-arg`);if(!r)return t;const i=String(r);return Object.prototype.hasOwnProperty.call(t,i)?p.asPlainRecord(t[i])??{}:p.resolveAncestorArgOwner(e,i)?.value??{}}static resolveAncestorKeyOwner(e,t){let r=e.getParent();for(;r;){const i=r.getRawBindingData();if(i&&Object.prototype.hasOwnProperty.call(i,t))return r.getListKey()!==null?null:{owner:r,value:i[t]};r=r.getParent()}return null}static resolveAncestorArgOwner(e,t){const r=p.resolveAncestorKeyOwner(e,t);if(r===null)return null;const i=p.asPlainRecord(r.value);return i===null?(p.warnArgOwnerIsNotRecord(e,t,r.value),null):{owner:r.owner,value:i}}static ancestorBaseResolver(e){return t=>p.resolveAncestorKeyOwner(e,t)?.value}static warnArgOwnerIsNotRecord(e,t,r){if(!U.isEnabled()||r==null)return;const i=e.getTarget(),s=p.warnedArgOwnerNotRecord.get(i);s?.has(t)||(s?s.add(t):p.warnedArgOwnerNotRecord.set(i,new Set([t])),m.warn("[Haori]",`${c.prefix}form-arg="${t}" のキーを祖先が${Array.isArray(r)?"配列":`${typeof r} 型の値`}で持っています。${c.prefix}form-arg はそのキーの配下に入力欄が対応することを宣言するため、値はレコード(オブジェクト)である必要があります。このままでは収集値がそのキーへ直接入り、値の型が変わります。`))}static buildConditionScope(e,t=null){const r={...e.getBindingData()},i=t?{source:t,argKey:p.resolveFormArgKey(t)}:p.resolveConditionValueSource(e);if(!i)return r;const s=p.getValues(i.source),n=p.collectDeclaredFieldKeys(i.source);if(i.argKey===null){for(const o of n)r[o]=s[o];return r}const a={...p.asPlainRecord(r[i.argKey])??{}};for(const o of n)a[o]=s[o];return r[i.argKey]=a,r}static resolveConditionValueSource(e){let t=e;for(;t;){const i=t.getParent();if(i&&i.hasAttribute(`${c.prefix}each`)&&i.hasAttribute(`${c.prefix}form-list`)){const s=i.getRawAttribute(`${c.prefix}each-arg`);return{source:t,argKey:typeof s=="string"&&s!==""?s:null}}t=i}const r=p.getFormFragment(e);return r?{source:r,argKey:p.resolveFormArgKey(r)}:null}static resolveFormArgKey(e){const t=e.getAttribute(`${c.prefix}form-arg`);return t?String(t):null}static collectDeclaredFieldKeys(e){return p.collectDeclaredKeysInFragment(e)}static collectDeclaredKeysInFragment(e){const t=new Set,r=e.getTarget(),i=p.resolveFieldName(e);i&&t.add(String(i));const s=`${c.prefix}form-object`,n=`${c.prefix}form-list`,a=r.getAttribute(s)??r.getAttribute(n);if(a)return t.add(a),t;const o=`input[name],select[name],textarea[name],[${c.prefix}form-name],[${s}],[${n}]`;return r.querySelectorAll(o).forEach(l=>{if(!(l instanceof HTMLElement))return;let u=null,d=!1,y=l;for(;y&&y!==r;)y.hasAttribute(`${c.prefix}form-detach`)&&(d=!0),(y.hasAttribute(s)||y.hasAttribute(n))&&(u=y),y=y.parentElement;if(d)return;const b=u??l,E=b.getAttribute(s)||b.getAttribute(n)||b.getAttribute(`${c.prefix}form-name`)||b.getAttribute("name");E&&t.add(E)}),t}static applyCustomValidity(e){const t=`${c.prefix}validity`,r=i=>{i.hasAttribute(t)&&p.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 s=p.buildConditionScope(e),n=ne.evaluateDetailed(p.unwrapConditionExpression(i),s);if(n.unresolvedReference){m.warn("Haori",`${t} の参照が解決できないため無効として扱います: ${i}`),r.setCustomValidity(p.resolveValidityMessage(e));return}r.setCustomValidity(n.value?"":p.resolveValidityMessage(e))}static resolveValidityMessage(e){const t=e.getAttribute(`${c.prefix}validity-message`);return typeof t=="string"&&t.trim()!==""?t:mr}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(!U.isEnabled()||!e)return;const r=`${c.prefix}validity`;(e.hasAttribute(r)||e.getTarget().querySelector(`[${r}]`)!==null)&&m.warn("Haori",`${r} は指定されていますが検証は行われません(${t})。${c.prefix}{event}-validate を指定するか、${c.prefix}{event}-if を使用してください。`)}static asPlainRecord(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}static registerCollectedRowIdentity(e,t,r,i){p.COLLECTED_ROW_IDENTITY.set(e,{keyArg:t,keys:r,identifiesItems:i})}static registerCollectedExcludedKeys(e,t){t.size>0&&p.COLLECTED_EXCLUDED_KEYS.set(e,t)}static carryCollectedRowIdentity(e,t){const r=p.COLLECTED_ROW_IDENTITY.get(e);r&&p.COLLECTED_ROW_IDENTITY.set(t,r);const i=p.COLLECTED_EXCLUDED_KEYS.get(e);i&&p.COLLECTED_EXCLUDED_KEYS.set(t,i)}static warnPositionalRowFallback(e){!U.isEnabled()||p.warnedPositionalRowFallbacks.has(e)||(p.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!U.isEnabled()||e.getRawAttribute(`${c.prefix}each-key`)!==null)return;const t=e.getRawAttribute(`${c.prefix}each`);t===null||p.resolveLeadingPath(t)!==null||p.warnedDerivedRowsWithoutKey.has(t)||(p.warnedDerivedRowsWithoutKey.add(t),m.warn("[Haori]",`${c.prefix}each="${t}" の一覧を ${c.prefix}form-list で収集していますが、${c.prefix}each-key がありません。行と配列要素を出現順で対応付けるため、画面に出ていない要素があると行の値を取り違えます。${c.prefix}each-key を宣言してください。`))}static mergeCollectedValues(e,t,r=null){const i={...e??{}};for(const[n,a]of Object.entries(t)){if(p.UNSAFE_MERGE_KEYS.has(n))continue;const o=e&&Object.prototype.hasOwnProperty.call(e,n)?e[n]:r?.(n);i[n]=p.overlayCollectedValue(o,a)}const s=p.COLLECTED_EXCLUDED_KEYS.get(t);if(s)for(const n of s)n in t||delete i[n];return i}static overlayCollectedValue(e,t){if(Array.isArray(t)){if(!Array.isArray(e))return t;const s=p.overlayIdentifiedRows(e,t);return s!==null?s:t.map((n,a)=>p.overlayCollectedValue(e[a],n))}const r=p.asPlainRecord(t),i=p.asPlainRecord(e);return r===null||i===null?t:p.mergeCollectedValues(i,r)}static resolveLeadingPath(e){const t=p.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(`${c.prefix}form-list`);if(t==null||t==="")return!0;const r=e.getRawAttribute(`${c.prefix}each`);if(typeof r!="string"||r.trim()==="")return!0;const i=p.resolveLeadingPath(r);if(i===null)return!0;const s=i.split(".");return s[s.length-1]===String(t)}static createRowKeyIndexes(e,t){const r=new Map;return e.forEach((i,s)=>{const n=C.createListKey(i,t,s),a=r.get(n);a?a.push(s):r.set(n,[s])}),r}static pairRowsWithItems(e,t,r){const i=e.map(n=>n.getListKey());if(i.some(n=>n===null))return null;const s=p.createRowKeyIndexes(t,r);return i.map(n=>{const a=s.get(n);return!a||a.length===0?null:t[a.shift()]})}static overlayIdentifiedRows(e,t){const r=p.COLLECTED_ROW_IDENTITY.get(t);if(r&&!r.identifiesItems)return null;if(!r)return t.some(n=>p.asPlainRecord(n)!==null)&&p.warnPositionalRowFallback("識別情報が引き継がれていません"),null;if(r.keys.length!==t.length)return p.warnPositionalRowFallback("収集後に行の数が変わっています"),null;if(r.keys.some(n=>n===null))return null;const i=p.createRowKeyIndexes(e,r.keyArg),s=e.slice();for(let n=0;n<t.length;n+=1){const a=r.keys[n],o=i.get(a);if(!o||o.length===0)continue;const l=o.shift();s[l]=p.overlayCollectedValue(e[l],t[n])}return s}static syncAncestorArgForms(e,t,r=null,i=null){const s=[];for(const{form:a,key:o}of p.collectArgForms(e)){if(a.wasResetAfter(t))continue;const l=p.resolveAncestorArgOwner(a,o);!l||l.owner!==e||s.push(p.pushAncestorArgValue(a,o,l.value,r))}const n=e.getRawBindingData();for(const{form:a,keys:o}of p.collectShadowingContainers(e)){if(a.wasResetAfter(t))continue;const l=o.filter(u=>p.createArgValueSignature(i?.[u])!==p.createArgValueSignature(n?.[u]));l.length!==0&&s.push(p.releaseOwnCopy(a,l,r))}return Promise.all(s).then(()=>{})}static collectShadowingContainers(e){const t=`${c.prefix}form-arg`,r=[];return e.getTarget().querySelectorAll(`form:not([${t}]), [${c.prefix}form]`).forEach(i=>{const s=D.get(i);if(!(s instanceof R))return;const n=s.getRawBindingData();if(n===null)return;const a=p.getInitialBindingData(s),o=Object.keys(n).filter(l=>Object.prototype.hasOwnProperty.call(a??{},l)?!1:p.resolveAncestorKeyOwner(s,l)?.owner===e);o.length>0&&r.push({form:s,keys:o})}),r}static releaseOwnCopy(e,t,r=null){const i=e.getRawBindingData();if(i===null)return Promise.resolve();const s={...i};for(const n of t)delete s[n];return C.setBindingData(e.getTarget(),s,{kind:r?.kind??"supply",sequence:r?.sequence??R.nextSequence()})}static collectArgForms(e){const t=`${c.prefix}form-arg`,r=e.getTarget().querySelectorAll(`form[${t}]`),i=[];return r.forEach(s=>{const n=D.get(s);if(!(n instanceof R))return;const a=n.getAttribute(t);a&&i.push({form:n,key:String(a)})}),i}static pushAncestorArgValue(e,t,r,i=null){const s=e.getTarget(),n=p.createArgValueSignature(r);if(n!==null){if(p.LAST_ANCESTOR_ARG_VALUES.get(s)===n)return Promise.resolve();p.LAST_ANCESTOR_ARG_VALUES.set(s,n)}else p.LAST_ANCESTOR_ARG_VALUES.delete(s);const a=e.getRawBindingData();return a&&Object.prototype.hasOwnProperty.call(a,t)?p.releaseOwnCopy(e,[t],i):p.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(p.INITIAL_RESTORED_FORMS.has(i))continue;const s=D.get(i);if(!(s instanceof R))continue;const n=s.getRawBindingData(),a=s.getAttribute(`${c.prefix}form-arg`),o=a?String(a):null,l=o!==null&&!(n&&Object.prototype.hasOwnProperty.call(n,o))?p.resolveAncestorArgOwner(s,o):null;if(!(!n&&!l)){if(p.INITIAL_RESTORED_FORMS.add(i),l){r.push(p.pushAncestorArgValue(s,o,l.value));continue}r.push(p.syncValues(s,p.resolveSyncValues(s,n)))}}return Promise.all(r).then(()=>{})}static collectGroupSelection(e,t,r){const i=[];p.collectGroupMembers(p.resolveCollectionScope(e),String(p.resolveFieldName(e)),i);let s=!1;const n=[];for(const a of i){a.getUserEditSequence()>r&&(s=!0);const o=a.getTarget();o instanceof HTMLInputElement&&o.checked&&n.push(o.value)}return t?{edited:s,value:p.markCompleteSet(n)}:n.length===0?{edited:s,value:null}:{edited:s,value:n.length===1?n[0]:p.markCompleteSet(n)}}static startsCollectionLevel(e){return p.resolveFieldName(e)?!1:!!(e.getAttribute(`${c.prefix}form-object`)||e.getAttribute(`${c.prefix}form-list`))}static resolveCollectionScope(e){let t=e,r=t.getParent();for(;r!==null;){if(p.startsCollectionLevel(r))return r.getAttribute(`${c.prefix}form-object`)?r:t;if(p.isFormScopeRoot(r))return r;t=r,r=r.getParent()}return t}static isFormScopeRoot(e){return e.getTarget()instanceof HTMLFormElement||e.hasAttribute(`${c.prefix}form`)}static collectGroupMembers(e,t,r){p.isGroupedCheckable(e)&&String(p.resolveFieldName(e))===t&&r.push(e);for(const i of e.getChildElementFragments())p.startsCollectionLevel(i)||i.hasAttribute(`${c.prefix}form-detach`)||i.getTarget().hasAttribute(`${c.prefix}if-false`)||p.collectGroupMembers(i,t,r)}static markCompleteSet(e){return p.COMPLETE_SET_VALUES.add(e),e}static isCompleteSetValue(e){return e!==null&&typeof e=="object"&&p.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,s=!1,n=new Map,a=null){const o=[];if(e.hasAttribute(`${c.prefix}form-detach`)&&!r)return Promise.resolve();const l=p.resolveFieldName(e),u=e.getAttribute(`${c.prefix}form-object`),d=e.getAttribute(`${c.prefix}form-list`),y=e.hasAttribute(`${c.prefix}form-list`);if(l){const b=t[String(l)],E=s&&p.hasResolvedDeclarativeState(e),A=s&&typeof b>"u"&&!p.isDeclarativeStateBound(e);let k=b;if(E?k=void 0:A&&(k=null),p.isFileInput(e))return(k===null||k==="")&&o.push(p.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(y&&Array.isArray(k)&&!p.isGroupedCheckable(e)&&!p.isMultipleSelect(e)){const M=String(l),P=n.get(M)??0;n.set(M,P+1),o.push(p.applyFragmentValue(e,k[P]??null,i,a))}else typeof k>"u"||(Array.isArray(k)&&p.isGroupedCheckable(e)||Array.isArray(k)&&p.isMultipleSelect(e)||typeof k=="string"||typeof k=="number"||typeof k=="boolean"||k===null||Array.isArray(k)&&e.collectsLines()?o.push(p.applyFragmentValue(e,k,i,a)):o.push(p.applyFragmentValue(e,String(k),i,a)))}else if(u){const b=t[String(u)],E=b&&typeof b=="object"?b:{},A=new Map;for(const k of e.getChildElementFragments())o.push(p.setPartValues(k,E,r,i,s,A,a))}else if(d){const b=t[String(d)],E=Array.isArray(b)?b:[],A=e.getChildElementFragments(),k=e.getAttribute(`${c.prefix}each-key`),M=p.isCollectedListFromEachSource(e)?p.pairRowsWithItems(A,E,k==null?null:String(k)):null;for(let P=0;P<A.length;P++){const ie=A[P],F=M?M[P]:E.length>P?E[P]:null;o.push(p.setPartValues(ie,p.asPlainRecord(F)??{},r,i,s,new Map,a))}}else for(const b of e.getChildElementFragments())o.push(p.setPartValues(b,t,r,i,s,n,a));return Promise.all(o).then(()=>{})}static async reset(e,t=R.nextSequence()){const r=p.collectBindingTargetForms(e);if(r.length>0&&r.every(s=>s.isSupplyStale(t)))return;p.markResetSubtree(e,t),C.clearUserEditMarks(e,t),p.clearValues(e),await Promise.all([p.clearMessages(e),p.clearEachClones(e)]),await Y.enqueue(()=>{const s=p.collectEditsAfter(e,t),n=e.getTarget();p.internalResetDepth+=1;try{n instanceof HTMLFormElement?n.reset():(n.querySelectorAll("form").forEach(a=>a.reset()),p.restoreDefaultValues(n))}finally{p.internalResetDepth-=1}p.clearDeclarativeStateFromDom(e),C.invalidateDerivedSubtreeSignatures(e),p.restoreEdits(s)});const i=r;for(const s of i){const n=p.getInitialBindingData(s);n===null&&s.getRawBindingData()===null||await C.setBindingData(s.getTarget(),n??{},{sequence:t})}p.syncValuesFromDom(e),await C.evaluateAll(e);for(const s of i)p.getInitialBindingData(s)!==null||s.getRawBindingData()!==null||await p.restoreAncestorArgValues(s,{sequence:t,kind:"supply"});for(const s of i){const n=p.getInitialBindingData(s);if(s.getRawBindingData()===null&&n===null)continue;const a=p.getValues(s),o=s.getAttribute(`${c.prefix}form-arg`);let l={...n||{}};if(o){const u=String(o);!Object.prototype.hasOwnProperty.call(n??{},u)&&p.resolveAncestorArgOwner(s,u)!==null||(l[u]=p.mergeCollectedValues(l[u]??null,a))}else l=p.mergeCollectedValues(l,a),p.deleteAncestorOwnedKeys(s,n,l);await C.setBindingData(s.getTarget(),l,{sequence:t})}se.refreshSubtree(e.getTarget())}static deleteAncestorOwnedKeys(e,t,r){for(const i of Object.keys(r))Object.prototype.hasOwnProperty.call(t??{},i)||p.resolveAncestorKeyOwner(e,i)!==null&&delete r[i]}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:C.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())p.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 s of r){const n=D.get(s);n instanceof R&&i.push(n)}return i}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${c.prefix}each`)){for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${c.prefix}each-before`),o=n.hasAttribute(`${c.prefix}each-after`);!a&&!o&&t.push(n.remove())}s.setEachInputSignature(null)}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())p.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(s=>s.value)}):r.push({element:i,value:i.value}));for(const s of e.getChildElementFragments())p.collectEditsAfter(s,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(`${c.prefix}form-arg`);if(!r)return;const i=String(r),s=p.resolveAncestorArgOwner(e,i);s&&(p.LAST_ANCESTOR_ARG_VALUES.delete(e.getTarget()),await p.pushAncestorArgValue(e,i,s.value,t))}static markResetSubtree(e,t){e.markResetAt(t),e.markSupplyApplied(t);for(const r of e.getChildElementFragments())p.markResetSubtree(r,t)}static clearMessages(e){return Wt().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return p.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=Wt(),a=n.addMessage,o=u=>typeof a=="function"?a.call(n,u,r,i):n.addErrorMessage(u,r),l=p.keepFirstRadio(p.findFragmentsByKey(e,t));return l.forEach(u=>{s.push(o(u.getTarget()))}),l.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static keepFirstRadio(e){let t=!1;return e.filter(r=>{const i=r.getTarget();return!(i instanceof HTMLInputElement)||i.type!=="radio"?!0:t?!1:(t=!0,!0)})}static findFragmentsByKey(e,t){return p.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&p.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${c.prefix}form-object`))t.length>1&&e.getAttribute(`${c.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...p.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${c.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${c.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const l=i.substring(n+1,a),u=Number(l);if(isNaN(u))m.error("Haori",`Invalid index: ${i}`);else{const d=e.getChildElementFragments().filter(y=>y.hasAttribute(`${c.prefix}row`));u<d.length&&r.push(...p.findFragmentByKeyParts(d[u],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...p.findFragmentByKeyParts(s,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${c.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};p.INITIAL_RESTORED_FORMS=new WeakSet,p.LAST_ANCESTOR_ARG_VALUES=new WeakMap,p.GROUP_SCOPE_IDS=new WeakMap,p.groupScopeSequence=0,p.internalResetDepth=0,p.warnedArgOwnerNotRecord=new WeakMap,p.UNSAFE_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]),p.COLLECTED_ROW_IDENTITY=new WeakMap,p.COMPLETE_SET_VALUES=new WeakSet,p.COLLECTED_EXCLUDED_KEYS=new WeakMap,p.warnedPositionalRowFallbacks=new Set,p.warnedDerivedRowsWithoutKey=new Set,p.LEADING_PATH_PATTERN=/^\s*([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*([\s\S]*)$/;let x=p;class B{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){B.dispatch(document,"ready",{version:e})}static importStart(e,t){B.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){B.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){B.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const l of o){const u=t?.[l],d=r[l];u!==d&&s.push(l)}B.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){B.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){B.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){B.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){B.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){B.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){B.dispatch(e,"show",{visible:!0})}static hide(e){B.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){B.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){B.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){B.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}static pollTimeout(e,t,r){B.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){B.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const br={401:"unauthorized-redirect",403:"forbidden-redirect"};function Er(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=ne.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function jt(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=D.get(f),i=r instanceof R?r.getBindingData():{},s=Er(t,i);return s===""?null:s}function Ar(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,a=t.indexOf("#"),o=a>=0?t.slice(a):"",l=a>=0?t.slice(0,a):t,u=l.includes("?")?"&":"?";return`${l}${u}${n}${o}`}function Kt(f,e,t){const r=Ar(f,e,t);if(!$e.isNavigableUrl(r))return m.error("Haori",`遷移先が http: / https: / 現在ページと同じスキームの URL ではないため遷移しません: ${r}`),!1;try{if(new URL(r,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=r,!0}function zt(f,e=null){const t=br[f];if(t===void 0||typeof document>"u")return!1;if(e!==null){const s=`${e.attrPrefix}${t}`;if(e.element.hasAttribute(s)){const n=jt(e.element,s);return n!==null&&Kt(e.element,s,n)}}const r=`${c.prefix}${t}`,i=[];document.body&&i.push(document.body),document.documentElement&&i.push(document.documentElement);for(const s of i){const n=jt(s,r);if(n!==null)return Kt(s,r,n)}return!1}class K{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 queryAllInListOrder(e,t){if(K.queryAll(e,t).length===0)return[];const r=new Set;return K.splitList(e).forEach(i=>{K.queryAll(i,t).forEach(s=>r.add(s))}),Array.from(r)}static splitList(e){const t=[];let r=0,i=null,s=0;for(let n=0;n<e.length;n++){const a=e[n];a==="\\"?n++:i!==null?a===i&&(i=null):a==='"'||a==="'"?i=a:a==="("||a==="["?r++:a===")"||a==="]"?r--:a===","&&r===0&&(t.push(e.slice(s,n)),s=n+1)}return t.push(e.slice(s)),t}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 が利用できないため ${c.prefix}store を無効にします:`,t)),null}}static isReservedKey(e){return R.isReservedBindingKey(e)}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(`${c.prefix}store`);if(r===null)return null;const i=r.trim();if(i==="")return N.warnOnce(t,"key",`${c.prefix}store にストレージキーが指定されていません。`),null;if(i.includes("{{"))return N.warnOnce(t,"expression",`${c.prefix}store に式は使用できません(静的な文字列を指定してください): ${i}`),null;const s=e.getRawAttribute(`${c.prefix}store-type`);let n="session";if(s!==null){const d=s.trim();d==="local"||d==="session"?n=d:N.warnOnce(t,"type",`${c.prefix}store-type は session または local を指定してください(session として扱います): ${d}`)}const a=e.getRawAttribute(`${c.prefix}store-arg`),o=a===null||a.trim()===""?null:a.trim(),l=e.getRawAttribute(`${c.prefix}store-params`);let u=null;if(l!==null){const d=l.split("&").map(b=>b.trim()).filter(b=>b!==""),y=d.filter(b=>!N.isReservedKey(b));y.length!==d.length&&N.warnOnce(t,"reserved",`${c.prefix}store-params の予約キー(先頭が _ のキー)は対象外です。`),u=y.length>0?y:null}return u===null&&o===null?(N.warnOnce(t,"target",`${c.prefix}store には ${c.prefix}store-params または ${c.prefix}store-arg のいずれかが必要です。`),null):{key:i,kind:n,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(s){return m.warn("Haori",`ストレージの読み取りに失敗しました: ${e.key}`,s),null}if(r===null)return null;let i;try{i=JSON.parse(r)}catch(s){return m.warn("Haori",`保存済みデータが JSON として解釈できません: ${e.key}`,s),null}return N.isPlainRecord(i)?i:(m.warn("Haori",`保存済みデータがオブジェクトではありません: ${e.key}`),null)}static extractFromRecord(e,t){let r=t;if(e.arg!==null){const n=t[e.arg];if(n===void 0)return{};if(!N.isPlainRecord(n))return m.warn("Haori",`保存済みデータの ${e.arg} がオブジェクトではありません: `+e.key),{};r=n}const i=e.params??Object.keys(r),s={};for(const n of i)N.isReservedKey(n)||Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n]);return s}static selectFromData(e,t){const r=e.params??Object.keys(t),i={};for(const s of r){if(N.isReservedKey(s)||!Object.prototype.hasOwnProperty.call(t,s))continue;const n=t[s];n!==void 0&&(i[s]=n)}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,s]of r)if(!e.refs.has(i)||e.refs.get(i)!==s)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 s=i[e.arg],n=N.isPlainRecord(s)?{...s}:{};i[e.arg]={...n,...t}}else Object.assign(i,t);try{return r.setItem(e.key,JSON.stringify(i)),!0}catch(s){return m.warn("Haori",`ストレージへの保存に失敗しました: ${e.key}`,s),!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",`${c.prefix}each の行の内側では ${c.prefix}store を使用できません(行データは親要素側で配列キーを指定してください)。`),Promise.resolve();N.RESTORED_ELEMENTS.add(r);const i=N.readRecord(t),s=i?N.extractFromRecord(t,i):{},n={...e.getRawBindingData()??{},...s};return N.seedSignature(r,N.selectFromData(t,n)),Object.keys(s).length===0?Promise.resolve():C.setBindingData(r,n,{reentrant:!0,kind:"nonSupply",sequence:R.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 s=N.selectFromData(t,i);if(Object.keys(s).length===0)return;const n=N.SIGNATURES.get(r);if(n&&N.hasSameRefs(n,s))return;const a=N.stringify(s);if(a===null){m.warn("Haori",`保存対象を直列化できないためミラーを行いません: ${t.key}`);return}if(n&&n.json===a){n.refs=N.createRefs(s);return}N.writeRecord(t,s)&&N.SIGNATURES.set(r,{json:a,refs:N.createRefs(s)})}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(`[${c.prefix}store]`).forEach(i=>{if(!N.RESTORED_ELEMENTS.has(i))return;const s=D.get(i);if(!(s instanceof R))return;const n=N.readDeclaration(s);if(!n||n.key!==e||n.kind!==t)return;const a=s.getRawBindingData();N.seedSignature(i,a?N.selectFromData(n,a):{})})}};N.SIGNATURES=new WeakMap,N.RESTORED_ELEMENTS=new WeakSet,N.WARNED_ELEMENTS=new WeakMap,N.WARNED_KINDS=new Set;let Pe=N;const De="[Haori]",xe={bodyIgnored:f=>`${f} is ignored because ${f}-handler is also declared.`,notRegistered:(f,e)=>`Handler "${f}" is not registered (${e}-handler). Register it with Haori.handlers.register().`,argsNotArray:f=>`${f}-args must evaluate to an array without unresolved references; the handler is not called.`,templateInBody:f=>`${f} with {{...}} is not run in the CSP mode. Write the expression without {{...}}, or use ${f}-handler and ${f}-args.`,notExpression:f=>`${f} is not run in the CSP mode because it is not a single expression. Use ${f}-handler and ${f}-args.`,shadowed:(f,e)=>`Handler(s) ${f.join(", ")} are shadowed by binding keys of the same name in ${e}; the binding values are used.`};class ae{static applies(e,t){return c.csp||e.hasAttribute(`${t}-handler`)}static declared(e,t){return e.hasAttribute(t)||e.hasAttribute(`${t}-handler`)}static compile(e,t,r){const i=`${t}-handler`;return e.hasAttribute(i)?(U.isEnabled()&&e.hasAttribute(t)&&m.warn(De,xe.bodyIgnored(t),e.getTarget()),ae.compileHandler(e,t)):ae.compileExpression(e,t,r)}static compileHandler(e,t){const r=e.getRawAttribute(`${t}-handler`),i=e.getRawAttribute(`${t}-args`);return s=>{const n=be.get(r);if(n===void 0){m.warn(De,xe.notRegistered(r,t),e.getTarget());return}let a=[];if(i!==null){const o=ne.evaluateDetailed(i,e.getBindingData());if(!Array.isArray(o.value)){m.warn(De,xe.argsNotArray(t),i);return}a=o.value}return n.call(e.getTarget(),...s,...a)}}static compileExpression(e,t,r){const i=e.getRawAttribute(t);if(i.includes("{{"))return m.warn(De,xe.templateInBody(t),e.getTarget()),null;try{Me.compile(i)}catch{return m.warn(De,xe.notExpression(t),e.getTarget()),null}return s=>{const n=e.getBindingData();U.isEnabled()&&ae.reportShadowedHandlers(n,t);const a={...be.entries(),...n};return r.forEach((o,l)=>{a[o]=s[l]}),ne.evaluate(i,a)}}static reportShadowedHandlers(e,t){const r=Object.keys(e).filter(i=>be.has(i));r.length>0&&m.warn(De,xe.shadowed(r,t))}}const vr=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],wr="__haoriHistoryState__",it="data-haori-click-lock",Gt="ファイルを保存できませんでした",Sr=100;let Le=null;const Rr=["info","warning","error","success"],Yt=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message|bind)$/;function Ee(){const e=globalThis.window?.Haori;return vr.every(r=>typeof e?.[r]=="function")?e:he}const Tr=new Set(["GET","HEAD","OPTIONS"]);function Ye(f){return Tr.has(f.toUpperCase())}function kr(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{f.append(t,Ne(i))}):f.append(t,Ne(r)))}function Ne(f){if(f==null)return"";if(typeof f=="object"||typeof f=="function")try{return JSON.stringify(f)??""}catch{return""}return String(f)}function Xt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return kr(r,e),t.search=r.toString(),t.toString()}function Dr(f){if(f==null)return{payload:{},dropped:!1};if(typeof f=="string"){const e=f.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:Jt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(f instanceof URLSearchParams)return{payload:Jt(f),dropped:!1};if(typeof FormData<"u"&&f instanceof FormData){const e={};let t=!1;for(const[r,i]of f.entries()){if(typeof i!="string"){t=!0;continue}Zt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Jt(f){const e={};for(const[t,r]of f.entries())Zt(e,t,r);return e}function Zt(f,e,t){const r=f[e];r===void 0?f[e]=t:Array.isArray(r)?r.push(t):f[e]=[r,t]}function Ae(f,e){if(x.isCompleteSetValue(e))return e;if(Array.isArray(e)){const t=Array.isArray(f)?f.slice():[];let r=!1;return e.forEach((i,s)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[s]=Ae(t[s],i),r=!0))}),r?t:f}if(e!==null&&typeof e=="object"){const t=f!==null&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};for(const[r,i]of Object.entries(e))t[r]=Ae(t[r],i);return t}return e}function xr(f){const e=f?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Nr(f,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Ye(r))return{url:f,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:s}=Dr(t.body);let n=f;Object.keys(i).length>0&&(n=Xt(n,i)),s&&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 ${c.prefix}{event}-data / ${c.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:n,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(n,window.location.href).search||void 0}}function Ir(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function Oe(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(Oe):f!==null&&typeof f=="object"?Object.values(f).some(Oe):!1}function Fr(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Oe(t)):Oe(e))}function Xe(f){return st(x.getValues(f))}function st(f){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 x.carryCollectedRowIdentity(r,i),i}if(r!==null&&typeof r=="object"){const i={};for(const[s,n]of Object.entries(r))i[s]=e(n);return x.carryCollectedRowIdentity(r,i),i}return r},t={};for(const[r,i]of Object.entries(f))t[r]=e(i);return x.carryCollectedRowIdentity(f,t),t}function Cr(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ir(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.downloadReceivedBytes=0,this.downloadTotalBytes=null,this.downloadFolder=null,this.twoWayCommitBind=!1,this.skipped=!1,this.operationSequence=r!=null?R.nextOperationSequence():R.nextSequence(),g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static recordClickOutcome(e,t){g.CLICK_OUTCOMES.set(e,t)}static takeClickOutcome(e){const t=g.CLICK_OUTCOMES.get(e);return t?(g.CLICK_OUTCOMES.delete(e),t):null}static attrName(e,t,r=!1){return e?`${c.prefix}${e}-${t}`:r?`${c.prefix}fetch-${t}`:`${c.prefix}${t}`}static warnAuthRedirectWithoutFetch(e,t){if(!e.hasAttribute(g.attrName(t,"fetch")))for(const r of["unauthorized-redirect","forbidden-redirect"]){const i=g.attrName(t,r);if(e.hasAttribute(i)){const s=g.attrName(t,"fetch");m.warn("Haori",`${i} has no effect without ${s}.`,e.getTarget())}}}static resolveSelectorTargets(e,t,r){const i=K.read(e,t),s=[];if(i)(r==="click"||r==="error-click"?K.queryAllInListOrder(i,t):K.queryAll(i,t)).forEach(a=>{const o=D.get(a);o&&s.push(o)}),s.length===0&&m.error("Haori",`Element not found: ${i} (${t})`);else if(r==="error-click")m.error("Haori",`${t} にはクリックする要素のセレクタが必要です。`);else if(r==="open"||r==="close"||r==="error-close"){const n=e.getTarget().closest("dialog");n?s.push(D.get(n)):m.error("Haori",`Ancestor <dialog> not found (${t})`)}else s.push(e);return s}static readToastLevel(e,t,r,i){return g.toToastLevel(g.readLateAttribute(e,t,r,i))}static readNoMessageDeclarations(e,t,r){const i=g.attrName(r,"error-status");e.hasAttribute(i)&&(t.errorStatuses=g.parseErrorStatuses(e.getRawAttribute(i),i)),t.errorNoMessage=e.hasAttribute(g.attrName(r,"error-no-message"));const s=g.attrName(r,"error-"),n=new Map;for(const a of e.getAttributeNames()){const o=a.startsWith(s)?Yt.exec(a.slice(s.length)):null;o&&o[2]==="no-message"&&n.set(Number(o[1]),{key:`error-${o[1]}`,clickFragments:null,clickAwait:!1,closeFragments:null,toastMessage:null,toastLevel:null,noMessage:!0,bind:!1})}t.errorStatusActions=n}static readErrorStatusActions(e,t,r){const i=g.attrName(r,"error-"),s=new Set;for(const a of e.getAttributeNames()){if(!a.startsWith(i))continue;const o=Yt.exec(a.slice(i.length));o&&s.add(o[1])}const n=new Map;return s.forEach(a=>{const o=`error-${a}`,l=u=>g.attrName(r,`${o}-${u}`);n.set(Number(a),{key:o,clickFragments:e.hasAttribute(l("click"))?g.resolveSelectorTargets(e,l("click"),"error-click"):null,clickAwait:e.hasAttribute(l("click-await")),closeFragments:e.hasAttribute(l("close"))?g.resolveSelectorTargets(e,l("close"),"error-close"):null,toastMessage:g.readLateAttribute(e,t,`${o}-toast`,l("toast")),toastLevel:g.readToastLevel(e,t,`${o}-toast-level`,l("toast-level")),noMessage:e.hasAttribute(l("no-message")),bind:e.hasAttribute(l("bind"))})}),n}static toToastLevel(e){return Rr.includes(e)?e:null}static parseErrorStatuses(e,t){const r=[];for(const i of(e??"").split("&")){const s=i.trim();/^\d{3}$/.test(s)?r.push(Number(s)):m.warn("Haori",`${t} の "${s}" は 3 桁のステータスではないため無視します。`)}return r}static readLateAttribute(e,t,r,i){const s=e.getAttributeEvaluation(i);return t.lateAttributes||(t.lateAttributes=new Map),t.lateAttributes.set(r,{attributeName:i,hasUnresolvedReference:s?.hasUnresolvedReference??!1}),s?.value??null}static normalizeAttributeText(e){return e?String(e):null}static readFetchHeaders(e,t){if(!e.hasAttribute(t))return null;const r=e.getRawAttribute(t);let i;try{i=C.parseDataBind(r)}catch(s){return m.error("Haori",`Invalid fetch headers: ${s}`),null}return i===null||typeof i!="object"||Array.isArray(i)?(m.warn("Haori",`${t} はヘッダー名と値のオブジェクトで指定してください(${Array.isArray(i)?"配列":`${typeof i} 型の値`}が指定されたため、ヘッダーは設定しません)。`),null):i}static hasDeclaredContentType(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>t.toLowerCase()==="content-type")}static withContentType(e,t){const r={};return e&&typeof e=="object"&&Object.entries(e).forEach(([i,s])=>{i.toLowerCase()!=="content-type"&&(r[i]=s)}),r["Content-Type"]=t,r}static invokeFetch(e,t){try{return fetch(e,t)}catch(r){return Promise.reject(r)}}static unescapeNewlines(e){return typeof e=="string"?e.replace(/\\n/g,`
21
+ `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=ne.evaluateDetailed(n??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 s=0;s<t;s+=1){const n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const l=ne.evaluateDetailed(n??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),s=i?.value??null,n=i?.hasUnresolvedReference??!1;if(s&&typeof s=="object"&&!Array.isArray(s))return{value:s,hasUnresolvedReference:n};if(typeof s!="string"||r===null)return{value:null,hasUnresolvedReference:n};const a=r.trim();if(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:C.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:C.parseDataBind(l.value),hasUnresolvedReference:n||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:C.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e},i=t?g.attrName(t,"if"):g.attrName(null,"if",!0);if(e.hasAttribute(i)){const w=e.getRawAttribute(i);typeof w=="string"&&w.trim()!==""?(r.conditionExpression=x.unwrapConditionExpression(w),r.conditionAttributeName=i):m.warn("Haori",`${i} に条件式が指定されていません。`)}if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=g.unescapeNewlines(g.normalizeAttributeText(e.getAttribute(g.attrName(t,"confirm"))))),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const j=K.read(e,g.attrName(t,"form"));if(j){const V=K.query(j,g.attrName(t,"form"));V!==null?r.formFragment=x.getFormFragment(D.get(V)):m.error("Haori",`Form element not found: ${j} (${g.attrName(t,"form")})`)}else r.formFragment=x.getFormFragment(e)}else if(t==="change"||t==="input"){r.formFragment=x.getFormFragment(e);const j=`${c.prefix}${t}-`;r.implicitFormFragment=!e.getAttributeNames().some(V=>V.startsWith(j)),r.formFragment===null&&g.isNamedInputFragment(e)&&(r.selfValueFragment=e)}U.isEnabled()&&g.warnAuthRedirectWithoutFetch(e,t);const w=`${c.prefix}${t}-before-run`;if(ae.declared(e,w)&&ae.applies(e,w)){const j=ae.compile(e,w,["fetchUrl","fetchOptions"]);j&&(r.beforeCallback=(V,de)=>j([V,de]))}else if(e.hasAttribute(w)){const j=e.getRawAttribute(w);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
17
22
  "use strict";
18
- ${$}
19
- `)}catch(z){g.error("Haori",`Invalid before script: ${z}`)}}const R=p.attrName(t,"run");if(e.hasAttribute(R)){const $=String(e.getAttribute(R)??"");let z=null;try{z=new Function("event",`"use strict"; return (
20
- ${$}
21
- );`)}catch{try{z=new Function("event",`"use strict";
22
- ${$}
23
- `)}catch(_){g.error("Haori",`Invalid run script: ${_}`)}}z&&(r.runScript=z)}}const n=p.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?p.attrName(t,"fetch-method"):p.attrName(null,"method",!0);if(e.hasAttribute(o)){const R=e.getAttributeEvaluation(o);R?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=p.normalizeAttributeText(R?.value)??void 0}const l=t?p.attrName(t,"fetch-headers"):p.attrName(null,"headers",!0),u=p.readFetchHeaders(e,l);u!==null&&(a.headers=u);const h=t?p.attrName(t,"fetch-content-type"):p.attrName(null,"content-type",!0);let m=null;if(e.hasAttribute(h)){const R=e.getAttributeEvaluation(h);R?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),m=p.normalizeAttributeText(R?.value)}if(m!==null)a.headers=p.withContentType(a.headers,m);else if(a.method&&!p.hasDeclaredContentType(a.headers)){const R=a.method.toUpperCase();a.headers=p.withContentType(a.headers,R==="GET"||R==="HEAD"||R==="OPTIONS"?"application/x-www-form-urlencoded":"application/json")}Object.keys(a).length>0&&(r.fetchOptions=a);const y=t?p.attrName(t,"fetch-download"):p.attrName(null,"download",!0);if(e.hasAttribute(y)&&!s)g.warn("Haori",`${y} は ${n} と併せて指定してください(保存する応答が無いため、この宣言は無視します)。`);else if(e.hasAttribute(y)){r.download=!0;const R=e.getAttributeEvaluation(y);r.downloadFileName=R?.hasUnresolvedReference?null:p.normalizeAttributeText(R?.value)}const E=t?p.attrName(t,"fetch-download-folder"):p.attrName(null,"download-folder",!0);e.hasAttribute(E)&&(r.download?r.downloadFolder=!0:g.warn("Haori",`${E} は ${y} と併せて指定してください(書き出す応答が無いため、この宣言は無視します)。`));const A=t?p.attrName(t,"bind"):p.attrName(null,"bind",!0);if(e.hasAttribute(A)){const R=W.read(e,A);if(R){const $=W.queryAll(R,A);$.length>0?(r.bindFragments=[],$.forEach(z=>{const _=N.get(z);_&&r.bindFragments.push(_)})):g.error("Haori",`Bind element not found: ${R} (${A})`)}}const D=p.attrName(t,"bind-arg"),M=p.attrName(null,"arg",!0),L=p.attrName(null,"bind-arg",!0);t?e.hasAttribute(D)&&(r.bindArg=e.getRawAttribute(D)):e.hasAttribute(M)?r.bindArg=e.getRawAttribute(M):e.hasAttribute(L)&&(r.bindArg=e.getRawAttribute(L));const ee=t?p.attrName(t,"bind-params"):p.attrName(null,"bind-params",!0);if(e.hasAttribute(ee)){const R=e.getRawAttribute(ee);r.bindParams=R.split("&").map($=>$.trim())}const x=t?p.attrName(t,"bind-append"):p.attrName(null,"bind-append",!0);if(e.hasAttribute(x)){const R=e.getRawAttribute(x);r.bindAppendParams=R.split("&").map($=>$.trim()).filter(Boolean)}const X=t?p.attrName(t,"bind-merge"):p.attrName(null,"bind-merge",!0);e.hasAttribute(X)&&(r.bindMerge=!0);const Q=t?p.attrName(t,"bind-transform"):p.attrName(null,"bind-transform",!0);e.hasAttribute(Q)&&(r.bindTransform=e.getRawAttribute(Q));const J=t?p.attrName(t,"copy-params"):null;if(J&&e.hasAttribute(J)){const R=e.getRawAttribute(J);r.copyParams=R.split("&").map($=>$.trim()).filter(Boolean)}if(t){if(e.hasAttribute(p.attrName(t,"adjust"))){const U=W.read(e,p.attrName(t,"adjust"));if(U){const G=W.queryAll(U,p.attrName(t,"adjust"));G.length>0?(r.adjustFragments=[],G.forEach(Z=>{const Be=N.get(Z);Be&&r.adjustFragments.push(Be)})):g.error("Haori",`Adjust element not found: ${U} (${p.attrName(t,"adjust")})`)}if(e.hasAttribute(p.attrName(t,"adjust-value"))){const G=e.getRawAttribute(p.attrName(t,"adjust-value")),Z=Number(G);isNaN(Z)||(r.adjustValue=Z)}}if(e.hasAttribute(p.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(p.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(p.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(p.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${c.prefix}${t}-after-run`)){const U=e.getRawAttribute(`${c.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
23
+ ${j}
24
+ `)}catch(V){m.error("Haori",`Invalid before script: ${V}`)}}const O=g.attrName(t,"run");if(ae.declared(e,O)&&ae.applies(e,O)){const j=ae.compile(e,O,["event"]);j&&(r.runScript=V=>j([V]))}else if(e.hasAttribute(O)){const j=String(e.getAttribute(O)??"");let V=null;try{V=new Function("event",`"use strict"; return (
25
+ ${j}
26
+ );`)}catch{try{V=new Function("event",`"use strict";
27
+ ${j}
28
+ `)}catch(de){m.error("Haori",`Invalid run script: ${de}`)}}V&&(r.runScript=V)}}const s=g.attrName(t,"fetch"),n=e.hasAttribute(s);if(n){const w=e.getAttributeEvaluation(s);w&&(r.fetchHasUnresolvedReference=w.hasUnresolvedReference,r.fetchUrl=w.hasUnresolvedReference?null:w.value)}const a={},o=t?g.attrName(t,"fetch-method"):g.attrName(null,"method",!0);if(e.hasAttribute(o)){const w=e.getAttributeEvaluation(o);w?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=g.normalizeAttributeText(w?.value)??void 0}const l=t?g.attrName(t,"fetch-headers"):g.attrName(null,"headers",!0),u=g.readFetchHeaders(e,l);u!==null&&(a.headers=u);const d=t?g.attrName(t,"fetch-content-type"):g.attrName(null,"content-type",!0);let y=null;if(e.hasAttribute(d)){const w=e.getAttributeEvaluation(d);w?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),y=g.normalizeAttributeText(w?.value)}if(y!==null)a.headers=g.withContentType(a.headers,y);else if(a.method&&!g.hasDeclaredContentType(a.headers)){const w=a.method.toUpperCase();a.headers=g.withContentType(a.headers,w==="GET"||w==="HEAD"||w==="OPTIONS"?"application/x-www-form-urlencoded":"application/json")}Object.keys(a).length>0&&(r.fetchOptions=a);const b=t?g.attrName(t,"fetch-download"):g.attrName(null,"download",!0);if(e.hasAttribute(b)&&!n)m.warn("Haori",`${b} は ${s} と併せて指定してください(保存する応答が無いため、この宣言は無視します)。`);else if(e.hasAttribute(b)){r.download=!0;const w=e.getAttributeEvaluation(b);r.downloadFileName=w?.hasUnresolvedReference?null:g.normalizeAttributeText(w?.value)}const E=t?g.attrName(t,"fetch-download-folder"):g.attrName(null,"download-folder",!0);e.hasAttribute(E)&&(r.download?r.downloadFolder=!0:m.warn("Haori",`${E} は ${b} と併せて指定してください(書き出す応答が無いため、この宣言は無視します)。`));const A=t?g.attrName(t,"bind"):g.attrName(null,"bind",!0);if(e.hasAttribute(A)){const w=K.read(e,A);if(w){const O=K.queryAll(w,A);O.length>0?(r.bindFragments=[],O.forEach(j=>{const V=D.get(j);V&&r.bindFragments.push(V)})):m.error("Haori",`Bind element not found: ${w} (${A})`)}}const k=g.attrName(t,"bind-arg"),M=g.attrName(null,"arg",!0),P=g.attrName(null,"bind-arg",!0);t?e.hasAttribute(k)&&(r.bindArg=e.getRawAttribute(k)):e.hasAttribute(M)?r.bindArg=e.getRawAttribute(M):e.hasAttribute(P)&&(r.bindArg=e.getRawAttribute(P));const ie=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(ie)){const w=e.getRawAttribute(ie);r.bindParams=w.split("&").map(O=>O.trim())}const F=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(F)){const w=e.getRawAttribute(F);r.bindAppendParams=w.split("&").map(O=>O.trim()).filter(Boolean)}const Q=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(Q)&&(r.bindMerge=!0);const te=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(te)&&(r.bindTransform=e.getRawAttribute(te));const _=t?g.attrName(t,"copy-params"):null;if(_&&e.hasAttribute(_)){const w=e.getRawAttribute(_);r.copyParams=w.split("&").map(O=>O.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const W=K.read(e,g.attrName(t,"adjust"));if(W){const G=K.queryAll(W,g.attrName(t,"adjust"));G.length>0?(r.adjustFragments=[],G.forEach(re=>{const Te=D.get(re);Te&&r.adjustFragments.push(Te)})):m.error("Haori",`Adjust element not found: ${W} (${g.attrName(t,"adjust")})`)}if(e.hasAttribute(g.attrName(t,"adjust-value"))){const G=e.getRawAttribute(g.attrName(t,"adjust-value")),re=Number(G);isNaN(re)||(r.adjustValue=re)}}e.hasAttribute(g.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(g.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(g.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(g.attrName(t,"row-next"))&&(r.rowMoveNext=!0);const w=`${c.prefix}${t}-after-run`;if(ae.declared(e,w)&&ae.applies(e,w)){const W=ae.compile(e,w,["response"]);W&&(r.afterCallback=G=>W([G]))}else if(e.hasAttribute(w)){const W=e.getRawAttribute(w);try{r.afterCallback=new Function("response",`
24
29
  "use strict";
25
- ${U}
26
- `)}catch(G){g.error("Haori",`Invalid after script: ${G}`)}}if(e.hasAttribute(p.attrName(t,"dialog"))&&(r.dialogMessage=p.unescapeNewlines(p.readLateAttribute(e,r,"dialog",p.attrName(t,"dialog")))),e.hasAttribute(p.attrName(t,"toast"))&&(r.toastMessage=p.readLateAttribute(e,r,"toast",p.attrName(t,"toast")),r.toastLevel=p.readToastLevel(e,r,"toast-level",p.attrName(t,"toast-level"))),t!=="poll"){const U=p.attrName(t,"error-toast");e.hasAttribute(U)&&(r.errorToastMessage=p.readLateAttribute(e,r,"error-toast",U),r.errorToastLevel=p.readToastLevel(e,r,"error-toast-level",p.attrName(t,"error-toast-level")));const G=p.attrName(t,"error-status");e.hasAttribute(G)&&(r.errorStatuses=p.parseErrorStatuses(e.getRawAttribute(G),G)),r.errorNoMessage=e.hasAttribute(p.attrName(t,"error-no-message")),r.errorBind=e.hasAttribute(p.attrName(t,"error-bind"))}const R=p.attrName(t,"redirect"),$=p.attrName(t,"redirect-replace"),z=e.hasAttribute(R),_=e.hasAttribute($);if(z&&(r.redirectUrl=p.readLateAttribute(e,r,"redirect",R)),_&&(r.redirectReplaceUrl=p.readLateAttribute(e,r,"redirect-replace",$)),z||_){const U=p.attrName(t,"redirect-return-param");e.hasAttribute(U)&&(r.redirectReturnParam=p.readLateAttribute(e,r,"redirect-return-param",U))}if(e.hasAttribute(p.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(p.attrName(t,"clear-messages"))&&(r.clearMessagesOnSuccess=!0),e.hasAttribute(p.attrName(t,"scroll"))&&(r.scrollTarget=p.readLateAttribute(e,r,"scroll",p.attrName(t,"scroll"))),e.hasAttribute(p.attrName(t,"history"))&&(r.historyUrl=p.readLateAttribute(e,r,"history",p.attrName(t,"history"))),e.hasAttribute(p.attrName(t,"history-data"))&&(r.historyDataAttrName=p.attrName(t,"history-data")),e.hasAttribute(p.attrName(t,"history-form"))){const U=W.read(e,p.attrName(t,"history-form"));if(U){const G=W.query(U,p.attrName(t,"history-form"));G!==null?r.historyFormFragment=F.getFormFragment(N.get(G)):g.error("Haori",`Form element not found: ${U} (${p.attrName(t,"history-form")})`)}else r.historyFormFragment=F.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close","error-click","error-close"].forEach(U=>{if(U.startsWith("error-")&&t==="poll")return;const G=p.attrName(t,U);if(!e.hasAttribute(G))return;const Z=p.resolveSelectorTargets(e,G,U);if(Z.length>0)switch(U){case"reset-before":r.resetBeforeFragments=Z;break;case"reset":r.resetFragments=Z;break;case"refetch":r.refetchFragments=Z;break;case"click":r.clickFragments=Z,r.clickAwait=e.hasAttribute(`${G}-await`);break;case"copy":r.copyFragments=Z;break;case"open":r.openFragments=Z;break;case"close":r.closeFragments=Z;break;case"error-click":r.errorClickFragments=Z,r.errorClickAwait=e.hasAttribute(`${G}-await`);break;case"error-close":r.errorCloseFragments=Z;break}}),t!=="poll"&&(r.errorStatusActions=p.readErrorStatusActions(e,r,t));const oe=p.attrName(t,"copy-source");if(e.hasAttribute(oe)){const U=W.read(e,oe);if(U){const G=W.query(U,oe);if(G!==null){const Z=N.get(G);Z?r.copySourceFragment=Z:g.error("Haori",`Element is not managed by Haori: ${U} (${oe})`)}else g.error("Haori",`Element not found: ${U} (${oe})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(p.attrName(null,"data",!0))&&(r.dataAttrName=p.attrName(null,"data",!0)),e.hasAttribute(p.attrName(null,"form",!0)))){const R=W.read(e,p.attrName(null,"form",!0));if(R){const $=W.query(R,p.attrName(null,"form",!0));$!==null?r.formFragment=F.getFormFragment(N.get($)):g.error("Haori",`Form element not found: ${R} (${p.attrName(null,"fetch-form",!0)})`)}else r.formFragment=F.getFormFragment(e)}(!t||t==="poll")&&p.readNoMessageDeclarations(e,r,t??"fetch");const j=t?p.attrName(t,"fetch-state"):p.attrName(null,"state",!0);if(e.hasAttribute(j)){const R=W.read(e,j),$=[];R?(W.queryAll(R,j).forEach(_=>{const Re=N.get(_);Re&&$.push(Re)}),$.length===0&&g.error("Haori",`Element not found: ${R} (${j})`)):$.push(e),$.length>0&&(r.fetchStateFragments=$)}const se=t?p.attrName(t,"store-clear"):p.attrName(null,"store-clear",!0);if(e.hasAttribute(se)){const R=e.getRawAttribute(se),$=R===null?"":R.trim();if($==="")g.error("Haori",`ストレージキーが指定されていません (${se})`);else{r.storeClearKey=$;const z=e.getRawAttribute(`${se}-type`),_=z===null?"session":z.trim();_==="local"||_==="session"?r.storeClearKind=_:(g.warn("Haori",`${se}-type は session または local を指定してください(session として扱います): ${_}`),r.storeClearKind="session")}}return s&&!r.download&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r.download&&r.bindFragments&&r.bindFragments.length>0&&(g.warn("Haori",`${y} と同時にバインド先が指定されています(応答はファイルとして保存し、バインドは行いません)。`),r.bindFragments=null),p.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(`${c.prefix}each`)||!n.hasAttribute(`${c.prefix}form-list`)||t.set(i,p.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(`${c.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 p(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async runWithOutcome(){return await this.execute()?"success":this.skipped?"skipped":"failure"}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0)return this.skipped=!0,!1;if(this.options.formFragment&&this.validate(this.options.formFragment)===!1)return await this.commitEditOnStop(),!1;if(!this.options.formFragment&&this.options.targetFragment&&F.warnUnvalidatedCustomValidity(F.getFormFragment(this.options.targetFragment),`${c.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition())return this.skipped=!0,await this.commitEditOnStop(),!1;if(this.options.runScript){const m=this.options.targetFragment?.getTarget()??null;try{const y=this.options.runScript.call(m,this.domEvent);y===!1&&this.domEvent&&this.domEvent.preventDefault(),y!=null&&typeof y.then=="function"&&await y}catch(y){g.error("Haori",`Run script execution error: ${y}`)}}if(!await this.confirm())return await this.commitEditOnStop(),!1;if(this.options.downloadFolder&&await this.prepareDownloadFolder()==="cancelled")return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(m=>F.reset(m,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=w.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const m=this.options.beforeCallback(n||null,s||null);if(m!=null){if(m===!1||typeof m=="object"&&m.stop)return!1;typeof m=="object"&&(a="fetchUrl"in m,o="fetchOptions"in m,n=a?m.fetchUrl:n,s=o?m.fetchOptions:s)}}const l=Object.keys(i).length>0;if(n){this.isInputEditProcedure()&&await this.commitFormValues(this.options.formFragment,i,e);const m=(s?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&zt(s)&&!Pe(m)?r.baseUrl??n:n,A=Gt(E,s);n=A.url;const D={...A.options},M=A.normalized?A.requestedMethod:r.requestedMethod,L=A.effectiveMethod,ee=r.transportMode==="query-get"||A.normalized,x=A.queryString??r.queryString;if(ee&&g.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:M,effectiveMethod:L,transportMode:"query-get",url:n,payload:l?i:void 0,queryString:x}),this.options.targetFragment&&n){const X=performance.now(),Q={runtime:c.runtime,requestedMethod:M,effectiveMethod:L,transportMode:ee?"query-get":"http",...ee?{queryString:x}:{}};return B.fetchStart(this.options.targetFragment.getTarget(),n,D,l?i:void 0,Q),await this.injectFetchState("loading"),await p.invokeFetch(n,D).then(J=>this.handleFetchResult(J,n||void 0,X)).catch(async J=>{throw n&&B.fetchError(this.options.targetFragment.getTarget(),n,J),await this.injectFetchState("error",null,J instanceof Error?J.message:String(J)),await this.runErrorActions(null),J})}return await fetch(n,D).then(X=>this.handleFetchResult(X,n||void 0))}(!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&l&&await this.commitFormValues(this.options.formFragment,i,e),this.suppressEmptyReplaceBind=!l&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=l?Ke(i):{},h=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(h)}finally{this.releaseExecutionLock(e)}}async commitEditOnStop(){!this.isInputEditProcedure()||!this.options.fetchUrl&&this.options.bindFragments&&this.options.bindFragments.length>0||await this.commitFormValues(this.options.formFragment,this.buildPayloadResolution().payload,null)}isInputEditProcedure(){return(this.eventType==="change"||this.eventType==="input")&&!!this.options.formFragment}async commitFormValues(e,t,r){const i=e.getTarget(),n=new Set;r&&r.appliedDisabledAttribute&&this.options.targetFragment&&n.add(this.options.targetFragment);const s=e.getRawBindingData(),a=Ke(t),o=e.getAttribute(`${c.prefix}form-arg`);let l;if(o){l={...s??{}};const u=String(o),h=F.resolveAncestorArgOwner(e,u);l[u]=F.mergeCollectedValues((h?h.value:l[u])??null,a)}else l=F.mergeCollectedValues(s,a,F.ancestorBaseResolver(e));await C.setBindingData(i,l,{skipFragments:n,kind:"nonSupply",sequence:this.operationSequence,editedPaths:F.collectEditedPaths(e,this.operationSequence,o?String(o):"",a)})}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment,t=e.getTarget();if(p.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(je))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return p.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(je,""),r||t.setAttribute("disabled",""),{target:t,fragment:e,appliedDisabledAttribute:!r}}static findDisabledDeclaration(e){const t=`${c.prefix}attr-disabled`,r=e.getRawAttribute(t);if(r!==null)return{name:t,value:r};const i=e.getRawAttribute("disabled");return i!==null&&i.includes("{{")?{name:"disabled",value:i}:null}releaseExecutionLock(e){if(!e)return;const t=e.target;if(p.RUNNING_CLICK_TARGETS.delete(t),t.removeAttribute(je),!e.appliedDisabledAttribute)return;const r=p.findDisabledDeclaration(e.fragment);if(r===null){t.removeAttribute("disabled");return}C.setAttribute(t,r.name,r.value).catch(i=>{g.error("Haori",`ロックの解除で ${r.name} を適用し直せませんでした: ${i}`)})}static forgetDownloadFolder(){Ne=null}async prepareDownloadFolder(){if(Ne)return this.downloadFolder=Ne,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return g.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Ne=t,this.downloadFolder=t,"ready"}catch(t){return t?.name==="AbortError"?"cancelled":(g.info("Haori",`保存先のフォルダを選ばせられなかったため、今までどおり保存します: ${t}`),"fallback")}}async readResponseBody(e){const t=e.headers.get("Content-Type")??"",r=e.body;if(!r||typeof r.getReader!="function")try{const s=await e.blob();return this.downloadReceivedBytes=s.size,this.dropTotalBytesIfExceeded(),await this.injectFetchState("loading"),s}catch(s){return g.error("Haori",`応答をファイルとして読み取れませんでした: ${s}`),null}const i=[];return await this.pumpResponseBody(r,s=>{i.push(new Blob([s]))})?new Blob(i,t!==""?{type:t}:void 0):null}async pumpResponseBody(e,t){await this.injectFetchState("loading");let r=Date.now();const i=e.getReader();try{for(;;){const{done:n,value:s}=await i.read();if(n)break;await t(s),this.downloadReceivedBytes+=s.byteLength,this.dropTotalBytesIfExceeded();const a=Date.now();a-r>=Vt&&(r=a,await this.injectFetchState("loading"))}}catch(n){return g.error("Haori",`応答をファイルとして読み取れませんでした: ${n}`),!1}return!0}dropTotalBytesIfExceeded(){this.downloadTotalBytes!==null&&this.downloadReceivedBytes>this.downloadTotalBytes&&(this.downloadTotalBytes=null)}static resolveDownloadTotalBytes(e){const t=e.headers.get("Content-Encoding");if(t!==null){const s=t.trim().toLowerCase();if(s!==""&&s!=="identity")return null}const r=e.headers.get("Content-Length");if(r===null)return null;const i=r.trim();if(i==="")return null;const n=Number(i);return!Number.isSafeInteger(n)||n<0?null:n}async saveResponseToFolder(e,t,r){const i=t.body;if(!i||typeof i.getReader!="function")return"fallback";const n=p.resolveDownloadFileName(t,this.options.downloadFileName??null,r??this.options.fetchUrl??null);let s=!0;try{await e.getFileHandle(n)}catch(l){if(l?.name==="NotFoundError")s=!1;else return g.info("Haori",`保存先のフォルダを確かめられなかったため、今までどおり保存します: ${l}`),"fallback"}if(s&&!await pe().confirm(`${n} は既にあります。上書きしますか?`))return"cancelled";let a;try{a=await(await e.getFileHandle(n,{create:!0})).createWritable()}catch(l){return g.info("Haori",`保存先のファイルを作れなかったため、今までどおり保存します: ${l}`),"fallback"}if(await this.pumpResponseBody(i,l=>a.write(l)))try{return await a.close(),"saved"}catch(l){g.error("Haori",`ファイルを書き終えられませんでした: ${l}`)}try{await a.abort()}catch(l){g.error("Haori",`書きかけを取り消せませんでした: ${l}`)}if(!s)try{await e.removeEntry(n)}catch(l){g.error("Haori",`作りかけのファイルを取り除けませんでした: ${l}`)}return"failed"}async saveResponseAsFile(e,t){if(this.downloadTotalBytes=p.resolveDownloadTotalBytes(e),this.downloadFolder){const a=await this.saveResponseToFolder(this.downloadFolder,e,t);if(a!=="fallback")return a;this.downloadFolder=null,Ne=null}const r=await this.readResponseBody(e);if(r===null)return"failed";const i=p.resolveDownloadFileName(e,this.options.downloadFileName??null,t??this.options.fetchUrl??null);if(typeof URL>"u"||typeof URL.createObjectURL!="function")return g.error("Haori","この環境では Blob の URL を生成できないため、ファイルを保存できません。"),"failed";const n=URL.createObjectURL(r),s=document.createElement("a");return s.href=n,s.download=i,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0),"saved"}async showDownloadFailure(e){const t=this.resolveMessageScope(),r=pe();await r.clearMessages(t),e&&await r.addErrorMessage(t,bt)}static resolveDownloadFileName(e,t,r){const n=[p.readContentDispositionFileName(e.headers.get("Content-Disposition")),t,p.readUrlFileName(r)];for(const s of n){const a=p.sanitizeFileName(s);if(a!==null)return a}return"download"}static readContentDispositionFileName(e){if(!e)return null;const t=/filename\*\s*=\s*([^;]+)/i.exec(e);if(t){const n=t[1].trim(),s=n.split("'"),a=s.length>=3?s.slice(2).join("'"):n;try{return decodeURIComponent(a)}catch(o){g.warn("Haori",`Content-Disposition を解釈できません: ${o}`)}}const r=/filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(r)return r[1].replace(/\\(.)/g,"$1");const i=/filename\s*=\s*([^;]+)/i.exec(e);return i?i[1].trim():null}static readUrlFileName(e){if(!e)return null;const r=e.split("#")[0].split("?")[0].split("/"),i=r[r.length-1];return i===""?null:i}static sanitizeFileName(e){if(e===null)return null;const t=e.replace(/[\u0000-\u001f\u007f/\\]/g,"").trim();return t===""?null:t}async handleFetchResult(e,t,r){const i=pe();if(!e.ok){if(yt(e.status))return!1;this.options.targetFragment&&t&&B.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r);const E=this.selectErrorActions(e.status),A=E?.bind===!0,D=await this.handleFetchError(A?e.clone():e,E?.noMessage!==!0&&!A);return A&&await this.bindResult(e).catch(M=>{g.error("Haori","Failed to bind the error response:",M)}),await this.injectFetchState("error",e.status,e.statusText||null,D),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&B.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const E=this.options.afterCallback(e);if(E!=null){if(E===!1||typeof E=="object"&&E.stop)return!1;typeof E=="object"&&"response"in E&&(e="response"in E?E.response:e)}}if(this.options.download){const E=await this.saveResponseAsFile(e,t);if(E==="cancelled")return await this.injectFetchState("success",e.status,null),!1;if(E==="failed"){const A=this.selectErrorActions(null);return await this.showDownloadFailure(A?.noMessage!==!0),await this.injectFetchState("error",e.status,bt),await this.runErrorActions(null),!1}}this.options.clearMessagesOnSuccess&&await i.clearMessages(this.resolveMessageScope());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(E=>F.reset(E,this.operationSequence))),await this.copy();const s=[];this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(E=>{s.push(new p(E,null).run())});const a=await this.clickTargets(this.options.clickFragments,this.options.clickAwait===!0,"click-await");if(!a&&this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?s.push(i.openDialog(A)):g.error("Haori","Element is not an HTML element: ",A)}),!a&&this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?s.push(i.closeDialog(A)):g.error("Haori","Element is not an HTML element: ",A)}),await Promise.all(s),a)return!1;const o=p.unescapeNewlines(p.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));o&&await i.dialog(o);const l=p.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));if(l){const E=p.toToastLevel(this.resolveLateAttribute("toast-level",this.options.toastLevel));await i.toast(l,E??"info")}this.clearStore(),this.pushHistory();const u=this.resolveLateAttribute("scroll",this.options.scrollTarget);u&&W.query(u,p.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const h=this.resolveLateAttribute("redirect",this.options.redirectUrl),m=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);h&&m&&g.warn("Haori",`${p.attrName(this.eventType,"redirect")} と ${p.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const y=m||h;if(y){let E=y;const A=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(A){const M=new URLSearchParams(window.location.search).get(A);if(M!==null){const L=M.trim();Te.isSafeLocalPath(L)?E=L:g.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${M}`)}}Te.isNavigableUrl(E)?m?window.location.replace(E):window.location.href=E:g.error("Haori",`遷移先が http: / https: / 現在ページと同じスキームの URL ではないため遷移しません: ${E}`)}return!0}clearStore(){const e=this.options.storeClearKey;e&&De.clear(e,this.options.storeClearKind??"session")}async clickTargets(e,t,r){if(!e||e.length===0)return!1;for(const i of e){await C.evaluateAll(i);const n=i.getTarget();if(t&&p.takeClickOutcome(n),typeof n.click=="function"?n.click():n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),!t)continue;const s=p.takeClickOutcome(n);if(s===null){g.warn("Haori",`${c.prefix}${this.eventType??"fetch"}-${r} はこの対象の完了を待てません(手続きが同期に起動していません)。`);continue}if(await s==="failure")return!0}return!1}async runErrorActions(e){const t=this.selectErrorActions(e);if(!t||await this.clickTargets(t.clickFragments,t.clickAwait,`${t.key}-click-await`))return;const i=pe(),n=[];t.closeFragments?.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):g.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n);const s=p.normalizeAttributeText(this.resolveLateAttribute(`${t.key}-toast`,t.toastMessage));if(s){const a=p.toToastLevel(this.resolveLateAttribute(`${t.key}-toast-level`,t.toastLevel));await i.toast(s,a??"info")}}selectErrorActions(e){const t=e===null?void 0:this.options.errorStatusActions?.get(e);return t||(this.appliesErrorActions(e)?{key:"error",clickFragments:this.options.errorClickFragments??null,clickAwait:this.options.errorClickAwait===!0,closeFragments:this.options.errorCloseFragments??null,toastMessage:this.options.errorToastMessage??null,toastLevel:this.options.errorToastLevel??null,noMessage:this.options.errorNoMessage===!0,bind:this.options.errorBind===!0}:null)}appliesErrorActions(e){const t=this.options.errorStatuses;return t===void 0||e!==null&&t.includes(e)}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()&&g.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();g.error("Haori",u);return}const l=u=>{for(const[h,m]of Object.entries(u))m!=null&&(Array.isArray(m)?(o.searchParams.delete(h),m.forEach(y=>o.searchParams.append(h,String(y)))):typeof m=="object"?o.searchParams.set(h,JSON.stringify(m)):o.searchParams.set(h,String(m)))};n&&l(r),s&&l(i),history.pushState({[Ut]:!0},"",o.toString()),C.refreshUrlParams()}catch(a){g.error("Haori",`history.pushState failed: ${a}`)}}resolveMessageScope(){const e=this.options.formFragment??(this.options.targetFragment?F.getFormFragment(this.options.targetFragment)||this.options.targetFragment:null);return e?e.getTarget():document.body}async handleFetchError(e,t){let r=null;this.options.formFragment?r=this.options.formFragment:this.options.targetFragment&&(r=F.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const i=r?r.getTarget():document.body;await pe().clearMessages(i);const n=async u=>{const h=r?r.getTarget():document.body;await pe().addErrorMessage(h,u)},s=()=>{if(!this.options.scrollOnError)return;const u=r?r.getTarget():document.body,h=u.nextElementSibling;(u.getAttribute("data-message-level")==="error"?u:u.parentElement?.getAttribute("data-message-level")==="error"?u.parentElement:u.querySelector('[data-message-level="error"]')??(h?.getAttribute("data-message-level")==="error"?h:null))?.scrollIntoView({behavior:"smooth",block:"nearest"})},a=async u=>{if(t){u.length===0&&await n(`${e.status} ${e.statusText}`);for(const h of u)h.key&&r?await F.addErrorMessage(r,h.key,h.message):await n(h.message);s()}return u.length===0?null:u.map(h=>h.message).join(`
27
- `)};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const u=await e.json(),h=[];if(Array.isArray(u)){const m=new Map,y=[];for(const E of u)if(E&&typeof E=="object"&&!Array.isArray(E)){const A=E.key,D=E.message,M=typeof A=="string"&&A.length>0?A:null,L=typeof D=="string"?D:D!=null?String(D):"";if(L.length===0)continue;if(M!==null){const ee=m.get(M)??[];ee.push(L),m.set(M,ee)}else y.push(L)}else typeof E=="string"&&E.length>0&&y.push(E);for(const[E,A]of m)h.push({key:E,message:A.join(`
28
- `)});for(const E of y)h.push({message:E})}else if(u&&typeof u=="object"){if(typeof u.message=="string"&&h.push({message:u.message}),Array.isArray(u.messages))for(const m of u.messages)typeof m=="string"&&h.push({message:m});if(u.errors&&typeof u.errors=="object")for(const[m,y]of Object.entries(u.errors))Array.isArray(y)?h.push({key:m,message:y.join(`
29
- `)}):typeof y=="string"?h.push({key:m,message:y}):y!=null&&h.push({key:m,message:String(y)});if(h.length===0)for(const[m,y]of Object.entries(u))m==="message"||m==="messages"||m==="errors"||(Array.isArray(y)?h.push({key:m,message:y.join(`
30
- `)}):typeof y=="string"&&h.push({key:m,message:y}))}return await a(h)}catch{}let l="";try{l=(await e.text()).trim()}catch{}return await a(l.length>0?[{message:l}]:[])}validate(e){if(this.options.valid!==!0)return this.options.implicitFormFragment||F.warnUnvalidatedCustomValidity(e,`${c.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;F.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return p.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"}),p.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++p.validationReportGeneration,r=performance.now();let i=null,n=0;const s=()=>{if(t!==p.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>=p.VALIDATION_SCROLL_STABLE_FRAMES&&p.isRectPartlyVisible(a)||performance.now()-r>=p.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}=p.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=p.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??`${c.prefix}if`,n=F.buildConditionScope(r,this.options.formFragment??null),s=ie.evaluateDetailed(t,n);return s.unresolvedReference?(e||g.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(e||g.info("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${c.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):pe().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=ie.evaluate(this.options.bindTransform,{response:i})}catch(o){g.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(l=>{i&&typeof i=="object"&&l in i&&(o[l]=i[l])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){g.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 ${c.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?p.attrName(this.eventType,"bind"):p.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){const m=this.options.bindArg;a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const E=this.resolveCurrentRowItem(o,y),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const D=E[m],M=D!==null&&typeof D=="object"&&!Array.isArray(D)?D:{};A[m]=this.mergeAppendBindingData(o,i,M)}else A[m]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},h=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const m=u[h],y=m&&typeof m=="object"&&!Array.isArray(m)?m:{};u[h]=this.mergeAppendBindingData(o,i,y)}else u[h]=i;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u,[h]),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){g.warn("Haori","string data is not bound because no bind target was specified.");return}return g.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 l=this.resolveRowWrite(o,s);if(l.kind==="skip")return;if(l.kind==="row"){a.push({container:l.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:m=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,m):m,E=this.mergeAppendBindingData(o,i,y),A=this.options.bindMerge?{...y,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),h=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,h,Object.keys(u)),{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(l=>{B.bindComplete(l.getTarget(),o)})})})}reconcileUserEditsForBind(e,t,r){const i=this.requestUserEditSequence;if(i===null)return t;const n=this.eventType==="poll";if(!n&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,i),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,r,n?0:i);const s=F.getValuesEditedAfter(e,n?0:i);if(Object.keys(s).length===0)return t;const a=e.getAttribute(`${c.prefix}form-arg`);if(a){const o=String(a),l=t[o],u=l&&typeof l=="object"&&!Array.isArray(l)?l:{};return{...t,[o]:ge(u,s)}}return ge(t,s)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,r);const n=F.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:ge(t,n)}reconcileAncestorArgFormEdits(e,t,r,i){let n=t;for(const{form:s,key:a}of F.collectArgForms(e)){if(!r.includes(a))continue;const o=F.getValuesEditedAfter(s,i);if(Object.keys(o).length===0)continue;const l=n[a],u=l&&typeof l=="object"&&!Array.isArray(l)?l:{};n={...n,[a]:ge(u,o)}}return n}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=p.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:l=>this.applyCopyToRowItem(s,l,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(C.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:ge(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Le(this.options.copySourceFragment):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Le(this.options.formFragment):this.options.targetFragment?C.withoutReservedBindingKeys(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=p.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=c.runtime==="demo"&&!Pe(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&Fe(t)){const h=s.get("Content-Type")||"";!Pe(a)&&/multipart\/form-data/i.test(h)?Xt(t)&&g.warn("Haori",`A File value nested under ${c.prefix}form-object / ${c.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):g.warn("Haori",`A File value cannot be sent without ${c.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=At(i,t));else if(Object.keys(t).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const m=new FormData;for(const[y,E]of Object.entries(t))E==null?m.append(y,""):E instanceof Blob?m.append(y,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?m.append(y,A):m.append(y,Ee(A))}):m.append(y,Ee(E));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(h)){const m=new URLSearchParams;for(const[y,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>m.append(y,Ee(A))):m.append(y,Ee(E)));n.body=m}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:l,queryString:u,transportMode:o?"query-get":"http",signature:Jt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Le(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?p.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return Le(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 g.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(g.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return g.error("Haori","Target fragment is not specified for row operation."),null;const r=p.attrName(this.eventType,e),i=W.read(t,r);if(i!==null&&i.trim()!==""){const s=W.query(i,r,document);if(s===null)return g.error("Haori",`Row container not found: ${i} (${r})`),null;const a=N.get(s);return a instanceof w?a.hasAttribute(`${c.prefix}each`)?a:(g.error("Haori",`Row container must have ${c.prefix}each: ${i} (${r})`),null):(g.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(`${c.prefix}each`);if(r===null)return t||g.error("Haori",`Row container has no ${c.prefix}each expression.`),null;const i=e.getRawAttribute(`${c.prefix}each-array`),n=i!==null,s=n?`${c.prefix}each-array`:`${c.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||g.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${c.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${c.prefix}each-key`)===null)return t||g.error("Haori",`${c.prefix}each-array requires ${c.prefix}each-key (${c.prefix}each-array="${a}").`),null;const u=p.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let h,m,y;if(u)h=u.owner,m=u.ownerData,y=[...u.path,...o.slice(1)];else{for(h=e,m=null;h;){const A=h.getRawBindingData();if(A&&o[0]in A&&!p.isRowScopeKey(h,o[0])){m=A;break}h=h.getParent()}y=o}if(!h||!m)return t||g.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=p.readPathValue(m,y);return Array.isArray(E)?{owner:h,ownerData:m,array:E,path:y,mapped:n}:(t||g.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${c.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${c.prefix}each-arg`)===t){const s=p.resolveEachArray(n,!0);if(!s)return g.error("Haori",`Row operations cannot resolve the write-back array for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}": the ancestor container that supplies "${t}" (${c.prefix}each="${n.getRawAttribute(`${c.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${c.prefix}derive and declare ${c.prefix}each-array on this ${c.prefix}each.`),"unresolvable";const a=p.resolveRowIndex(n,i,s.array,`${c.prefix}each="${n.getRawAttribute(`${c.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(`${c.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${c.prefix}each-arg`)===t||r.getAttribute(`${c.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],l=Array.isArray(o)?o.slice():{...o};n[a]=l,n=l}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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?(g.warn("Haori",`Target is not a row of the ${c.prefix}each container (${t}).`),{kind:"skip"}):p.getRowFragments(i).includes(e)?{kind:"row",container:i}:(g.warn("Haori",`The target row is no longer in the ${c.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=p.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const h=p.resolveRowArrayIndex(u,a);if(h===null)continue;const m=a[h];if(m===null||typeof m!="object"||Array.isArray(m)){g.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const y=u.apply(m);if(p.isSameRowItem(m,y)){u.syncWhenUnchanged&&r.push(p.syncUnchangedRowValues(u.row,y,u.syncWhenUnchanged));continue}a[h]=y,o=!0,u.syncWhenUnchanged==="supply"&&F.clearRowUserEditMarksForChangedKeys(u.row,y)}if(!o)return;const l=C.setBindingData(s.owner.getTarget(),p.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(C.isEachUpdateRunning(n)){l.catch(u=>{g.error("Haori","Failed to write row data.",u)});return}r.push(l)}),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 p.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const n=p.getRowFragments(e),s=n.indexOf(t);if(s===-1)return g.warn("Haori",`The target row is no longer in the ${c.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${c.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const l=[];r.forEach((m,y)=>{C.createListKey(m,String(a),y)===o&&l.push(y)});const u=n.slice(0,s).filter(m=>m.getListKey()===o).length,h=l[u]??-1;return h===-1?(g.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):h}return s>=r.length?(g.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(p.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=p.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${c.prefix}row`):null,a=p.getRowFragments(r),o=s?a.indexOf(s):a.length-1,l=y=>y<0||y>=a.length?null:i.mapped?p.resolveRowIndex(r,a[y],i.array,p.attrName(this.eventType,e)):y,u=o>=0?l(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const h=i.array.slice();if(!t(h,u,()=>l(o-1),()=>l(o+1)))return Promise.resolve();const m=new Map;return a.forEach(y=>{const E=y.getListKey();E!==null&&!m.has(String(E))&&m.set(String(E),y)}),h.forEach((y,E)=>{if(p.isSameRowItem(i.array[E],y))return;const A=m.get(C.createListKey(y,null,E));A&&C.clearUserEditMarks(A)}),C.setBindingData(i.owner.getTarget(),p.withPathValue(i.ownerData,i.path,h),{kind:"nonSupply",sequence:this.operationSequence})}async injectFetchState(e,t=null,r=null,i=null){const n=this.options.fetchStateFragments;if(!n||n.length===0)return;const s={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r,responseMessage:i};this.options.download&&(s.receivedBytes=this.downloadReceivedBytes,s.totalBytes=this.downloadTotalBytes),await Promise.all(n.map(a=>{const o=a.getTarget(),l={...a.getRawBindingData()??{},_fetch:s};return C.setBindingData(o,l,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};p.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,p.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,p.RUNNING_CLICK_TARGETS=new WeakSet,p.CLICK_OUTCOMES=new WeakMap,p.validationReportGeneration=0,p.VALIDATION_SCROLL_TIMEOUT_MS=1e3,p.VALIDATION_SCROLL_STABLE_FRAMES=2;let ae=p;class Zt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw g.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){yt(r.status);const n=`${r.status} ${r.statusText}`;throw g.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw g.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:(g.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return g.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=N.get(e);return r instanceof w?r.hasAttribute(`${c.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?t.push(d.evaluateAll(r)):r instanceof ne&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=w.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof w&&d.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e)||!e.isInitialized())return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}validity`)&&F.applyCustomValidity(e),e.hasAttribute(`${c.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(d.executeManagedImport(e)),e.isVisible()?(e.getChildren().forEach(i=>{i instanceof w&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget();if(!t&&d.initialValueRestores.size>0&&e.hasAttribute(`${c.prefix}fetch-form`))return Promise.all(d.initialValueRestores).then(()=>d.executeManagedFetch(e,!0)).catch(a=>{g.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=d.getReactiveFetchState(r),n=ae.resolveAutoFetchSignature(e);if(i.running)return(n.hasUnresolvedReference||n.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(n.hasUnresolvedReference||n.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===n.signature)return Promise.resolve();i.lastSignature=n.signature,i.running=!0;const s=new ae(e,null);return s.markReentrantBind(),s.runWithResult().then(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${c.prefix}importing`,""),B.importStart(t,n),Zt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${c.prefix}importing`),B.importEnd(t,n,o,s),d.adoptImportedChildren(e);const l=[];return e.getChildren().forEach(u=>{u instanceof w?l.push(d.scan(u.getTarget())):u instanceof ne&&l.push(d.evaluateText(u))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),B.importError(t,n,a),g.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.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=N.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return d.scanElement(e,!0)}static scanElement(e,t){const r=N.get(e);if(!r)return Promise.resolve();const i=d.initializeElementFragment(r,!1).then(()=>F.restoreInitialValues(e));return d.initialValueRestores.add(i),i.then(()=>{d.initialValueRestores.delete(i),t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return w.retryUnappliedValueWrites(r,t).then(()=>{te.applySubtree(r)})}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e),te.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e)){d.refreshDerivedSubtreeSignature(e);return}const r=t&&e.hasAttribute(`${c.prefix}each`),i=[];return e.getChildren().forEach(n=>{n instanceof w?(!r||d.isEachFixedChild(n))&&i.push(d.initializeElementFragment(n,t)):n instanceof ne&&i.push(d.evaluateText(n))}),Promise.all(i).then(()=>{d.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>(e.markInitialized(),d.setAttribute(e.getTarget(),i,n))))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=c.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>(e.markInitialized(),d.setAttribute(e.getTarget(),n,e.getRawAttribute(n)))),r.add(n))}return t.then(()=>(e.markInitialized(),F.prepareFormName(e)))}static shouldSkipChildInitialization(e){const t=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&d.isHiddenIfCondition(t)}static setAttribute(e,t,r,i=!1,n){const s=N.get(e),a=d.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let l=null,u=null,h=null;switch(t){case`${c.prefix}bind`:{if(r!==null&&i&&s instanceof w&&s.consumeSelfWrittenBind(r))break;const m=r===null?{}:d.parseDataBind(r);if(i){const y=n??w.nextSequence();return r===null?(o.push(d.setBindingData(e,m,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(d.setBindingData(e,m,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(m);break}case`${c.prefix}derive`:u=d.createDeriveInputSignature(s,r,s.getRawAttribute(`${c.prefix}derive-name`)),l=d.evaluateDerive(s,r,s.getRawAttribute(`${c.prefix}derive-name`)),o.push(l.then(()=>{}));break;case`${c.prefix}derive-name`:u=d.createDeriveInputSignature(s,s.getRawAttribute(`${c.prefix}derive`),r),l=d.evaluateDerive(s,s.getRawAttribute(`${c.prefix}derive`),r),o.push(l.then(()=>{}));break;case`${c.prefix}if`:h=()=>d.evaluateIfOnAttributeWrite(s);break;case`${c.prefix}each`:h=()=>d.evaluateEach(s);break;case`${c.prefix}fetch`:h=()=>d.executeManagedFetch(s);break;case`${c.prefix}import`:typeof r=="string"&&(h=()=>d.executeManagedImport(s));break;case`${c.prefix}store`:r!==null&&o.push(De.restore(s));break;case`${c.prefix}validity`:case`${c.prefix}validity-message`:return r!==null&&F.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${c.prefix}url-param`:{const m=s.getAttribute(`${c.prefix}url-arg`),y=Te.readParams();m===null&&s.hasAttribute(`${c.prefix}store`)&&g.warn("Haori",`${c.prefix}url-param を ${c.prefix}url-arg なしで ${c.prefix}store と併用すると復元した値が消えます(${c.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()};if(m===null)o.push(d.setBindingData(e,y,E));else{const A=s.getRawBindingData()||{};A[String(m)]=y,o.push(d.setBindingData(e,A,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>h===null?void 0:h()).then(()=>{if(l!==null)return s.setDeriveInputSignature(u),l.then(m=>{if(m)return d.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=N.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",l=r.sequence??w.nextOperationSequence(),u={sequence:l,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},h=o==="supply";h&&i.markSupplyApplied(l);const m=w.currentSequence(),y=i.getRawBindingData();h&&(r.clearUserEdits??!0)&&d.clearUserEditMarks(i,l);const E=a?d.resolveByPathAuthority(i,y,t,u):t;i.setBindingData(E),a&&(B.bindChange(e,y,E,"manual"),De.mirror(i));const A=()=>{i.markBindingWorkStart();const D=i.getRawBindingData()??E;let M=a?i.setAttribute(`${c.prefix}bind`,JSON.stringify(d.withoutReservedBindingKeys(D))):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(m))return;const L=i.getRawBindingData()??E;return F.syncValues(i,F.resolveSyncValues(i,L),!1,u)})),M=M.then(()=>F.syncAncestorArgForms(i,m,u,y)),M=M.then(()=>d.evaluateAll(i,n)),M=M.then(()=>w.retryUnappliedValueWrites(e,m)),M=M.then(()=>d.reevaluateReactiveSpecialAttributes(i,n)),M.then(()=>i.markBindingWorkEnd(),L=>{throw i.markBindingWorkEnd(),L})};return s?A():i.enqueueBindingWork(A)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))w.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const n=d.mergePathAuthority(e,t??{},r,i,"",new Map);return n===d.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n,s){if(d.isPlainRecord(t)&&d.isPlainRecord(r)){const h=t,m=r,y={};let E=Object.keys(h).some(D=>!Object.prototype.hasOwnProperty.call(m,D));const A=new Set([...Object.keys(h),...Object.keys(m)]);for(const D of A){const M=n===""?D:`${n}.${D}`,L=d.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(h,D)?h[D]:d.ABSENT_PATH,Object.prototype.hasOwnProperty.call(m,D)?m[D]:d.ABSENT_PATH,i,M,s);L!==d.ABSENT_PATH&&(y[D]=L),L!==(Object.prototype.hasOwnProperty.call(m,D)?m[D]:d.ABSENT_PATH)&&(E=!0)}return E?y:m}const a=d.resolveArrayPairing(e,t,r,n,s);if(a!==null){const h=t,m=r,y=m.map((E,A)=>d.mergePathAuthority(e,h[A],E,i,`${n}[${a[A]}]`,s));return y.some((E,A)=>E!==m[A])?y:m}if(d.isSameBindingValue(t,r))return r;const o=i.editedPaths?.get(n),l=o===void 0?i.kind:"edit",u={sequence:o??i.sequence,kind:l};return e.canApplyPath(n,u)?(e.markPathApplied(n,u),r):t}static resolveArrayPairing(e,t,r,i,n){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const s=r.some(l=>d.isPlainRecord(l))?d.resolveEachKeyArg(e,i,n):null,a=t.map((l,u)=>d.createListKey(l,s,u)),o=r.map((l,u)=>d.createListKey(l,s,u));return a.some((l,u)=>l!==o[u])?null:o}static resolveEachKeyArg(e,t,r){const i=t.replace(/\[[^\]]*\]/g,""),n=r.get(i);if(n!==void 0)return n;const s=d.findEachKeyArg(e.getTarget(),i);return r.set(i,s),s}static findEachKeyArg(e,t){const r=`${c.prefix}each`,i=e.querySelectorAll(`[${r}]`);for(const n of Array.from(i)){const s=d.resolveEachDeclarationPath(n,e);if(s===null||s!==t)continue;const a=n.getAttribute(`${r}-key`);return a===null?null:a.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${c.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===d.ABSENT_PATH||t===d.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=N.get(e);return r instanceof w?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=d.collectScope(e);return q.isEnabled()&&g.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=N.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const u=l.getTarget(),h=d.resolveElementId(u);return h!==""?`#${h}`:u.tagName.toLowerCase()},s=(l,u,h,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(u),kind:h,depth:m})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return g.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=N.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=N.get(t.nextSibling),n=N.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.attachObserved(n,i),n instanceof w)return d.scan(n.getTarget());if(n instanceof ne)return d.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=N.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;if(t instanceof w){t.detachObserved();return}t.remove()}}static changeText(e,t){const r=N.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=N.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=F.getValues(n),a=n.getAttribute(`${c.prefix}form-arg`),o=n.getRawBindingData();let l;if(a){l={...o??{}};const u=String(a),h=F.resolveAncestorArgOwner(n,u);l[u]=F.mergeCollectedValues((h?h.value:l[u])??null,s)}else l=F.mergeCollectedValues(o,s,F.ancestorBaseResolver(n));i.push(d.setBindingData(n.getTarget(),l,{kind:"nonSupply",sequence:w.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),n=e.hasAttribute(`${c.prefix}if`),s=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,u=!1,h=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const E=d.createDeriveInputSignature(e,a,o);E===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==E&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(E)})))}let m=!1,y=0;return n&&(r=r.then(()=>{const E=e.isVisible();return y=w.currentSequence(),d.evaluateIf(e,t).then(()=>{m=!E&&e.isVisible()})})),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEachFixedChildren(e)).then(()=>d.evaluateEach(e)).then(()=>{if(m)return d.applyEnhancersOnShow(e,y)})):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}h=d.createDescendantBindingSignature(e,"evaluateAll"),u=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const E=[];return e.getChildren().forEach(A=>{if(A instanceof w){if(d.canSkipUnchangedNestedEach(A))return;E.push(d.evaluateAll(A,t))}else A instanceof ne&&!t.has(A)&&E.push(d.evaluateText(A))}),Promise.all(E).then(()=>{})}).then(()=>{u&&h!==null&&e.setDeriveSubtreeSignature(h)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=ie.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(ie.hasCompileFailure(t)){g.warn("[Haori]","data-if is hidden because the expression could not be compiled (see the preceding compile error):",t);return}const{sources:r}=d.collectScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),g.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${c.prefix}each-before`)||e.hasAttribute(`${c.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof w&&d.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?d.isEachFixedChild(r)&&t.push(d.evaluateAll(r)):r instanceof ne&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIfOnAttributeWrite(e){if(!e.hasAttribute(`${c.prefix}each`))return d.evaluateIf(e);const t=e.isVisible(),r=w.currentSequence();return d.evaluateIf(e).then(()=>{if(!t)return d.evaluateEach(e).then(()=>d.reevaluateReactiveSpecialAttributes(e)).then(()=>d.applyEnhancersOnShow(e,r))})}static evaluateIf(e,t=new Set){const r=[],i=e.getAttribute(`${c.prefix}if`);if(d.isHiddenIfCondition(i))q.isEnabled()&&e.isVisible()&&d.logFalsyIfDiagnostics(e),r.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const n=e.isVisible(),s=w.currentSequence(),a=[],o=e.hasAttribute(`${c.prefix}each`);e.getChildren().forEach(l=>{if(l instanceof w){if(o&&!d.isEachFixedChild(l))return;l.isMounted()?n?a.push(d.evaluateAll(l,t)):a.push(d.evaluateAll(l).then(()=>d.reevaluateReactiveSpecialAttributes(l))):a.push(d.scanElement(l.getTarget(),!1))}else l instanceof ne&&!(n&&t.has(l))&&a.push(d.evaluateText(l))}),r.push(e.show().then(()=>{B.show(e.getTarget()),n||(d.triggerLoadOnShow(e),te.refreshSubtree(e.getTarget(),!1))})),r.push(Promise.all(a).then(()=>{if(!(n||o))return d.applyEnhancersOnShow(e,s)}))}return Promise.all(r).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new ae(e,"load").run().catch(i=>{g.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(q.isEnabled()&&ie.recordRowScopeIdentifiers([d.getRowScopeName(e,"each-arg"),d.getRowScopeName(e,"each-index")]),e.isMounted()||d.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${c.prefix}each-done`),Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${c.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return d.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${c.prefix}each-done`,""),te.refreshSubtree(i,!1),d.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}d.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${c.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 (
31
- ${r}
32
- );`)}catch{try{i=new Function(`"use strict";
33
- ${r}
34
- `)}catch(n){g.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){g.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${c.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(d.EACH_RENDERED_CHANGE_WARNED.has(r)||(d.EACH_RENDERED_CHANGE_WARNED.add(r),g.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),d.countEachRenderedRows(e)!==0){if(!n){if(d.EACH_RENDERED_CHANGE_FIRED.has(r))return;d.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){g.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${c.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof w){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),s&&d.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!s){const h=N.get(l);h instanceof w&&(r=h.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=N.get(l);u instanceof w&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?d.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(d.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>d.evaluateAll(r,d.collectRowLocalFragments(e,r)))).then(()=>{})}static collectRowLocalFragments(e,t){const r=new Set,i=d.getEachScopeNames(e);if(i===null)return r;const n=s=>{if(d.keepsRowScopeNames(s))for(const a of s.getChildren())a instanceof ne?d.areExpressionsRowLocal(d.extractInterpolations(a.getRawText()),i)&&r.add(a):a instanceof w&&(d.isRowLocalSubtree(a,i)?r.add(a):n(a))};return n(t),r}static keepsRowScopeNames(e){return e.getAttributeNames().every(t=>!t.startsWith(c.prefix)||t===`${c.prefix}if`||t===`${c.prefix}row`)}static getEachScopeNames(e){const t=e.getAttribute(`${c.prefix}each-arg`);if(!t)return null;const r=new Set([String(t)]),i=e.getAttribute(`${c.prefix}each-index`);return i&&r.add(String(i)),r}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(g.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||d.hasNonEachDynamicElementState(e)||!d.isRowLocalEachTemplate(e)||d.hasEachFixedChildren(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=d.getEachScopeNames(e);if(r===null||i===null)return e.setRowLocalTemplate(!1),!1;const n=d.isRowLocalSubtree(r,i);return e.setRowLocalTemplate(n),n}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!d.areExpressionsRowLocal(d.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(c.prefix))continue;const a=i.slice(c.prefix.length);if(d.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!d.areExpressionsRowLocal([s],t))return!1;continue}if(d.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&d.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${c.prefix}each`)){const i=e.getRawAttribute(`${c.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${c.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof w){if(!d.isRowLocalSubtree(i,r))return!1}else if(i instanceof ne){const n=i.getRawText();if(n.includes("{{")&&!d.areExpressionsRowLocal(d.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=ie.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(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof w?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshUrlParams(){const e=`${c.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const n=N.peek(i);return n instanceof w?d.setAttribute(i,e,n.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{g.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof w&&t(i)})};t(e)}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!q.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.DERIVE_SUBTREE_PROFILES.set(e,r),r}static 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=d.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${c.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${c.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(u=>u instanceof w).findIndex(u=>u===r);n+=`:nth-child(${l+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof ne&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof w?!d.markFreshInitializationSkippable(n):n instanceof ne?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return g.error("[Haori]",`Template is not set for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${c.prefix}each-key`),s=e.getAttribute(`${c.prefix}each-arg`),a=t.map((x,X)=>d.createListKey(x,n?String(n):null,X)),o=new Set(a),l=new Map;a.forEach(x=>{l.set(x,(l.get(x)??0)+1)}),n&&o.size!==a.length&&d.warnDuplicateEachKey(String(n));const u=[];let h=e.getChildren().filter(x=>x instanceof w).filter(x=>!x.hasAttribute(`${c.prefix}each-before`)&&!x.hasAttribute(`${c.prefix}each-after`));const m=h.map(x=>x.getListKey()),y=new Set;h=h.filter((x,X)=>{const Q=String(x.getListKey()),J=l.get(Q)??0;if(J===0){y.add(x);const j=x.getListKey();return j!==null&&B.rowRemove(x.getTarget(),j,X),u.push(x.remove()),!1}return l.set(Q,J-1),!0});const E=h.map(x=>x.getListKey()),A=new Map;h.forEach(x=>{const X=x.getListKey();if(X===null)return;const Q=A.get(X);Q?Q.push(x):A.set(X,[x])});const D=e.getChildElementFragments().filter(x=>!y.has(x)),M=D.filter(x=>x.hasAttribute(`${c.prefix}each-before`)).length;let L=Promise.resolve();const ee=[];return a.forEach((x,X)=>{const Q=t[X],J=X;let j;const se=A.get(x)?.shift();if(se){j=se;const R=M+X;L=L.then(()=>d.updateRowFragment(j,Q,i,J,s?String(s):null,x).then($=>d.repositionEachRow(e,j,D,R).then(z=>{z!==null&&B.rowMove(j.getTarget(),x,z-M,X),!(!$&&d.isRowLocalEachTemplate(e))&&ee.push(d.evaluateAll(j,$?new Set:d.collectRowLocalFragments(e,j)).then(()=>d.applyRowFormValues(e,j,Q)))})))}else{j=r.clone();const R=M+X;L=L.then(()=>d.updateRowFragment(j,Q,i,J,s?String(s):null,x).then(()=>{const $=D[R]??null;return e.insertBefore(j,$).then(()=>{D.splice(R,0,j)}).then(()=>d.initializeFreshEachRow(j)).then(()=>d.applyRowFormValues(e,j,Q)).then(()=>{B.rowAdd(j.getTarget(),x,J,Q)})}))}}),Promise.all(u).then(()=>L).then(()=>Promise.all(ee)).then(()=>{const x=a.filter(R=>R!==null),X=E.filter(R=>R!==null),Q=new Set(X),J=x.filter(R=>!Q.has(R)),se=m.filter(R=>R!==null).filter(R=>!o.has(R));B.eachUpdate(e.getTarget(),J,se,x)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof w).filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));t.length!==0&&g.warn("[Haori]",`${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!q.isEnabled()||d.WARNED_DUPLICATE_EACH_KEYS.has(e)||(d.WARNED_DUPLICATE_EACH_KEYS.add(e),g.warn("[Haori]",`${c.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(`${c.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 g.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.initialValueRestores=new Set,d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),d.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"]),d.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap,d.EACH_RENDERED_CHANGE_FIRED=new WeakSet,d.EACH_RENDERED_CHANGE_WARNED=new WeakSet,d.WARNED_DUPLICATE_EACH_KEYS=new Set,d.ABSENT_PATH=Symbol("absent");let C=d;const we=class we{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||F.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>te.refreshSubtree(r),0)},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;if(!r||r[we.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=N.get(e);t&&new ae(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){g.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("reset",this.onReset),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("reset",this.onReset),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`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(we.BUILTIN_EVENT_NAMES.has(e)){g.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=N.get(i);n instanceof w&&this.isFromTarget(n,t)&&new ae(n,"on",t).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=W.read(e,r),n=t.target;return i===null||!(n instanceof Node)?!1:W.queryAll(i,r).some(s=>s.contains(n))}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=`${c.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${c.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=N.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{const s=new ae(i,t,r).runWithOutcome().catch(a=>(g.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){ae.recordClickOutcome(e,s);const a=r.target;a instanceof HTMLElement&&a!==e&&ae.recordClickOutcome(a,s)}};if(t==="click"&&e.hasAttribute(`${c.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=N.get(e);t instanceof w&&t.markUserEdit()}syncUserEdit(e,t){const r=N.get(e);if(r instanceof w&&(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=N.get(n);s instanceof w&&(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=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};we.HISTORY_STATE_KEY="__haoriHistoryState__",we.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let ze=we;const V=class V{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)&&(V.isHtmlElement(e)&&V.syncElement(e),e.querySelectorAll("*").forEach(t=>{V.syncElement(t)}))}static syncElement(e){const t=V.registrations.get(e),r=N.get(e);if(!r||!V.shouldObserve(r)){t&&(t.observer.disconnect(),V.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=V.resolveRoot(r),n=V.resolveRootMargin(r),s=V.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===n&&t.threshold===s&&t.once===a){t.fragment=r,V.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),V.registrations.delete(e));const o=new IntersectionObserver(l=>{const u=V.registrations.get(e);u&&l.forEach(h=>{if(u.intersecting=h.isIntersecting,!!h.isIntersecting){if(u.running||V.isDisabled(u.fragment)){u.pending=!0;return}V.runProcedure(e,u)}})},{root:i,rootMargin:n,threshold:s});o.observe(e),V.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:n,threshold:s})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new ae(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{g.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=V.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),V.registrations.delete(e);return}V.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||V.isDisabled(t.fragment)||V.runProcedure(e,t)}static cleanupTree(e){if(V.isHtmlElement(e)){const t=V.registrations.get(e);t&&(t.observer.disconnect(),V.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=V.registrations.get(t);r&&(r.observer.disconnect(),V.registrations.delete(t))})}static disconnectAll(){V.registrations.forEach(e=>{e.observer.disconnect()}),V.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!V.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=W.query(r,t,document);return V.isHtmlElement(i)?i:(g.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}};V.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),V.registrations=new Map;let Ae=V;const S=class S{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(S.isHtmlElement(e)&&S.syncElement(e),e.querySelectorAll("*").forEach(t=>{S.syncElement(t)}))}static syncElement(e){const t=S.registrations.get(e);if(!t&&!S.hasPollAttribute(e))return;const r=N.get(e);if(!(r instanceof w)||!S.shouldObserve(r)){t&&S.teardown(e,t);return}const i=S.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}S.teardown(e,t)}S.startPolling(e,r,i)}static cleanupTree(e){if(S.isHtmlElement(e)){const t=S.registrations.get(e);t&&S.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=S.registrations.get(t);r&&S.teardown(t,r)})}static disconnectAll(){S.registrations.forEach(e=>{S.clearTimers(e)}),S.registrations.clear(),S.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",S.visibilityListener),S.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=`${c.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=`${c.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!S.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
35
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:S.resolveInterval(t),timeoutMs:S.resolveTimeout(t),errorLimit:S.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};S.registrations.set(e,i),S.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{S.handleTimeout(e)},i.timeoutMs)),S.injectState(i),S.tick(e)}static async tick(e){const t=S.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await S.stop(e,t,"detached");return}const r=S.isHidden(e)||S.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await S.injectState(t)),r){S.schedule(e,t);return}if(S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ae(t.fragment,"poll").runWithResult()}catch(n){g.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(S.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await S.stop(e,t,"error");return}if(i&&S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}S.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{S.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=S.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,S.elapsed(t)),await S.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,S.clearTimers(t),r==="detached"){S.registrations.delete(e);return}await S.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,S.elapsed(t))}}static teardown(e,t){S.clearTimers(t),S.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(S.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(S.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),S.tick(t))})};S.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=S.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:S.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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=W.queryAll(i,t,document);if(n.length===0)return g.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=N.get(a);o instanceof w&&s.push(o)}),s}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return S.DEFAULT_INTERVAL_MS;const r=S.toNumber(e.getAttribute(t));return r===null?(g.warn("[Haori]",`${t} は数値で指定してください。既定値 ${S.DEFAULT_INTERVAL_MS}ms を使用します。`),S.DEFAULT_INTERVAL_MS):r<S.MIN_INTERVAL_MS?(g.warn("[Haori]",`${t} の下限は ${S.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),S.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=S.toNumber(e.getAttribute(t));return r===null||r<=0?(g.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=S.toNumber(e.getAttribute(t));return r===null||r<1?(g.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?S.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(g.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):S.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}};S.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),S.DEFAULT_INTERVAL_MS=5e3,S.MIN_INTERVAL_MS=100,S.registrations=new Map,S.visibilityListener=null;let ve=S;const wt="0.62.3";function Qt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const O=class O{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)&&(O.isHtmlElement(e)&&O.syncElement(e),e.querySelectorAll("*").forEach(t=>{O.syncElement(t)}))}static syncElement(e){const t=O.registrations.get(e),r=N.get(e);if(!(r instanceof w)||!O.shouldObserve(r)){t&&(t.observer.disconnect(),O.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=O.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),O.registrations.delete(e)),g.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=O.resolveRoot(r),s=O.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,O.refreshRows(t);return}t&&(t.observer.disconnect(),O.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=O.registrations.get(e);if(!u)return;let h=!1;l.forEach(m=>{const y=m.target;u.observedRows.has(y)&&(m.isIntersecting?u.visibleRows.has(y)||(u.visibleRows.add(y),h=!0):u.visibleRows.delete(y)&&(h=!0))}),h&&O.scheduleCompute(u)},{root:n,rootMargin:s,threshold:O.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};O.registrations.set(e,o),O.refreshRows(o)}static cleanupTree(e){if(O.isHtmlElement(e)){const t=O.registrations.get(e);t&&(t.observer.disconnect(),O.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=O.registrations.get(t);r&&(r.observer.disconnect(),O.registrations.delete(t))})}static disconnectAll(){O.registrations.forEach(e=>{e.observer.disconnect()}),O.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=W.query(r,t,document);return O.isHtmlElement(i)?i:(g.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?O.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof w&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=O.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));O.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Qt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();O.registrations.get(t)===e&&O.computeAndPublish(e)}))}static computeAndPublish(e){const t=O.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,O.publish(e,n))}static publish(e,t){const r=O.resolveBindOwner(e.fragment);if(!r){g.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]);C.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()}).catch(o=>{g.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};O.THRESHOLD=0,O.DEFAULT_ROOT_MARGIN="0px",O.registrations=new Map;let me=O;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers(),w.setPendingMutationFlusher(()=>{H.flushPendingMutations()});const e=new ze;H._dispatcher=e,e.startDeferred(),H._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",i.reason),await H.waitInitialIntakes(),await K.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),Ae.syncTree(document.body),ve.syncTree(document.body),me.syncTree(document.body)}finally{H._initialIntakes=null,e.release()}B.ready(wt)}static getDispatcher(){return H._dispatcher}static async waitInitialIntakes(){const e=H._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(H._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>H.toCapturedRecord(i));t.disconnect(),H.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!H.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>w.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=w.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{H.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}static flushPendingMutations(){for(const e of H._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(H.isBindAttributeRecord),i=t.filter(n=>!H.isBindAttributeRecord(n));r.length>0&&H.processMutations(r,w.nextSequence()),i.length>0&&Promise.resolve().then(()=>{H.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(H.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(he)&&(r.attributeName==="disabled"||r.attributeName===he))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&w.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const n=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);H._initialIntakes?.push(n),Ae.syncElement(i),ve.syncElement(i),me.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{H.isStaleExternalRemoval(r,i)||(Ae.cleanupTree(i),ve.cleanupTree(i),me.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const n=C.addNode(i.parentElement,i);H._initialIntakes?.push(n),Ae.syncTree(i),ve.syncTree(i),me.syncTree(i)}),r.target instanceof Element&&me.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.changeText(r.target,r.target.textContent):g.warn("[Haori]","Unsupported character data type:",r.target);break}default:g.warn("[Haori]","Unknown mutation type:",r.type);continue}}catch(i){g.error("[Haori]","Error processing mutation:",i)}}};H._initialized=!1,H._mutationObservers=[],H._dispatcher=null,H._initialIntakes=null;let ke=H;te.setMutationCapture(b=>ke.captureMutations(b)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ke.init):ke.init();const _t=()=>ce.waitForRenders(),er=ce.enhancers,tr=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:te,Env:c,Form:F,Fragment:N,Haori:ce,Log:g,Queue:K,default:ce,enhancers:er,version:wt,waitForRenders:_t},Symbol.toStringTag,{value:"Module"})),Ge=ce;for(const[b,e]of Object.entries(tr))b in Ge||Object.defineProperty(Ge,b,{value:e,writable:!0,enumerable:!0,configurable:!0});return Ge}();
30
+ ${W}
31
+ `)}catch(G){m.error("Haori",`Invalid after script: ${G}`)}}if(e.hasAttribute(g.attrName(t,"dialog"))&&(r.dialogMessage=g.unescapeNewlines(g.readLateAttribute(e,r,"dialog",g.attrName(t,"dialog")))),e.hasAttribute(g.attrName(t,"toast"))&&(r.toastMessage=g.readLateAttribute(e,r,"toast",g.attrName(t,"toast")),r.toastLevel=g.readToastLevel(e,r,"toast-level",g.attrName(t,"toast-level"))),t!=="poll"){const W=g.attrName(t,"error-toast");e.hasAttribute(W)&&(r.errorToastMessage=g.readLateAttribute(e,r,"error-toast",W),r.errorToastLevel=g.readToastLevel(e,r,"error-toast-level",g.attrName(t,"error-toast-level")));const G=g.attrName(t,"error-status");e.hasAttribute(G)&&(r.errorStatuses=g.parseErrorStatuses(e.getRawAttribute(G),G)),r.errorNoMessage=e.hasAttribute(g.attrName(t,"error-no-message")),r.errorBind=e.hasAttribute(g.attrName(t,"error-bind"))}const O=g.attrName(t,"redirect"),j=g.attrName(t,"redirect-replace"),V=e.hasAttribute(O),de=e.hasAttribute(j);if(V&&(r.redirectUrl=g.readLateAttribute(e,r,"redirect",O)),de&&(r.redirectReplaceUrl=g.readLateAttribute(e,r,"redirect-replace",j)),V||de){const W=g.attrName(t,"redirect-return-param");e.hasAttribute(W)&&(r.redirectReturnParam=g.readLateAttribute(e,r,"redirect-return-param",W))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"clear-messages"))&&(r.clearMessagesOnSuccess=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=g.readLateAttribute(e,r,"scroll",g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=g.readLateAttribute(e,r,"history",g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const W=K.read(e,g.attrName(t,"history-form"));if(W){const G=K.query(W,g.attrName(t,"history-form"));G!==null?r.historyFormFragment=x.getFormFragment(D.get(G)):m.error("Haori",`Form element not found: ${W} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=x.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close","error-click","error-close"].forEach(W=>{if(W.startsWith("error-")&&t==="poll")return;const G=g.attrName(t,W);if(!e.hasAttribute(G))return;const re=g.resolveSelectorTargets(e,G,W);if(re.length>0)switch(W){case"reset-before":r.resetBeforeFragments=re;break;case"reset":r.resetFragments=re;break;case"refetch":r.refetchFragments=re;break;case"click":r.clickFragments=re,r.clickAwait=e.hasAttribute(`${G}-await`);break;case"copy":r.copyFragments=re;break;case"open":r.openFragments=re;break;case"close":r.closeFragments=re;break;case"error-click":r.errorClickFragments=re,r.errorClickAwait=e.hasAttribute(`${G}-await`);break;case"error-close":r.errorCloseFragments=re;break}}),t!=="poll"&&(r.errorStatusActions=g.readErrorStatusActions(e,r,t));const oe=g.attrName(t,"copy-source");if(e.hasAttribute(oe)){const W=K.read(e,oe);if(W){const G=K.query(W,oe);if(G!==null){const re=D.get(G);re?r.copySourceFragment=re:m.error("Haori",`Element is not managed by Haori: ${W} (${oe})`)}else m.error("Haori",`Element not found: ${W} (${oe})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const w=K.read(e,g.attrName(null,"form",!0));if(w){const O=K.query(w,g.attrName(null,"form",!0));O!==null?r.formFragment=x.getFormFragment(D.get(O)):m.error("Haori",`Form element not found: ${w} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=x.getFormFragment(e)}(!t||t==="poll")&&g.readNoMessageDeclarations(e,r,t??"fetch");const z=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(z)){const w=K.read(e,z),O=[];w?(K.queryAll(w,z).forEach(V=>{const de=D.get(V);de&&O.push(de)}),O.length===0&&m.error("Haori",`Element not found: ${w} (${z})`)):O.push(e),O.length>0&&(r.fetchStateFragments=O)}const ce=t?g.attrName(t,"store-clear"):g.attrName(null,"store-clear",!0);if(e.hasAttribute(ce)){const w=e.getRawAttribute(ce),O=w===null?"":w.trim();if(O==="")m.error("Haori",`ストレージキーが指定されていません (${ce})`);else{r.storeClearKey=O;const j=e.getRawAttribute(`${ce}-type`),V=j===null?"session":j.trim();V==="local"||V==="session"?r.storeClearKind=V:(m.warn("Haori",`${ce}-type は session または local を指定してください(session として扱います): ${V}`),r.storeClearKind="session")}}return n&&!r.download&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r.download&&r.bindFragments&&r.bindFragments.length>0&&(m.warn("Haori",`${b} と同時にバインド先が指定されています(応答はファイルとして保存し、バインドは行いません)。`),r.bindFragments=null),g.recordRowWriteTargets(r),r}static recordRowWriteTargets(e){const t=new Map,r=[...e.bindFragments??[],...e.copyFragments??[]];for(const i of r){const s=i.getParent();!s||!s.hasAttribute(`${c.prefix}each`)||!s.hasAttribute(`${c.prefix}form-list`)||t.set(i,g.getRowFragments(s).includes(i)?s: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(`${c.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 g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async runWithOutcome(){return await this.execute()?"success":this.skipped?"skipped":"failure"}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0)return this.skipped=!0,!1;if(this.options.formFragment&&this.validate(this.options.formFragment)===!1)return await this.commitEditOnStop(),!1;if(!this.options.formFragment&&this.options.targetFragment&&x.warnUnvalidatedCustomValidity(x.getFormFragment(this.options.targetFragment),`${c.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition())return this.skipped=!0,await this.commitEditOnStop(),!1;if(this.options.runScript){const y=this.options.targetFragment?.getTarget()??null;try{const b=this.options.runScript.call(y,this.domEvent);b===!1&&this.domEvent&&this.domEvent.preventDefault(),b!=null&&typeof b.then=="function"&&await b}catch(b){m.error("Haori",`Run script execution error: ${b}`)}}if(!await this.confirm())return await this.commitEditOnStop(),!1;if(this.options.downloadFolder&&await this.prepareDownloadFolder()==="cancelled")return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(y=>x.reset(y,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=R.currentSequence();const i=r.payload;let s=r.url,n=r.options,a=!1,o=!1;if(this.options.beforeCallback){const y=this.options.beforeCallback(s||null,n||null);if(y!=null){if(y===!1||typeof y=="object"&&y.stop)return!1;typeof y=="object"&&(a="fetchUrl"in y,o="fetchOptions"in y,s=a?y.fetchUrl:s,n=o?y.fetchOptions:n)}}const l=Object.keys(i).length>0;if(s){this.isInputEditProcedure()&&await this.commitFormValues(this.options.formFragment,i,e);const y=(n?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&xr(n)&&!Ye(y)?r.baseUrl??s:s,A=Nr(E,n);s=A.url;const k={...A.options},M=A.normalized?A.requestedMethod:r.requestedMethod,P=A.effectiveMethod,ie=r.transportMode==="query-get"||A.normalized,F=A.queryString??r.queryString;if(ie&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:M,effectiveMethod:P,transportMode:"query-get",url:s,payload:l?i:void 0,queryString:F}),this.options.targetFragment&&s){const Q=performance.now(),te={runtime:c.runtime,requestedMethod:M,effectiveMethod:P,transportMode:ie?"query-get":"http",...ie?{queryString:F}:{}};return B.fetchStart(this.options.targetFragment.getTarget(),s,k,l?i:void 0,te),await this.injectFetchState("loading"),await g.invokeFetch(s,k).then(_=>this.handleFetchResult(_,s||void 0,Q)).catch(async _=>{throw s&&B.fetchError(this.options.targetFragment.getTarget(),s,_),await this.injectFetchState("error",null,_ instanceof Error?_.message:String(_)),await this.runErrorActions(null),_})}return await fetch(s,k).then(Q=>this.handleFetchResult(Q,s||void 0))}(!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&l&&await this.commitFormValues(this.options.formFragment,i,e),this.suppressEmptyReplaceBind=!l&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=l?st(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}async commitEditOnStop(){!this.isInputEditProcedure()||!this.options.fetchUrl&&this.options.bindFragments&&this.options.bindFragments.length>0||await this.commitFormValues(this.options.formFragment,this.buildPayloadResolution().payload,null)}isInputEditProcedure(){return(this.eventType==="change"||this.eventType==="input")&&!!this.options.formFragment}async commitFormValues(e,t,r){const i=e.getTarget(),s=new Set;r&&r.appliedDisabledAttribute&&this.options.targetFragment&&s.add(this.options.targetFragment);const n=e.getRawBindingData(),a=st(t),o=e.getAttribute(`${c.prefix}form-arg`);let l;if(o){l={...n??{}};const u=String(o),d=x.resolveAncestorArgOwner(e,u);l[u]=x.mergeCollectedValues((d?d.value:l[u])??null,a)}else l=x.mergeCollectedValues(n,a,x.ancestorBaseResolver(e));await C.setBindingData(i,l,{skipFragments:s,kind:"nonSupply",sequence:this.operationSequence,editedPaths:x.collectEditedPaths(e,this.operationSequence,o?String(o):"",a)})}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment,t=e.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(it))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(it,""),r||t.setAttribute("disabled",""),{target:t,fragment:e,appliedDisabledAttribute:!r}}static findDisabledDeclaration(e){const t=`${c.prefix}attr-disabled`,r=e.getRawAttribute(t);if(r!==null)return{name:t,value:r};const i=e.getRawAttribute("disabled");return i!==null&&i.includes("{{")?{name:"disabled",value:i}:null}releaseExecutionLock(e){if(!e)return;const t=e.target;if(g.RUNNING_CLICK_TARGETS.delete(t),t.removeAttribute(it),!e.appliedDisabledAttribute)return;const r=g.findDisabledDeclaration(e.fragment);if(r===null){t.removeAttribute("disabled");return}C.setAttribute(t,r.name,r.value).catch(i=>{m.error("Haori",`ロックの解除で ${r.name} を適用し直せませんでした: ${i}`)})}static forgetDownloadFolder(){Le=null}async prepareDownloadFolder(){if(Le)return this.downloadFolder=Le,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return m.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Le=t,this.downloadFolder=t,"ready"}catch(t){return t?.name==="AbortError"?"cancelled":(m.info("Haori",`保存先のフォルダを選ばせられなかったため、今までどおり保存します: ${t}`),"fallback")}}async readResponseBody(e){const t=e.headers.get("Content-Type")??"",r=e.body;if(!r||typeof r.getReader!="function")try{const n=await e.blob();return this.downloadReceivedBytes=n.size,this.dropTotalBytesIfExceeded(),await this.injectFetchState("loading"),n}catch(n){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${n}`),null}const i=[];return await this.pumpResponseBody(r,n=>{i.push(new Blob([n]))})?new Blob(i,t!==""?{type:t}:void 0):null}async pumpResponseBody(e,t){await this.injectFetchState("loading");let r=Date.now();const i=e.getReader();try{for(;;){const{done:s,value:n}=await i.read();if(s)break;await t(n),this.downloadReceivedBytes+=n.byteLength,this.dropTotalBytesIfExceeded();const a=Date.now();a-r>=Sr&&(r=a,await this.injectFetchState("loading"))}}catch(s){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${s}`),!1}return!0}dropTotalBytesIfExceeded(){this.downloadTotalBytes!==null&&this.downloadReceivedBytes>this.downloadTotalBytes&&(this.downloadTotalBytes=null)}static resolveDownloadTotalBytes(e){const t=e.headers.get("Content-Encoding");if(t!==null){const n=t.trim().toLowerCase();if(n!==""&&n!=="identity")return null}const r=e.headers.get("Content-Length");if(r===null)return null;const i=r.trim();if(i==="")return null;const s=Number(i);return!Number.isSafeInteger(s)||s<0?null:s}async saveResponseToFolder(e,t,r){const i=t.body;if(!i||typeof i.getReader!="function")return"fallback";const s=g.resolveDownloadFileName(t,this.options.downloadFileName??null,r??this.options.fetchUrl??null);let n=!0;try{await e.getFileHandle(s)}catch(l){if(l?.name==="NotFoundError")n=!1;else return m.info("Haori",`保存先のフォルダを確かめられなかったため、今までどおり保存します: ${l}`),"fallback"}if(n&&!await Ee().confirm(`${s} は既にあります。上書きしますか?`))return"cancelled";let a;try{a=await(await e.getFileHandle(s,{create:!0})).createWritable()}catch(l){return m.info("Haori",`保存先のファイルを作れなかったため、今までどおり保存します: ${l}`),"fallback"}if(await this.pumpResponseBody(i,l=>a.write(l)))try{return await a.close(),"saved"}catch(l){m.error("Haori",`ファイルを書き終えられませんでした: ${l}`)}try{await a.abort()}catch(l){m.error("Haori",`書きかけを取り消せませんでした: ${l}`)}if(!n)try{await e.removeEntry(s)}catch(l){m.error("Haori",`作りかけのファイルを取り除けませんでした: ${l}`)}return"failed"}async saveResponseAsFile(e,t){if(this.downloadTotalBytes=g.resolveDownloadTotalBytes(e),this.downloadFolder){const a=await this.saveResponseToFolder(this.downloadFolder,e,t);if(a!=="fallback")return a;this.downloadFolder=null,Le=null}const r=await this.readResponseBody(e);if(r===null)return"failed";const i=g.resolveDownloadFileName(e,this.options.downloadFileName??null,t??this.options.fetchUrl??null);if(typeof URL>"u"||typeof URL.createObjectURL!="function")return m.error("Haori","この環境では Blob の URL を生成できないため、ファイルを保存できません。"),"failed";const s=URL.createObjectURL(r),n=document.createElement("a");return n.href=s,n.download=i,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(s),0),"saved"}async showDownloadFailure(e){const t=this.resolveMessageScope(),r=Ee();await r.clearMessages(t),e&&await r.addErrorMessage(t,Gt)}static resolveDownloadFileName(e,t,r){const s=[g.readContentDispositionFileName(e.headers.get("Content-Disposition")),t,g.readUrlFileName(r)];for(const n of s){const a=g.sanitizeFileName(n);if(a!==null)return a}return"download"}static readContentDispositionFileName(e){if(!e)return null;const t=/filename\*\s*=\s*([^;]+)/i.exec(e);if(t){const s=t[1].trim(),n=s.split("'"),a=n.length>=3?n.slice(2).join("'"):s;try{return decodeURIComponent(a)}catch(o){m.warn("Haori",`Content-Disposition を解釈できません: ${o}`)}}const r=/filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(r)return r[1].replace(/\\(.)/g,"$1");const i=/filename\s*=\s*([^;]+)/i.exec(e);return i?i[1].trim():null}static readUrlFileName(e){if(!e)return null;const r=e.split("#")[0].split("?")[0].split("/"),i=r[r.length-1];return i===""?null:i}static sanitizeFileName(e){if(e===null)return null;const t=e.replace(/[\u0000-\u001f\u007f/\\]/g,"").trim();return t===""?null:t}async handleFetchResult(e,t,r){const i=Ee();if(!e.ok){if(zt(e.status,{element:this.options.targetFragment.getTarget(),attrPrefix:g.attrName(this.eventType,"",!0)}))return!1;this.options.targetFragment&&t&&B.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r);const E=this.selectErrorActions(e.status),A=E?.bind===!0,k=await this.handleFetchError(A?e.clone():e,E?.noMessage!==!0&&!A);return A&&await this.bindResult(e).catch(M=>{m.error("Haori","Failed to bind the error response:",M)}),await this.injectFetchState("error",e.status,e.statusText||null,k),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&B.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const E=this.options.afterCallback(e);if(E!=null){if(E===!1||typeof E=="object"&&E.stop)return!1;typeof E=="object"&&"response"in E&&(e="response"in E?E.response:e)}}if(this.options.download){const E=await this.saveResponseAsFile(e,t);if(E==="cancelled")return await this.injectFetchState("success",e.status,null),!1;if(E==="failed"){const A=this.selectErrorActions(null);return await this.showDownloadFailure(A?.noMessage!==!0),await this.injectFetchState("error",e.status,Gt),await this.runErrorActions(null),!1}}this.options.clearMessagesOnSuccess&&await i.clearMessages(this.resolveMessageScope());const s=[];s.push(this.bindResult(e)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(E=>x.reset(E,this.operationSequence))),await this.copy();const n=[];this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(E=>{n.push(new g(E,null).run())});const a=await this.clickTargets(this.options.clickFragments,this.options.clickAwait===!0,"click-await");if(!a&&this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?n.push(i.openDialog(A)):m.error("Haori","Element is not an HTML element: ",A)}),!a&&this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?n.push(i.closeDialog(A)):m.error("Haori","Element is not an HTML element: ",A)}),await Promise.all(n),a)return!1;const o=g.unescapeNewlines(g.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));o&&await i.dialog(o);const l=g.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));if(l){const E=g.toToastLevel(this.resolveLateAttribute("toast-level",this.options.toastLevel));await i.toast(l,E??"info")}this.clearStore(),this.pushHistory();const u=this.resolveLateAttribute("scroll",this.options.scrollTarget);u&&K.query(u,g.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const d=this.resolveLateAttribute("redirect",this.options.redirectUrl),y=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);d&&y&&m.warn("Haori",`${g.attrName(this.eventType,"redirect")} と ${g.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const b=y||d;if(b){let E=b;const A=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(A){const M=new URLSearchParams(window.location.search).get(A);if(M!==null){const P=M.trim();$e.isSafeLocalPath(P)?E=P:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${M}`)}}$e.isNavigableUrl(E)?y?window.location.replace(E):window.location.href=E:m.error("Haori",`遷移先が http: / https: / 現在ページと同じスキームの URL ではないため遷移しません: ${E}`)}return!0}clearStore(){const e=this.options.storeClearKey;e&&Pe.clear(e,this.options.storeClearKind??"session")}async clickTargets(e,t,r){if(!e||e.length===0)return!1;for(const i of e){await C.evaluateAll(i);const s=i.getTarget();if(t&&g.takeClickOutcome(s),typeof s.click=="function"?s.click():s.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),!t)continue;const n=g.takeClickOutcome(s);if(n===null){m.warn("Haori",`${c.prefix}${this.eventType??"fetch"}-${r} はこの対象の完了を待てません(手続きが同期に起動していません)。`);continue}if(await n==="failure")return!0}return!1}async runErrorActions(e){const t=this.selectErrorActions(e);if(!t||await this.clickTargets(t.clickFragments,t.clickAwait,`${t.key}-click-await`))return;const i=Ee(),s=[];t.closeFragments?.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.push(i.closeDialog(o)):m.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s);const n=g.normalizeAttributeText(this.resolveLateAttribute(`${t.key}-toast`,t.toastMessage));if(n){const a=g.toToastLevel(this.resolveLateAttribute(`${t.key}-toast-level`,t.toastLevel));await i.toast(n,a??"info")}}selectErrorActions(e){const t=e===null?void 0:this.options.errorStatusActions?.get(e);return t||(this.appliesErrorActions(e)?{key:"error",clickFragments:this.options.errorClickFragments??null,clickAwait:this.options.errorClickAwait===!0,closeFragments:this.options.errorCloseFragments??null,toastMessage:this.options.errorToastMessage??null,toastLevel:this.options.errorToastLevel??null,noMessage:this.options.errorNoMessage===!0,bind:this.options.errorBind===!0}:null)}appliesErrorActions(e){const t=this.options.errorStatuses;return t===void 0||e!==null&&t.includes(e)}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,s=this.options.targetFragment??null;if(!i||!s||!s.hasAttribute(i.attributeName))return r;const n=s.getAttributeEvaluation(i.attributeName);return n===null?r:n.hasUnresolvedReference&&!i.hasUnresolvedReference?(U.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):n.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),s=r!=null,n=i!=null;if(!(!t&&!s&&!n))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 l=u=>{for(const[d,y]of Object.entries(u))y!=null&&(Array.isArray(y)?(o.searchParams.delete(d),y.forEach(b=>o.searchParams.append(d,String(b)))):typeof y=="object"?o.searchParams.set(d,JSON.stringify(y)):o.searchParams.set(d,String(y)))};s&&l(r),n&&l(i),history.pushState({[wr]:!0},"",o.toString()),C.refreshUrlParams()}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}resolveMessageScope(){const e=this.options.formFragment??(this.options.targetFragment?x.getFormFragment(this.options.targetFragment)||this.options.targetFragment:null);return e?e.getTarget():document.body}async handleFetchError(e,t){let r=null;this.options.formFragment?r=this.options.formFragment:this.options.targetFragment&&(r=x.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const i=r?r.getTarget():document.body;await Ee().clearMessages(i);const s=async u=>{const d=r?r.getTarget():document.body;await Ee().addErrorMessage(d,u)},n=()=>{if(!this.options.scrollOnError)return;const u=r?r.getTarget():document.body,d=u.nextElementSibling;(u.getAttribute("data-message-level")==="error"?u:u.parentElement?.getAttribute("data-message-level")==="error"?u.parentElement:u.querySelector('[data-message-level="error"]')??(d?.getAttribute("data-message-level")==="error"?d:null))?.scrollIntoView({behavior:"smooth",block:"nearest"})},a=async u=>{if(t){u.length===0&&await s(`${e.status} ${e.statusText}`);for(const d of u)d.key&&r?await x.addErrorMessage(r,d.key,d.message):await s(d.message);n()}return u.length===0?null:u.map(d=>d.message).join(`
32
+ `)};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const u=await e.json(),d=[];if(Array.isArray(u)){const y=new Map,b=[];for(const E of u)if(E&&typeof E=="object"&&!Array.isArray(E)){const A=E.key,k=E.message,M=typeof A=="string"&&A.length>0?A:null,P=typeof k=="string"?k:k!=null?String(k):"";if(P.length===0)continue;if(M!==null){const ie=y.get(M)??[];ie.push(P),y.set(M,ie)}else b.push(P)}else typeof E=="string"&&E.length>0&&b.push(E);for(const[E,A]of y)d.push({key:E,message:A.join(`
33
+ `)});for(const E of b)d.push({message:E})}else if(u&&typeof u=="object"){if(typeof u.message=="string"&&d.push({message:u.message}),Array.isArray(u.messages))for(const y of u.messages)typeof y=="string"&&d.push({message:y});if(u.errors&&typeof u.errors=="object")for(const[y,b]of Object.entries(u.errors))Array.isArray(b)?d.push({key:y,message:b.join(`
34
+ `)}):typeof b=="string"?d.push({key:y,message:b}):b!=null&&d.push({key:y,message:String(b)});if(d.length===0)for(const[y,b]of Object.entries(u))y==="message"||y==="messages"||y==="errors"||(Array.isArray(b)?d.push({key:y,message:b.join(`
35
+ `)}):typeof b=="string"&&d.push({key:y,message:b}))}return await a(d)}catch{}let l="";try{l=(await e.text()).trim()}catch{}return await a(l.length>0?[{message:l}]:[])}validate(e){if(this.options.valid!==!0)return this.options.implicitFormFragment||x.warnUnvalidatedCustomValidity(e,`${c.prefix}${this.eventType??"fetch"}-validate の指定がありません`),!0;x.applyCustomValidity(e);const t=this.findFirstInvalid(e);if(t===null)return!0;const r=t;return g.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"}),g.reportValidityAfterScroll(r),!1)}static reportValidityAfterScroll(e){const t=++g.validationReportGeneration,r=performance.now();let i=null,s=0;const n=()=>{if(t!==g.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(s=o===i?s+1:0,i=o,s>=g.VALIDATION_SCROLL_STABLE_FRAMES&&g.isRectPartlyVisible(a)||performance.now()-r>=g.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(n)};requestAnimationFrame(n)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=g.getViewportSize();return e.top>=0&&e.left>=0&&e.bottom<=r&&e.right<=t}static isRectPartlyVisible(e){const{width:t,height:r}=g.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??`${c.prefix}if`,s=x.buildConditionScope(r,this.options.formFragment??null),n=ne.evaluateDetailed(t,s);return n.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):n.value?!0:(e||m.info("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${c.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):Ee().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=ne.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(l=>{i&&typeof i=="object"&&l in i&&(o[l]=i[l])}),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 ${c.prefix}${this.eventType}-form.`);return}const s=[],n=this.eventType?g.attrName(this.eventType,"bind"):g.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const l=this.resolveRowWrite(o,n);if(l.kind==="skip")return;if(l.kind==="row"){const y=this.options.bindArg;a.push({container:l.container,row:o,attributeName:n,syncWhenUnchanged:"reflect",apply:b=>{const E=this.resolveCurrentRowItem(o,b),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const k=E[y],M=k!==null&&typeof k=="object"&&!Array.isArray(k)?k:{};A[y]=this.mergeAppendBindingData(o,i,M)}else A[y]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const y=u[d],b=y&&typeof y=="object"&&!Array.isArray(y)?y:{};u[d]=this.mergeAppendBindingData(o,i,b)}else u[d]=i;s.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u,[d]),{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 l=this.resolveRowWrite(o,n);if(l.kind==="skip")return;if(l.kind==="row"){a.push({container:l.container,row:o,attributeName:n,syncWhenUnchanged:"reflect",apply:y=>{const b=this.options.bindMerge?this.resolveCurrentRowItem(o,y):y,E=this.mergeAppendBindingData(o,i,b),A=this.options.bindMerge?{...b,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;s.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d,Object.keys(u)),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return s.push(this.applyRowWrites(a)),Promise.all(s).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(l=>{B.bindComplete(l.getTarget(),o)})})})}reconcileUserEditsForBind(e,t,r){const i=this.requestUserEditSequence;if(i===null)return t;const s=this.eventType==="poll";if(!s&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,i),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,r,s?0:i);const n=x.getValuesEditedAfter(e,s?0:i);if(Object.keys(n).length===0)return t;const a=e.getAttribute(`${c.prefix}form-arg`);if(a){const o=String(a),l=t[o],u=l&&typeof l=="object"&&!Array.isArray(l)?l:{};return{...t,[o]:Ae(u,n)}}return Ae(t,n)}reconcileRowUserEdits(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";!i&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,r);const s=x.getValuesEditedAfter(e,i?0:r);return Object.keys(s).length===0?t:Ae(t,s)}reconcileAncestorArgFormEdits(e,t,r,i){let s=t;for(const{form:n,key:a}of x.collectArgForms(e)){if(!r.includes(a))continue;const o=x.getValuesEditedAfter(n,i);if(Object.keys(o).length===0)continue;const l=s[a],u=l&&typeof l=="object"&&!Array.isArray(l)?l:{};s={...s,[a]:Ae(u,o)}}return s}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=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=g.attrName(this.eventType,"copy"),i=[],s=[];return this.options.copyFragments.forEach(n=>{const a=this.resolveRowWrite(n,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:n,attributeName:r,syncWhenUnchanged:"supply",apply:l=>this.applyCopyToRowItem(n,l,t)});return}const o={...n.getRawBindingData()??{},...t};s.push(C.setBindingData(n.getTarget(),o,{sequence:this.operationSequence}))}),s.push(this.applyRowWrites(i)),Promise.all(s).then(()=>{})}resolveCurrentRowItem(e,t){const r=x.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:Ae(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):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Xe(this.options.formFragment):this.options.targetFragment?C.withoutReservedBindingKeys(this.options.targetFragment.getRawBindingData()??{}):{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=x.getValues(r);Object.assign(e,i),x.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=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return 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 s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=c.runtime==="demo"&&!Ye(a),l=o?"GET":a;if(s.method=l,Object.keys(t).length>0&&Oe(t)){const d=n.get("Content-Type")||"";!Ye(a)&&/multipart\/form-data/i.test(d)?Fr(t)&&m.warn("Haori",`A File value nested under ${c.prefix}form-object / ${c.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 ${c.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=Xt(i,t));else if(Object.keys(t).length>0){const d=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){n.delete("Content-Type");const y=new FormData;for(const[b,E]of Object.entries(t))E==null?y.append(b,""):E instanceof Blob?y.append(b,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?y.append(b,A):y.append(b,Ne(A))}):y.append(b,Ne(E));s.body=y}else if(/application\/x-www-form-urlencoded/i.test(d)){const y=new URLSearchParams;for(const[b,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>y.append(b,Ne(A))):y.append(b,Ne(E)));s.body=y}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let u;return o&&(u=new URL(i,window.location.href).search||void 0,n.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:s,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:u,transportMode:o?"query-get":"http",signature:Cr(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Xe(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return 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(n=>{const a=n.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(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),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 s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${c.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=g.attrName(this.eventType,e),i=K.read(t,r);if(i!==null&&i.trim()!==""){const n=K.query(i,r,document);if(n===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=D.get(n);return a instanceof R?a.hasAttribute(`${c.prefix}each`)?a:(m.error("Haori",`Row container must have ${c.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const s=this.getRowFragment();return s?s.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${c.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${c.prefix}each expression.`),null;const i=e.getRawAttribute(`${c.prefix}each-array`),s=i!==null,n=s?`${c.prefix}each-array`:`${c.prefix}each`,a=s?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 ${n} (got: ${a}).`+(s?"":` Declare ${c.prefix}each-array to specify the array to write back to.`)),null;if(s&&e.getRawAttribute(`${c.prefix}each-key`)===null)return t||m.error("Haori",`${c.prefix}each-array requires ${c.prefix}each-key (${c.prefix}each-array="${a}").`),null;const u=g.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,y,b;if(u)d=u.owner,y=u.ownerData,b=[...u.path,...o.slice(1)];else{for(d=e,y=null;d;){const A=d.getRawBindingData();if(A&&o[0]in A&&!g.isRowScopeKey(d,o[0])){y=A;break}d=d.getParent()}b=o}if(!d||!y)return t||m.error("Haori",`Binding data owner not found for ${n}="${a}".`),null;const E=g.readPathValue(y,b);return Array.isArray(E)?{owner:d,ownerData:y,array:E,path:b,mapped:s}:(t||m.error("Haori",`${n}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${c.prefix}row`);if(!i)return null;const s=i.getParent();if(!s)return null;if(s.getAttribute(`${c.prefix}each-arg`)===t){const n=g.resolveEachArray(s,!0);if(!n)return m.error("Haori",`Row operations cannot resolve the write-back array for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}": the ancestor container that supplies "${t}" (${c.prefix}each="${s.getRawAttribute(`${c.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${c.prefix}derive and declare ${c.prefix}each-array on this ${c.prefix}each.`),"unresolvable";const a=g.resolveRowIndex(s,i,n.array,`${c.prefix}each="${s.getRawAttribute(`${c.prefix}each`)}"`);return a===null?null:{owner:n.owner,ownerData:n.ownerData,path:[...n.path,String(a)]}}r=s}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${c.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${c.prefix}each-arg`)===t||r.getAttribute(`${c.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 s=i;for(let n=0;n<t.length-1;n+=1){const a=t[n],o=s[a],l=Array.isArray(o)?o.slice():{...o};s[a]=l,s=l}return s[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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 ${c.prefix}each container (${t}).`),{kind:"skip"}):g.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${c.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 s=t.get(i.container);s?s.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,s)=>{const n=g.resolveEachArray(s);if(!n)return;const a=n.array.slice();let o=!1;for(const u of i){const d=g.resolveRowArrayIndex(u,a);if(d===null)continue;const y=a[d];if(y===null||typeof y!="object"||Array.isArray(y)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const b=u.apply(y);if(g.isSameRowItem(y,b)){u.syncWhenUnchanged&&r.push(g.syncUnchangedRowValues(u.row,b,u.syncWhenUnchanged));continue}a[d]=b,o=!0,u.syncWhenUnchanged==="supply"&&x.clearRowUserEditMarksForChangedKeys(u.row,b)}if(!o)return;const l=C.setBindingData(n.owner.getTarget(),g.withPathValue(n.ownerData,n.path,a),{reentrant:this.reentrantBind&&n.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(C.isEachUpdateRunning(s)){l.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(l)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&x.clearRowUserEditMarksForChangedKeys(e,t),x.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 g.resolveRowIndex(e.container,e.row,t,e.attributeName)}static resolveRowIndex(e,t,r,i){const s=g.getRowFragments(e),n=s.indexOf(t);if(n===-1)return m.warn("Haori",`The target row is no longer in the ${c.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${c.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const l=[];r.forEach((y,b)=>{C.createListKey(y,String(a),b)===o&&l.push(b)});const u=s.slice(0,n).filter(y=>y.getListKey()===o).length,d=l[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 n>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):n}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(g.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[s]=e.splice(t,1);return e.splice(i,0,s),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const s=i();if(s===null||t<0||t>=e.length-1)return!1;const[n]=e.splice(t,1);return e.splice(s,0,n),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=g.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const s=this.options.targetFragment,n=s?s.closestByAttribute(`${c.prefix}row`):null,a=g.getRowFragments(r),o=n?a.indexOf(n):a.length-1,l=b=>b<0||b>=a.length?null:i.mapped?g.resolveRowIndex(r,a[b],i.array,g.attrName(this.eventType,e)):b,u=o>=0?l(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>l(o-1),()=>l(o+1)))return Promise.resolve();const y=new Map;return a.forEach(b=>{const E=b.getListKey();E!==null&&!y.has(String(E))&&y.set(String(E),b)}),d.forEach((b,E)=>{if(g.isSameRowItem(i.array[E],b))return;const A=y.get(C.createListKey(b,null,E));A&&C.clearUserEditMarks(A)}),C.setBindingData(i.owner.getTarget(),g.withPathValue(i.ownerData,i.path,d),{kind:"nonSupply",sequence:this.operationSequence})}async injectFetchState(e,t=null,r=null,i=null){const s=this.options.fetchStateFragments;if(!s||s.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r,responseMessage:i};this.options.download&&(n.receivedBytes=this.downloadReceivedBytes,n.totalBytes=this.downloadTotalBytes),await Promise.all(s.map(a=>{const o=a.getTarget(),l={...a.getRawBindingData()??{},_fetch:n};return C.setBindingData(o,l,{reflectToAttribute:!1,kind:"nonSupply",sequence:this.operationSequence})}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet,g.CLICK_OUTCOMES=new WeakMap,g.validationReportGeneration=0,g.VALIDATION_SCROLL_TIMEOUT_MS=1e3,g.VALIDATION_SCROLL_STABLE_FRAMES=2;let ue=g;class Mr{static async load(e,t,r=null){let i;try{i=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!i.ok){zt(i.status,r);const n=`${i.status} ${i.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let s;try{s=await i.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const a=new DOMParser().parseFromString(s,"text/html");return a&&a.body?a.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),s)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),s}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${c.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${c.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=D.get(e);return r instanceof R?r.hasAttribute(`${c.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);h.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>h.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof R?t.push(h.evaluateAll(r)):r instanceof le&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=R.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof R&&h.clearUserEditMarks(r,t)})}static getReactiveFetchState(e){const t=h.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return h.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=h.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return h.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e)||!e.isInitialized())return Promise.resolve();const r=[];return e.hasAttribute(`${c.prefix}validity`)&&x.applyCustomValidity(e),e.hasAttribute(`${c.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${c.prefix}import`)&&r.push(h.executeManagedImport(e)),e.isVisible()?(e.getChildren().forEach(i=>{i instanceof R&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})):Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget();if(!t&&h.initialValueRestores.size>0&&e.hasAttribute(`${c.prefix}fetch-form`))return Promise.all(h.initialValueRestores).then(()=>h.executeManagedFetch(e,!0)).catch(a=>{m.error("Haori",`初期表示の取得に失敗しました: ${a}`)}),Promise.resolve();const i=h.getReactiveFetchState(r),s=ue.resolveAutoFetchSignature(e);if(i.running)return(s.hasUnresolvedReference||s.signature!==i.lastSignature)&&(i.rerunRequested=!0),Promise.resolve();if(s.hasUnresolvedReference||s.signature===null)return i.lastSignature=null,Promise.resolve();if(i.lastSignature===s.signature)return Promise.resolve();i.lastSignature=s.signature,i.running=!0;const n=new ue(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).catch(()=>{}).finally(()=>{if(i.running=!1,i.rerunRequested)return i.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.getAttributeEvaluation(`${c.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${c.prefix}importing`,""),B.importStart(t,s),Mr.load(s,void 0,{element:t,attrPrefix:`${c.prefix}import-`}).then(a=>{const o=new TextEncoder().encode(a).length;return Y.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${c.prefix}importing`),B.importEnd(t,s,o,n),h.adoptImportedChildren(e);const l=[];return e.getChildren().forEach(u=>{u instanceof R?l.push(h.scan(u.getTarget())):u instanceof le&&l.push(h.evaluateText(u))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),B.importError(t,s,a),m.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,h.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=D.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return h.scanElement(e,!0)}static scanElement(e,t){const r=D.get(e);if(!r)return Promise.resolve();const i=h.initializeElementFragment(r,!1).then(()=>x.restoreInitialValues(e));return h.initialValueRestores.add(i),i.then(()=>{h.initialValueRestores.delete(i),t&&se.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return R.retryUnappliedValueWrites(r,t).then(()=>{se.applySubtree(r)})}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e),se.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e)){h.refreshDerivedSubtreeSignature(e);return}const r=t&&e.hasAttribute(`${c.prefix}each`),i=[];return e.getChildren().forEach(s=>{s instanceof R?(!r||h.isEachFixedChild(s))&&i.push(h.initializeElementFragment(s,t)):s instanceof le&&i.push(h.evaluateText(s))}),Promise.all(i).then(()=>{h.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const s=c.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>h.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const s=e.getRawAttribute(i);s!==null&&(t=t.then(()=>(e.markInitialized(),h.setAttribute(e.getTarget(),i,s))))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const s=c.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>(e.markInitialized(),h.setAttribute(e.getTarget(),s,e.getRawAttribute(s)))),r.add(s))}return t.then(()=>(e.markInitialized(),x.prepareFormName(e)))}static shouldSkipChildInitialization(e){const t=e.getAttribute(`${c.prefix}if`);return e.hasAttribute(`${c.prefix}if`)&&h.isHiddenIfCondition(t)}static setAttribute(e,t,r,i=!1,s){const n=D.get(e),a=h.getAliasedAttributeName(t);if(a!==null)return r===null?n.removeAliasedAttribute(t,a):n.setAliasedAttribute(t,a,r,i);const o=[];let l=null,u=null,d=null;switch(t){case`${c.prefix}bind`:{if(r!==null&&i&&n instanceof R&&n.consumeSelfWrittenBind(r))break;const y=r===null?{}:h.parseDataBind(r);if(i){const b=s??R.nextSequence();return r===null?(o.push(h.setBindingData(e,y,{reflectToAttribute:!1,sequence:b})),o.push(n.removeAttribute(t))):o.push(h.setBindingData(e,y,{sequence:b})),Promise.all(o).then(()=>{})}r===null&&n.clearBindingDataCache(),n.setBindingData(y);break}case`${c.prefix}derive`:u=h.createDeriveInputSignature(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),l=h.evaluateDerive(n,r,n.getRawAttribute(`${c.prefix}derive-name`)),o.push(l.then(()=>{}));break;case`${c.prefix}derive-name`:u=h.createDeriveInputSignature(n,n.getRawAttribute(`${c.prefix}derive`),r),l=h.evaluateDerive(n,n.getRawAttribute(`${c.prefix}derive`),r),o.push(l.then(()=>{}));break;case`${c.prefix}if`:d=()=>h.evaluateIfOnAttributeWrite(n);break;case`${c.prefix}each`:d=()=>h.evaluateEach(n);break;case`${c.prefix}fetch`:d=()=>h.executeManagedFetch(n);break;case`${c.prefix}import`:typeof r=="string"&&(d=()=>h.executeManagedImport(n));break;case`${c.prefix}store`:r!==null&&o.push(Pe.restore(n));break;case`${c.prefix}validity`:case`${c.prefix}validity-message`:return r!==null&&x.applyCustomValidity(n),Promise.all(o).then(()=>{});case`${c.prefix}url-param`:{const y=n.getAttribute(`${c.prefix}url-arg`),b=$e.readParams();y===null&&n.hasAttribute(`${c.prefix}store`)&&m.warn("Haori",`${c.prefix}url-param を ${c.prefix}url-arg なしで ${c.prefix}store と併用すると復元した値が消えます(${c.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:R.nextSequence()};if(y===null)o.push(h.setBindingData(e,b,E));else{const A=n.getRawBindingData()||{};A[String(y)]=b,o.push(h.setBindingData(e,A,E))}break}}return r===null?o.push(n.removeAttribute(t)):o.push(n.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(l!==null)return n.setDeriveInputSignature(u),l.then(y=>{if(y)return h.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=D.get(e),s=r.skipFragments??new Set,n=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",l=r.sequence??R.nextOperationSequence(),u={sequence:l,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(l);const y=R.currentSequence(),b=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&h.clearUserEditMarks(i,l);const E=a?h.resolveByPathAuthority(i,b,t,u):t;i.setBindingData(E),a&&(B.bindChange(e,b,E,"manual"),Pe.mirror(i));const A=()=>{i.markBindingWorkStart();const k=i.getRawBindingData()??E;let M=a?i.setAttribute(`${c.prefix}bind`,JSON.stringify(h.withoutReservedBindingKeys(k))):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(y))return;const P=i.getRawBindingData()??E;return x.syncValues(i,x.resolveSyncValues(i,P),!1,u)})),M=M.then(()=>x.syncAncestorArgForms(i,y,u,b)),M=M.then(()=>h.evaluateAll(i,s)),M=M.then(()=>R.retryUnappliedValueWrites(e,y)),M=M.then(()=>h.reevaluateReactiveSpecialAttributes(i,s)),M.then(()=>i.markBindingWorkEnd(),P=>{throw i.markBindingWorkEnd(),P})};return n?A():i.enqueueBindingWork(A)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))R.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const s=h.mergePathAuthority(e,t??{},r,i,"",new Map);return s===h.ABSENT_PATH?r:s}static mergePathAuthority(e,t,r,i,s,n){if(h.isPlainRecord(t)&&h.isPlainRecord(r)){const d=t,y=r,b={};let E=Object.keys(d).some(k=>!Object.prototype.hasOwnProperty.call(y,k));const A=new Set([...Object.keys(d),...Object.keys(y)]);for(const k of A){const M=s===""?k:`${s}.${k}`,P=h.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(d,k)?d[k]:h.ABSENT_PATH,Object.prototype.hasOwnProperty.call(y,k)?y[k]:h.ABSENT_PATH,i,M,n);P!==h.ABSENT_PATH&&(b[k]=P),P!==(Object.prototype.hasOwnProperty.call(y,k)?y[k]:h.ABSENT_PATH)&&(E=!0)}return E?b:y}const a=h.resolveArrayPairing(e,t,r,s,n);if(a!==null){const d=t,y=r,b=y.map((E,A)=>h.mergePathAuthority(e,d[A],E,i,`${s}[${a[A]}]`,n));return b.some((E,A)=>E!==y[A])?b:y}if(h.isSameBindingValue(t,r))return r;const o=i.editedPaths?.get(s),l=o===void 0?i.kind:"edit",u={sequence:o??i.sequence,kind:l};return e.canApplyPath(s,u)?(e.markPathApplied(s,u),r):t}static resolveArrayPairing(e,t,r,i,s){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(l=>h.isPlainRecord(l))?h.resolveEachKeyArg(e,i,s):null,a=t.map((l,u)=>h.createListKey(l,n,u)),o=r.map((l,u)=>h.createListKey(l,n,u));return a.some((l,u)=>l!==o[u])?null:o}static resolveEachKeyArg(e,t,r){const i=t.replace(/\[[^\]]*\]/g,""),s=r.get(i);if(s!==void 0)return s;const n=h.findEachKeyArg(e.getTarget(),i);return r.set(i,n),n}static findEachKeyArg(e,t){const r=`${c.prefix}each`,i=e.querySelectorAll(`[${r}]`);for(const s of Array.from(i)){const n=h.resolveEachDeclarationPath(s,e);if(n===null||n!==t)continue;const a=s.getAttribute(`${r}-key`);return a===null?null:a.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${c.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let s=e.parentElement;for(;s!==null&&s!==t;){const n=s.getAttribute(r)?.trim();if(n!=null){if(n==="")return null;const a=s.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?n:`${n}.${i.slice(a.length+1)}`}else i=`${n}.${i}`}s=s.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===h.ABSENT_PATH||t===h.ABSENT_PATH)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}static getBindingData(e,t={}){const r=D.get(e);return r instanceof R?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=h.collectScope(e);return U.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=D.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},s=l=>{const u=l.getTarget(),d=h.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},n=(l,u,d,y)=>{if(l)for(const b of Object.keys(l))b in i||(i[b]={value:l[b],source:s(u),kind:d,depth:y})};let a=t,o=0;for(;a;)a!==t&&n(a.getRawDerivedBindingData(),a,"derive",o),n(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,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=D.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=D.get(t.nextSibling),s=D.get(t);if(s){if(s.getParent()===r)return Promise.resolve();if(r.attachObserved(s,i),s instanceof R)return h.scan(s.getTarget());if(s instanceof le)return h.evaluateText(s)}return Promise.resolve()}static removeNode(e){const t=D.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;if(t instanceof R){t.detachObserved();return}t.remove()}}static changeText(e,t){const r=D.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=D.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=h.getFormFragment(r);if(s){const n=x.getValues(s),a=s.getAttribute(`${c.prefix}form-arg`),o=s.getRawBindingData();let l;if(a){l={...o??{}};const u=String(a),d=x.resolveAncestorArgOwner(s,u);l[u]=x.mergeCollectedValues((d?d.value:l[u])??null,n)}else l=x.mergeCollectedValues(o,n,x.ancestorBaseResolver(s));i.push(h.setBindingData(s.getTarget(),l,{kind:"nonSupply",sequence:R.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?h.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=h.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${c.prefix}derive`),s=e.hasAttribute(`${c.prefix}if`),n=e.hasAttribute(`${c.prefix}each`),a=e.getRawAttribute(`${c.prefix}derive`),o=e.getRawAttribute(`${c.prefix}derive-name`);let l=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const E=h.createDeriveInputSignature(e,a,o);E===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==E&&(r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(E)})))}let y=!1,b=0;return s&&(r=r.then(()=>{const E=e.isVisible();return b=R.currentSequence(),h.evaluateIf(e,t).then(()=>{y=!E&&e.isVisible()})})),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEachFixedChildren(e)).then(()=>h.evaluateEach(e)).then(()=>{if(y)return h.applyEnhancersOnShow(e,b)})):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=h.createDescendantBindingSignature(e,"evaluateAll"),u=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,h.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const E=[];return e.getChildren().forEach(A=>{if(A instanceof R){if(h.canSkipUnchangedNestedEach(A))return;E.push(h.evaluateAll(A,t))}else A instanceof le&&!t.has(A)&&E.push(h.evaluateText(A))}),Promise.all(E).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${c.prefix}derive`),r=e.getRawAttribute(`${c.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=ne.evaluateDetailed(t,e.getBindingData());if(n.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[s]:n.value};return h.createBindingSignature(i)===h.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${c.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(ne.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}=h.collectScope(e.getTarget()),i=new Set,s=t.match(/[A-Za-z_$][\w$]*/g)??[];let n=0;s.forEach(o=>{const l=t.indexOf(o,n);n=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${c.prefix}each-before`)||e.hasAttribute(`${c.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof R&&h.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof R?h.isEachFixedChild(r)&&t.push(h.evaluateAll(r)):r instanceof le&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIfOnAttributeWrite(e){if(!e.hasAttribute(`${c.prefix}each`))return h.evaluateIf(e);const t=e.isVisible(),r=R.currentSequence();return h.evaluateIf(e).then(()=>{if(!t)return h.evaluateEach(e).then(()=>h.reevaluateReactiveSpecialAttributes(e)).then(()=>h.applyEnhancersOnShow(e,r))})}static evaluateIf(e,t=new Set){const r=[],i=e.getAttribute(`${c.prefix}if`);if(h.isHiddenIfCondition(i))U.isEnabled()&&e.isVisible()&&h.logFalsyIfDiagnostics(e),r.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const s=e.isVisible(),n=R.currentSequence(),a=[],o=e.hasAttribute(`${c.prefix}each`);e.getChildren().forEach(l=>{if(l instanceof R){if(o&&!h.isEachFixedChild(l))return;l.isMounted()?s?a.push(h.evaluateAll(l,t)):a.push(h.evaluateAll(l).then(()=>h.reevaluateReactiveSpecialAttributes(l))):a.push(h.scanElement(l.getTarget(),!1))}else l instanceof le&&!(s&&t.has(l))&&a.push(h.evaluateText(l))}),r.push(e.show().then(()=>{B.show(e.getTarget()),s||(h.triggerLoadOnShow(e),se.refreshSubtree(e.getTarget(),!1))})),r.push(Promise.all(a).then(()=>{if(!(s||o))return h.applyEnhancersOnShow(e,n)}))}return Promise.all(r).then(()=>{})}static triggerLoadOnShow(e){const t=`${c.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new ue(e,"load").run().catch(i=>{m.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=h.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},h.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(U.isEnabled()&&ne.recordRowScopeIdentifiers([h.getRowScopeName(e,"each-arg"),h.getRowScopeName(e,"each-index")]),e.isMounted()||h.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${c.prefix}each-done`),Promise.resolve();const t=h.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):h.runEachUpdateLoop(e,t)}static getRowScopeName(e,t){const r=e.getAttribute(`${c.prefix}${t}`);return typeof r!="string"||r===""?null:r}static isEachUpdateRunning(e){return h.getEachUpdateState(e).running}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${c.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${c.prefix}each-done`,""),se.refreshSubtree(i,!1),h.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}h.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${c.prefix}each-rendered-run`,r=D.get(e);if(r===null||!ae.declared(r,t))return;if(ae.applies(r,t)){const n=ae.compile(r,t,[]);try{n?.([])}catch(a){m.error("[Haori]",`each-rendered-run execution error: ${a}`)}return}const i=String(e.getAttribute(t)??"");let s=null;try{s=new Function(`"use strict"; return (
36
+ ${i}
37
+ );`)}catch{try{s=new Function(`"use strict";
38
+ ${i}
39
+ `)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(s)try{s.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${c.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let s=!1;if(i==="always"?s=!0:i!==""&&i!=="once"&&(h.EACH_RENDERED_CHANGE_WARNED.has(r)||(h.EACH_RENDERED_CHANGE_WARNED.add(r),m.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),h.countEachRenderedRows(e)!==0){if(!s){if(h.EACH_RENDERED_CHANGE_FIRED.has(r))return;h.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(n){m.error("[Haori]",`each-rendered-change dispatch error: ${n}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${c.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=h.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${c.prefix}each-key`),s=h.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof R){if(a.hasAttribute(`${c.prefix}each-before`)||a.hasAttribute(`${c.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),n&&h.warnExtraEachChildren(e),!n){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${c.prefix}each-before`)&&!l.hasAttribute(`${c.prefix}each-after`)).forEach(l=>{if(!n){const d=D.get(l);d instanceof R&&(r=d.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const u=D.get(l);u instanceof R&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?h.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}static reevaluateEachRows(e){if(h.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>h.evaluateAll(r,h.collectRowLocalFragments(e,r)))).then(()=>{})}static collectRowLocalFragments(e,t){const r=new Set,i=h.getEachScopeNames(e);if(i===null)return r;const s=n=>{if(h.keepsRowScopeNames(n))for(const a of n.getChildren())a instanceof le?h.areExpressionsRowLocal(h.extractInterpolations(a.getRawText()),i)&&r.add(a):a instanceof R&&(h.isRowLocalSubtree(a,i)?r.add(a):s(a))};return s(t),r}static keepsRowScopeNames(e){return e.getAttributeNames().every(t=>!t.startsWith(c.prefix)||t===`${c.prefix}if`||t===`${c.prefix}row`)}static getEachScopeNames(e){const t=e.getAttribute(`${c.prefix}each-arg`);if(!t)return null;const r=new Set([String(t)]),i=e.getAttribute(`${c.prefix}each-index`);return i&&r.add(String(i)),r}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${c.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${c.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${c.prefix}derive`)||t?.closestByAttribute(`${c.prefix}derive-name`)||t?.closestByAttribute(`${c.prefix}if`)||t?.closestByAttribute(`${c.prefix}fetch`)||t?.closestByAttribute(`${c.prefix}import`)||h.hasNonEachDynamicElementState(e)||!h.isRowLocalEachTemplate(e)||h.hasEachFixedChildren(e))return!1;const r=h.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${c.prefix}each-key`),s=h.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=h.getEachScopeNames(e);if(r===null||i===null)return e.setRowLocalTemplate(!1),!1;const s=h.isRowLocalSubtree(r,i);return e.setRowLocalTemplate(s),s}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const s=e.getRawAttribute(i),n=typeof s=="string"?s:"";if(n.includes("{{")){if(!h.areExpressionsRowLocal(h.extractInterpolations(n),t))return!1;continue}if(!i.startsWith(c.prefix))continue;const a=i.slice(c.prefix.length);if(h.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!h.areExpressionsRowLocal([n],t))return!1;continue}if(h.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))continue;const o=a.indexOf("-");if(!(o!==-1&&h.ROW_LOCAL_ROW_OPERATIONS.has(a.slice(o+1))))return!1}let r=t;if(e.hasAttribute(`${c.prefix}each`)){const i=e.getRawAttribute(`${c.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const s=new Set(t);s.add(i);const n=e.getRawAttribute(`${c.prefix}each-index`);typeof n=="string"&&n!==""&&s.add(n),r=s}for(const i of e.getChildren())if(i instanceof R){if(!h.isRowLocalSubtree(i,r))return!1}else if(i instanceof le){const s=i.getRawText();if(s.includes("{{")&&!h.areExpressionsRowLocal(h.extractInterpolations(s),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const s=ne.getFreeIdentifiers(i);if(s.length===0||s.some(n=>!t.has(n)))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(`${c.prefix}derive`)||e.hasAttribute(`${c.prefix}if`)||e.hasAttribute(`${c.prefix}each`)||e.hasAttribute(`${c.prefix}fetch`)||e.hasAttribute(`${c.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof R?t.hasAttribute(`${c.prefix}derive`)||t.hasAttribute(`${c.prefix}derive-name`)||t.hasAttribute(`${c.prefix}fetch`)||t.hasAttribute(`${c.prefix}import`)?!0:h.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return h.recordDerivedSubtreeSignatureComputation(e,t),h.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:h.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshUrlParams(){const e=`${c.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const s=D.peek(i);return s instanceof R?h.setAttribute(i,e,s.getRawAttribute(e)??""):Promise.resolve()});return Promise.all(r).then(()=>{}).catch(i=>{m.error("Haori",`${e} を読み直せませんでした: ${i}`)})}static invalidateDerivedSubtreeSignatures(e){for(let r=e.getParent();r!==null;r=r.getParent())r.setDeriveSubtreeSignature(null);const t=r=>{r.setDeriveSubtreeSignature(null),r.getChildren().forEach(i=>{i instanceof R&&t(i)})};t(e)}static refreshDerivedSubtreeSignature(e){if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(h.createDescendantBindingSignature(e,"refresh")),h.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!U.isEnabled()||!e.hasAttribute(`${c.prefix}derive`))return null;const t=h.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:h.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return h.DERIVE_SUBTREE_PROFILES.set(e,r),r}static 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 s=i.tagName.toLowerCase();const n=h.resolveElementId(i).trim();if(n!==""){s+=`#${n}`,t.unshift(s);break}const a=r.getRawAttribute(`${c.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(s+=`[${c.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const l=o.getChildren().filter(u=>u instanceof R).findIndex(u=>u===r);s+=`:nth-child(${l+1})`}t.unshift(s),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=h.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${c.prefix}each`,`${c.prefix}each-key`,`${c.prefix}each-arg`,`${c.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${c.prefix}attr-`)||i.startsWith(c.prefix))return!0;const s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof le&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>h.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof R?!h.markFreshInitializationSkippable(s):s instanceof le?s.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${c.prefix}attr-`)||t.startsWith(c.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${c.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${c.prefix}each-key`),n=e.getAttribute(`${c.prefix}each-arg`),a=t.map((F,Q)=>h.createListKey(F,s?String(s):null,Q)),o=new Set(a),l=new Map;a.forEach(F=>{l.set(F,(l.get(F)??0)+1)}),s&&o.size!==a.length&&h.warnDuplicateEachKey(String(s));const u=[];let d=e.getChildren().filter(F=>F instanceof R).filter(F=>!F.hasAttribute(`${c.prefix}each-before`)&&!F.hasAttribute(`${c.prefix}each-after`));const y=d.map(F=>F.getListKey()),b=new Set;d=d.filter((F,Q)=>{const te=String(F.getListKey()),_=l.get(te)??0;if(_===0){b.add(F);const z=F.getListKey();return z!==null&&B.rowRemove(F.getTarget(),z,Q),u.push(F.remove()),!1}return l.set(te,_-1),!0});const E=d.map(F=>F.getListKey()),A=new Map;d.forEach(F=>{const Q=F.getListKey();if(Q===null)return;const te=A.get(Q);te?te.push(F):A.set(Q,[F])});const k=e.getChildElementFragments().filter(F=>!b.has(F)),M=k.filter(F=>F.hasAttribute(`${c.prefix}each-before`)).length;let P=Promise.resolve();const ie=[];return a.forEach((F,Q)=>{const te=t[Q],_=Q;let z;const ce=A.get(F)?.shift();if(ce){z=ce;const w=M+Q;P=P.then(()=>h.updateRowFragment(z,te,i,_,n?String(n):null,F).then(O=>h.repositionEachRow(e,z,k,w).then(j=>{j!==null&&B.rowMove(z.getTarget(),F,j-M,Q),!(!O&&h.isRowLocalEachTemplate(e))&&ie.push(h.evaluateAll(z,O?new Set:h.collectRowLocalFragments(e,z)).then(()=>h.applyRowFormValues(e,z,te)))})))}else{z=r.clone();const w=M+Q;P=P.then(()=>h.updateRowFragment(z,te,i,_,n?String(n):null,F).then(()=>{const O=k[w]??null;return e.insertBefore(z,O).then(()=>{k.splice(w,0,z)}).then(()=>h.initializeFreshEachRow(z)).then(()=>h.applyRowFormValues(e,z,te)).then(()=>{B.rowAdd(z.getTarget(),F,_,te)})}))}}),Promise.all(u).then(()=>P).then(()=>Promise.all(ie)).then(()=>{const F=a.filter(w=>w!==null),Q=E.filter(w=>w!==null),te=new Set(Q),_=F.filter(w=>!te.has(w)),ce=y.filter(w=>w!==null).filter(w=>!o.has(w));B.eachUpdate(e.getTarget(),_,ce,F)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof R).filter(r=>!r.hasAttribute(`${c.prefix}each-before`)&&!r.hasAttribute(`${c.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${c.prefix}each="${e.getRawAttribute(`${c.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!U.isEnabled()||h.WARNED_DUPLICATE_EACH_KEYS.has(e)||(h.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${c.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const s=r.indexOf(t);if(s===-1||s===i)return Promise.resolve(null);r.splice(s,1);const n=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,n).then(()=>s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${c.prefix}form-list`)||!x.isCollectedListFromEachSource(e)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():x.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a;if(typeof t=="object"&&t!==null)a=s?{[s]:{...t}}:{...t};else if(s)a={[s]:t};else return m.error("[Haori]",`Primitive value requires '${c.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,l=h.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${c.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${c.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(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(s=>h.createBindingSignature(s,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 s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${h.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{h.evaluateAll(e)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.initialValueRestores=new Set,h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param","store","validity","validity-message"],h.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,h.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),h.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"]),h.ROW_LOCAL_ROW_OPERATIONS=new Set(["row-add","row-remove","row-prev","row-next"]),h.REACTIVE_FETCH_STATES=new WeakMap,h.REACTIVE_IMPORT_STATES=new WeakMap,h.DERIVE_SUBTREE_PROFILES=new WeakMap,h.EACH_UPDATE_STATES=new WeakMap,h.EACH_RENDERED_CHANGE_FIRED=new WeakSet,h.EACH_RENDERED_CHANGE_WARNED=new WeakSet,h.WARNED_DUPLICATE_EACH_KEYS=new Set,h.ABSENT_PATH=Symbol("absent");let C=h;const Ce=class Ce{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onReset=t=>{if(t.defaultPrevented||x.isResettingInternally())return;const r=t.target;r instanceof HTMLElement&&setTimeout(()=>se.refreshSubtree(r),0)},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;if(!r||r[Ce.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=D.get(e);t&&new ue(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("reset",this.onReset),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("reset",this.onReset),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`${c.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(Ce.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 s=D.get(i);s instanceof R&&this.isFromTarget(s,t)&&new ue(s,"on",t).run().catch(n=>{m.error("[Haori]","Procedure execution error:",n)})})}isFromTarget(e,t){const r=`${this.onAttributeName}-target`;if(!e.hasAttribute(r))return!0;const i=K.read(e,r),s=t.target;return i===null||!(s instanceof Node)?!1:K.queryAll(i,r).some(n=>n.contains(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(s=>{s instanceof HTMLElement&&(s.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(s.getAttribute(this.onAttributeName)),s.querySelectorAll(`[${this.onAttributeName}]`).forEach(n=>this.subscribeCustomEvent(n.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=`${c.prefix}input-`;if(!r.getAttributeNames().some(n=>n.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${c.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=D.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const s=()=>{const n=new ue(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){ue.recordClickOutcome(e,n);const a=r.target;a instanceof HTMLElement&&a!==e&&ue.recordClickOutcome(a,n)}};if(t==="click"&&e.hasAttribute(`${c.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}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=D.get(e);t instanceof R&&t.markUserEdit()}syncUserEdit(e,t){const r=D.get(e);if(r instanceof R&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const i=document.getElementsByName(e.name);for(const s of Array.from(i)){if(s===e||!(s instanceof HTMLInputElement)||s.type!=="radio"||s.form!==e.form)continue;const n=D.get(s);n instanceof R&&(n.syncValue(),n.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=`${c.prefix}click-`,r=`${c.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(n=>n.startsWith(t)&&n!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Ce.HISTORY_STATE_KEY="__haoriHistoryState__",Ce.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let nt=Ce;const q=class q{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)&&(q.isHtmlElement(e)&&q.syncElement(e),e.querySelectorAll("*").forEach(t=>{q.syncElement(t)}))}static syncElement(e){const t=q.registrations.get(e),r=D.get(e);if(!r||!q.shouldObserve(r)){t&&(t.observer.disconnect(),q.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=q.resolveRoot(r),s=q.resolveRootMargin(r),n=q.resolveThreshold(r),a=r.hasAttribute(`${c.prefix}intersect-once`);if(t&&t.root===i&&t.rootMargin===s&&t.threshold===n&&t.once===a){t.fragment=r,q.runPendingIntersect(e,t);return}t&&(t.observer.disconnect(),q.registrations.delete(e));const o=new IntersectionObserver(l=>{const u=q.registrations.get(e);u&&l.forEach(d=>{if(u.intersecting=d.isIntersecting,!!d.isIntersecting){if(u.running||q.isDisabled(u.fragment)){u.pending=!0;return}q.runProcedure(e,u)}})},{root:i,rootMargin:s,threshold:n});o.observe(e),q.registrations.set(e,{fragment:r,observer:o,once:a,running:t?.running??!1,intersecting:!1,pending:!1,root:i,rootMargin:s,threshold:n})}static runProcedure(e,t){t.pending=!1,t.running=!0;let r=!1;new ue(t.fragment,"intersect").runWithResult().then(i=>{r=i}).catch(i=>{m.error("[Haori]","Intersect procedure execution error:",i)}).finally(()=>{const i=q.registrations.get(e);if(i){if(i.running=!1,r&&i.once){i.observer.disconnect(),q.registrations.delete(e);return}q.runPendingIntersect(e,i)}})}static runPendingIntersect(e,t){!t.pending||!t.intersecting||t.running||q.isDisabled(t.fragment)||q.runProcedure(e,t)}static cleanupTree(e){if(q.isHtmlElement(e)){const t=q.registrations.get(e);t&&(t.observer.disconnect(),q.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=q.registrations.get(t);r&&(r.observer.disconnect(),q.registrations.delete(t))})}static disconnectAll(){q.registrations.forEach(e=>{e.observer.disconnect()}),q.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${c.prefix}intersect-`))return!1;const r=t.slice(`${c.prefix}intersect-`.length);return!q.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${c.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=K.query(r,t,document);return q.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${c.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${c.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${c.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}};q.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),q.registrations=new Map;let Ie=q;const S=class S{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(S.isHtmlElement(e)&&S.syncElement(e),e.querySelectorAll("*").forEach(t=>{S.syncElement(t)}))}static syncElement(e){const t=S.registrations.get(e);if(!t&&!S.hasPollAttribute(e))return;const r=D.get(e);if(!(r instanceof R)||!S.shouldObserve(r)){t&&S.teardown(e,t);return}const i=S.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}S.teardown(e,t)}S.startPolling(e,r,i)}static cleanupTree(e){if(S.isHtmlElement(e)){const t=S.registrations.get(e);t&&S.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=S.registrations.get(t);r&&S.teardown(t,r)})}static disconnectAll(){S.registrations.forEach(e=>{S.clearTimers(e)}),S.registrations.clear(),S.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",S.visibilityListener),S.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=`${c.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=`${c.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!S.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${c.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
40
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:S.resolveInterval(t),timeoutMs:S.resolveTimeout(t),errorLimit:S.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};S.registrations.set(e,i),S.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{S.handleTimeout(e)},i.timeoutMs)),S.injectState(i),S.tick(e)}static async tick(e){const t=S.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await S.stop(e,t,"detached");return}const r=S.isHidden(e)||S.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await S.injectState(t)),r){S.schedule(e,t);return}if(S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ue(t.fragment,"poll").runWithResult()}catch(s){m.error("[Haori]","Poll procedure execution error:",s)}finally{t.fetching=!1}if(!(S.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await S.stop(e,t,"error");return}if(i&&S.isUntilSatisfied(t.fragment)){await S.stop(e,t,"until");return}S.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{S.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=S.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,S.elapsed(t)),await S.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,S.clearTimers(t),r==="detached"){S.registrations.delete(e);return}await S.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,S.elapsed(t))}}static teardown(e,t){S.clearTimers(t),S.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(S.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(S.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),S.tick(t))})};S.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=S.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:S.elapsed(e)};return Promise.all(t.map(i=>{const s=i.getTarget(),n={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(s,n,{reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${c.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 s=K.queryAll(i,t,document);if(s.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const n=[];return s.forEach(a=>{if(!a.isConnected)return;const o=D.get(a);o instanceof R&&n.push(o)}),n}static resolveInterval(e){const t=`${c.prefix}poll-interval`;if(!e.hasAttribute(t))return S.DEFAULT_INTERVAL_MS;const r=S.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${S.DEFAULT_INTERVAL_MS}ms を使用します。`),S.DEFAULT_INTERVAL_MS):r<S.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${S.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),S.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${c.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=S.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${c.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=S.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(`[${c.prefix}if-false]`)!==null}static isDisabled(e){const t=`${c.prefix}poll-disabled`;return e.hasAttribute(t)?S.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${c.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):S.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}};S.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),S.DEFAULT_INTERVAL_MS=5e3,S.MIN_INTERVAL_MS=100,S.registrations=new Map,S.visibilityListener=null;let Fe=S;const Qt="0.64.0";function $r(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}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=D.get(e);if(!(r instanceof R)||!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 s=L.resolveRoot(r),n=L.resolveRootMargin(r);if(t&&t.observer.root===s&&t.observer.rootMargin===n&&t.varName===i){t.fragment=r,L.refreshRows(t);return}t&&(t.observer.disconnect(),L.registrations.delete(e));const a=new IntersectionObserver(l=>{const u=L.registrations.get(e);if(!u)return;let d=!1;l.forEach(y=>{const b=y.target;u.observedRows.has(b)&&(y.isIntersecting?u.visibleRows.has(b)||(u.visibleRows.add(b),d=!0):u.visibleRows.delete(b)&&(d=!0))}),d&&L.scheduleCompute(u)},{root:s,rootMargin:n,threshold:L.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:s,rootMargin:n,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(`${c.prefix}each`)&&e.hasAttribute(`${c.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${c.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${c.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=K.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=`${c.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 R&&!t.hasAttribute(`${c.prefix}each-before`)&&!t.hasAttribute(`${c.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,$r(()=>{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 s;if(i.length===0)s={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);s={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const n=JSON.stringify(s);n!==e.lastSnapshot&&(e.lastSnapshot=n,L.publish(e,s))}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(),s={...r.getRawBindingData()??{}};s[e.varName]={...t};const n=e.fragment.getTarget(),a=i===n?new Set:new Set([e.fragment]);C.setBindingData(i,s,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:R.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${c.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};L.THRESHOLD=0,L.DEFAULT_ROOT_MARGIN="0px",L.registrations=new Map;let ve=L;const H=class H{static disconnectMutationObservers(){H._mutationObservers.forEach(e=>{e.disconnect()}),H._mutationObservers.length=0}static async init(){if(H._initialized)return;H._initialized=!0,H.disconnectMutationObservers(),R.setPendingMutationFlusher(()=>{H.flushPendingMutations()});const e=new nt;H._dispatcher=e,e.startDeferred(),H._initialIntakes=[];try{const t=await Promise.allSettled([C.scan(document.head),C.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 H.waitInitialIntakes(),await Y.wait(),document.body.setAttribute("data-haori-ready",""),H.observe(document.head),H.observe(document.body),Ie.syncTree(document.body),Fe.syncTree(document.body),ve.syncTree(document.body)}finally{H._initialIntakes=null,e.release()}B.ready(Qt)}static getDispatcher(){return H._dispatcher}static async waitInitialIntakes(){const e=H._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(H._mutationObservers.length>0){e();return}const t=new MutationObserver(()=>{});t.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});try{e()}finally{const r=t.takeRecords().map(i=>H.toCapturedRecord(i));t.disconnect(),H.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!H.hasKnownDescendant(t)),removedNodes:[]}}static hasKnownDescendant(e){return e instanceof Element&&Array.from(e.querySelectorAll("*")).some(t=>R.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=R.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${c.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${c.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(r=>{H.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),H._mutationObservers.push(t)}static flushPendingMutations(){for(const e of H._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(H.isBindAttributeRecord),i=t.filter(s=>!H.isBindAttributeRecord(s));r.length>0&&H.processMutations(r,R.nextSequence()),i.length>0&&Promise.resolve().then(()=>{H.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${c.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(H.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(ye)&&(r.attributeName==="disabled"||r.attributeName===ye))break;if(r.attributeName&&(r.attributeName===`${c.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${c.prefix}if-false`))){r.attributeName==="style"&&R.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const s=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);H._initialIntakes?.push(s),Ie.syncElement(i),Fe.syncElement(i),ve.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{H.isStaleExternalRemoval(r,i)||(Ie.cleanupTree(i),Fe.cleanupTree(i),ve.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);H._initialIntakes?.push(s),Ie.syncTree(i),Fe.syncTree(i),ve.syncTree(i)}),r.target instanceof Element&&ve.syncElement(r.target);break}case"characterData":{r.target instanceof Text||r.target instanceof Comment?C.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)}}};H._initialized=!1,H._mutationObservers=[],H._dispatcher=null,H._initialIntakes=null;let Be=H;se.setMutationCapture(f=>Be.captureMutations(f)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Be.init):Be.init();const Pr=()=>he.waitForRenders(),Lr=he.enhancers,Or=he.handlers,Br=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:se,Env:c,Form:x,Fragment:D,Haori:he,Log:m,Queue:Y,default:he,enhancers:Lr,handlers:Or,version:Qt,waitForRenders:Pr},Symbol.toStringTag,{value:"Module"})),at=he;for(const[f,e]of Object.entries(Br))f in at||Object.defineProperty(at,f,{value:e,writable:!0,enumerable:!0,configurable:!0});return at}();
36
41
  //# sourceMappingURL=haori.iife.js.map