haori 0.66.0 → 0.67.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,23 +1,23 @@
1
1
  var Haori=function(){"use strict";const Re=class Re{static isEnabled(){return Re.devMode}static enable(){Re.devMode=!0}static disable(){Re.devMode=!1}static set(e){Re.devMode=e}};Re.devMode=!1;let B=Re;const _e="embedded";function dt(f){return f==="embedded"||f==="demo"}function tr(f){return f===null?null:dt(f)?f:_e}function ht(f){const e=f.trim().toLowerCase();return e!=="false"&&e!=="off"&&e!=="0"}const te=class te{static get csp(){return te._csp}static setCsp(e){te._csp=e}static get strictBind(){return te._strictBind}static setStrictBind(e){te._strictBind=e}static get runtime(){return te._runtime}static setRuntime(e){te._runtime=dt(e)?e:_e}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||te._prefix;te._prefix=r.endsWith("-")?r:r+"-";const i=tr(e.getAttribute("data-runtime"));i!==null&&(te._runtime=i),te._strictBind=e.hasAttribute(`${te._prefix}strict-bind`);const s=e.getAttribute(`${te._prefix}csp`);s!==null&&(te._csp=ht(s))}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${te._prefix}dev`)){B.set(ht(e.getAttribute(`${te._prefix}dev`)??""));return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){B.set(!0);return}B.set(!1)}catch{}}static get prefix(){return te._prefix}};te._prefix="data-",te._runtime=_e,te._strictBind=!1,te._csp=!0;let c=te;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c.detect):c.detect());class m{static info(e,...t){B.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){B.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const rr=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,ft="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=`${ft}${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(ft))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(!rr.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"?(B.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){!B.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 pt="yyyy/MM/dd HH:mm",ir="en-US",gt=1e4;function me(f){return String(f).padStart(2,"0")}function mt(f,e,t,r,i,s){return{yyyy:String(f).padStart(4,"0"),yy:me(f%100),MM:me(e),M:String(e),dd:me(t),d:String(t),HH:me(r),H:String(r),mm:me(i),ss:me(s)}}function yt(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:mt(i,s,n,a,o,l)}function Ve(f,e=pt,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=yt(r,t.trim()),i===null)return""}else i=mt(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 sr="yyyy-MM-dd";function bt(f=pt,e){return Ve(new Date,f,e)}function Et(f=0,e=sr,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=yt(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 Ve(o,e,"UTC")}function At(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(ir,r).format(t)}function vt(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<gt;a+=s)n.push(a);else for(let a=r;a>i&&n.length<gt;a+=s)n.push(a);return n}function wt(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 nr=/^(\d{4})-(\d{1,2})$/,ar=1200;function qe(f,e){const t=Number(f);return Number.isFinite(t)?Math.trunc(t):e}function We(f,e){if(typeof f!="string")return"";const t=nr.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")}-${me(o)}`}function or(f){if(typeof f=="string"&&f.trim()!=="")return We(f,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${me(e.getMonth()+1)}`}function St(f,e){const t=Math.trunc(Number(f));if(!Number.isFinite(t)||t<0)return[];const r=or(e);if(r==="")return[];const i=Math.min(t,ar),s=[];for(let n=0;n<=i;n+=1){const a=We(r,-n);s.push({targetMonth:a,label:a.replace(/-/g,"/")})}return s}function Rt(f,e){const t={start:0,end:0,total:0,empty:!0};if(!f||typeof f!="object")return t;const r=f,i=qe(r.totalElements??r.totalCount,0);if(i<=0)return t;const s=Math.max(0,qe(r.number,0)),n=Math.max(0,qe(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=qe(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 Tt(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 kt(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 Dt(f,e){return e==null||f==null?String(f):String(f[e])}function xt(f,e){if(!Array.isArray(f))return[];const t=new Set,r=[];for(const i of f){const s=Dt(i,e);t.has(s)||(t.add(s),r.push(i))}return r}function Nt(f,e){if(!Array.isArray(f))return[];const t=new Map,r=[];for(const i of f){const s=Dt(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 lr=Object.freeze({date:Ve,now:bt,today:Et,number:At,pages:wt,range:vt,monthAdd:We,monthRange:St,pageSummary:Rt,findBy:Tt,sum:kt,distinct:xt,groupBy:Nt});class et{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 et.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const lt=class lt{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)}};lt.ASYNC_QUEUE=new et;let Y=lt;const It=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"]),je=new Set(["eval","arguments"]),Ft=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),Ke=new Set(["constructor","__proto__","prototype"]),ze=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"]),tt=new Set(["enum","implements","interface","package","private","protected","public","static","super"]),Ct=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"]),cr=[">>>","===","!==","...","**","?.","??","&&","||","==","!=","<=",">=","<<",">>","=>","++","--","(",")","[","]","{","}",".",",","?",":","+","-","*","/","%","!","<",">"],ur={"==":1,"!=":1,"===":1,"!==":1,"<":2,">":2,"<=":2,">=":2,"<<":3,">>":3,">>>":3,"+":4,"-":4,"*":5,"/":5,"%":5},dr=new Set(["undefined","NaN","Infinity"]);function rt(f){return f===`
2
- `||f==="\r"||f==="\u2028"||f==="\u2029"}function hr(f){return/[A-Za-z_$]/.test(f)}function $t(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 fr{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(rt(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(hr(i)){let n=r+1;for(;$t(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 cr)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||rt(l))throw X(J.unterminatedRegExp,e);if(l==="\\"){const u=r[i+1];if(rt(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(;$t(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===`
2
+ `||f==="\r"||f==="\u2028"||f==="\u2029"}function hr(f){return/[A-Za-z_$]/.test(f)}function Mt(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 fr{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(rt(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(hr(i)){let n=r+1;for(;Mt(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 cr)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||rt(l))throw X(J.unterminatedRegExp,e);if(l==="\\"){const u=r[i+1];if(rt(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(;Mt(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
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
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
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 pr{constructor(e){this.lastEnd=0,this.lexer=new fr(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(ze.has(e)||je.has(e)||tt.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(ze.has(e)||je.has(e)||Ke.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"?ur[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!dr.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(Ke.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 gr(f){return new pr(f).parseProgram()}class Mt extends ReferenceError{constructor(e){super(`${e} is not defined`),this.identifier=e}}const Pt=new Map([["undefined",void 0],["NaN",NaN],["Infinity",1/0]]);function Lt(f,e){return Object.prototype.propertyIsEnumerable.call(f,e)}function Ot(f){const e=typeof f=="symbol"?f:String(f);return Ke.has(e)?"undefined":e}function mr(f){return typeof f=="bigint"?f:Number(f)}function Bt(f){return f[Symbol.iterator]()}function Ut(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 ct=class ct{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=gr(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 Ft.has(e)?"rebindable":It.has(e)?"forbidden":Pt.has(e)?"constant":Ct.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(Lt(n.bindings,e))return n.bindings[e];switch(i){case"rebindable":case"constant":return Pt.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=mr(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"&&Lt(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[Ot(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=Bt(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?Ut(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:Ot(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={};Ut(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=Bt(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}}};ct.COMPILE_CACHE=new Map;let Pe=ct;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(`;
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 pr{constructor(e){this.lastEnd=0,this.lexer=new fr(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(ze.has(e)||je.has(e)||tt.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(ze.has(e)||je.has(e)||Ke.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"?ur[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!dr.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(Ke.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 gr(f){return new pr(f).parseProgram()}class $t extends ReferenceError{constructor(e){super(`${e} is not defined`),this.identifier=e}}const Pt=new Map([["undefined",void 0],["NaN",NaN],["Infinity",1/0]]);function Lt(f,e){return Object.prototype.propertyIsEnumerable.call(f,e)}function Ot(f){const e=typeof f=="symbol"?f:String(f);return Ke.has(e)?"undefined":e}function mr(f){return typeof f=="bigint"?f:Number(f)}function Bt(f){return f[Symbol.iterator]()}function Ut(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 ct=class ct{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=gr(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 Ft.has(e)?"rebindable":It.has(e)?"forbidden":Pt.has(e)?"constant":Ct.has(e)?"builtin":"free"}static missing(e,t){if(e.missingIdentifier==="throw")throw new $t(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(Lt(n.bindings,e))return n.bindings[e];switch(i){case"rebindable":case"constant":return Pt.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=mr(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"&&Lt(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[Ot(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=Bt(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?Ut(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:Ot(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={};Ut(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=Bt(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}}};ct.COMPILE_CACHE=new Map;let Pe=ct;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(`;
7
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(", ")};
8
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}B.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(B.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}
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 $t)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}B.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(B.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
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 withoutDiagnosis(e){T.evaluatingForDiagnosis=!0;try{return e()}finally{T.evaluatingForDiagnosis=!1}}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),B.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(B.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=()=>Pe.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(B.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";
11
11
  ${l};
12
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'. Use the CSP mode (the default) by removing data-csp="false" from the <script> or not calling Haori.setCsp(false).`))}static prepareInterpretedEvaluator(e,t){try{const r=Pe.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;const[i,s]=T.withoutDiagnosis(()=>[T.evaluateDetailed(r.left,t),T.evaluateDetailed(r.right,t)]);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={...lr},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([...[...ze].filter(e=>e!=="await"),...tt,...je,"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=[...It],T.STRICT_FORBIDDEN_NAMES=[...je],T.REBINDABLE_FORBIDDEN_NAMES=Ft,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=Ke,T.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),T.DISALLOWED_KEYWORDS=ze,T.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity",...tt]),T.ALLOWED_GLOBAL_IDENTIFIERS=Ct,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 re=T;class Le{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 Ee="data-haori-if-disabled",Ht="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&&B.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((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=P.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)};P.snapshot().forEach(l=>{l.attributes.forEach(u=>{s(`@${u.name}
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={...lr},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([...[...ze].filter(e=>e!=="await"),...tt,...je,"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=[...It],T.STRICT_FORBIDDEN_NAMES=[...je],T.REBINDABLE_FORBIDDEN_NAMES=Ft,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=Ke,T.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),T.DISALLOWED_KEYWORDS=ze,T.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity",...tt]),T.ALLOWED_GLOBAL_IDENTIFIERS=Ct,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 re=T;class Le{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 Ae="data-haori-if-disabled",Ht="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&&B.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((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=P.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)};P.snapshot().forEach(l=>{l.attributes.forEach(u=>{s(`@${u.name}
14
14
  ${u.template}`,`${l.elementId} @${u.name}`,u)}),l.texts.forEach(u=>{s(`#${u.childIndex}
15
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 P.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}
16
16
  `+t.join(`
17
- `))}static record(e,t,r){if(!B.isEnabled()||!e||t.length===0||(P.ensureGlobalAccess(),!P.isCollecting()))return;const i=P.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=P.getOrCreateCounter(i.attributes,e.rawName,e.template);P.updateCounter(n,t,r);return}const s=P.getOrCreateCounter(i.texts,String(e.childIndex),e.template);P.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.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 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=P.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(!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 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(" > ")}};P.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",P.ELEMENT_STORES=new Map,P.collecting=!1,P.DEFAULT_REPORT_LIMIT=20;let Ge=P;const be=class be{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,be.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(be.FRAGMENT_CACHE.has(e))return be.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new R(e);break;case Node.TEXT_NODE:t=new ue(e);break;case Node.COMMENT_NODE:t=new it(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return be.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),be.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};be.FRAGMENT_CACHE=new WeakMap;let D=be;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 Ye(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(Ee)&&(t.removeAttribute(Ee),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 re.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(`
17
+ `))}static record(e,t,r){if(!B.isEnabled()||!e||t.length===0||(P.ensureGlobalAccess(),!P.isCollecting()))return;const i=P.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=P.getOrCreateCounter(i.attributes,e.rawName,e.template);P.updateCounter(n,t,r);return}const s=P.getOrCreateCounter(i.texts,String(e.childIndex),e.template);P.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.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 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=P.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(!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 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(" > ")}};P.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",P.ELEMENT_STORES=new Map,P.collecting=!1,P.DEFAULT_REPORT_LIMIT=20;let Ge=P;const Ee=class Ee{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.skipMutationNodeSet=new Set,this.target=e,Ee.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Ee.FRAGMENT_CACHE.has(e))return Ee.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new R(e);break;case Node.TEXT_NODE:t=new ue(e);break;case Node.COMMENT_NODE:t=new it(e);break;default:return m.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}static peek(e){return Ee.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),Ee.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Ee.FRAGMENT_CACHE=new WeakMap;let D=Ee;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 Ye(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(Ae)&&(t.removeAttribute(Ae),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 re.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(`
18
18
  `);return v.normalizeLinesValue(i.value).join(`
19
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(!B.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(!B.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}static isLateActionAttribute(e){return e.startsWith(c.prefix)&&v.LATE_ACTION_ATTRIBUTE_SUFFIX.test(e.slice(c.prefix.length))}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 Ye(e,r);if(s){const pe=this.attributeMap.get(e);if(pe&&(pe.isEvaluate||pe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const xe=Y.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,xe),xe}}this.attributeMap.set(e,o);const l=this.getTarget(),u=()=>o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),d=v.isLateActionAttribute(e)?re.withoutDiagnosis(u):u(),y=o.isEvaluate||o.isRawEvaluate,b=e===t&&v.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),E=o.isSingleExpression(),A=ye.joinEvaluateResults(d.results),w=d.results.length===1?d.results[0]:A,M=t==="value"&&v.resolveDeclaredValueType(l)==="boolean",$=w===!1&&!M,ne=!o.isForceEvaluation()&&(t!==e?d.hasUnresolvedReference||w===null||w===void 0||$:b?d.hasUnresolvedReference||w===null||w===void 0||w===!1:E?d.hasUnresolvedReference||w===null||w===void 0||$:y&&A==="");if(ne&&d.hasUnresolvedReference&&v.warnUnresolvedAttribute(e,t,r,l),B.isEnabled()&&w===!1&&E){const pe=o.getSingleExpression(),xe=pe===null?null:re.diagnoseStrictComparison(pe,this.getBindingData());xe!==null&&v.warnTypeMismatchedComparison(e,r,xe,l)}const F=o.isForceEvaluation()?r:E?w:A,Z=i&&o.isEvaluate&&t==="value"&&v.isValuePropertyTarget(l),ee=l.getRootNode(),oe=this.userEditSequence,K=Z&&v.isUserEditableValue(l)&&(l===ee.activeElement||this.hasPendingUserEdit()),le=ne||F===null||F===!1&&!M?null:String(F),j=o.isEvaluate&&le!==null&&v.URL_ATTRIBUTES.has(t)&&Le.hasScriptScheme(le);j&&m.warn("[Haori]",`Attribute "${t}" was removed because the evaluated URL uses a script scheme: ${e}="${r}" -> ${le}`,l);const k=j?null:le,H=e!==t&&l.getAttribute(e)!==r,de=k===null?l.hasAttribute(t):l.getAttribute(t)!==k,V=k===null?"":k,_=Z&&!K&&l.value!==V,ge=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),ce=t==="selected"&&l instanceof HTMLOptionElement,W=ee.activeElement,G=W!==null&&(ge&&l===W||ce&&l.closest("select")===W)||(ge||ce)&&this.hasPendingCheckableUserEdit(ce),ie=this.getCheckableUserEditSequence(ce),De=k!==null,ut=ge&&o.isEvaluate&&!G&&l.checked!==De,Qe=ce&&o.isEvaluate&&!G&&l.selected!==De;if(!H&&!de&&!_&&!ut&&!Qe)return Z&&!K&&(this.value=this.normalizeValueForElement(l,V),this.clearUnappliedValueWrite()),(ge||ce)&&!G&&this.syncCheckableValueFromDom(ce),Promise.resolve();const er=Y.enqueue(()=>{const pe=this.getCheckableUserEditSequence(ce)!==ie,xe=ce&&(G||pe)?v.captureSelection(l.closest("select")):null;H&&l.setAttribute(e,r),k===null?l.removeAttribute(t):de&&(l.setAttribute(t,k),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(k)),t==="style"&&this.captureAndHideDisplay(),xe?.(),Z&&!K&&!(v.isUserEditableValue(l)&&this.isSupersededByUserEdit(oe))&&(this.value=this.normalizeValueForElement(l,V),_&&(l.value=V),this.recordValueWriteResult(l.value===V));const Hr=ut&&!pe,Vr=Qe&&!pe;Hr&&(l.checked=De),Vr&&(l.selected=De),(ut||Qe)&&this.syncCheckableValueFromDom(Qe)}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,er),er}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:ye.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(Ht)&&t(e);const r=i=>{Array.from(i.children).forEach(s=>{s.hasAttribute(`${c.prefix}if-false`)||(s instanceof HTMLElement&&s.matches(Ht)&&t(s),r(s))})};r(e)}static disableFormControlsInBranch(e){v.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(Ee,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){v.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(Ee)&&(e.removeAttribute(Ee),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,v.LATE_ACTION_ATTRIBUTE_SUFFIX=new RegExp("^.+-(?:dialog|toast|toast-level|history|scroll|redirect|redirect-replace|redirect-return-param)$");let R=v;class ue extends D{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new ye(this.text)}clone(){const e=new ue(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 ye(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=ye.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 it extends D{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new it(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 Ze=class Ze{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(Ze.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=Ge.measure(()=>re.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("")}}),Ge.record(t,n,a),{results:s,hasUnresolvedReference:o}}};Ze.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let ye=Ze;const Q=class Q extends ye{constructor(e,t){const r=Q.isEventHandlerAttribute(e);super(t,e===`${c.prefix}bind`||r),this.name=e,this.forceEvaluation=Q.needsForceEvaluation(e),this.checksUrlPath=Q.isRequestUrlAttribute(e),r&&B.isEnabled()&&t.includes("{{")&&Q.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}`;Q.WARNED_EVENT_HANDLER_PLACEHOLDERS.has(r)||(Q.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)&&Q.changesUrlPath(n)){const a=`${this.name}\0${this.getValue()}\0${n}`;Q.WARNED_URL_PATH_VALUES.has(a)||(Q.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(Q.forceEvaluationNames===null||Q.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Q.FORCE_EVALUATION_PREFIXES])for(const i of Q.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Q.forceEvaluationNames=t,Q.forceEvaluationPrefix=c.prefix}return Q.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&&B.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}};Q.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Q.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Q.forceEvaluationNames=null,Q.forceEvaluationPrefix=null,Q.WARNED_EVENT_HANDLER_PLACEHOLDERS=new Set,Q.WARNED_URL_PATH_VALUES=new Set;let Ye=Q;const Vt="[Haori]",qt={nameRequired:"Handler name is required.",notFunction:f=>`Handler "${f}" must be a function.`},Te=class Te{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error(Vt,qt.nameRequired);return}if(typeof t!="function"){m.error(Vt,qt.notFunction(r));return}Te.handlers.set(r,t)}static has(e){return Te.handlers.has(e)}static get(e){return Te.handlers.get(e)}static entries(){return Object.fromEntries(Te.handlers)}};Te.handlers=new Map;let Ae=Te;const ke=class ke{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?(ke.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 ke.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")),ke.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 Ve(e,t,r)}static now(e,t){return bt(e,t)}static today(e,t,r){return Et(e,t,r)}static number(e,t){return At(e,t)}static range(e,t,r){return vt(e,t,r)}static pages(e,t,r){return wt(e,t,r)}static monthAdd(e,t){return We(e,t)}static monthRange(e,t){return St(e,t)}static pageSummary(e,t){return Rt(e,t)}static findBy(e,t,r){return Tt(e,t,r)}static sum(e,t){return kt(e,t)}static distinct(e,t){return xt(e,t)}static groupBy(e,t){return Nt(e,t)}};ke.handlers={register(e,t){Ae.register(e,t)},has(e){return Ae.has(e)}},ke.enhancers={register(e,t){se.register(e,t)},has(e){return se.has(e)}};let fe=ke;const yr="入力内容を確認してください",br=["addErrorMessage","clearMessages"],Wt="data-haori-group-name";function jt(){const e=globalThis.window?.Haori;return br.every(r=>typeof e?.[r]=="function")?e:fe}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(Wt))return;const i=p.resolveGroupScope(e),s=`${String(t)}--haori${p.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==s)return e.setAttribute(Wt,"").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(!B.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=re.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:yr}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(!B.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){!B.isEnabled()||p.warnedPositionalRowFallbacks.has(e)||(p.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!B.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&&re.withoutDiagnosis(()=>p.hasResolvedDeclarativeState(e)),A=s&&typeof b>"u"&&!p.isDeclarativeStateBound(e);let w=b;if(E?w=void 0:A&&(w=null),p.isFileInput(e))return(w===null||w==="")&&o.push(p.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(y&&Array.isArray(w)&&!p.isGroupedCheckable(e)&&!p.isMultipleSelect(e)){const M=String(l),$=n.get(M)??0;n.set(M,$+1),o.push(p.applyFragmentValue(e,w[$]??null,i,a))}else typeof w>"u"||(Array.isArray(w)&&p.isGroupedCheckable(e)||Array.isArray(w)&&p.isMultipleSelect(e)||typeof w=="string"||typeof w=="number"||typeof w=="boolean"||w===null||Array.isArray(w)&&e.collectsLines()?o.push(p.applyFragmentValue(e,w,i,a)):o.push(p.applyFragmentValue(e,String(w),i,a)))}else if(u){const b=t[String(u)],E=b&&typeof b=="object"?b:{},A=new Map;for(const w of e.getChildElementFragments())o.push(p.setPartValues(w,E,r,i,s,A,a))}else if(d){const b=t[String(d)],E=Array.isArray(b)?b:[],A=e.getChildElementFragments(),w=e.getAttribute(`${c.prefix}each-key`),M=p.isCollectedListFromEachSource(e)?p.pairRowsWithItems(A,E,w==null?null:String(w)):null;for(let $=0;$<A.length;$++){const ne=A[$],F=M?M[$]:E.length>$?E[$]:null;o.push(p.setPartValues(ne,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 jt().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return p.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=jt(),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 O{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){O.dispatch(document,"ready",{version:e})}static importStart(e,t){O.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){O.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){O.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const 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)}O.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){O.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){O.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){O.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){O.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){O.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){O.dispatch(e,"show",{visible:!0})}static hide(e){O.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){O.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){O.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){O.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}static pollTimeout(e,t,r){O.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){O.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const Er={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ar(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=re.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Kt(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=Ar(t,i);return s===""?null:s}function vr(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 zt(f,e,t){const r=vr(f,e,t);if(!Le.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 Gt(f,e=null){const t=Er[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=Kt(e.element,s);return n!==null&&zt(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=Kt(s,r);if(n!==null)return zt(s,r,n)}return!1}class z{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static queryAllInListOrder(e,t){if(z.queryAll(e,t).length===0)return[];const r=new Set;return z.splitList(e).forEach(i=>{z.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 Oe=N;const Ne="[Haori]",Ie={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 (the default). Write the expression without {{...}}, or use ${f}-handler and ${f}-args. To run it as JavaScript, select the legacy mode with <script data-csp="false">.`,notExpression:f=>`${f} is not run in the CSP mode (the default) because it is not a single expression. Use ${f}-handler and ${f}-args. To run it as JavaScript, select the legacy mode with <script data-csp="false">.`,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)?(B.isEnabled()&&e.hasAttribute(t)&&m.warn(Ne,Ie.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=Ae.get(r);if(n===void 0){m.warn(Ne,Ie.notRegistered(r,t),e.getTarget());return}let a=[];if(i!==null){const o=re.evaluateDetailed(i,e.getBindingData());if(!Array.isArray(o.value)){m.warn(Ne,Ie.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(Ne,Ie.templateInBody(t),e.getTarget()),null;try{Pe.compile(i)}catch{return m.warn(Ne,Ie.notExpression(t),e.getTarget()),null}return s=>{const n=e.getBindingData();B.isEnabled()&&ae.reportShadowedHandlers(n,t);const a={...Ae.entries(),...n};return r.forEach((o,l)=>{a[o]=s[l]}),re.evaluate(i,a)}}static reportShadowedHandlers(e,t){const r=Object.keys(e).filter(i=>Ae.has(i));r.length>0&&m.warn(Ne,Ie.shadowed(r,t))}}const wr=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Sr="__haoriHistoryState__",st="data-haori-click-lock",Yt="ファイルを保存できませんでした",Rr=100;let Be=null;const Tr=["info","warning","error","success"],Xt=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message|bind)$/;function ve(){const e=globalThis.window?.Haori;return wr.every(r=>typeof e?.[r]=="function")?e:fe}const kr=new Set(["GET","HEAD","OPTIONS"]);function Xe(f){return kr.has(f.toUpperCase())}function Dr(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{f.append(t,Fe(i))}):f.append(t,Fe(r)))}function Fe(f){if(f==null)return"";if(typeof f=="object"||typeof f=="function")try{return JSON.stringify(f)??""}catch{return""}return String(f)}function Jt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return Dr(r,e),t.search=r.toString(),t.toString()}function xr(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:Zt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(f instanceof URLSearchParams)return{payload:Zt(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}Qt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Zt(f){const e={};for(const[t,r]of f.entries())Qt(e,t,r);return e}function Qt(f,e,t){const r=f[e];r===void 0?f[e]=t:Array.isArray(r)?r.push(t):f[e]=[r,t]}function we(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]=we(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]=we(t[r],i);return t}return e}function Nr(f){const e=f?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Ir(f,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Xe(r))return{url:f,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:s}=xr(t.body);let n=f;Object.keys(i).length>0&&(n=Jt(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 Fr(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 Ue(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(Ue):f!==null&&typeof f=="object"?Object.values(f).some(Ue):!1}function Cr(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Ue(t)):Ue(e))}function Je(f){return nt(x.getValues(f))}function nt(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 $r(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:Fr(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=z.read(e,t),s=[];if(i)(r==="click"||r==="error-click"?z.queryAllInListOrder(i,t):z.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)?Xt.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=Xt.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 Tr.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=re.withoutDiagnosis(()=>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,`
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(!B.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}static isLateActionAttribute(e){return e.startsWith(c.prefix)&&v.LATE_ACTION_ATTRIBUTE_SUFFIX.test(e.slice(c.prefix.length))}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 Ye(e,r);if(s){const pe=this.attributeMap.get(e);if(pe&&(pe.isEvaluate||pe.isForceEvaluation())&&!o.isEvaluate&&!o.isForceEvaluation()){const xe=Y.enqueue(()=>{}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,xe),xe}}this.attributeMap.set(e,o);const l=this.getTarget(),u=()=>o.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:l,rawName:e,template:r}),d=v.isLateActionAttribute(e)?re.withoutDiagnosis(u):u(),y=o.isEvaluate||o.isRawEvaluate,b=e===t&&v.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),E=o.isSingleExpression(),A=ye.joinEvaluateResults(d.results),w=d.results.length===1?d.results[0]:A,$=t==="value"&&v.resolveDeclaredValueType(l)==="boolean",M=w===!1&&!$,ne=!o.isForceEvaluation()&&(t!==e?d.hasUnresolvedReference||w===null||w===void 0||M:b?d.hasUnresolvedReference||w===null||w===void 0||w===!1:E?d.hasUnresolvedReference||w===null||w===void 0||M:y&&A==="");if(ne&&d.hasUnresolvedReference&&v.warnUnresolvedAttribute(e,t,r,l),B.isEnabled()&&w===!1&&E){const pe=o.getSingleExpression(),xe=pe===null?null:re.diagnoseStrictComparison(pe,this.getBindingData());xe!==null&&v.warnTypeMismatchedComparison(e,r,xe,l)}const F=o.isForceEvaluation()?r:E?w:A,Z=i&&o.isEvaluate&&t==="value"&&v.isValuePropertyTarget(l),ee=l.getRootNode(),oe=this.userEditSequence,K=Z&&v.isUserEditableValue(l)&&(l===ee.activeElement||this.hasPendingUserEdit()),le=ne||F===null||F===!1&&!$?null:String(F),j=o.isEvaluate&&le!==null&&v.URL_ATTRIBUTES.has(t)&&Le.hasScriptScheme(le);j&&m.warn("[Haori]",`Attribute "${t}" was removed because the evaluated URL uses a script scheme: ${e}="${r}" -> ${le}`,l);const k=j?null:le,H=e!==t&&l.getAttribute(e)!==r,de=k===null?l.hasAttribute(t):l.getAttribute(t)!==k,V=k===null?"":k,_=Z&&!K&&l.value!==V,ge=t==="checked"&&l instanceof HTMLInputElement&&(l.type==="checkbox"||l.type==="radio"),ce=t==="selected"&&l instanceof HTMLOptionElement,W=ee.activeElement,G=W!==null&&(ge&&l===W||ce&&l.closest("select")===W)||(ge||ce)&&this.hasPendingCheckableUserEdit(ce),ie=this.getCheckableUserEditSequence(ce),De=k!==null,ut=ge&&o.isEvaluate&&!G&&l.checked!==De,Qe=ce&&o.isEvaluate&&!G&&l.selected!==De;if(!H&&!de&&!_&&!ut&&!Qe)return Z&&!K&&(this.value=this.normalizeValueForElement(l,V),this.clearUnappliedValueWrite()),(ge||ce)&&!G&&this.syncCheckableValueFromDom(ce),Promise.resolve();const er=Y.enqueue(()=>{const pe=this.getCheckableUserEditSequence(ce)!==ie,xe=ce&&(G||pe)?v.captureSelection(l.closest("select")):null;H&&l.setAttribute(e,r),k===null?l.removeAttribute(t):de&&(l.setAttribute(t,k),t===`${c.prefix}bind`&&this.recordSelfWrittenBind(k)),t==="style"&&this.captureAndHideDisplay(),xe?.(),Z&&!K&&!(v.isUserEditableValue(l)&&this.isSupersededByUserEdit(oe))&&(this.value=this.normalizeValueForElement(l,V),_&&(l.value=V),this.recordValueWriteResult(l.value===V));const Hr=ut&&!pe,Vr=Qe&&!pe;Hr&&(l.checked=De),Vr&&(l.selected=De),(ut||Qe)&&this.syncCheckableValueFromDom(Qe)}).finally(()=>{this.releaseSelfWritingAttributes(n)});return this.holdSelfWritingAttributes(n,er),er}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:ye.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(Ht)&&t(e);const r=i=>{Array.from(i.children).forEach(s=>{s.hasAttribute(`${c.prefix}if-false`)||(s instanceof HTMLElement&&s.matches(Ht)&&t(s),r(s))})};r(e)}static disableFormControlsInBranch(e){v.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(Ae,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){v.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(Ae)&&(e.removeAttribute(Ae),e.removeAttribute("disabled"))})}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${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,v.LATE_ACTION_ATTRIBUTE_SUFFIX=new RegExp("^.+-(?:dialog|toast|toast-level|history|scroll|redirect|redirect-replace|redirect-return-param)$");let R=v;class ue extends D{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new ye(this.text)}clone(){const e=new ue(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 ye(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=ye.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 it extends D{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new it(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 Ze=class Ze{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(Ze.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=Ge.measure(()=>re.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("")}}),Ge.record(t,n,a),{results:s,hasUnresolvedReference:o}}};Ze.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let ye=Ze;const Q=class Q extends ye{constructor(e,t){const r=Q.isEventHandlerAttribute(e);super(t,e===`${c.prefix}bind`||r),this.name=e,this.forceEvaluation=Q.needsForceEvaluation(e),this.checksUrlPath=Q.isRequestUrlAttribute(e),r&&B.isEnabled()&&t.includes("{{")&&Q.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}`;Q.WARNED_EVENT_HANDLER_PLACEHOLDERS.has(r)||(Q.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)&&Q.changesUrlPath(n)){const a=`${this.name}\0${this.getValue()}\0${n}`;Q.WARNED_URL_PATH_VALUES.has(a)||(Q.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(Q.forceEvaluationNames===null||Q.forceEvaluationPrefix!==c.prefix){const t=new Set;for(const r of[c.prefix,...Q.FORCE_EVALUATION_PREFIXES])for(const i of Q.FORCE_EVALUATION_SUFFIXES)t.add(`${r}${i}`);Q.forceEvaluationNames=t,Q.forceEvaluationPrefix=c.prefix}return Q.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&&B.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}};Q.FORCE_EVALUATION_SUFFIXES=["if","each","derive"],Q.FORCE_EVALUATION_PREFIXES=["data-","hor-"],Q.forceEvaluationNames=null,Q.forceEvaluationPrefix=null,Q.WARNED_EVENT_HANDLER_PLACEHOLDERS=new Set,Q.WARNED_URL_PATH_VALUES=new Set;let Ye=Q;const Vt="[Haori]",qt={nameRequired:"Handler name is required.",notFunction:f=>`Handler "${f}" must be a function.`},Te=class Te{static register(e,t){const r=typeof e=="string"?e.trim():"";if(r===""){m.error(Vt,qt.nameRequired);return}if(typeof t!="function"){m.error(Vt,qt.notFunction(r));return}Te.handlers.set(r,t)}static has(e){return Te.handlers.has(e)}static get(e){return Te.handlers.get(e)}static entries(){return Object.fromEntries(Te.handlers)}};Te.handlers=new Map;let ve=Te;const ke=class ke{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?(ke.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 ke.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")),ke.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 Ve(e,t,r)}static now(e,t){return bt(e,t)}static today(e,t,r){return Et(e,t,r)}static number(e,t){return At(e,t)}static range(e,t,r){return vt(e,t,r)}static pages(e,t,r){return wt(e,t,r)}static monthAdd(e,t){return We(e,t)}static monthRange(e,t){return St(e,t)}static pageSummary(e,t){return Rt(e,t)}static findBy(e,t,r){return Tt(e,t,r)}static sum(e,t){return kt(e,t)}static distinct(e,t){return xt(e,t)}static groupBy(e,t){return Nt(e,t)}};ke.handlers={register(e,t){ve.register(e,t)},has(e){return ve.has(e)}},ke.enhancers={register(e,t){se.register(e,t)},has(e){return se.has(e)}};let fe=ke;const yr="入力内容を確認してください",br=["addErrorMessage","clearMessages"],Wt="data-haori-group-name";function jt(){const e=globalThis.window?.Haori;return br.every(r=>typeof e?.[r]=="function")?e:fe}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(Wt))return;const i=p.resolveGroupScope(e),s=`${String(t)}--haori${p.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==s)return e.setAttribute(Wt,"").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(!B.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=re.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:yr}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(!B.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){!B.isEnabled()||p.warnedPositionalRowFallbacks.has(e)||(p.warnedPositionalRowFallbacks.add(e),m.warn("[Haori]",`${c.prefix}form-list の行を出現順で対応付けます(${e})。配列と画面の行数・並びが一致していない場合、行の値を取り違えます。`))}static warnDerivedRowsWithoutKey(e){if(!B.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&&re.withoutDiagnosis(()=>p.hasResolvedDeclarativeState(e)),A=s&&typeof b>"u"&&!p.isDeclarativeStateBound(e);let w=b;if(E?w=void 0:A&&(w=null),p.isFileInput(e))return(w===null||w==="")&&o.push(p.applyFragmentValue(e,null,i,a)),Promise.all(o).then(()=>{});if(y&&Array.isArray(w)&&!p.isGroupedCheckable(e)&&!p.isMultipleSelect(e)){const $=String(l),M=n.get($)??0;n.set($,M+1),o.push(p.applyFragmentValue(e,w[M]??null,i,a))}else typeof w>"u"||(Array.isArray(w)&&p.isGroupedCheckable(e)||Array.isArray(w)&&p.isMultipleSelect(e)||typeof w=="string"||typeof w=="number"||typeof w=="boolean"||w===null||Array.isArray(w)&&e.collectsLines()?o.push(p.applyFragmentValue(e,w,i,a)):o.push(p.applyFragmentValue(e,String(w),i,a)))}else if(u){const b=t[String(u)],E=b&&typeof b=="object"?b:{},A=new Map;for(const w of e.getChildElementFragments())o.push(p.setPartValues(w,E,r,i,s,A,a))}else if(d){const b=t[String(d)],E=Array.isArray(b)?b:[],A=e.getChildElementFragments(),w=e.getAttribute(`${c.prefix}each-key`),$=p.isCollectedListFromEachSource(e)?p.pairRowsWithItems(A,E,w==null?null:String(w)):null;for(let M=0;M<A.length;M++){const ne=A[M],F=$?$[M]:E.length>M?E[M]:null;o.push(p.setPartValues(ne,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 jt().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return p.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=jt(),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 O{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){O.dispatch(document,"ready",{version:e})}static importStart(e,t){O.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){O.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){O.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const 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)}O.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){O.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){O.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){O.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){O.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){O.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){O.dispatch(e,"show",{visible:!0})}static hide(e){O.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){O.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){O.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){O.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}static pollTimeout(e,t,r){O.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){O.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const Er={401:"unauthorized-redirect",403:"forbidden-redirect"};function Ar(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=re.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function Kt(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=Ar(t,i);return s===""?null:s}function vr(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 zt(f,e,t){const r=vr(f,e,t);if(!Le.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 Gt(f,e=null){const t=Er[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=Kt(e.element,s);return n!==null&&zt(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=Kt(s,r);if(n!==null)return zt(s,r,n)}return!1}class z{static read(e,t){if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);return typeof r=="string"?r:null}static queryAll(e,t,r=document.body){try{return Array.from(r.querySelectorAll(e))}catch(i){return m.error("Haori",`Invalid selector: ${e} (${t})`,i),[]}}static queryAllInListOrder(e,t){if(z.queryAll(e,t).length===0)return[];const r=new Set;return z.splitList(e).forEach(i=>{z.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 Oe=N;const Ne="[Haori]",Ie={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 (the default). Write the expression without {{...}}, or use ${f}-handler and ${f}-args. To run it as JavaScript, select the legacy mode with <script data-csp="false">.`,notExpression:f=>`${f} is not run in the CSP mode (the default) because it is not a single expression. Use ${f}-handler and ${f}-args. To run it as JavaScript, select the legacy mode with <script data-csp="false">.`,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)?(B.isEnabled()&&e.hasAttribute(t)&&m.warn(Ne,Ie.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=ve.get(r);if(n===void 0){m.warn(Ne,Ie.notRegistered(r,t),e.getTarget());return}let a=[];if(i!==null){const o=re.evaluateDetailed(i,e.getBindingData());if(!Array.isArray(o.value)){m.warn(Ne,Ie.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(Ne,Ie.templateInBody(t),e.getTarget()),null;try{Pe.compile(i)}catch{return m.warn(Ne,Ie.notExpression(t),e.getTarget()),null}return s=>{const n=e.getBindingData();B.isEnabled()&&ae.reportShadowedHandlers(n,t);const a={...ve.entries(),...n};return r.forEach((o,l)=>{a[o]=s[l]}),re.evaluate(i,a)}}static reportShadowedHandlers(e,t){const r=Object.keys(e).filter(i=>ve.has(i));r.length>0&&m.warn(Ne,Ie.shadowed(r,t))}}const wr=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],Sr="__haoriHistoryState__",st="data-haori-click-lock",Yt="ファイルを保存できませんでした",Rr=100;let Be=null;const Tr=["info","warning","error","success"],Xt=/^(\d{3})-(click|click-await|close|toast|toast-level|no-message|bind)$/;function be(){const e=globalThis.window?.Haori;return wr.every(r=>typeof e?.[r]=="function")?e:fe}const kr=new Set(["GET","HEAD","OPTIONS"]);function Xe(f){return kr.has(f.toUpperCase())}function Dr(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{f.append(t,Fe(i))}):f.append(t,Fe(r)))}function Fe(f){if(f==null)return"";if(typeof f=="object"||typeof f=="function")try{return JSON.stringify(f)??""}catch{return""}return String(f)}function Jt(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return Dr(r,e),t.search=r.toString(),t.toString()}function xr(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:Zt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(f instanceof URLSearchParams)return{payload:Zt(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}Qt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Zt(f){const e={};for(const[t,r]of f.entries())Qt(e,t,r);return e}function Qt(f,e,t){const r=f[e];r===void 0?f[e]=t:Array.isArray(r)?r.push(t):f[e]=[r,t]}function we(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]=we(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]=we(t[r],i);return t}return e}function Nr(f){const e=f?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function Ir(f,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(c.runtime!=="demo"||Xe(r))return{url:f,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:s}=xr(t.body);let n=f;Object.keys(i).length>0&&(n=Jt(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 Fr(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 Ue(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(Ue):f!==null&&typeof f=="object"?Object.values(f).some(Ue):!1}function Cr(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&Ue(t)):Ue(e))}function Je(f){return nt(x.getValues(f))}function nt(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 Mr(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:Fr(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=z.read(e,t),s=[];if(i)(r==="click"||r==="error-click"?z.queryAllInListOrder(i,t):z.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)?Xt.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=Xt.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 Tr.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=re.withoutDiagnosis(()=>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
21
  `):e}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=re.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=re.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 k=e.getRawAttribute(i);typeof k=="string"&&k.trim()!==""?(r.conditionExpression=x.unwrapConditionExpression(k),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 V=z.read(e,g.attrName(t,"form"));if(V){const _=z.query(V,g.attrName(t,"form"));_!==null?r.formFragment=x.getFormFragment(D.get(_)):m.error("Haori",`Form element not found: ${V} (${g.attrName(t,"form")})`)}else r.formFragment=x.getFormFragment(e)}else if(t==="change"||t==="input"){r.formFragment=x.getFormFragment(e);const V=`${c.prefix}${t}-`;r.implicitFormFragment=!e.getAttributeNames().some(_=>_.startsWith(V)),r.formFragment===null&&g.isNamedInputFragment(e)&&(r.selfValueFragment=e)}B.isEnabled()&&g.warnAuthRedirectWithoutFetch(e,t);const k=`${c.prefix}${t}-before-run`;if(ae.declared(e,k)&&ae.applies(e,k)){const V=ae.compile(e,k,["fetchUrl","fetchOptions"]);V&&(r.beforeCallback=(_,ge)=>V([_,ge]))}else if(e.hasAttribute(k)){const V=e.getRawAttribute(k);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
22
22
  "use strict";
23
23
  ${V}
@@ -25,17 +25,17 @@ ${V}
25
25
  ${V}
26
26
  );`)}catch{try{_=new Function("event",`"use strict";
27
27
  ${V}
28
- `)}catch(ge){m.error("Haori",`Invalid run script: ${ge}`)}}_&&(r.runScript=_)}const de=g.attrName(t,"clipboard");e.hasAttribute(de)&&(r.clipboardAttrName=de)}const s=g.attrName(t,"fetch"),n=e.hasAttribute(s);if(n){const k=e.getAttributeEvaluation(s);k&&(r.fetchHasUnresolvedReference=k.hasUnresolvedReference,r.fetchUrl=k.hasUnresolvedReference?null:k.value)}const a={},o=t?g.attrName(t,"fetch-method"):g.attrName(null,"method",!0);if(e.hasAttribute(o)){const k=e.getAttributeEvaluation(o);k?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=g.normalizeAttributeText(k?.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 k=e.getAttributeEvaluation(d);k?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),y=g.normalizeAttributeText(k?.value)}if(y!==null)a.headers=g.withContentType(a.headers,y);else if(a.method&&!g.hasDeclaredContentType(a.headers)){const k=a.method.toUpperCase();a.headers=g.withContentType(a.headers,k==="GET"||k==="HEAD"||k==="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 k=e.getAttributeEvaluation(b);r.downloadFileName=k?.hasUnresolvedReference?null:g.normalizeAttributeText(k?.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 k=z.read(e,A);if(k){const H=z.queryAll(k,A);H.length>0?(r.bindFragments=[],H.forEach(de=>{const V=D.get(de);V&&r.bindFragments.push(V)})):m.error("Haori",`Bind element not found: ${k} (${A})`)}}const w=g.attrName(t,"bind-arg"),M=g.attrName(null,"arg",!0),$=g.attrName(null,"bind-arg",!0);t?e.hasAttribute(w)&&(r.bindArg=e.getRawAttribute(w)):e.hasAttribute(M)?r.bindArg=e.getRawAttribute(M):e.hasAttribute($)&&(r.bindArg=e.getRawAttribute($));const ne=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(ne)){const k=e.getRawAttribute(ne);r.bindParams=k.split("&").map(H=>H.trim())}const F=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(F)){const k=e.getRawAttribute(F);r.bindAppendParams=k.split("&").map(H=>H.trim()).filter(Boolean)}const Z=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(Z)&&(r.bindMerge=!0);const ee=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(ee)&&(r.bindTransform=e.getRawAttribute(ee));const oe=t?g.attrName(t,"payload-transform"):g.attrName(null,"payload-transform",!0);e.hasAttribute(oe)&&(r.payloadTransform=e.getRawAttribute(oe));const K=t?g.attrName(t,"copy-params"):null;if(K&&e.hasAttribute(K)){const k=e.getRawAttribute(K);r.copyParams=k.split("&").map(H=>H.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const W=z.read(e,g.attrName(t,"adjust"));if(W){const G=z.queryAll(W,g.attrName(t,"adjust"));G.length>0?(r.adjustFragments=[],G.forEach(ie=>{const De=D.get(ie);De&&r.adjustFragments.push(De)})):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")),ie=Number(G);isNaN(ie)||(r.adjustValue=ie)}}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 k=`${c.prefix}${t}-after-run`;if(ae.declared(e,k)&&ae.applies(e,k)){const W=ae.compile(e,k,["response"]);W&&(r.afterCallback=G=>W([G]))}else if(e.hasAttribute(k)){const W=e.getRawAttribute(k);try{r.afterCallback=new Function("response",`
28
+ `)}catch(ge){m.error("Haori",`Invalid run script: ${ge}`)}}_&&(r.runScript=_)}const de=g.attrName(t,"clipboard");e.hasAttribute(de)&&(r.clipboardAttrName=de,r.clipboardErrorToastMessage=g.readLateAttribute(e,r,"clipboard-error-toast",g.attrName(t,"clipboard-error-toast")),r.clipboardErrorToastLevel=g.readToastLevel(e,r,"clipboard-error-toast-level",g.attrName(t,"clipboard-error-toast-level")))}const s=g.attrName(t,"fetch"),n=e.hasAttribute(s);if(n){const k=e.getAttributeEvaluation(s);k&&(r.fetchHasUnresolvedReference=k.hasUnresolvedReference,r.fetchUrl=k.hasUnresolvedReference?null:k.value)}const a={},o=t?g.attrName(t,"fetch-method"):g.attrName(null,"method",!0);if(e.hasAttribute(o)){const k=e.getAttributeEvaluation(o);k?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:a.method=g.normalizeAttributeText(k?.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 k=e.getAttributeEvaluation(d);k?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),y=g.normalizeAttributeText(k?.value)}if(y!==null)a.headers=g.withContentType(a.headers,y);else if(a.method&&!g.hasDeclaredContentType(a.headers)){const k=a.method.toUpperCase();a.headers=g.withContentType(a.headers,k==="GET"||k==="HEAD"||k==="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 k=e.getAttributeEvaluation(b);r.downloadFileName=k?.hasUnresolvedReference?null:g.normalizeAttributeText(k?.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 k=z.read(e,A);if(k){const H=z.queryAll(k,A);H.length>0?(r.bindFragments=[],H.forEach(de=>{const V=D.get(de);V&&r.bindFragments.push(V)})):m.error("Haori",`Bind element not found: ${k} (${A})`)}}const w=g.attrName(t,"bind-arg"),$=g.attrName(null,"arg",!0),M=g.attrName(null,"bind-arg",!0);t?e.hasAttribute(w)&&(r.bindArg=e.getRawAttribute(w)):e.hasAttribute($)?r.bindArg=e.getRawAttribute($):e.hasAttribute(M)&&(r.bindArg=e.getRawAttribute(M));const ne=t?g.attrName(t,"bind-params"):g.attrName(null,"bind-params",!0);if(e.hasAttribute(ne)){const k=e.getRawAttribute(ne);r.bindParams=k.split("&").map(H=>H.trim())}const F=t?g.attrName(t,"bind-append"):g.attrName(null,"bind-append",!0);if(e.hasAttribute(F)){const k=e.getRawAttribute(F);r.bindAppendParams=k.split("&").map(H=>H.trim()).filter(Boolean)}const Z=t?g.attrName(t,"bind-merge"):g.attrName(null,"bind-merge",!0);e.hasAttribute(Z)&&(r.bindMerge=!0);const ee=t?g.attrName(t,"bind-transform"):g.attrName(null,"bind-transform",!0);e.hasAttribute(ee)&&(r.bindTransform=e.getRawAttribute(ee));const oe=t?g.attrName(t,"payload-transform"):g.attrName(null,"payload-transform",!0);e.hasAttribute(oe)&&(r.payloadTransform=e.getRawAttribute(oe));const K=t?g.attrName(t,"copy-params"):null;if(K&&e.hasAttribute(K)){const k=e.getRawAttribute(K);r.copyParams=k.split("&").map(H=>H.trim()).filter(Boolean)}if(t){if(e.hasAttribute(g.attrName(t,"adjust"))){const W=z.read(e,g.attrName(t,"adjust"));if(W){const G=z.queryAll(W,g.attrName(t,"adjust"));G.length>0?(r.adjustFragments=[],G.forEach(ie=>{const De=D.get(ie);De&&r.adjustFragments.push(De)})):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")),ie=Number(G);isNaN(ie)||(r.adjustValue=ie)}}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 k=`${c.prefix}${t}-after-run`;if(ae.declared(e,k)&&ae.applies(e,k)){const W=ae.compile(e,k,["response"]);W&&(r.afterCallback=G=>W([G]))}else if(e.hasAttribute(k)){const W=e.getRawAttribute(k);try{r.afterCallback=new Function("response",`
29
29
  "use strict";
30
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 H=g.attrName(t,"redirect"),de=g.attrName(t,"redirect-replace"),V=e.hasAttribute(H),_=e.hasAttribute(de);if(V&&(r.redirectUrl=g.readLateAttribute(e,r,"redirect",H)),_&&(r.redirectReplaceUrl=g.readLateAttribute(e,r,"redirect-replace",de)),V||_){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=z.read(e,g.attrName(t,"history-form"));if(W){const G=z.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 ie=g.resolveSelectorTargets(e,G,W);if(ie.length>0)switch(W){case"reset-before":r.resetBeforeFragments=ie;break;case"reset":r.resetFragments=ie;break;case"refetch":r.refetchFragments=ie;break;case"click":r.clickFragments=ie,r.clickAwait=e.hasAttribute(`${G}-await`);break;case"copy":r.copyFragments=ie;break;case"open":r.openFragments=ie;break;case"close":r.closeFragments=ie;break;case"error-click":r.errorClickFragments=ie,r.errorClickAwait=e.hasAttribute(`${G}-await`);break;case"error-close":r.errorCloseFragments=ie;break}}),t!=="poll"&&(r.errorStatusActions=g.readErrorStatusActions(e,r,t));const ce=g.attrName(t,"copy-source");if(e.hasAttribute(ce)){const W=z.read(e,ce);if(W){const G=z.query(W,ce);if(G!==null){const ie=D.get(G);ie?r.copySourceFragment=ie:m.error("Haori",`Element is not managed by Haori: ${W} (${ce})`)}else m.error("Haori",`Element not found: ${W} (${ce})`)}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 k=z.read(e,g.attrName(null,"form",!0));if(k){const H=z.query(k,g.attrName(null,"form",!0));H!==null?r.formFragment=x.getFormFragment(D.get(H)):m.error("Haori",`Form element not found: ${k} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=x.getFormFragment(e)}(!t||t==="poll")&&g.readNoMessageDeclarations(e,r,t??"fetch");const le=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(le)){const k=z.read(e,le),H=[];k?(z.queryAll(k,le).forEach(V=>{const _=D.get(V);_&&H.push(_)}),H.length===0&&m.error("Haori",`Element not found: ${k} (${le})`)):H.push(e),H.length>0&&(r.fetchStateFragments=H)}const j=t?g.attrName(t,"store-clear"):g.attrName(null,"store-clear",!0);if(e.hasAttribute(j)){const k=e.getRawAttribute(j),H=k===null?"":k.trim();if(H==="")m.error("Haori",`ストレージキーが指定されていません (${j})`);else{r.storeClearKey=H;const de=e.getRawAttribute(`${j}-type`),V=de===null?"session":de.trim();V==="local"||V==="session"?r.storeClearKind=V:(m.warn("Haori",`${j}-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"}startClipboardWrite(e){const t=this.options.targetFragment?.getAttributeEvaluation(e);if(t?.hasUnresolvedReference)return Promise.resolve(!1);const r=t?.value,i=r==null||r===!1||Number.isNaN(r)?"":String(r);if(i==="")return Promise.resolve(!1);const s=typeof navigator>"u"?void 0:navigator.clipboard;if(!s||typeof s.writeText!="function")return m.warn("Haori",`${e}: navigator.clipboard is not available (it requires a secure context such as HTTPS).`),Promise.resolve(!1);try{return s.writeText(i).then(()=>!0,n=>(m.warn("Haori",`${e}: failed to write: ${n}`),!1))}catch(n){return m.warn("Haori",`${e}: failed to write: ${n}`),Promise.resolve(!1)}}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;let t;if(this.options.runScript){const A=this.options.targetFragment?.getTarget()??null;try{t=this.options.runScript.call(A,this.domEvent),t===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(w){m.error("Haori",`Run script execution error: ${w}`)}}const r=this.options.clipboardAttrName?this.startClipboardWrite(this.options.clipboardAttrName):null;if(t!=null&&typeof t.then=="function")try{await t}catch(A){m.error("Haori",`Run script execution error: ${A}`)}if(r&&!await r)return await this.commitEditOnStop(),!1;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(A=>x.reset(A,this.operationSequence))),this.captureHistorySnapshots());const s=this.prepareFetchRequest();if(s.payloadTransformFailed)return await this.commitEditOnStop(),!1;this.requestUserEditSequence=R.currentSequence();const n=s.payload,a=Object.keys(s.sentPayload).length>0?s.sentPayload:void 0;let o=s.url,l=s.options,u=!1,d=!1;if(this.options.beforeCallback){const A=this.options.beforeCallback(o||null,l||null);if(A!=null){if(A===!1||typeof A=="object"&&A.stop)return!1;typeof A=="object"&&(u="fetchUrl"in A,d="fetchOptions"in A,o=u?A.fetchUrl:o,l=d?A.fetchOptions:l)}}const y=Object.keys(n).length>0;if(o){this.isInputEditProcedure()&&await this.commitFormValues(this.options.formFragment,n,e);const A=(l?.method||"GET").toUpperCase(),M=!u&&d&&s.transportMode==="query-get"&&Nr(l)&&!Xe(A)?s.baseUrl??o:o,$=Ir(M,l);o=$.url;const ne={...$.options},F=$.normalized?$.requestedMethod:s.requestedMethod,Z=$.effectiveMethod,ee=s.transportMode==="query-get"||$.normalized,oe=$.queryString??s.queryString;if(ee&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:F,effectiveMethod:Z,transportMode:"query-get",url:o,payload:a,queryString:oe}),this.options.targetFragment&&o){const K=performance.now(),le={runtime:c.runtime,requestedMethod:F,effectiveMethod:Z,transportMode:ee?"query-get":"http",...ee?{queryString:oe}:{}};return O.fetchStart(this.options.targetFragment.getTarget(),o,ne,a,le),await this.injectFetchState("loading"),await g.invokeFetch(o,ne).then(j=>this.handleFetchResult(j,o||void 0,K)).catch(async j=>{throw o&&O.fetchError(this.options.targetFragment.getTarget(),o,j),await this.injectFetchState("error",null,j instanceof Error?j.message:String(j)),await this.runErrorActions(null),j})}return await fetch(o,ne).then(K=>this.handleFetchResult(K,o||void 0))}(!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&y&&await this.commitFormValues(this.options.formFragment,n,e),this.suppressEmptyReplaceBind=!y&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const b=y?nt(n):{},E=new Response(JSON.stringify(b),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(E)}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=nt(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(st))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(st,""),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(st),!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(){Be=null}async prepareDownloadFolder(){if(Be)return this.downloadFolder=Be,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return m.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Be=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>=Rr&&(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 ve().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,Be=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=ve();await r.clearMessages(t),e&&await r.addErrorMessage(t,Yt)}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=ve();if(!e.ok){if(Gt(e.status,{element:this.options.targetFragment.getTarget(),attrPrefix:g.attrName(this.eventType,"",!0)}))return!1;this.options.targetFragment&&t&&O.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,w=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,w),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&O.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,Yt),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&&z.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 $=M.trim();Le.isSafeLocalPath($)?E=$:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${M}`)}}Le.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&&Oe.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=ve(),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?(B.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({[Sr]:!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 ve().clearMessages(i);const s=async u=>{const d=r?r.getTarget():document.body;await ve().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,w=E.message,M=typeof A=="string"&&A.length>0?A:null,$=typeof w=="string"?w:w!=null?String(w):"";if($.length===0)continue;if(M!==null){const ne=y.get(M)??[];ne.push($),y.set(M,ne)}else b.push($)}else typeof E=="string"&&E.length>0&&b.push(E);for(const[E,A]of y)d.push({key:E,message:A.join(`
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 H=g.attrName(t,"redirect"),de=g.attrName(t,"redirect-replace"),V=e.hasAttribute(H),_=e.hasAttribute(de);if(V&&(r.redirectUrl=g.readLateAttribute(e,r,"redirect",H)),_&&(r.redirectReplaceUrl=g.readLateAttribute(e,r,"redirect-replace",de)),V||_){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=z.read(e,g.attrName(t,"history-form"));if(W){const G=z.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 ie=g.resolveSelectorTargets(e,G,W);if(ie.length>0)switch(W){case"reset-before":r.resetBeforeFragments=ie;break;case"reset":r.resetFragments=ie;break;case"refetch":r.refetchFragments=ie;break;case"click":r.clickFragments=ie,r.clickAwait=e.hasAttribute(`${G}-await`);break;case"copy":r.copyFragments=ie;break;case"open":r.openFragments=ie;break;case"close":r.closeFragments=ie;break;case"error-click":r.errorClickFragments=ie,r.errorClickAwait=e.hasAttribute(`${G}-await`);break;case"error-close":r.errorCloseFragments=ie;break}}),t!=="poll"&&(r.errorStatusActions=g.readErrorStatusActions(e,r,t));const ce=g.attrName(t,"copy-source");if(e.hasAttribute(ce)){const W=z.read(e,ce);if(W){const G=z.query(W,ce);if(G!==null){const ie=D.get(G);ie?r.copySourceFragment=ie:m.error("Haori",`Element is not managed by Haori: ${W} (${ce})`)}else m.error("Haori",`Element not found: ${W} (${ce})`)}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 k=z.read(e,g.attrName(null,"form",!0));if(k){const H=z.query(k,g.attrName(null,"form",!0));H!==null?r.formFragment=x.getFormFragment(D.get(H)):m.error("Haori",`Form element not found: ${k} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=x.getFormFragment(e)}(!t||t==="poll")&&g.readNoMessageDeclarations(e,r,t??"fetch");const le=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(le)){const k=z.read(e,le),H=[];k?(z.queryAll(k,le).forEach(V=>{const _=D.get(V);_&&H.push(_)}),H.length===0&&m.error("Haori",`Element not found: ${k} (${le})`)):H.push(e),H.length>0&&(r.fetchStateFragments=H)}const j=t?g.attrName(t,"store-clear"):g.attrName(null,"store-clear",!0);if(e.hasAttribute(j)){const k=e.getRawAttribute(j),H=k===null?"":k.trim();if(H==="")m.error("Haori",`ストレージキーが指定されていません (${j})`);else{r.storeClearKey=H;const de=e.getRawAttribute(`${j}-type`),V=de===null?"session":de.trim();V==="local"||V==="session"?r.storeClearKind=V:(m.warn("Haori",`${j}-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"}startClipboardWrite(e){const t=this.options.targetFragment?.getAttributeEvaluation(e);if(t?.hasUnresolvedReference)return Promise.resolve(!1);const r=t?.value,i=r==null||r===!1||Number.isNaN(r)?"":String(r);if(i==="")return Promise.resolve(!1);const s=typeof navigator>"u"?void 0:navigator.clipboard;if(!s||typeof s.writeText!="function")return m.warn("Haori",`${e}: navigator.clipboard is not available (it requires a secure context such as HTTPS).`),Promise.resolve(!1);try{return s.writeText(i).then(()=>!0,n=>(m.warn("Haori",`${e}: failed to write: ${n}`),!1))}catch(n){return m.warn("Haori",`${e}: failed to write: ${n}`),Promise.resolve(!1)}}async showClipboardErrorToast(){const e=g.normalizeAttributeText(this.resolveLateAttribute("clipboard-error-toast",this.options.clipboardErrorToastMessage));if(!e)return;const t=g.toToastLevel(this.resolveLateAttribute("clipboard-error-toast-level",this.options.clipboardErrorToastLevel));await be().toast(e,t??"info")}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;let t;if(this.options.runScript){const A=this.options.targetFragment?.getTarget()??null;try{t=this.options.runScript.call(A,this.domEvent),t===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(w){m.error("Haori",`Run script execution error: ${w}`)}}const r=this.options.clipboardAttrName?this.startClipboardWrite(this.options.clipboardAttrName):null;if(t!=null&&typeof t.then=="function")try{await t}catch(A){m.error("Haori",`Run script execution error: ${A}`)}if(r&&!await r)return await this.commitEditOnStop(),await this.showClipboardErrorToast(),!1;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(A=>x.reset(A,this.operationSequence))),this.captureHistorySnapshots());const s=this.prepareFetchRequest();if(s.payloadTransformFailed)return await this.commitEditOnStop(),!1;this.requestUserEditSequence=R.currentSequence();const n=s.payload,a=Object.keys(s.sentPayload).length>0?s.sentPayload:void 0;let o=s.url,l=s.options,u=!1,d=!1;if(this.options.beforeCallback){const A=this.options.beforeCallback(o||null,l||null);if(A!=null){if(A===!1||typeof A=="object"&&A.stop)return!1;typeof A=="object"&&(u="fetchUrl"in A,d="fetchOptions"in A,o=u?A.fetchUrl:o,l=d?A.fetchOptions:l)}}const y=Object.keys(n).length>0;if(o){this.isInputEditProcedure()&&await this.commitFormValues(this.options.formFragment,n,e);const A=(l?.method||"GET").toUpperCase(),$=!u&&d&&s.transportMode==="query-get"&&Nr(l)&&!Xe(A)?s.baseUrl??o:o,M=Ir($,l);o=M.url;const ne={...M.options},F=M.normalized?M.requestedMethod:s.requestedMethod,Z=M.effectiveMethod,ee=s.transportMode==="query-get"||M.normalized,oe=M.queryString??s.queryString;if(ee&&m.info("Haori demo fetch normalization",{runtime:c.runtime,requestedMethod:F,effectiveMethod:Z,transportMode:"query-get",url:o,payload:a,queryString:oe}),this.options.targetFragment&&o){const K=performance.now(),le={runtime:c.runtime,requestedMethod:F,effectiveMethod:Z,transportMode:ee?"query-get":"http",...ee?{queryString:oe}:{}};return O.fetchStart(this.options.targetFragment.getTarget(),o,ne,a,le),await this.injectFetchState("loading"),await g.invokeFetch(o,ne).then(j=>this.handleFetchResult(j,o||void 0,K)).catch(async j=>{throw o&&O.fetchError(this.options.targetFragment.getTarget(),o,j),await this.injectFetchState("error",null,j instanceof Error?j.message:String(j)),await this.runErrorActions(null),j})}return await fetch(o,ne).then(K=>this.handleFetchResult(K,o||void 0))}(!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&y&&await this.commitFormValues(this.options.formFragment,n,e),this.suppressEmptyReplaceBind=!y&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const b=y?nt(n):{},E=new Response(JSON.stringify(b),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(E)}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=nt(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(st))return!1;const r=t.hasAttribute(`${c.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(st,""),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(st),!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(){Be=null}async prepareDownloadFolder(){if(Be)return this.downloadFolder=Be,"ready";const e=globalThis.showDirectoryPicker;if(typeof e!="function")return m.info("Haori","この環境では保存先のフォルダを選ばせられないため、今までどおり保存します。"),"fallback";try{const t=await e.call(globalThis,{mode:"readwrite"});return Be=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>=Rr&&(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 be().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,Be=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=be();await r.clearMessages(t),e&&await r.addErrorMessage(t,Yt)}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=be();if(!e.ok){if(Gt(e.status,{element:this.options.targetFragment.getTarget(),attrPrefix:g.attrName(this.eventType,"",!0)}))return!1;this.options.targetFragment&&t&&O.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,w=await this.handleFetchError(A?e.clone():e,E?.noMessage!==!0&&!A);return A&&await this.bindResult(e).catch($=>{m.error("Haori","Failed to bind the error response:",$)}),await this.injectFetchState("error",e.status,e.statusText||null,w),await this.runErrorActions(e.status),!1}if(this.options.targetFragment&&t&&r&&O.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,Yt),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&&z.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 $=new URLSearchParams(window.location.search).get(A);if($!==null){const M=$.trim();Le.isSafeLocalPath(M)?E=M:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${$}`)}}Le.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&&Oe.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=be(),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?(B.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({[Sr]:!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 be().clearMessages(i);const s=async u=>{const d=r?r.getTarget():document.body;await be().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,w=E.message,$=typeof A=="string"&&A.length>0?A:null,M=typeof w=="string"?w:w!=null?String(w):"";if(M.length===0)continue;if($!==null){const ne=y.get($)??[];ne.push(M),y.set($,ne)}else b.push(M)}else typeof E=="string"&&E.length>0&&b.push(E);for(const[E,A]of y)d.push({key:E,message:A.join(`
33
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
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=re.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):ve().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=re.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 w=E[y],M=w!==null&&typeof w=="object"&&!Array.isArray(w)?w:{};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=>{O.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]:we(u,n)}}return we(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:we(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]:we(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:we(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Je(this.options.copySourceFragment):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Je(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}}transformPayload(e,t){const r=re.evaluateDetailed(e,{payload:t});if(r.unresolvedReference)return null;const i=r.value;return i===null||typeof i!="object"||Array.isArray(i)?(m.error("Haori","payload-transform must return an object: "+e),null):i}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,sentPayload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=t;if(this.options.payloadTransform){const y=this.transformPayload(this.options.payloadTransform,t);if(y===null)return{url:null,baseUrl:null,options:null,payload:t,sentPayload:t,payloadTransformFailed:!0,hasUnresolvedReference:!1,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};i=y}let s=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},a=new Headers(n.headers||void 0),o=(n.method||"GET").toUpperCase(),l=c.runtime==="demo"&&!Xe(o),u=l?"GET":o;if(n.method=u,Object.keys(i).length>0&&Ue(i)){const y=a.get("Content-Type")||"";!Xe(o)&&/multipart\/form-data/i.test(y)?Cr(i)&&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(u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(i).length>0&&(s=Jt(s,i));else if(Object.keys(i).length>0){const y=a.get("Content-Type")||"";if(/multipart\/form-data/i.test(y)){a.delete("Content-Type");const b=new FormData;for(const[E,A]of Object.entries(i))A==null?b.append(E,""):A instanceof Blob?b.append(E,A):Array.isArray(A)?A.forEach(w=>{w instanceof Blob?b.append(E,w):b.append(E,Fe(w))}):b.append(E,Fe(A));n.body=b}else if(/application\/x-www-form-urlencoded/i.test(y)){const b=new URLSearchParams;for(const[E,A]of Object.entries(i))A!==void 0&&(Array.isArray(A)?A.forEach(w=>b.append(E,Fe(w))):b.append(E,Fe(A)));n.body=b}else a.set("Content-Type","application/json"),n.body=JSON.stringify(i)}n.headers=a;let d;return l&&(d=new URL(s,window.location.href).search||void 0,a.delete("Content-Type")),{url:s,baseUrl:this.options.fetchUrl,options:n,payload:t,sentPayload:i,hasUnresolvedReference:!1,requestedMethod:o,effectiveMethod:u,queryString:d,transportMode:l?"query-get":"http",signature:$r(s,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Je(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 Je(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=z.read(t,r);if(i!==null&&i.trim()!==""){const n=z.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 he=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){Gt(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 ue&&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=he.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 he(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`,""),O.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`),O.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 ue&&l.push(h.evaluateText(u))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),O.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 ue&&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(Oe.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=Le.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&&(O.bindChange(e,b,E,"manual"),Oe.mirror(i));const A=()=>{i.markBindingWorkStart();const w=i.getRawBindingData()??E;let M=a?i.setAttribute(`${c.prefix}bind`,JSON.stringify(h.withoutReservedBindingKeys(w))):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(y))return;const $=i.getRawBindingData()??E;return x.syncValues(i,x.resolveSyncValues(i,$),!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(),$=>{throw i.markBindingWorkEnd(),$})};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(w=>!Object.prototype.hasOwnProperty.call(y,w));const A=new Set([...Object.keys(d),...Object.keys(y)]);for(const w of A){const M=s===""?w:`${s}.${w}`,$=h.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(d,w)?d[w]:h.ABSENT_PATH,Object.prototype.hasOwnProperty.call(y,w)?y[w]:h.ABSENT_PATH,i,M,n);$!==h.ABSENT_PATH&&(b[w]=$),$!==(Object.prototype.hasOwnProperty.call(y,w)?y[w]: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 B.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 ue)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 ue&&!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=re.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(re.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 ue&&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))B.isEnabled()&&e.isVisible()&&h.logFalsyIfDiagnostics(e),r.push(e.hide().then(()=>{O.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 ue&&!(s&&t.has(l))&&a.push(h.evaluateText(l))}),r.push(e.show().then(()=>{O.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 he(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(B.isEnabled()&&re.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 (
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=re.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):be().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=re.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 w=E[y],$=w!==null&&typeof w=="object"&&!Array.isArray(w)?w:{};A[y]=this.mergeAppendBindingData(o,i,$)}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=>{O.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]:we(u,n)}}return we(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:we(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]:we(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:we(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Je(this.options.copySourceFragment):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Je(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}}transformPayload(e,t){const r=re.evaluateDetailed(e,{payload:t});if(r.unresolvedReference)return null;const i=r.value;return i===null||typeof i!="object"||Array.isArray(i)?(m.error("Haori","payload-transform must return an object: "+e),null):i}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,sentPayload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=t;if(this.options.payloadTransform){const y=this.transformPayload(this.options.payloadTransform,t);if(y===null)return{url:null,baseUrl:null,options:null,payload:t,sentPayload:t,payloadTransformFailed:!0,hasUnresolvedReference:!1,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};i=y}let s=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},a=new Headers(n.headers||void 0),o=(n.method||"GET").toUpperCase(),l=c.runtime==="demo"&&!Xe(o),u=l?"GET":o;if(n.method=u,Object.keys(i).length>0&&Ue(i)){const y=a.get("Content-Type")||"";!Xe(o)&&/multipart\/form-data/i.test(y)?Cr(i)&&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(u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(i).length>0&&(s=Jt(s,i));else if(Object.keys(i).length>0){const y=a.get("Content-Type")||"";if(/multipart\/form-data/i.test(y)){a.delete("Content-Type");const b=new FormData;for(const[E,A]of Object.entries(i))A==null?b.append(E,""):A instanceof Blob?b.append(E,A):Array.isArray(A)?A.forEach(w=>{w instanceof Blob?b.append(E,w):b.append(E,Fe(w))}):b.append(E,Fe(A));n.body=b}else if(/application\/x-www-form-urlencoded/i.test(y)){const b=new URLSearchParams;for(const[E,A]of Object.entries(i))A!==void 0&&(Array.isArray(A)?A.forEach(w=>b.append(E,Fe(w))):b.append(E,Fe(A)));n.body=b}else a.set("Content-Type","application/json"),n.body=JSON.stringify(i)}n.headers=a;let d;return l&&(d=new URL(s,window.location.href).search||void 0,a.delete("Content-Type")),{url:s,baseUrl:this.options.fetchUrl,options:n,payload:t,sentPayload:i,hasUnresolvedReference:!1,requestedMethod:o,effectiveMethod:u,queryString:d,transportMode:l?"query-get":"http",signature:Mr(s,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Je(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 Je(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=z.read(t,r);if(i!==null&&i.trim()!==""){const n=z.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 he=g;class $r{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){Gt(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 ue&&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=he.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 he(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`,""),O.importStart(t,s),$r.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`),O.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 ue&&l.push(h.evaluateText(u))}),Promise.all(l).then(()=>{})})}).catch(a=>{t.removeAttribute(`${c.prefix}importing`),O.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 ue&&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(Oe.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=Le.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&&(O.bindChange(e,b,E,"manual"),Oe.mirror(i));const A=()=>{i.markBindingWorkStart();const w=i.getRawBindingData()??E;let $=a?i.setAttribute(`${c.prefix}bind`,JSON.stringify(h.withoutReservedBindingKeys(w))):Promise.resolve();return e.tagName==="FORM"&&($=$.then(()=>{if(i.wasResetAfter(y))return;const M=i.getRawBindingData()??E;return x.syncValues(i,x.resolveSyncValues(i,M),!1,u)})),$=$.then(()=>x.syncAncestorArgForms(i,y,u,b)),$=$.then(()=>h.evaluateAll(i,s)),$=$.then(()=>R.retryUnappliedValueWrites(e,y)),$=$.then(()=>h.reevaluateReactiveSpecialAttributes(i,s)),$.then(()=>i.markBindingWorkEnd(),M=>{throw i.markBindingWorkEnd(),M})};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(w=>!Object.prototype.hasOwnProperty.call(y,w));const A=new Set([...Object.keys(d),...Object.keys(y)]);for(const w of A){const $=s===""?w:`${s}.${w}`,M=h.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(d,w)?d[w]:h.ABSENT_PATH,Object.prototype.hasOwnProperty.call(y,w)?y[w]:h.ABSENT_PATH,i,$,n);M!==h.ABSENT_PATH&&(b[w]=M),M!==(Object.prototype.hasOwnProperty.call(y,w)?y[w]: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 B.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 ue)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 ue&&!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=re.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(re.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 ue&&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))B.isEnabled()&&e.isVisible()&&h.logFalsyIfDiagnostics(e),r.push(e.hide().then(()=>{O.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 ue&&!(s&&t.has(l))&&a.push(h.evaluateText(l))}),r.push(e.show().then(()=>{O.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 he(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(B.isEnabled()&&re.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
36
  ${i}
37
37
  );`)}catch{try{s=new Function(`"use strict";
38
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 ue?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 ue){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=re.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(!B.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 ue&&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 ue?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,Z)=>h.createListKey(F,s?String(s):null,Z)),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,Z)=>{const ee=String(F.getListKey()),oe=l.get(ee)??0;if(oe===0){b.add(F);const K=F.getListKey();return K!==null&&O.rowRemove(F.getTarget(),K,Z),u.push(F.remove()),!1}return l.set(ee,oe-1),!0});const E=d.map(F=>F.getListKey()),A=new Map;d.forEach(F=>{const Z=F.getListKey();if(Z===null)return;const ee=A.get(Z);ee?ee.push(F):A.set(Z,[F])});const w=e.getChildElementFragments().filter(F=>!b.has(F)),M=w.filter(F=>F.hasAttribute(`${c.prefix}each-before`)).length;let $=Promise.resolve();const ne=[];return a.forEach((F,Z)=>{const ee=t[Z],oe=Z;let K;const le=A.get(F)?.shift();if(le){K=le;const j=M+Z;$=$.then(()=>h.updateRowFragment(K,ee,i,oe,n?String(n):null,F).then(k=>h.repositionEachRow(e,K,w,j).then(H=>{H!==null&&O.rowMove(K.getTarget(),F,H-M,Z),!(!k&&h.isRowLocalEachTemplate(e))&&ne.push(h.evaluateAll(K,k?new Set:h.collectRowLocalFragments(e,K)).then(()=>h.applyRowFormValues(e,K,ee)))})))}else{K=r.clone();const j=M+Z;$=$.then(()=>h.updateRowFragment(K,ee,i,oe,n?String(n):null,F).then(()=>{const k=w[j]??null;return e.insertBefore(K,k).then(()=>{w.splice(j,0,K)}).then(()=>h.initializeFreshEachRow(K)).then(()=>h.applyRowFormValues(e,K,ee)).then(()=>{O.rowAdd(K.getTarget(),F,oe,ee)})}))}}),Promise.all(u).then(()=>$).then(()=>Promise.all(ne)).then(()=>{const F=a.filter(j=>j!==null),Z=E.filter(j=>j!==null),ee=new Set(Z),oe=F.filter(j=>!ee.has(j)),le=y.filter(j=>j!==null).filter(j=>!o.has(j));O.eachUpdate(e.getTarget(),oe,le,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){!B.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 Me=class Me{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[Me.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=D.get(e);t&&new he(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(Me.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 he(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=z.read(e,r),s=t.target;return i===null||!(s instanceof Node)?!1:z.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 he(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){he.recordClickOutcome(e,n);const a=r.target;a instanceof HTMLElement&&a!==e&&he.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}};Me.HISTORY_STATE_KEY="__haoriHistoryState__",Me.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let at=Me;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 he(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=z.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 Ce=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 he(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&&O.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&&O.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=z.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 $e=S;const _t="0.66.0";function Pr(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=z.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,Pr(()=>{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 Se=L;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),R.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new at;U._dispatcher=e,e.startDeferred(),U._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 U.waitInitialIntakes(),await Y.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ce.syncTree(document.body),$e.syncTree(document.body),Se.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}O.ready(_t)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._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=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.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=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(s=>!U.isBindAttributeRecord(s));r.length>0&&U.processMutations(r,R.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.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(U.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(Ee)&&(r.attributeName==="disabled"||r.attributeName===Ee))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);U._initialIntakes?.push(s),Ce.syncElement(i),$e.syncElement(i),Se.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ce.cleanupTree(i),$e.cleanupTree(i),Se.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);U._initialIntakes?.push(s),Ce.syncTree(i),$e.syncTree(i),Se.syncTree(i)}),r.target instanceof Element&&Se.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)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let He=U;se.setMutationCapture(f=>He.captureMutations(f)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Lr=()=>fe.waitForRenders(),Or=fe.enhancers,Br=fe.handlers,Ur=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:se,Env:c,Form:x,Fragment:D,Haori:fe,Log:m,Queue:Y,default:fe,enhancers:Or,handlers:Br,version:_t,waitForRenders:Lr},Symbol.toStringTag,{value:"Module"})),ot=fe;for(const[f,e]of Object.entries(Ur))f in ot||Object.defineProperty(ot,f,{value:e,writable:!0,enumerable:!0,configurable:!0});return ot}();
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 ue?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 ue){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=re.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(!B.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 ue&&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 ue?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,Z)=>h.createListKey(F,s?String(s):null,Z)),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,Z)=>{const ee=String(F.getListKey()),oe=l.get(ee)??0;if(oe===0){b.add(F);const K=F.getListKey();return K!==null&&O.rowRemove(F.getTarget(),K,Z),u.push(F.remove()),!1}return l.set(ee,oe-1),!0});const E=d.map(F=>F.getListKey()),A=new Map;d.forEach(F=>{const Z=F.getListKey();if(Z===null)return;const ee=A.get(Z);ee?ee.push(F):A.set(Z,[F])});const w=e.getChildElementFragments().filter(F=>!b.has(F)),$=w.filter(F=>F.hasAttribute(`${c.prefix}each-before`)).length;let M=Promise.resolve();const ne=[];return a.forEach((F,Z)=>{const ee=t[Z],oe=Z;let K;const le=A.get(F)?.shift();if(le){K=le;const j=$+Z;M=M.then(()=>h.updateRowFragment(K,ee,i,oe,n?String(n):null,F).then(k=>h.repositionEachRow(e,K,w,j).then(H=>{H!==null&&O.rowMove(K.getTarget(),F,H-$,Z),!(!k&&h.isRowLocalEachTemplate(e))&&ne.push(h.evaluateAll(K,k?new Set:h.collectRowLocalFragments(e,K)).then(()=>h.applyRowFormValues(e,K,ee)))})))}else{K=r.clone();const j=$+Z;M=M.then(()=>h.updateRowFragment(K,ee,i,oe,n?String(n):null,F).then(()=>{const k=w[j]??null;return e.insertBefore(K,k).then(()=>{w.splice(j,0,K)}).then(()=>h.initializeFreshEachRow(K)).then(()=>h.applyRowFormValues(e,K,ee)).then(()=>{O.rowAdd(K.getTarget(),F,oe,ee)})}))}}),Promise.all(u).then(()=>M).then(()=>Promise.all(ne)).then(()=>{const F=a.filter(j=>j!==null),Z=E.filter(j=>j!==null),ee=new Set(Z),oe=F.filter(j=>!ee.has(j)),le=y.filter(j=>j!==null).filter(j=>!o.has(j));O.eachUpdate(e.getTarget(),oe,le,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){!B.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 $e=class $e{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[$e.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=D.get(e);t&&new he(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($e.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 he(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=z.read(e,r),s=t.target;return i===null||!(s instanceof Node)?!1:z.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 he(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){he.recordClickOutcome(e,n);const a=r.target;a instanceof HTMLElement&&a!==e&&he.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}};$e.HISTORY_STATE_KEY="__haoriHistoryState__",$e.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let at=$e;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 he(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=z.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 Ce=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 he(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&&O.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&&O.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=z.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 Me=S;const _t="0.67.0";function Pr(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=z.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,Pr(()=>{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 Se=L;const U=class U{static disconnectMutationObservers(){U._mutationObservers.forEach(e=>{e.disconnect()}),U._mutationObservers.length=0}static async init(){if(U._initialized)return;U._initialized=!0,U.disconnectMutationObservers(),R.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new at;U._dispatcher=e,e.startDeferred(),U._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 U.waitInitialIntakes(),await Y.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),Ce.syncTree(document.body),Me.syncTree(document.body),Se.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}O.ready(_t)}static getDispatcher(){return U._dispatcher}static async waitInitialIntakes(){const e=U._initialIntakes;for(;e!==null&&e.length>0;)await Promise.allSettled(e.splice(0))}static captureMutations(e){if(U._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=>U.toCapturedRecord(i));t.disconnect(),U.processMutations(r)}}static toCapturedRecord(e){return e.type!=="childList"?e:{type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes).filter(t=>!U.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=>{U.processMutations(r)});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),U._mutationObservers.push(t)}static flushPendingMutations(){for(const e of U._mutationObservers){const t=e.takeRecords();if(t.length===0)continue;const r=t.filter(U.isBindAttributeRecord),i=t.filter(s=>!U.isBindAttributeRecord(s));r.length>0&&U.processMutations(r,R.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.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(U.isExternallyManaged(r.target))continue;switch(r.type){case"attributes":{const i=r.target;if(r.attributeName&&i.hasAttribute("data-haori-click-lock")&&(r.attributeName==="disabled"||r.attributeName==="data-haori-click-lock")||r.attributeName&&i.hasAttribute(Ae)&&(r.attributeName==="disabled"||r.attributeName===Ae))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);U._initialIntakes?.push(s),Ce.syncElement(i),Me.syncElement(i),Se.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(Ce.cleanupTree(i),Me.cleanupTree(i),Se.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const s=C.addNode(i.parentElement,i);U._initialIntakes?.push(s),Ce.syncTree(i),Me.syncTree(i),Se.syncTree(i)}),r.target instanceof Element&&Se.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)}}};U._initialized=!1,U._mutationObservers=[],U._dispatcher=null,U._initialIntakes=null;let He=U;se.setMutationCapture(f=>He.captureMutations(f)),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",He.init):He.init();const Lr=()=>fe.waitForRenders(),Or=fe.enhancers,Br=fe.handlers,Ur=Object.freeze(Object.defineProperty({__proto__:null,Core:C,Enhance:se,Env:c,Form:x,Fragment:D,Haori:fe,Log:m,Queue:Y,default:fe,enhancers:Or,handlers:Br,version:_t,waitForRenders:Lr},Symbol.toStringTag,{value:"Module"})),ot=fe;for(const[f,e]of Object.entries(Ur))f in ot||Object.defineProperty(ot,f,{value:e,writable:!0,enumerable:!0,configurable:!0});return ot}();
41
41
  //# sourceMappingURL=haori.iife.js.map