haori 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/haori.cjs.js +3 -3
- package/dist/haori.es.js +105 -52
- package/dist/haori.iife.js +10 -10
- package/dist/index.d.ts +37 -4
- package/package.json +1 -1
package/README.ja.md
CHANGED
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
|
|
4
4
|
|
|
5
|
-
Version: 0.
|
|
5
|
+
Version: 0.52.0
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
package/dist/haori.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=class be{static isEnabled(){return be.devMode}static enable(){be.devMode=!0}static disable(){be.devMode=!1}static set(e){be.devMode=e}};be.devMode=!1;let V=be;const Oe="embedded";function Ze(b){return b==="embedded"||b==="demo"}function bt(b){return b===null?null:Ze(b)?b:Oe}const ee=class ee{static get strictBind(){return ee._strictBind}static setStrictBind(e){ee._strictBind=e}static get runtime(){return ee._runtime}static setRuntime(e){ee._runtime=Ze(e)?e:Oe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||ee._prefix;ee._prefix=r.endsWith("-")?r:r+"-";const i=bt(e.getAttribute("data-runtime"));i!==null&&(ee._runtime=i),ee._strictBind=e.hasAttribute(`${ee._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${ee._prefix}dev`)){const r=(e.getAttribute(`${ee._prefix}dev`)??"").trim().toLowerCase();V.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){V.set(!0);return}V.set(!1)}catch{}}static get prefix(){return ee._prefix}};ee._prefix="data-",ee._runtime=Oe,ee._strictBind=!1;let l=ee;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){V.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){V.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const Et=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,je="new:",k=class k{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}k.enhancers.set(r,t),k.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&k.forEachTarget(document.body,i=>{k.visited.has(i)&&k.applyElement(i)})}static setMutationCapture(e){k.mutationCapture=e}static has(e){return k.enhancers.has(e)}static applySubtree(e){k.forEachTarget(e,t=>{k.visited.add(t),k.applyElement(t)})}static isApplied(e){return(k.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){k.forEachTarget(e,r=>{k.refreshElement(r,t)})}static destroySubtree(e){k.forEachTarget(e,t=>{k.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){const t=k.instances.get(e)??null;k.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=k.enhancers.get(r);if(!i){k.warnUnknownName(r);return}k.run(`enhance "${r}"`,()=>{const n=i.init(e);k.appliedKeys(e).set(r,n)})}),k.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${je}${r}`;if(k.instances.get(e)?.has(i))return;const n=k.resolveGlobal(r);n!==null&&k.run(`enhance-new "${r}"`,()=>{const s=new n(e);k.appliedKeys(e).set(i,s)})})}static refreshElement(e,t){const r=k.instances.get(e);k.names(e,`${l.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const n=k.enhancers.get(i);!n||typeof n.refresh!="function"||k.run(`enhance "${i}" refresh`,()=>{n.refresh(e,r.get(i))})}),t&&k.applyElement(e)}static destroyElement(e){const t=k.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(je))return;const n=k.enhancers.get(i);!n||typeof n.destroy!="function"||k.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),k.instances.delete(e))}static appliedKeys(e){const t=k.instances.get(e);if(t)return t;const r=new Map;return k.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(!Et.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(V.isEnabled()&&!k.warnedMissingGlobals.has(e)&&(k.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!V.isEnabled()||k.warnedUnknownNames.has(e)||(k.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)}};k.mutationCapture?k.mutationCapture(r):r()}};k.enhancers=new Map,k.instances=new WeakMap,k.warnedUnknownNames=new Set,k.warnedMissingGlobals=new Set,k.visited=new WeakSet,k.mutationCapture=null;let te=k;const Qe="yyyy/MM/dd HH:mm",At="en-US",Ke=1e4;function de(b){return String(b).padStart(2,"0")}function _e(b,e,t,r,i,n){return{yyyy:String(b).padStart(4,"0"),yy:de(b%100),MM:de(e),M:String(e),dd:de(t),d:String(t),HH:de(r),H:String(r),mm:de(i),ss:de(n)}}function et(b,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(b)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:_e(i,n,s,a,o,c)}function $e(b,e=Qe,t){if(b==null||b==="")return"";const r=b instanceof Date?b:new Date(b);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=et(r,t.trim()),i===null)return""}else i=_e(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}const vt="yyyy-MM-dd";function tt(b=Qe,e){return $e(new Date,b,e)}function rt(b=0,e=vt,t){const r=Number.isFinite(b)?Math.trunc(b):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=et(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return $e(o,e,"UTC")}function it(b,e){if(b==null)return"";let t;if(typeof b=="number")t=b;else{const i=String(b).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(At,r).format(t)}function nt(b,e,t){let r,i,n;if(e===void 0?(r=0,i=b,n=1):(r=b,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<Ke;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ke;a+=n)s.push(a);return s}function st(b,e,t={}){const r=Math.trunc(Number(b));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,p)=>d-p),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const p=u+1;c.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const St=/^(\d{4})-(\d{1,2})$/,wt=1200;function Fe(b,e){const t=Number(b);return Number.isFinite(t)?Math.trunc(t):e}function Pe(b,e){if(typeof b!="string")return"";const t=St.exec(b.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${de(o)}`}function Rt(b){if(typeof b=="string"&&b.trim()!=="")return Pe(b,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${de(e.getMonth()+1)}`}function at(b,e){const t=Math.trunc(Number(b));if(!Number.isFinite(t)||t<0)return[];const r=Rt(e);if(r==="")return[];const i=Math.min(t,wt),n=[];for(let s=0;s<=i;s+=1){const a=Pe(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function ot(b,e){const t={start:0,end:0,total:0,empty:!0};if(!b||typeof b!="object")return t;const r=b,i=Fe(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,Fe(r.number,0)),s=Math.max(0,Fe(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=Fe(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function lt(b,e,t){if(!Array.isArray(b)||b.length===0)return null;const r=String(t),i=b.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function ct(b,e){if(!Array.isArray(b))return 0;let t=0;for(const r of b){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ut(b,e){return e==null||b==null?String(b):String(b[e])}function dt(b,e){if(!Array.isArray(b))return[];const t=new Set,r=[];for(const i of b){const n=ut(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function ft(b,e){if(!Array.isArray(b))return[];const t=new Map,r=[];for(const i of b){const n=ut(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const Tt=Object.freeze({date:$e,now:tt,today:rt,number:it,pages:st,range:nt,monthAdd:Pe,monthRange:at,pageSummary:ot,findBy:lt,sum:ct,distinct:dt,groupBy:ft});class Ve{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Ve.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const We=class We{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};We.ASYNC_QUEUE=new Ve;let K=We;const T=class T{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,T.readStorageSafely(()=>e.localStorage),T.readStorageSafely(()=>e.sessionStorage),e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!V.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const be=class be{static isEnabled(){return be.devMode}static enable(){be.devMode=!0}static disable(){be.devMode=!1}static set(e){be.devMode=e}};be.devMode=!1;let V=be;const Oe="embedded";function Ze(b){return b==="embedded"||b==="demo"}function bt(b){return b===null?null:Ze(b)?b:Oe}const ee=class ee{static get strictBind(){return ee._strictBind}static setStrictBind(e){ee._strictBind=e}static get runtime(){return ee._runtime}static setRuntime(e){ee._runtime=Ze(e)?e:Oe}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||ee._prefix;ee._prefix=r.endsWith("-")?r:r+"-";const i=bt(e.getAttribute("data-runtime"));i!==null&&(ee._runtime=i),ee._strictBind=e.hasAttribute(`${ee._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${ee._prefix}dev`)){const r=(e.getAttribute(`${ee._prefix}dev`)??"").trim().toLowerCase();V.set(r!=="false"&&r!=="off"&&r!=="0");return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){V.set(!0);return}V.set(!1)}catch{}}static get prefix(){return ee._prefix}};ee._prefix="data-",ee._runtime=Oe,ee._strictBind=!1;let l=ee;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class m{static info(e,...t){V.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){V.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const Et=/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/,je="new:",k=class k{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}k.enhancers.set(r,t),k.warnedUnknownNames.delete(r),typeof document<"u"&&document.body&&k.forEachTarget(document.body,i=>{k.visited.has(i)&&k.applyElement(i)})}static setMutationCapture(e){k.mutationCapture=e}static has(e){return k.enhancers.has(e)}static applySubtree(e){k.forEachTarget(e,t=>{k.visited.add(t),k.applyElement(t)})}static isApplied(e){return(k.instances.get(e)?.size??0)>0}static refreshSubtree(e,t=!0){k.forEachTarget(e,r=>{k.refreshElement(r,t)})}static destroySubtree(e){k.forEachTarget(e,t=>{k.destroyElement(t)})}static forEachTarget(e,t){if(!e||typeof e.querySelectorAll!="function")return;const r=`[${l.prefix}enhance],[${l.prefix}enhance-new]`;typeof e.matches=="function"&&e.matches(r)&&t(e),e.querySelectorAll(r).forEach(i=>{t(i)})}static applyElement(e){if(e.closest(`[${l.prefix}if-false]`))return;const t=k.instances.get(e)??null;k.names(e,`${l.prefix}enhance`).forEach(r=>{if(t?.has(r))return;const i=k.enhancers.get(r);if(!i){k.warnUnknownName(r);return}k.run(`enhance "${r}"`,()=>{const n=i.init(e);k.appliedKeys(e).set(r,n)})}),k.names(e,`${l.prefix}enhance-new`).forEach(r=>{const i=`${je}${r}`;if(k.instances.get(e)?.has(i))return;const n=k.resolveGlobal(r);n!==null&&k.run(`enhance-new "${r}"`,()=>{const s=new n(e);k.appliedKeys(e).set(i,s)})})}static refreshElement(e,t){const r=k.instances.get(e);k.names(e,`${l.prefix}enhance`).forEach(i=>{if(!r||!r.has(i))return;const n=k.enhancers.get(i);!n||typeof n.refresh!="function"||k.run(`enhance "${i}" refresh`,()=>{n.refresh(e,r.get(i))})}),t&&k.applyElement(e)}static destroyElement(e){const t=k.instances.get(e);t&&(t.forEach((r,i)=>{if(i.startsWith(je))return;const n=k.enhancers.get(i);!n||typeof n.destroy!="function"||k.run(`enhance "${i}" destroy`,()=>{n.destroy(e,r)})}),k.instances.delete(e))}static appliedKeys(e){const t=k.instances.get(e);if(t)return t;const r=new Map;return k.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(!Et.test(e))return m.error("[Haori]",`${l.prefix}enhance-new accepts a dot-separated global reference only: ${e}`),null;let t=globalThis;for(const r of e.split(".")){if(t===null||typeof t!="object"){t=void 0;break}if(t=t[r],t===void 0)break}return typeof t!="function"?(V.isEnabled()&&!k.warnedMissingGlobals.has(e)&&(k.warnedMissingGlobals.add(e),m.warn("[Haori]",`${l.prefix}enhance-new could not resolve the global reference (load the library before Haori runs): ${e}`)),null):t}static warnUnknownName(e){!V.isEnabled()||k.warnedUnknownNames.has(e)||(k.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)}};k.mutationCapture?k.mutationCapture(r):r()}};k.enhancers=new Map,k.instances=new WeakMap,k.warnedUnknownNames=new Set,k.warnedMissingGlobals=new Set,k.visited=new WeakSet,k.mutationCapture=null;let te=k;const Qe="yyyy/MM/dd HH:mm",At="en-US",Ke=1e4;function de(b){return String(b).padStart(2,"0")}function _e(b,e,t,r,i,n){return{yyyy:String(b).padStart(4,"0"),yy:de(b%100),MM:de(e),M:String(e),dd:de(t),d:String(t),HH:de(r),H:String(r),mm:de(i),ss:de(n)}}function et(b,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(b)}catch{return null}const r={};for(const u of t)u.type!=="literal"&&(r[u.type]=u.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),c=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(c)?null:_e(i,n,s,a,o,c)}function $e(b,e=Qe,t){if(b==null||b==="")return"";const r=b instanceof Date?b:new Date(b);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=et(r,t.trim()),i===null)return""}else i=_e(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}const vt="yyyy-MM-dd";function tt(b=Qe,e){return $e(new Date,b,e)}function rt(b=0,e=vt,t){const r=Number.isFinite(b)?Math.trunc(b):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const c=et(new Date,i);if(c===null)return"";n=Number(c.yyyy),s=Number(c.MM),a=Number(c.dd)}else{const c=new Date;n=c.getFullYear(),s=c.getMonth()+1,a=c.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return $e(o,e,"UTC")}function it(b,e){if(b==null)return"";let t;if(typeof b=="number")t=b;else{const i=String(b).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(At,r).format(t)}function nt(b,e,t){let r,i,n;if(e===void 0?(r=0,i=b,n=1):(r=b,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<Ke;a+=n)s.push(a);else for(let a=r;a>i&&s.length<Ke;a+=n)s.push(a);return s}function st(b,e,t={}){const r=Math.trunc(Number(b));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let d=0;d<s&&d<r;d+=1)a.add(d);for(let d=Math.max(0,r-s);d<r;d+=1)a.add(d);for(let d=Math.max(0,i-n);d<=Math.min(r-1,i+n);d+=1)a.add(d);const o=Array.from(a).sort((d,p)=>d-p),c=[];let u=null;for(const d of o){if(u!==null&&d-u>1)if(d-u===2){const p=u+1;c.push({page:p,label:p+1,active:p===i,ellipsis:!1})}else c.push({page:null,label:"…",active:!1,ellipsis:!0});c.push({page:d,label:d+1,active:d===i,ellipsis:!1}),u=d}return c}const St=/^(\d{4})-(\d{1,2})$/,wt=1200;function Fe(b,e){const t=Number(b);return Number.isFinite(t)?Math.trunc(t):e}function Pe(b,e){if(typeof b!="string")return"";const t=St.exec(b.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${de(o)}`}function Rt(b){if(typeof b=="string"&&b.trim()!=="")return Pe(b,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${de(e.getMonth()+1)}`}function at(b,e){const t=Math.trunc(Number(b));if(!Number.isFinite(t)||t<0)return[];const r=Rt(e);if(r==="")return[];const i=Math.min(t,wt),n=[];for(let s=0;s<=i;s+=1){const a=Pe(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function ot(b,e){const t={start:0,end:0,total:0,empty:!0};if(!b||typeof b!="object")return t;const r=b,i=Fe(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,Fe(r.number,0)),s=Math.max(0,Fe(r.size,0)),a=n*s,o=Math.min(a+1,i);let c;if(e!==void 0&&Number.isFinite(e))c=Math.max(0,Math.trunc(e));else{const d=Fe(r.numberOfElements,NaN);c=Number.isFinite(d)?d:Math.min(s,i-a)}const u=Math.min(a+c,i);return{start:o,end:Math.max(u,o),total:i,empty:!1}}function lt(b,e,t){if(!Array.isArray(b)||b.length===0)return null;const r=String(t),i=b.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function ct(b,e){if(!Array.isArray(b))return 0;let t=0;for(const r of b){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function ut(b,e){return e==null||b==null?String(b):String(b[e])}function dt(b,e){if(!Array.isArray(b))return[];const t=new Set,r=[];for(const i of b){const n=ut(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function ft(b,e){if(!Array.isArray(b))return[];const t=new Map,r=[];for(const i of b){const n=ut(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const Tt=Object.freeze({date:$e,now:tt,today:rt,number:it,pages:st,range:nt,monthAdd:Pe,monthRange:at,pageSummary:ot,findBy:lt,sum:ct,distinct:dt,groupBy:ft});class Ve{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Ve.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const We=class We{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};We.ASYNC_QUEUE=new Ve;let K=We;const T=class T{static readStorageSafely(e){try{return e()}catch{return}}static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,T.readStorageSafely(()=>e.localStorage),T.readStorageSafely(()=>e.sessionStorage),e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}static hasCompileFailure(e){return this.compileFailedExpressions.has(e)}static isUsableBindingKey(e){const t=this.usableBindingKeyCache.get(e);if(t!==void 0)return t;let r=this.IDENTIFIER_NAME_PATTERN.test(e);if(r)try{new Function(e,"")}catch{r=!1}return this.usableBindingKeyCache.set(e,r),r}static reportUnusableBindingKeys(e){if(e.length===0||!V.isEnabled())return;const t=e.filter(r=>!this.loggedUnusableBindingKeys.has(r));t.length!==0&&(t.forEach(r=>this.loggedUnusableBindingKeys.add(r)),m.warn("[Haori]",`Binding key(s) that cannot be used as identifiers are excluded from expressions: ${t.join(", ")}. Read them as haori.data['key'], or use ${l.prefix}form-object to collect nested values.`))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
|
|
2
2
|
`)}static detectForbiddenIdentifiers(e){const t=this.FORBIDDEN_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.FORBIDDEN_NAME_PATTERNS.filter(i=>i.pattern.test(e)).map(i=>i.name);return this.FORBIDDEN_IDENTIFIER_CACHE.set(e,r),r}static extractFreeIdentifiers(e){const t=this.FREE_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];if(r!==null){let n=null;for(const s of r){const a=n?.value==="."||n?.value==="?.";s.type==="identifier"&&!a&&!this.NON_SHADOWABLE_IDENTIFIERS.has(s.value)&&!this.DISALLOWED_KEYWORDS.has(s.value)&&!this.STRICT_FORBIDDEN_NAMES.includes(s.value)&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s.value)&&!i.includes(s.value)&&i.push(s.value),n=s}}return this.FREE_IDENTIFIER_CACHE.set(e,i),i}static extractBoundIdentifiers(e){const t=this.BOUND_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=new Set,i=this.tokenizeExpression(e);if(i!==null){const n=new Set(["(",",","{","["]);for(let s=0;s<i.length;s+=1){if(i[s].value!=="=>")continue;const a=i[s-1];if(a===void 0)continue;if(a.type==="identifier"){r.add(a.value);continue}if(a.value!==")")continue;let o=0,c=0;for(let u=s-1;u>=0;u-=1){const d=i[u].value;if(d===")"||d==="]"||d==="}"){o+=1,d===")"&&(c+=1);continue}if(d==="("||d==="["||d==="{"){if(o-=1,d==="("&&(c-=1),o===0)break;continue}c===1&&i[u].type==="identifier"&&n.has(i[u-1]?.value??"")&&r.add(i[u].value)}}}return this.BOUND_IDENTIFIER_CACHE.set(e,r),r}static buildShadowDeclarations(e){return e.length===0?"":`
|
|
3
3
|
let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),m.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static toGuardedMemberExpression(e){const t=this.GUARDED_MEMBER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[],s=[];let a=null;for(const o of r){if(o.value==="["){const c=this.startsMemberAccess(a);s.push(c),c&&n.push({start:o.position+1,end:o.position+1,text:T.MEMBER_KEY_GUARD_OPEN})}else o.value==="]"&&s.pop()===!0&&n.push({start:o.position,end:o.position,text:")"});a=o}for(let o=n.length-1;o>=0;o-=1){const c=n[o];i=i.slice(0,c.start)+c.text+i.slice(c.end)}}return this.GUARDED_MEMBER_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(e.length!==0){if(l.strictBind){m.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}V.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,K.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),m.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static recordSuppliedIdentifiers(e){for(const t of Object.keys(e))this.suppliedIdentifiers.add(t)}static recordRowScopeIdentifiers(e){if(V.isEnabled())for(const t of e)typeof t=="string"&&t!==""&&this.rowScopeIdentifiers.add(t)}static recordScopeMissingIdentifiers(e,t){if(e.length===0){this.pendingScopeMissingIdentifiers.delete(t);return}this.pendingScopeMissingIdentifiers.set(t,new Set(e)),!this.scopeMissingReportScheduled&&(this.scopeMissingReportScheduled=!0,K.waitForIdle().then(()=>{this.scopeMissingReportScheduled=!1,this.reportScopeMissingIdentifiers()}))}static reportScopeMissingIdentifiers(){if(this.pendingScopeMissingIdentifiers.size===0)return;const e=Array.from(this.pendingScopeMissingIdentifiers.entries());this.pendingScopeMissingIdentifiers.clear();for(const[t,r]of e){const i=[];for(const n of r){if(!this.suppliedIdentifiers.has(n)||this.rowScopeIdentifiers.has(n))continue;const s=`${n}
|
|
4
4
|
${t}`;this.loggedScopeMissingIdentifiers.has(s)||(this.loggedScopeMissingIdentifiers.add(s),i.push(n))}i.length!==0&&m.warn("[Haori]",`Expression key(s) are missing from this scope but are provided in another scope: ${i.join(", ")}. A binding is visible only to the target element itself and its descendants, so bind the response to this element or one of its ancestors (data-fetch-bind / data-{event}-bind):`,t)}}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(c=>s[c]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const d=this.detectDisallowedKeywords(e);if(d.length>0){const p=d.some(y=>y==="function"||y==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";m.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+d.join(", ")+"."+p)}else m.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const d=r.join(",");this.loggedForbiddenKeySignatures.has(d)||(this.loggedForbiddenKeySignatures.add(d),this.scheduleForbiddenKeyLogReset(),m.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&m.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const d of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(d)||(a[d]=t[d]);s&&(this.BUILTIN_DATA_REFERENCE_PATTERN.test(n)?a[this.BUILTIN_NAMESPACE]={...this.BUILTIN_HELPERS,[this.BUILTIN_DATA_PROPERTY]:{...a}}:a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a),V.isEnabled()&&this.recordSuppliedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),c=this.extractFreeIdentifiers(e).filter(d=>!(d in a)&&!this.FORBIDDEN_NAMES.includes(d)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(d));if(V.isEnabled()){const d=this.extractBoundIdentifiers(e);this.recordScopeMissingIdentifiers(d.size===0?c:c.filter(p=>!d.has(p)),e)}o&&c.forEach(d=>{a[d]=void 0});const u=o?[]:c;for(let d=0;d<=this.MAX_IDENTIFIER_RECOVERY_COUNT;d+=1){const p=this.prepareEvaluator(e,a,u);if(p.compileFailed||p.evaluator===null)return{value:null,unresolvedReference:!1};try{const y=[],E=this.wrapBoundValues(a);p.bindKeys.forEach(D=>{y.push(E[D])});const A=this.withBlockedPropertyAccess(()=>p.evaluator(...y));return A===void 0&&this.warnBlockedIdentifiers(e),{value:A,unresolvedReference:A===void 0}}catch(y){if(o&&y instanceof ReferenceError){const E=this.extractMissingIdentifier(y);if(E!==null&&this.canRecoverMissingIdentifier(E,a)){a[E]=void 0;continue}}if(this.warnBlockedIdentifiers(e),y instanceof ReferenceError&&u.length>0){const E=this.evaluateAsCondition(e,a,u);return E!==void 0?{value:E,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(y,u),e),{value:void 0,unresolvedReference:!0})}return m.error("[Haori]","Expression evaluation error:",e,y),y instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(A=>!this.FORBIDDEN_BINDING_NAMES.has(A)),n=[],s=[];i.forEach(A=>{this.isUsableBindingKey(A)?n.push(A):s.push(A)}),n.sort(),this.reportUnusableBindingKeys(s);const a=new Set(n),o=r.filter(A=>!a.has(A)),c=`${e}:${n.join(",")}:${o.join(",")}`;let u=this.EXPRESSION_CACHE.get(c)||null;if(u!==null)return this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:u,compileFailed:!1};const d=this.buildAssignments(n),p=this.buildShadowDeclarations(o),y=this.toGuardedMemberExpression(this.toOptionalChainExpression(e)),E=d?`"use strict";
|
|
@@ -23,10 +23,10 @@ ${q}
|
|
|
23
23
|
`)}catch(z){m.error("Haori",`Invalid after script: ${z}`)}}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"));const q=e.getRawAttribute(g.attrName(t,"toast-level")),_=["info","warning","error","success"].includes(q);r.toastLevel=_?q:null}const R=g.attrName(t,"redirect"),$=g.attrName(t,"redirect-replace"),G=e.hasAttribute(R),Z=e.hasAttribute($);if(G&&(r.redirectUrl=g.readLateAttribute(e,r,"redirect",R)),Z&&(r.redirectReplaceUrl=g.readLateAttribute(e,r,"redirect-replace",$)),G||Z){const q=g.attrName(t,"redirect-return-param");e.hasAttribute(q)&&(r.redirectReturnParam=g.readLateAttribute(e,r,"redirect-return-param",q))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!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 q=X.read(e,g.attrName(t,"history-form"));if(q){const z=X.query(q,g.attrName(t,"history-form"));z!==null?r.historyFormFragment=x.getFormFragment(I.get(z)):m.error("Haori",`Form element not found: ${q} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=x.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(q=>{const z=g.attrName(t,q);if(!e.hasAttribute(z))return;const _=X.read(e,z),J=[];if(_)X.queryAll(_,z).forEach(ce=>{const ue=I.get(ce);ue&&J.push(ue)}),J.length===0&&m.error("Haori",`Element not found: ${_} (${z})`);else if(q==="open"||q==="close"){const Ee=e.getTarget().closest("dialog");Ee?J.push(I.get(Ee)):m.error("Haori",`Ancestor <dialog> not found (${z})`)}else J.push(e);if(J.length>0)switch(q){case"reset-before":r.resetBeforeFragments=J;break;case"reset":r.resetFragments=J;break;case"refetch":r.refetchFragments=J;break;case"click":r.clickFragments=J,r.clickAwait=e.hasAttribute(`${z}-await`);break;case"copy":r.copyFragments=J;break;case"open":r.openFragments=J;break;case"close":r.closeFragments=J;break}});const le=g.attrName(t,"copy-source");if(e.hasAttribute(le)){const q=X.read(e,le);if(q){const z=X.query(q,le);if(z!==null){const _=I.get(z);_?r.copySourceFragment=_:m.error("Haori",`Element is not managed by Haori: ${q} (${le})`)}else m.error("Haori",`Element not found: ${q} (${le})`)}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 R=X.read(e,g.attrName(null,"form",!0));if(R){const $=X.query(R,g.attrName(null,"form",!0));$!==null?r.formFragment=x.getFormFragment(I.get($)):m.error("Haori",`Form element not found: ${R} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=x.getFormFragment(e)}const P=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(P)){const R=X.read(e,P),$=[];R?(X.queryAll(R,P).forEach(Z=>{const oe=I.get(Z);oe&&$.push(oe)}),$.length===0&&m.error("Haori",`Element not found: ${R} (${P})`)):$.push(e),$.length>0&&(r.fetchStateFragments=$)}const ne=t?g.attrName(t,"store-clear"):g.attrName(null,"store-clear",!0);if(e.hasAttribute(ne)){const R=e.getRawAttribute(ne),$=R===null?"":R.trim();if($==="")m.error("Haori",`ストレージキーが指定されていません (${ne})`);else{r.storeClearKey=$;const G=e.getRawAttribute(`${ne}-type`),Z=G===null?"session":G.trim();Z==="local"||Z==="session"?r.storeClearKind=Z:(m.warn("Haori",`${ne}-type は session または local を指定してください(session として扱います): ${Z}`),r.storeClearKind="session")}}return s&&!r.download&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r.download&&r.bindFragments&&r.bindFragments.length>0&&(m.warn("Haori",`${y} と同時にバインド先が指定されています(応答はファイルとして保存し、バインドは行いません)。`),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 n=i.getParent();!n||!n.hasAttribute(`${l.prefix}each`)||!n.hasAttribute(`${l.prefix}form-list`)||t.set(i,g.getRowFragments(n).includes(i)?n:null)}t.size>0&&(e.rowWriteTargets=t)}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async runWithOutcome(){return await this.execute()?"success":this.skipped?"skipped":"failure"}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0)return this.skipped=!0,!1;if(this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(!this.options.formFragment&&this.options.targetFragment&&x.warnUnvalidatedCustomValidity(x.getFormFragment(this.options.targetFragment),`${l.prefix}${this.eventType??"fetch"}-form が解決できません`),!this.evaluateExecutionCondition())return this.skipped=!0,!1;if(this.options.runScript){const p=this.options.targetFragment?.getTarget()??null;try{const y=this.options.runScript.call(p,this.domEvent);y===!1&&this.domEvent&&this.domEvent.preventDefault(),y!=null&&typeof y.then=="function"&&await y}catch(y){m.error("Haori",`Run script execution error: ${y}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(p=>x.reset(p,this.operationSequence))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=w.currentSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const p=this.options.beforeCallback(n||null,s||null);if(p!=null){if(p===!1||typeof p=="object"&&p.stop)return!1;typeof p=="object"&&(a="fetchUrl"in p,o="fetchOptions"in p,n=a?p.fetchUrl:n,s=o?p.fetchOptions:s)}}const c=Object.keys(i).length>0;if(n){const p=(s?.method||"GET").toUpperCase(),E=!a&&o&&r.transportMode==="query-get"&&Ot(s)&&!Be(p)?r.baseUrl??n:n,A=Bt(E,s);n=A.url;const D={...A.options},M=A.normalized?A.requestedMethod:r.requestedMethod,H=A.effectiveMethod,F=r.transportMode==="query-get"||A.normalized,j=A.queryString??r.queryString;if(F&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:M,effectiveMethod:H,transportMode:"query-get",url:n,payload:c?i:void 0,queryString:j}),this.options.targetFragment&&n){const Y=performance.now(),Q={runtime:l.runtime,requestedMethod:M,effectiveMethod:H,transportMode:F?"query-get":"http",...F?{queryString:j}:{}};return B.fetchStart(this.options.targetFragment.getTarget(),n,D,c?i:void 0,Q),await this.injectFetchState("loading"),await g.invokeFetch(n,D).then(P=>this.handleFetchResult(P,n||void 0,Y)).catch(async P=>{throw n&&B.fetchError(this.options.targetFragment.getTarget(),n,P),await this.injectFetchState("error",null,P instanceof Error?P.message:String(P)),P})}return await fetch(n,D).then(Y=>this.handleFetchResult(Y,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&c){const p=this.options.formFragment,y=p.getTarget(),E=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&E.add(this.options.targetFragment);const A=p.getRawBindingData(),D=Ue(i),M=p.getAttribute(`${l.prefix}form-arg`);let H;if(M){H={...A??{}};const F=String(M),j=x.resolveAncestorArgOwner(p,F);H[F]=x.mergeCollectedValues((j?j.value:H[F])??null,D)}else H=x.mergeCollectedValues(A,D,x.ancestorBaseResolver(p));await C.setBindingData(y,H,{skipFragments:E,kind:"nonSupply",sequence:this.operationSequence,editedPaths:x.collectEditedPaths(p,this.operationSequence,M?String(M):"",D)})}this.suppressEmptyReplaceBind=!c&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input"),this.twoWayCommitBind=this.eventType==="change"||this.eventType==="input";const u=c?Ue(i):{},d=new Response(JSON.stringify(u),{headers:{"Content-Type":"application/json"}});return await this.handleFetchResult(d)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const e=this.options.targetFragment,t=e.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(Le))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(Le,""),r||t.setAttribute("disabled",""),{target:t,fragment:e,appliedDisabledAttribute:!r}}static findDisabledDeclaration(e){const t=`${l.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(Le),!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}`)})}async saveResponseAsFile(e,t){let r;try{r=await e.blob()}catch(a){return m.error("Haori",`応答をファイルとして読み取れませんでした: ${a}`),!1}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 を生成できないため、ファイルを保存できません。"),!1;const n=URL.createObjectURL(r),s=document.createElement("a");return s.href=n,s.download=i,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0),!0}async showDownloadFailure(){const e=this.options.formFragment??(this.options.targetFragment?x.getFormFragment(this.options.targetFragment)||this.options.targetFragment:null),t=e?e.getTarget():document.body,r=Te();await r.clearMessages(t),await r.addErrorMessage(t,Xe)}static resolveDownloadFileName(e,t,r){const n=[g.readContentDispositionFileName(e.headers.get("Content-Disposition")),t,g.readUrlFileName(r)];for(const s of n){const a=g.sanitizeFileName(s);if(a!==null)return a}return"download"}static readContentDispositionFileName(e){if(!e)return null;const t=/filename\*\s*=\s*([^;]+)/i.exec(e);if(t){const n=t[1].trim(),s=n.split("'"),a=s.length>=3?s.slice(2).join("'"):n;try{return decodeURIComponent(a)}catch(o){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=Te();if(!e.ok)return ht(e.status)||(this.options.targetFragment&&t&&B.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&B.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const E=this.options.afterCallback(e);if(E!=null){if(E===!1||typeof E=="object"&&E.stop)return!1;typeof E=="object"&&"response"in E&&(e="response"in E?E.response:e)}}if(this.options.download&&!await this.saveResponseAsFile(e,t))return await this.showDownloadFailure(),await this.injectFetchState("error",e.status,Xe),!1;const n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(E=>x.reset(E,this.operationSequence))),await this.copy();const s=[];this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(E=>{s.push(new g(E,null).run())});let a=!1;if(this.options.clickFragments&&this.options.clickFragments.length>0)for(const E of this.options.clickFragments){await C.evaluateAll(E);const A=E.getTarget();if(this.options.clickAwait&&g.takeClickOutcome(A),typeof A.click=="function"?A.click():A.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),!this.options.clickAwait)continue;const D=g.takeClickOutcome(A);if(D===null){m.warn("Haori",`${l.prefix}${this.eventType??"fetch"}-click-await はこの対象の完了を待てません(手続きが同期に起動していません)。`);continue}if(await D==="failure"){a=!0;break}}if(!a&&this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(E=>{const A=E.getTarget();A instanceof HTMLElement?s.push(i.openDialog(A)):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?s.push(i.closeDialog(A)):m.error("Haori","Element is not an HTML element: ",A)}),await Promise.all(s),a)return!1;const o=g.unescapeNewlines(g.normalizeAttributeText(this.resolveLateAttribute("dialog",this.options.dialogMessage)));o&&await i.dialog(o);const c=g.normalizeAttributeText(this.resolveLateAttribute("toast",this.options.toastMessage));c&&await i.toast(c,this.options.toastLevel??"info"),this.clearStore(),this.pushHistory();const u=this.resolveLateAttribute("scroll",this.options.scrollTarget);u&&X.query(u,g.attrName(this.eventType,"scroll"),document)?.scrollIntoView({behavior:"smooth",block:"nearest"});const d=this.resolveLateAttribute("redirect",this.options.redirectUrl),p=this.resolveLateAttribute("redirect-replace",this.options.redirectReplaceUrl);d&&p&&m.warn("Haori",`${g.attrName(this.eventType,"redirect")} と ${g.attrName(this.eventType,"redirect-replace")} の両方が指定されています。履歴を置き換える方を採用します。`);const y=p||d;if(y){let E=y;const A=this.resolveLateAttribute("redirect-return-param",this.options.redirectReturnParam);if(A){const M=new URLSearchParams(window.location.search).get(A);if(M!==null){const H=M.trim();pt.isSafeLocalPath(H)?E=H:m.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${M}`)}}p?window.location.replace(E):window.location.href=E}return!0}clearStore(){const e=this.options.storeClearKey;e&&De.clear(e,this.options.storeClearKind??"session")}resolveLateAttribute(e,t){const r=t??null,i=this.options.lateAttributes?.get(e)??null,n=this.options.targetFragment??null;if(!i||!n||!n.hasAttribute(i.attributeName))return r;const s=n.getAttributeEvaluation(i.attributeName);return s===null?r:s.hasUnresolvedReference&&!i.hasUnresolvedReference?(V.isEnabled()&&m.warn("Haori",`${i.attributeName} の参照が手続きの途中で解決できなくなったため、手続き開始時の値を使います`),r):s.value??null}pushHistory(){const e=this.resolveLateAttribute("history",this.options.historyUrl),t=e!=null,r=this.resolveHistoryDataValues(),i=this.resolveHistoryFormValues(),n=r!=null,s=i!=null;if(!(!t&&!n&&!s))try{const a=t?e:window.location.pathname,o=new URL(a,window.location.href);if(o.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+o.toString();m.error("Haori",u);return}const c=u=>{for(const[d,p]of Object.entries(u))p!=null&&(Array.isArray(p)?(o.searchParams.delete(d),p.forEach(y=>o.searchParams.append(d,String(y)))):typeof p=="object"?o.searchParams.set(d,JSON.stringify(p)):o.searchParams.set(d,String(p)))};n&&c(r),s&&c(i),history.pushState({[Ct]:!0},"",o.toString()),C.refreshUrlParams()}catch(a){m.error("Haori",`history.pushState failed: ${a}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=x.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await Te().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await Te().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const c=new Map,u=[];for(const d of a)if(d&&typeof d=="object"&&!Array.isArray(d)){const p=d.key,y=d.message,E=typeof p=="string"&&p.length>0?p:null,A=typeof y=="string"?y:y!=null?String(y):"";if(A.length===0)continue;if(E!==null){const D=c.get(E)??[];D.push(A),c.set(E,D)}else u.push(A)}else typeof d=="string"&&d.length>0&&u.push(d);for(const[d,p]of c)o.push({key:d,message:p.join(`
|
|
24
24
|
`)});for(const d of u)o.push({message:d})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const c of a.messages)typeof c=="string"&&o.push({message:c});if(a.errors&&typeof a.errors=="object")for(const[c,u]of Object.entries(a.errors))Array.isArray(u)?o.push({key:c,message:u.join(`
|
|
25
25
|
`)}):typeof u=="string"?o.push({key:c,message:u}):u!=null&&o.push({key:c,message:String(u)});if(o.length===0)for(const[c,u]of Object.entries(a))c==="message"||c==="messages"||c==="errors"||(Array.isArray(u)?o.push({key:c,message:u.join(`
|
|
26
|
-
`)}):typeof u=="string"&&o.push({key:c,message:u}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const c of o)c.key&&t?await x.addErrorMessage(t,c.key,c.message):await i(c.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return x.warnUnvalidatedCustomValidity(e,`${l.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,n=0;const s=()=>{if(t!==g.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=g.VALIDATION_SCROLL_STABLE_FRAMES&&g.isRectPartlyVisible(a)||performance.now()-r>=g.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=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??`${l.prefix}if`,n=x.buildConditionScope(r,this.options.formFragment??null),s=ie.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&V.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):Te().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=ie.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?g.attrName(this.eventType,"bind"):g.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const p=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const E=this.resolveCurrentRowItem(o,y),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const D=E[p],M=D!==null&&typeof D=="object"&&!Array.isArray(D)?D:{};A[p]=this.mergeAppendBindingData(o,i,M)}else A[p]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const p=u[d],y=p&&typeof p=="object"&&!Array.isArray(p)?p:{};u[d]=this.mergeAppendBindingData(o,i,y)}else u[d]=i;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:p=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,p):p,E=this.mergeAppendBindingData(o,i,y),A=this.options.bindMerge?{...y,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{B.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=x.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:me(c,n)}}return me(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 n=x.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:me(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of x.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=x.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:me(c,a)}}return i}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=g.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(C.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=x.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:me(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Ne(this.options.copySourceFragment):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Ne(this.options.formFragment):this.options.targetFragment?C.withoutReservedBindingKeys(this.options.targetFragment.getRawBindingData()??{}):{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=x.getValues(r);Object.assign(e,i),x.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,baseUrl:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Be(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Ie(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Ht(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=gt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const p=new FormData;for(const[y,E]of Object.entries(t))E==null?p.append(y,""):E instanceof Blob?p.append(y,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?p.append(y,A):p.append(y,Ae(A))}):p.append(y,Ae(E));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(d)){const p=new URLSearchParams;for(const[y,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>p.append(y,Ae(A))):p.append(y,Ae(E)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:Vt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Ne(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 Ne(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=g.attrName(this.eventType,e),i=X.read(t,r);if(i!==null&&i.trim()!==""){const s=X.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=I.get(s);return a instanceof w?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(A=>/^[A-Za-z_$][\w$]*$/.test(A))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=g.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,p,y;if(u)d=u.owner,p=u.ownerData,y=[...u.path,...o.slice(1)];else{for(d=e,p=null;d;){const A=d.getRawBindingData();if(A&&o[0]in A&&!g.isRowScopeKey(d,o[0])){p=A;break}d=d.getParent()}y=o}if(!d||!p)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=g.readPathValue(p,y);return Array.isArray(E)?{owner:d,ownerData:p,array:E,path:y,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=g.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=g.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):g.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=g.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=g.resolveRowArrayIndex(u,a);if(d===null)continue;const p=a[d];if(p===null||typeof p!="object"||Array.isArray(p)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const y=u.apply(p);if(g.isSameRowItem(p,y)){u.syncWhenUnchanged&&r.push(g.syncUnchangedRowValues(u.row,y,u.syncWhenUnchanged));continue}a[d]=y,o=!0,u.syncWhenUnchanged==="supply"&&x.clearRowUserEditMarksForChangedKeys(u.row,y)}if(!o)return;const c=C.setBindingData(s.owner.getTarget(),g.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(C.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&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 n=g.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((p,y)=>{C.createListKey(p,String(a),y)===o&&c.push(y)});const u=n.slice(0,s).filter(p=>p.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(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[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=g.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=g.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=y=>y<0||y>=a.length?null:i.mapped?g.resolveRowIndex(r,a[y],i.array,g.attrName(this.eventType,e)):y,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const p=new Map;return a.forEach(y=>{const E=y.getListKey();E!==null&&!p.has(String(E))&&p.set(String(E),y)}),d.forEach((y,E)=>{if(g.isSameRowItem(i.array[E],y))return;const A=p.get(C.createListKey(y,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){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return C.setBindingData(a,o,{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 ae=g;class qt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ht(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=I.get(e);return r instanceof w?r.hasAttribute(`${l.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 w?t.push(h.evaluateAll(r)):r instanceof se&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=w.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof w&&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))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}validity`)&&x.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(h.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof w&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget(),i=h.initialValueRestore;if(!t&&i!==null&&e.hasAttribute(`${l.prefix}fetch-form`))return i.then(()=>h.executeManagedFetch(e,!0)).catch(o=>{m.error("Haori",`初期表示の取得に失敗しました: ${o}`)}),Promise.resolve();const n=h.getReactiveFetchState(r),s=ae.resolveAutoFetchSignature(e);if(n.running)return(s.hasUnresolvedReference||s.signature!==n.lastSignature)&&(n.rerunRequested=!0),Promise.resolve();if(s.hasUnresolvedReference||s.signature===null)return n.lastSignature=null,Promise.resolve();if(n.lastSignature===s.signature)return Promise.resolve();n.lastSignature=s.signature,n.running=!0;const a=new ae(e,null);return a.markReentrantBind(),a.runWithResult().then(()=>{}).finally(()=>{if(n.running=!1,n.rerunRequested)return n.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${l.prefix}importing`,""),B.importStart(t,n),qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),B.importEnd(t,n,o,s),h.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof w?c.push(h.scan(u.getTarget())):u instanceof se&&c.push(h.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),B.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,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=I.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){const t=I.get(e);if(!t)return Promise.resolve();const r=h.initializeElementFragment(t,!1).then(()=>x.restoreInitialValues(e)),i=h.initialValueRestore;return h.initialValueRestore=r,r.then(()=>{h.initialValueRestore=i,te.applySubtree(e)})}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e),te.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e,t)){h.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof w?r.push(h.initializeElementFragment(i,t)):i instanceof se&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>h.setAttribute(e.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>x.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&h.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=I.get(e),a=h.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof w&&s.consumeSelfWrittenBind(r))break;const p=r===null?{}:h.parseDataBind(r);if(i){const y=n??w.nextSequence();return r===null?(o.push(h.setBindingData(e,p,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(h.setBindingData(e,p,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(p);break}case`${l.prefix}derive`:u=h.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=h.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=h.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=h.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:d=()=>h.evaluateIf(s);break;case`${l.prefix}each`:d=()=>h.evaluateEach(s);break;case`${l.prefix}fetch`:d=()=>h.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>h.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(De.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&x.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const p=s.getAttribute(`${l.prefix}url-arg`),y=pt.readParams();p===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()};if(p===null)o.push(h.setBindingData(e,y,E));else{const A=s.getRawBindingData()||{};A[String(p)]=y,o.push(h.setBindingData(e,A,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(p=>{if(p)return h.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=I.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??w.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const p=w.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&h.clearUserEditMarks(i,c);const E=a?h.resolveByPathAuthority(i,y,t,u):t;i.setBindingData(E),a&&(B.bindChange(e,y,E,"manual"),De.mirror(i));const A=()=>{i.markBindingWorkStart();const D=i.getRawBindingData()??E;let M=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(h.withoutReservedBindingKeys(D))):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(p))return;const H=i.getRawBindingData()??E;return x.syncValues(i,x.resolveSyncValues(i,H),!1,u)})),M=M.then(()=>x.syncAncestorArgForms(i,p,u,y)),M=M.then(()=>h.evaluateAll(i,n)),M=M.then(()=>w.retryUnappliedValueWrites(e,p)),M=M.then(()=>h.reevaluateReactiveSpecialAttributes(i,n)),M.then(()=>i.markBindingWorkEnd(),H=>{throw i.markBindingWorkEnd(),H})};return s?A():i.enqueueBindingWork(A)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))w.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const n=h.mergePathAuthority(e,t??{},r,i,"");return n===h.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(h.isPlainRecord(t)&&h.isPlainRecord(r)){const u=t,d=r,p={};let y=Object.keys(u).some(A=>!Object.prototype.hasOwnProperty.call(d,A));const E=new Set([...Object.keys(u),...Object.keys(d)]);for(const A of E){const D=n===""?A:`${n}.${A}`,M=h.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,A)?u[A]:h.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,A)?d[A]:h.ABSENT_PATH,i,D);M!==h.ABSENT_PATH&&(p[A]=M),M!==(Object.prototype.hasOwnProperty.call(d,A)?d[A]:h.ABSENT_PATH)&&(y=!0)}return y?p:d}const s=h.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,p=d.map((y,E)=>h.mergePathAuthority(e,u[E],y,i,`${n}[${s[E]}]`));return p.some((y,E)=>y!==d[E])?p:d}if(h.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>h.isPlainRecord(o))?h.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>h.createListKey(o,n,c)),a=r.map((o,c)=>h.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=h.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===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=I.get(e);return r instanceof w?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=h.collectScope(e);return V.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=I.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=h.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,p)=>{if(c)for(const y of Object.keys(c))y in i||(i[y]={value:c[y],source:n(u),kind:d,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=I.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=I.get(t.nextSibling),n=I.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof w)return h.scan(n.getTarget());if(n instanceof se)return h.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=I.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=I.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=I.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=h.getFormFragment(r);if(n){const s=x.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=x.resolveAncestorArgOwner(n,u);c[u]=x.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=x.mergeCollectedValues(o,s,x.ancestorBaseResolver(n));i.push(h.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:w.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?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(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const p=h.createDeriveInputSignature(e,a,o);p===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==p&&(r=r.then(()=>h.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(p)})))}return n&&(r=r.then(()=>h.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEachFixedChildren(e)).then(()=>h.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=h.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,h.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const p=[];return e.getChildren().forEach(y=>{if(y instanceof w){if(h.canSkipUnchangedNestedEach(y))return;p.push(h.evaluateAll(y,t))}else y instanceof se&&p.push(h.evaluateText(y))}),Promise.all(p).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=ie.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return 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(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(ie.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,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${l.prefix}each-before`)||e.hasAttribute(`${l.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof w&&h.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?h.isEachFixedChild(r)&&t.push(h.evaluateAll(r)):r instanceof se&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(h.isHiddenIfCondition(r))V.isEnabled()&&e.isVisible()&&h.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=[],s=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(a=>{if(a instanceof w){if(s&&!h.isEachFixedChild(a))return;n.push(a.isMounted()?h.evaluateAll(a):h.scan(a.getTarget()))}else a instanceof se&&n.push(h.evaluateText(a))}),t.push(e.show().then(()=>{B.show(e.getTarget()),i||(h.triggerLoadOnShow(e),te.refreshSubtree(e.getTarget()))})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new ae(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(V.isEnabled()&&ie.recordRowScopeIdentifiers([h.getRowScopeName(e,"each-arg"),h.getRowScopeName(e,"each-index")]),e.isMounted()||h.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${l.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(`${l.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(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),te.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=`${l.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
26
|
+
`)}):typeof u=="string"&&o.push({key:c,message:u}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const c of o)c.key&&t?await x.addErrorMessage(t,c.key,c.message):await i(c.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return x.warnUnvalidatedCustomValidity(e,`${l.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,n=0;const s=()=>{if(t!==g.validationReportGeneration||!e.isConnected)return;const a=e.getBoundingClientRect(),o=`${Math.round(a.top)}:${Math.round(a.left)}`;if(n=o===i?n+1:0,i=o,n>=g.VALIDATION_SCROLL_STABLE_FRAMES&&g.isRectPartlyVisible(a)||performance.now()-r>=g.VALIDATION_SCROLL_TIMEOUT_MS){e.reportValidity();return}requestAnimationFrame(s)};requestAnimationFrame(s)}static getViewportSize(){return{width:window.innerWidth||document.documentElement.clientWidth,height:window.innerHeight||document.documentElement.clientHeight}}static isRectFullyVisible(e){const{width:t,height:r}=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??`${l.prefix}if`,n=x.buildConditionScope(r,this.options.formFragment??null),s=ie.evaluateDetailed(t,n);return s.unresolvedReference?(e||m.warn("Haori",`${i} の参照が解決できないため実行しません: ${t}`),!1):s.value?!0:(!e&&V.isEnabled()&&m.warn("Haori",`${i} の条件が偽のため手続きを中断しました: ${t}`),!1)}findFirstInvalid(e){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return null;let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):Te().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=ie.evaluate(this.options.bindTransform,{response:i})}catch(o){m.error("Haori",`Invalid bind-transform: ${o}`)}if(this.options.bindParams){const o={};this.options.bindParams.forEach(c=>{i&&typeof i=="object"&&c in i&&(o[c]=i[c])}),i=o}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){m.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${l.prefix}${this.eventType}-form.`);return}const n=[],s=this.eventType?g.attrName(this.eventType,"bind"):g.attrName(null,"bind",!0),a=[];if(this.options.bindArg)this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){const p=this.options.bindArg;a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:y=>{const E=this.resolveCurrentRowItem(o,y),A={...E};if(i&&typeof i=="object"&&!Array.isArray(i)){const D=E[p],M=D!==null&&typeof D=="object"&&!Array.isArray(D)?D:{};A[p]=this.mergeAppendBindingData(o,i,M)}else A[p]=i;return this.reconcileRowUserEdits(o,A)}});return}const u={...o.getRawBindingData()??{}},d=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const p=u[d],y=p&&typeof p=="object"&&!Array.isArray(p)?p:{};u[d]=this.mergeAppendBindingData(o,i,y)}else u[d]=i;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,u),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});else if(typeof i=="string"){if(this.options.defaultSelfBind){m.warn("Haori","string data is not bound because no bind target was specified.");return}return m.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(o=>{const c=this.resolveRowWrite(o,s);if(c.kind==="skip")return;if(c.kind==="row"){a.push({container:c.container,row:o,attributeName:s,syncWhenUnchanged:"reflect",apply:p=>{const y=this.options.bindMerge?this.resolveCurrentRowItem(o,p):p,E=this.mergeAppendBindingData(o,i,y),A=this.options.bindMerge?{...y,...E}:E;return this.reconcileRowUserEdits(o,A)}});return}const u=this.mergeAppendBindingData(o,i),d=this.options.bindMerge?{...o.getRawBindingData()??{},...u}:u;n.push(C.setBindingData(o.getTarget(),this.reconcileUserEditsForBind(o,d),{reentrant:this.reentrantBind&&o.isExecutingBindingWork(),sequence:this.operationSequence,clearUserEdits:!1}))});return n.push(this.applyRowWrites(a)),Promise.all(n).then(()=>{const o=this.options.bindArg??null;this.options.bindFragments.forEach(c=>{B.bindComplete(c.getTarget(),o)})})})}reconcileUserEditsForBind(e,t){const r=this.requestUserEditSequence;if(r===null)return t;const i=this.eventType==="poll";if(!i&&!this.twoWayCommitBind&&C.clearUserEditMarks(e,r),!(e.getTarget()instanceof HTMLFormElement))return this.reconcileAncestorArgFormEdits(e,t,i?0:r);const n=x.getValuesEditedAfter(e,i?0:r);if(Object.keys(n).length===0)return t;const s=e.getAttribute(`${l.prefix}form-arg`);if(s){const a=String(s),o=t[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...t,[a]:me(c,n)}}return me(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 n=x.getValuesEditedAfter(e,i?0:r);return Object.keys(n).length===0?t:me(t,n)}reconcileAncestorArgFormEdits(e,t,r){let i=t;for(const{form:n,key:s}of x.collectArgForms(e)){if(!Object.prototype.hasOwnProperty.call(i,s))continue;const a=x.getValuesEditedAfter(n,r);if(Object.keys(a).length===0)continue;const o=i[s],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};i={...i,[s]:me(c,a)}}return i}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=g.attrName(this.eventType,"copy"),i=[],n=[];return this.options.copyFragments.forEach(s=>{const a=this.resolveRowWrite(s,r);if(a.kind==="skip")return;if(a.kind==="row"){i.push({container:a.container,row:s,attributeName:r,syncWhenUnchanged:"supply",apply:c=>this.applyCopyToRowItem(s,c,t)});return}const o={...s.getRawBindingData()??{},...t};n.push(C.setBindingData(s.getTarget(),o,{sequence:this.operationSequence}))}),n.push(this.applyRowWrites(i)),Promise.all(n).then(()=>{})}resolveCurrentRowItem(e,t){const r=x.getValuesEditedAfter(e,0);return Object.keys(r).length===0?t:me(t,r)}applyCopyToRowItem(e,t,r){return{...this.resolveCurrentRowItem(e,t),...r}}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?Ne(this.options.copySourceFragment):C.withoutReservedBindingKeys(this.options.copySourceFragment.getRawBindingData()??{}):this.options.formFragment?Ne(this.options.formFragment):this.options.targetFragment?C.withoutReservedBindingKeys(this.options.targetFragment.getRawBindingData()??{}):{}}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r){const i=x.getValues(r);Object.assign(e,i),x.carryCollectedRowIdentity(i,e)}if(this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return e.signature===null||!this.options.conditionExpression?{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}:{signature:`${e.signature}|if=${String(this.evaluateExecutionCondition(!0))}`,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,baseUrl:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Be(a),c=o?"GET":a;if(n.method=c,Object.keys(t).length>0&&Ie(t)){const d=s.get("Content-Type")||"";c!=="GET"&&c!=="HEAD"&&c!=="OPTIONS"&&/multipart\/form-data/i.test(d)?Ht(t)&&m.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):m.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=gt(i,t));else if(Object.keys(t).length>0){const d=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(d)){s.delete("Content-Type");const p=new FormData;for(const[y,E]of Object.entries(t))E==null?p.append(y,""):E instanceof Blob?p.append(y,E):Array.isArray(E)?E.forEach(A=>{A instanceof Blob?p.append(y,A):p.append(y,Ae(A))}):p.append(y,Ae(E));n.body=p}else if(/application\/x-www-form-urlencoded/i.test(d)){const p=new URLSearchParams;for(const[y,E]of Object.entries(t))E!==void 0&&(Array.isArray(E)?E.forEach(A=>p.append(y,Ae(A))):p.append(y,Ae(E)));n.body=p}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let u;return o&&(u=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:u,transportMode:o?"query-get":"http",signature:Vt(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?Ne(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 Ne(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return m.error("Haori","Target fragment is not specified for row operation."),null;const r=g.attrName(this.eventType,e),i=X.read(t,r);if(i!==null&&i.trim()!==""){const s=X.query(i,r,document);if(s===null)return m.error("Haori",`Row container not found: ${i} (${r})`),null;const a=I.get(s);return a instanceof w?a.hasAttribute(`${l.prefix}each`)?a:(m.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(m.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e,t=!1){const r=e.getRawAttribute(`${l.prefix}each`);if(r===null)return t||m.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const i=e.getRawAttribute(`${l.prefix}each-array`),n=i!==null,s=n?`${l.prefix}each-array`:`${l.prefix}each`,a=n?i:r,o=a.trim().split(".");if(!(o.length>0&&o.every(A=>/^[A-Za-z_$][\w$]*$/.test(A))))return t||m.error("Haori",`Row operations require a plain identifier path for ${s} (got: ${a}).`+(n?"":` Declare ${l.prefix}each-array to specify the array to write back to.`)),null;if(n&&e.getRawAttribute(`${l.prefix}each-key`)===null)return t||m.error("Haori",`${l.prefix}each-array requires ${l.prefix}each-key (${l.prefix}each-array="${a}").`),null;const u=g.resolveRowScopeBase(e,o[0]);if(u==="unresolvable")return null;let d,p,y;if(u)d=u.owner,p=u.ownerData,y=[...u.path,...o.slice(1)];else{for(d=e,p=null;d;){const A=d.getRawBindingData();if(A&&o[0]in A&&!g.isRowScopeKey(d,o[0])){p=A;break}d=d.getParent()}y=o}if(!d||!p)return t||m.error("Haori",`Binding data owner not found for ${s}="${a}".`),null;const E=g.readPathValue(p,y);return Array.isArray(E)?{owner:d,ownerData:p,array:E,path:y,mapped:n}:(t||m.error("Haori",`${s}="${a}" does not resolve to an array.`),null)}static resolveRowScopeBase(e,t){let r=e;for(;r;){const i=r.closestByAttribute(`${l.prefix}row`);if(!i)return null;const n=i.getParent();if(!n)return null;if(n.getAttribute(`${l.prefix}each-arg`)===t){const s=g.resolveEachArray(n,!0);if(!s)return m.error("Haori",`Row operations cannot resolve the write-back array for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}": the ancestor container that supplies "${t}" (${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}") does not resolve to a writable array. Build the outer list with ${l.prefix}derive and declare ${l.prefix}each-array on this ${l.prefix}each.`),"unresolvable";const a=g.resolveRowIndex(n,i,s.array,`${l.prefix}each="${n.getRawAttribute(`${l.prefix}each`)}"`);return a===null?null:{owner:s.owner,ownerData:s.ownerData,path:[...s.path,String(a)]}}r=n}return null}static isRowScopeKey(e,t){if(!e.hasAttribute(`${l.prefix}row`))return!1;const r=e.getParent();return r?r.getAttribute(`${l.prefix}each-arg`)===t||r.getAttribute(`${l.prefix}each-index`)===t:!1}static readPathValue(e,t){let r=e;for(const i of t){if(r===null||typeof r!="object")return;r=r[i]}return r}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],o=n[a],c=Array.isArray(o)?o.slice():{...o};n[a]=c,n=c}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}resolveRowWrite(e,t){const r=this.options.rowWriteTargets;if(!r||!r.has(e))return{kind:"plain"};const i=r.get(e)??null;return i===null?(m.warn("Haori",`Target is not a row of the ${l.prefix}each container (${t}).`),{kind:"skip"}):g.getRowFragments(i).includes(e)?{kind:"row",container:i}:(m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${t}).`),{kind:"skip"})}applyRowWrites(e){if(e.length===0)return Promise.resolve();const t=new Map;for(const i of e){const n=t.get(i.container);n?n.push(i):t.set(i.container,[i])}const r=[];return t.forEach((i,n)=>{const s=g.resolveEachArray(n);if(!s)return;const a=s.array.slice();let o=!1;for(const u of i){const d=g.resolveRowArrayIndex(u,a);if(d===null)continue;const p=a[d];if(p===null||typeof p!="object"||Array.isArray(p)){m.warn("Haori",`Row data is not an object; the write was skipped (${u.attributeName}).`);continue}const y=u.apply(p);if(g.isSameRowItem(p,y)){u.syncWhenUnchanged&&r.push(g.syncUnchangedRowValues(u.row,y,u.syncWhenUnchanged));continue}a[d]=y,o=!0,u.syncWhenUnchanged==="supply"&&x.clearRowUserEditMarksForChangedKeys(u.row,y)}if(!o)return;const c=C.setBindingData(s.owner.getTarget(),g.withPathValue(s.ownerData,s.path,a),{reentrant:this.reentrantBind&&s.owner.isExecutingBindingWork(),kind:"nonSupply",sequence:this.operationSequence});if(C.isEachUpdateRunning(n)){c.catch(u=>{m.error("Haori","Failed to write row data.",u)});return}r.push(c)}),Promise.all(r).then(()=>{})}static syncUnchangedRowValues(e,t,r){return r==="supply"&&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 n=g.getRowFragments(e),s=n.indexOf(t);if(s===-1)return m.warn("Haori",`The target row is no longer in the ${l.prefix}each container; the write was skipped (${i}).`),null;const a=e.getAttribute(`${l.prefix}each-key`),o=t.getListKey();if(a&&o!==null){const c=[];r.forEach((p,y)=>{C.createListKey(p,String(a),y)===o&&c.push(y)});const u=n.slice(0,s).filter(p=>p.getListKey()===o).length,d=c[u]??-1;return d===-1?(m.warn("Haori",`No array element corresponds to the target row (key "${o}"); the write was skipped (${i}).`),null):d}return s>=r.length?(m.warn("Haori",`The target row index is out of range; the write was skipped (${i}).`),null):s}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(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[n]=e.splice(t,1);return e.splice(i,0,n),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t,r,i)=>{const n=i();if(n===null||t<0||t>=e.length-1)return!1;const[s]=e.splice(t,1);return e.splice(n,0,s),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=g.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=g.getRowFragments(r),o=s?a.indexOf(s):a.length-1,c=y=>y<0||y>=a.length?null:i.mapped?g.resolveRowIndex(r,a[y],i.array,g.attrName(this.eventType,e)):y,u=o>=0?c(o):i.mapped?i.array.length-1:o;if(u===null)return Promise.resolve();const d=i.array.slice();if(!t(d,u,()=>c(o-1),()=>c(o+1)))return Promise.resolve();const p=new Map;return a.forEach(y=>{const E=y.getListKey();E!==null&&!p.has(String(E))&&p.set(String(E),y)}),d.forEach((y,E)=>{if(g.isSameRowItem(i.array[E],y))return;const A=p.get(C.createListKey(y,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){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return C.setBindingData(a,o,{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 ae=g;class qt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw m.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){ht(r.status);const n=`${r.status} ${r.statusText}`;throw m.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw m.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return m.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const h=class h{static isDeferredAttributeName(e){return h.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return h.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!h.isEvaluateAllExcludedAttributeName(e)&&h.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${h.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=I.get(e);return r instanceof w?r.hasAttribute(`${l.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 w?t.push(h.evaluateAll(r)):r instanceof se&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static clearUserEditMarks(e,t=w.currentSequence()){e.clearUserEditMark(t),e.getChildren().forEach(r=>{r instanceof w&&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))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}validity`)&&x.applyCustomValidity(e),e.hasAttribute(`${l.prefix}fetch`)&&r.push(h.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(h.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof w&&r.push(h.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e,t=!1){const r=e.getTarget(),i=h.initialValueRestore;if(!t&&i!==null&&e.hasAttribute(`${l.prefix}fetch-form`))return i.then(()=>h.executeManagedFetch(e,!0)).catch(o=>{m.error("Haori",`初期表示の取得に失敗しました: ${o}`)}),Promise.resolve();const n=h.getReactiveFetchState(r),s=ae.resolveAutoFetchSignature(e);if(n.running)return(s.hasUnresolvedReference||s.signature!==n.lastSignature)&&(n.rerunRequested=!0),Promise.resolve();if(s.hasUnresolvedReference||s.signature===null)return n.lastSignature=null,Promise.resolve();if(n.lastSignature===s.signature)return Promise.resolve();n.lastSignature=s.signature,n.running=!0;const a=new ae(e,null);return a.markReentrantBind(),a.runWithResult().then(()=>{}).finally(()=>{if(n.running=!1,n.rerunRequested)return n.rerunRequested=!1,h.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=h.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${l.prefix}importing`,""),B.importStart(t,n),qt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return K.enqueue(()=>{t.innerHTML=a}).then(()=>{t.removeAttribute(`${l.prefix}importing`),B.importEnd(t,n,o,s),h.adoptImportedChildren(e);const c=[];return e.getChildren().forEach(u=>{u instanceof w?c.push(h.scan(u.getTarget())):u instanceof se&&c.push(h.evaluateText(u))}),Promise.all(c).then(()=>{})})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),B.importError(t,n,a),m.error("[Haori]","Failed to import HTML:",n,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=I.get(r);i!==null&&i.getParent()!==e&&e.pushChild(i)})}static scan(e){return h.scanElement(e,!0)}static scanElement(e,t){const r=I.get(e);if(!r)return Promise.resolve();const i=h.initializeElementFragment(r,!1).then(()=>x.restoreInitialValues(e)),n=h.initialValueRestore;return h.initialValueRestore=i,i.then(()=>{h.initialValueRestore=n,t&&te.applySubtree(e)})}static applyEnhancersOnShow(e,t){const r=e.getTarget();return w.retryUnappliedValueWrites(r,t).then(()=>{te.applySubtree(r)})}static initializeFreshEachRow(e){return h.initializeElementFragment(e,!0).then(()=>{h.needsScheduledEvaluateAll(e)&&h.scheduleEvaluateAll(e),te.applySubtree(e.getTarget())})}static initializeElementFragment(e,t){return h.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():h.initializeElementAttributes(e).then(()=>{if(h.shouldSkipChildInitialization(e,t)){h.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof w?r.push(h.initializeElementFragment(i,t)):i instanceof se&&r.push(h.evaluateText(i))}),Promise.all(r).then(()=>{h.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of h.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||h.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>h.setAttribute(e.getTarget(),i,n)))}for(const i of h.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>h.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>x.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&h.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1,n){const s=I.get(e),a=h.getAliasedAttributeName(t);if(a!==null)return r===null?s.removeAliasedAttribute(t,a):s.setAliasedAttribute(t,a,r,i);const o=[];let c=null,u=null,d=null;switch(t){case`${l.prefix}bind`:{if(r!==null&&i&&s instanceof w&&s.consumeSelfWrittenBind(r))break;const p=r===null?{}:h.parseDataBind(r);if(i){const y=n??w.nextSequence();return r===null?(o.push(h.setBindingData(e,p,{reflectToAttribute:!1,sequence:y})),o.push(s.removeAttribute(t))):o.push(h.setBindingData(e,p,{sequence:y})),Promise.all(o).then(()=>{})}r===null&&s.clearBindingDataCache(),s.setBindingData(p);break}case`${l.prefix}derive`:u=h.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),c=h.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o.push(c.then(()=>{}));break;case`${l.prefix}derive-name`:u=h.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),c=h.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),o.push(c.then(()=>{}));break;case`${l.prefix}if`:d=()=>h.evaluateIf(s);break;case`${l.prefix}each`:d=()=>h.evaluateEach(s);break;case`${l.prefix}fetch`:d=()=>h.executeManagedFetch(s);break;case`${l.prefix}import`:typeof r=="string"&&(d=()=>h.executeManagedImport(s));break;case`${l.prefix}store`:r!==null&&o.push(De.restore(s));break;case`${l.prefix}validity`:case`${l.prefix}validity-message`:return r!==null&&x.applyCustomValidity(s),Promise.all(o).then(()=>{});case`${l.prefix}url-param`:{const p=s.getAttribute(`${l.prefix}url-arg`),y=pt.readParams();p===null&&s.hasAttribute(`${l.prefix}store`)&&m.warn("Haori",`${l.prefix}url-param を ${l.prefix}url-arg なしで ${l.prefix}store と併用すると復元した値が消えます(${l.prefix}url-arg を指定してください)。`);const E={reentrant:!0,kind:"nonSupply",sequence:w.nextSequence()};if(p===null)o.push(h.setBindingData(e,y,E));else{const A=s.getRawBindingData()||{};A[String(p)]=y,o.push(h.setBindingData(e,A,E))}break}}return r===null?o.push(s.removeAttribute(t)):o.push(s.setAttribute(t,r,i)),Promise.all(o).then(()=>d===null?void 0:d()).then(()=>{if(c!==null)return s.setDeriveInputSignature(u),c.then(p=>{if(p)return h.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r={}){const i=I.get(e),n=r.skipFragments??new Set,s=r.reentrant??!1,a=r.reflectToAttribute??!0,o=r.kind??"supply",c=r.sequence??w.nextOperationSequence(),u={sequence:c,kind:o,...r.editedPaths===void 0?{}:{editedPaths:r.editedPaths}},d=o==="supply";d&&i.markSupplyApplied(c);const p=w.currentSequence(),y=i.getRawBindingData();d&&(r.clearUserEdits??!0)&&h.clearUserEditMarks(i,c);const E=a?h.resolveByPathAuthority(i,y,t,u):t;i.setBindingData(E),a&&(B.bindChange(e,y,E,"manual"),De.mirror(i));const A=()=>{i.markBindingWorkStart();const D=i.getRawBindingData()??E;let M=a?i.setAttribute(`${l.prefix}bind`,JSON.stringify(h.withoutReservedBindingKeys(D))):Promise.resolve();return e.tagName==="FORM"&&(M=M.then(()=>{if(i.wasResetAfter(p))return;const H=i.getRawBindingData()??E;return x.syncValues(i,x.resolveSyncValues(i,H),!1,u)})),M=M.then(()=>x.syncAncestorArgForms(i,p,u,y)),M=M.then(()=>h.evaluateAll(i,n)),M=M.then(()=>w.retryUnappliedValueWrites(e,p)),M=M.then(()=>h.reevaluateReactiveSpecialAttributes(i,n)),M.then(()=>i.markBindingWorkEnd(),H=>{throw i.markBindingWorkEnd(),H})};return s?A():i.enqueueBindingWork(A)}static withoutReservedBindingKeys(e){const t={};for(const r of Object.keys(e))w.isReservedBindingKey(r)||(t[r]=e[r]);return t}static resolveByPathAuthority(e,t,r,i){const n=h.mergePathAuthority(e,t??{},r,i,"");return n===h.ABSENT_PATH?r:n}static mergePathAuthority(e,t,r,i,n){if(h.isPlainRecord(t)&&h.isPlainRecord(r)){const u=t,d=r,p={};let y=Object.keys(u).some(A=>!Object.prototype.hasOwnProperty.call(d,A));const E=new Set([...Object.keys(u),...Object.keys(d)]);for(const A of E){const D=n===""?A:`${n}.${A}`,M=h.mergePathAuthority(e,Object.prototype.hasOwnProperty.call(u,A)?u[A]:h.ABSENT_PATH,Object.prototype.hasOwnProperty.call(d,A)?d[A]:h.ABSENT_PATH,i,D);M!==h.ABSENT_PATH&&(p[A]=M),M!==(Object.prototype.hasOwnProperty.call(d,A)?d[A]:h.ABSENT_PATH)&&(y=!0)}return y?p:d}const s=h.resolveArrayPairing(e,t,r,n);if(s!==null){const u=t,d=r,p=d.map((y,E)=>h.mergePathAuthority(e,u[E],y,i,`${n}[${s[E]}]`));return p.some((y,E)=>y!==d[E])?p:d}if(h.isSameBindingValue(t,r))return r;const a=i.editedPaths?.get(n),o=a===void 0?i.kind:"edit",c={sequence:a??i.sequence,kind:o};return e.canApplyPath(n,c)?(e.markPathApplied(n,c),r):t}static resolveArrayPairing(e,t,r,i){if(!Array.isArray(t)||!Array.isArray(r)||t.length!==r.length||r.length===0)return null;const n=r.some(o=>h.isPlainRecord(o))?h.resolveEachKeyArg(e,i):null,s=t.map((o,c)=>h.createListKey(o,n,c)),a=r.map((o,c)=>h.createListKey(o,n,c));return s.some((o,c)=>o!==a[c])?null:a}static resolveEachKeyArg(e,t){const r=`${l.prefix}each`,i=e.getTarget(),n=t.replace(/\[[^\]]*\]/g,""),s=i.querySelectorAll(`[${r}]`);for(const a of Array.from(s)){const o=h.resolveEachDeclarationPath(a,i);if(o===null||o!==n)continue;const c=a.getAttribute(`${r}-key`);return c===null?null:c.trim()}return null}static resolveEachDeclarationPath(e,t){const r=`${l.prefix}each`;let i=e.getAttribute(r)?.trim()??"";if(i==="")return null;let n=e.parentElement;for(;n!==null&&n!==t;){const s=n.getAttribute(r)?.trim();if(s!=null){if(s==="")return null;const a=n.getAttribute(`${r}-arg`)?.trim();if(a!=null&&a!==""){if(i!==a&&!i.startsWith(`${a}.`))return null;i=i===a?s:`${s}.${i.slice(a.length+1)}`}else i=`${s}.${i}`}n=n.parentElement}return i}static isPlainRecord(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}static isSameBindingValue(e,t){if(e===t)return!0;if(e===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=I.get(e);return r instanceof w?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=h.collectScope(e);return V.isEnabled()&&m.info("[Haori]","scope dump for",e,t),t}static collectScope(e){const t=I.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=c=>{const u=c.getTarget(),d=h.resolveElementId(u);return d!==""?`#${d}`:u.tagName.toLowerCase()},s=(c,u,d,p)=>{if(c)for(const y of Object.keys(c))y in i||(i[y]={value:c[y],source:n(u),kind:d,depth:p})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=I.get(e);if(r.isSkipMutationNode(t))return Promise.resolve();const i=I.get(t.nextSibling),n=I.get(t);if(n){if(n.getParent()===r)return Promise.resolve();if(r.insertBefore(n,i),n instanceof w)return h.scan(n.getTarget());if(n instanceof se)return h.evaluateText(n)}return Promise.resolve()}static removeNode(e){const t=I.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNode(e))return;t.remove()}}static changeText(e,t){const r=I.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=I.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=h.getFormFragment(r);if(n){const s=x.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`),o=n.getRawBindingData();let c;if(a){c={...o??{}};const u=String(a),d=x.resolveAncestorArgOwner(n,u);c[u]=x.mergeCollectedValues((d?d.value:c[u])??null,s)}else c=x.mergeCollectedValues(o,s,x.ancestorBaseResolver(n));i.push(h.setBindingData(n.getTarget(),c,{kind:"nonSupply",sequence:w.nextSequence()}))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?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(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,u=!1,d=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const 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 p=!1,y=0;return n&&(r=r.then(()=>{const E=e.isVisible();return y=w.currentSequence(),h.evaluateIf(e).then(()=>{p=!E&&e.isVisible()})})),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>h.evaluateEachFixedChildren(e)).then(()=>h.evaluateEach(e)).then(()=>{if(p)return h.applyEnhancersOnShow(e,y)})):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!h.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),h.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}d=h.createDescendantBindingSignature(e,"evaluateAll"),u=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===d,h.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const E=[];return e.getChildren().forEach(A=>{if(A instanceof w){if(h.canSkipUnchangedNestedEach(A))return;E.push(h.evaluateAll(A,t))}else A instanceof se&&E.push(h.evaluateText(A))}),Promise.all(E).then(()=>{})}).then(()=>{u&&d!==null&&e.setDeriveSubtreeSignature(d)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=ie.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return 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(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;if(ie.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,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const c=t.indexOf(o,s);s=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),m.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static isEachFixedChild(e){return e.hasAttribute(`${l.prefix}each-before`)||e.hasAttribute(`${l.prefix}each-after`)}static hasEachFixedChildren(e){return e.getChildren().some(t=>t instanceof w&&h.isEachFixedChild(t))}static evaluateEachFixedChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof w?h.isEachFixedChild(r)&&t.push(h.evaluateAll(r)):r instanceof se&&t.push(h.evaluateText(r))}),Promise.all(t).then(()=>{})}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(h.isHiddenIfCondition(r))V.isEnabled()&&e.isVisible()&&h.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{B.hide(e.getTarget())}));else{e.restoreFormControlsDisabledByIf();const i=e.isVisible(),n=w.currentSequence(),s=[],a=e.hasAttribute(`${l.prefix}each`);e.getChildren().forEach(o=>{if(o instanceof w){if(a&&!h.isEachFixedChild(o))return;s.push(o.isMounted()?h.evaluateAll(o):h.scanElement(o.getTarget(),!1))}else o instanceof se&&s.push(h.evaluateText(o))}),t.push(e.show().then(()=>{B.show(e.getTarget()),i||(h.triggerLoadOnShow(e),te.refreshSubtree(e.getTarget(),!1))})),t.push(Promise.all(s).then(()=>{if(!(i||a))return h.applyEnhancersOnShow(e,n)}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new ae(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(V.isEnabled()&&ie.recordRowScopeIdentifiers([h.getRowScopeName(e,"each-arg"),h.getRowScopeName(e,"each-index")]),e.isMounted()||h.syncMountedState(e),!e.isVisible()||!e.isMounted())return e.getTarget().removeAttribute(`${l.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(`${l.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(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await h.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),te.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=`${l.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
27
27
|
${r}
|
|
28
28
|
);`)}catch{try{i=new Function(`"use strict";
|
|
29
29
|
${r}
|
|
30
30
|
`)}catch(n){m.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){m.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(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(!n){if(h.EACH_RENDERED_CHANGE_FIRED.has(r))return;h.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){m.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=h.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof w){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),s&&h.warnExtraEachChildren(e),!s){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!s){const d=I.get(c);d instanceof w&&(r=d.clone(),h.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const u=I.get(c);u instanceof w&&e.getChildren().includes(u)&&(e.removeChild(u),u.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?h.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(h.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>h.evaluateAll(r))).then(()=>{})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||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(`${l.prefix}each-key`),n=h.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.prefix}each-index`);s&&n.add(String(s));const a=h.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!h.areExpressionsRowLocal(h.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(h.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!h.areExpressionsRowLocal([s],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(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof w){if(!h.isRowLocalSubtree(i,r))return!1}else if(i instanceof se){const n=i.getRawText();if(n.includes("{{")&&!h.areExpressionsRowLocal(h.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=ie.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!h.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof w?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.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=`${l.prefix}url-param`,r=Array.from(document.querySelectorAll(`[${e}]`)).map(i=>{const n=I.peek(i);return n instanceof w?h.setAttribute(i,e,n.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 w&&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(!V.isEnabled()||!e.hasAttribute(`${l.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 n=i.tagName.toLowerCase();const s=h.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const c=o.getChildren().filter(u=>u instanceof w).findIndex(u=>u===r);n+=`:nth-child(${c+1})`}t.unshift(n),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([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof se&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>h.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof w?!h.markFreshInitializationSkippable(n):n instanceof se?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return m.error("[Haori]",`Template is not set for ${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}". The container needs one element child as the row template.`,e.getTarget()),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=t.map((F,j)=>h.createListKey(F,n?String(n):null,j)),o=new Set(a),c=new Map;a.forEach(F=>{c.set(F,(c.get(F)??0)+1)}),n&&o.size!==a.length&&h.warnDuplicateEachKey(String(n));const u=[];let d=e.getChildren().filter(F=>F instanceof w).filter(F=>!F.hasAttribute(`${l.prefix}each-before`)&&!F.hasAttribute(`${l.prefix}each-after`));const p=d.map(F=>F.getListKey()),y=new Set;d=d.filter((F,j)=>{const Y=String(F.getListKey()),Q=c.get(Y)??0;if(Q===0){y.add(F);const P=F.getListKey();return P!==null&&B.rowRemove(F.getTarget(),P,j),u.push(F.remove()),!1}return c.set(Y,Q-1),!0});const E=d.map(F=>F.getListKey()),A=new Map;d.forEach(F=>{const j=F.getListKey();if(j===null)return;const Y=A.get(j);Y?Y.push(F):A.set(j,[F])});const D=e.getChildElementFragments().filter(F=>!y.has(F)),M=D.filter(F=>F.hasAttribute(`${l.prefix}each-before`)).length;let H=Promise.resolve();return a.forEach((F,j)=>{const Y=t[j],Q=j;let P;const ne=A.get(F)?.shift();if(ne){P=ne;const R=M+j;H=H.then(()=>h.updateRowFragment(P,Y,i,Q,s?String(s):null,F).then($=>h.repositionEachRow(e,P,D,R).then(G=>{if(G!==null&&B.rowMove(P.getTarget(),F,G-M,j),!(!$&&h.isRowLocalEachTemplate(e)))return h.evaluateAll(P).then(()=>h.applyRowFormValues(e,P,Y))})))}else{P=r.clone();const R=M+j;H=H.then(()=>h.updateRowFragment(P,Y,i,Q,s?String(s):null,F).then(()=>{const $=D[R]??null;return e.insertBefore(P,$).then(()=>{D.splice(R,0,P)}).then(()=>h.initializeFreshEachRow(P)).then(()=>h.applyRowFormValues(e,P,Y)).then(()=>{B.rowAdd(P.getTarget(),F,Q,Y)})}))}}),Promise.all(u).then(()=>H).then(()=>{const F=a.filter(R=>R!==null),j=E.filter(R=>R!==null),Y=new Set(j),Q=F.filter(R=>!Y.has(R)),ne=p.filter(R=>R!==null).filter(R=>!o.has(R));B.eachUpdate(e.getTarget(),Q,ne,F)})}static warnExtraEachChildren(e){const t=e.getChildren().filter(r=>r instanceof w).filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));t.length!==0&&m.warn("[Haori]",`${l.prefix}each="${e.getRawAttribute(`${l.prefix}each`)}" のコンテナに要素の子が 2 つ以上あります。テンプレートになるのは最初の子だけで、残り ${t.length} 個は行に入りません(${t.map(r=>r.getTarget().tagName.toLowerCase()).join(", ")})。行の中身は 1 つの要素で包んでください。`,e.getTarget())}static warnDuplicateEachKey(e){!V.isEnabled()||h.WARNED_DUPLICATE_EACH_KEYS.has(e)||(h.WARNED_DUPLICATE_EACH_KEYS.add(e),m.warn("[Haori]",`${l.prefix}each-key="${e}" の値が配列の中で重複しています。行は出現順で対応付けますが、キーによる行の識別はできません。`))}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve(null);r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s).then(()=>n)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||!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 n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return m.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,c=h.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&h.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${l.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>h.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${h.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{h.evaluateAll(e)},100)}};h.ATTRIBUTE_ALIAS_SUFFIX="attr-",h.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","store","url-param","derive-name","derive","if","each"],h.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],h.initialValueRestore=null,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 Re=class Re{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(()=>te.refreshSubtree(r),0)},this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;if(!r||r[Re.HISTORY_STATE_KEY]!==!0){C.refreshUrlParams();return}location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=I.get(e);t&&new ae(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){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`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(Re.BUILTIN_EVENT_NAMES.has(e)){m.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=I.get(i);n instanceof w&&new ae(n,"on",t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i))){this.recordUserEdit(r);return}}if(r.hasAttribute(`${l.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=I.get(e);if(!i)return;(t==="change"||t==="input")&&this.syncUserEdit(e,t==="change");const n=()=>{const s=new ae(i,t,r).runWithOutcome().catch(a=>(m.error("[Haori]","Procedure execution error:",a),"failure"));if(t==="click"){ae.recordClickOutcome(e,s);const a=r.target;a instanceof HTMLElement&&a!==e&&ae.recordClickOutcome(a,s)}};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}recordUserEdit(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!(e instanceof HTMLTextAreaElement))){if(this.deferred){this.deferredProcedures.push(()=>{e.isConnected&&this.markUserEditOnly(e)});return}this.markUserEditOnly(e)}}markUserEditOnly(e){const t=I.get(e);t instanceof w&&t.markUserEdit()}syncUserEdit(e,t){const r=I.get(e);if(r instanceof w&&(r.syncValue(),t?r.markUserEditOnChange():r.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const i=document.getElementsByName(e.name);for(const n of Array.from(i)){if(n===e||!(n instanceof HTMLInputElement)||n.type!=="radio"||n.form!==e.form)continue;const s=I.get(n);s instanceof w&&(s.syncValue(),s.markUserEdit())}}}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};Re.HISTORY_STATE_KEY="__haoriHistoryState__",Re.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let He=Re;const W=class W{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(W.isHtmlElement(e)&&W.syncElement(e),e.querySelectorAll("*").forEach(t=>{W.syncElement(t)}))}static syncElement(e){const t=W.registrations.get(e),r=I.get(e);if(!r||!W.shouldObserve(r)){t&&(t.observer.disconnect(),W.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=W.resolveRoot(r),n=W.resolveRootMargin(r),s=W.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&W.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),W.registrations.delete(e));const o=new IntersectionObserver(c=>{const u=W.registrations.get(e);u&&c.forEach(d=>{!d.isIntersecting||u.running||W.isDisabled(u.fragment)||(u.running=!0,new ae(u.fragment,"intersect").runWithResult().then(p=>{p&&u.once&&(u.observer.disconnect(),W.registrations.delete(e))}).catch(p=>{m.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=W.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),W.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(W.isHtmlElement(e)){const t=W.registrations.get(e);t&&(t.observer.disconnect(),W.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=W.registrations.get(t);r&&(r.observer.disconnect(),W.registrations.delete(t))})}static disconnectAll(){W.registrations.forEach(e=>{e.observer.disconnect()}),W.registrations.clear()}static shouldObserve(e){return e.getAttributeNames().some(t=>{if(!t.startsWith(`${l.prefix}intersect-`))return!1;const r=t.slice(`${l.prefix}intersect-`.length);return!W.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${l.prefix}intersect-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=X.query(r,t,document);return W.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${l.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};W.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),W.registrations=new Map;let ve=W;const v=class v{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(v.isHtmlElement(e)&&v.syncElement(e),e.querySelectorAll("*").forEach(t=>{v.syncElement(t)}))}static syncElement(e){const t=v.registrations.get(e);if(!t&&!v.hasPollAttribute(e))return;const r=I.get(e);if(!(r instanceof w)||!v.shouldObserve(r)){t&&v.teardown(e,t);return}const i=v.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}v.teardown(e,t)}v.startPolling(e,r,i)}static cleanupTree(e){if(v.isHtmlElement(e)){const t=v.registrations.get(e);t&&v.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=v.registrations.get(t);r&&v.teardown(t,r)})}static disconnectAll(){v.registrations.forEach(e=>{v.clearTimers(e)}),v.registrations.clear(),v.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",v.visibilityListener),v.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${l.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!v.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
|
|
31
|
-
`)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ae(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=X.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=I.get(a);o instanceof w&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let Se=v;const yt="0.51.0";function Wt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const O=class O{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(O.isHtmlElement(e)&&O.syncElement(e),e.querySelectorAll("*").forEach(t=>{O.syncElement(t)}))}static syncElement(e){const t=O.registrations.get(e),r=I.get(e);if(!(r instanceof w)||!O.shouldObserve(r)){t&&(t.observer.disconnect(),O.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=O.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),O.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=O.resolveRoot(r),s=O.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,O.refreshRows(t);return}t&&(t.observer.disconnect(),O.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=O.registrations.get(e);if(!u)return;let d=!1;c.forEach(p=>{const y=p.target;u.observedRows.has(y)&&(p.isIntersecting?u.visibleRows.has(y)||(u.visibleRows.add(y),d=!0):u.visibleRows.delete(y)&&(d=!0))}),d&&O.scheduleCompute(u)},{root:n,rootMargin:s,threshold:O.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};O.registrations.set(e,o),O.refreshRows(o)}static cleanupTree(e){if(O.isHtmlElement(e)){const t=O.registrations.get(e);t&&(t.observer.disconnect(),O.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=O.registrations.get(t);r&&(r.observer.disconnect(),O.registrations.delete(t))})}static disconnectAll(){O.registrations.forEach(e=>{e.observer.disconnect()}),O.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=X.query(r,t,document);return O.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?O.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof w&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=O.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));O.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Wt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();O.registrations.get(t)===e&&O.computeAndPublish(e)}))}static computeAndPublish(e){const t=O.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const c of i)c<a&&(a=c),c>o&&(o=c);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,O.publish(e,n))}static publish(e,t){const r=O.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);C.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};O.THRESHOLD=0,O.DEFAULT_ROOT_MARGIN="0px",O.registrations=new Map;let ye=O;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(),w.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new He;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 K.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),ve.syncTree(document.body),Se.syncTree(document.body),ye.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}B.ready(yt)}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=>w.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=w.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${l.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.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(n=>!U.isBindAttributeRecord(n));r.length>0&&U.processMutations(r,w.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(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(ge)&&(r.attributeName==="disabled"||r.attributeName===ge))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&w.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const n=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(n),ve.syncElement(i),Se.syncElement(i),ye.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(ve.cleanupTree(i),Se.cleanupTree(i),ye.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const n=C.addNode(i.parentElement,i);U._initialIntakes?.push(n),ve.syncTree(i),Se.syncTree(i),ye.syncTree(i)}),r.target instanceof Element&&ye.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 xe=U;te.setMutationCapture(b=>xe.captureMutations(b));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",xe.init):xe.init();const jt=()=>pe.waitForRenders(),Kt=pe.enhancers;exports.Core=C;exports.Enhance=te;exports.Env=l;exports.Form=x;exports.Fragment=I;exports.Haori=pe;exports.Log=m;exports.Queue=K;exports.default=pe;exports.enhancers=Kt;exports.version=yt;exports.waitForRenders=jt;
|
|
31
|
+
`)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new ae(t.fragment,"poll").runWithResult()}catch(n){m.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&B.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&B.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return C.setBindingData(n,s,{reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()})})).then(()=>{})}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=X.queryAll(i,t,document);if(n.length===0)return m.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=I.get(a);o instanceof w&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(m.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(m.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(m.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(m.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(m.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let Se=v;const yt="0.52.0";function Wt(b){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>b()):Promise.resolve().then(b)}const O=class O{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(O.isHtmlElement(e)&&O.syncElement(e),e.querySelectorAll("*").forEach(t=>{O.syncElement(t)}))}static syncElement(e){const t=O.registrations.get(e),r=I.get(e);if(!(r instanceof w)||!O.shouldObserve(r)){t&&(t.observer.disconnect(),O.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=O.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),O.registrations.delete(e)),m.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=O.resolveRoot(r),s=O.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,O.refreshRows(t);return}t&&(t.observer.disconnect(),O.registrations.delete(e));const a=new IntersectionObserver(c=>{const u=O.registrations.get(e);if(!u)return;let d=!1;c.forEach(p=>{const y=p.target;u.observedRows.has(y)&&(p.isIntersecting?u.visibleRows.has(y)||(u.visibleRows.add(y),d=!0):u.visibleRows.delete(y)&&(d=!0))}),d&&O.scheduleCompute(u)},{root:n,rootMargin:s,threshold:O.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};O.registrations.set(e,o),O.refreshRows(o)}static cleanupTree(e){if(O.isHtmlElement(e)){const t=O.registrations.get(e);t&&(t.observer.disconnect(),O.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=O.registrations.get(t);r&&(r.observer.disconnect(),O.registrations.delete(t))})}static disconnectAll(){O.registrations.forEach(e=>{e.observer.disconnect()}),O.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=X.query(r,t,document);return O.isHtmlElement(i)?i:(m.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?O.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof w&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=O.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));O.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Wt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();O.registrations.get(t)===e&&O.computeAndPublish(e)}))}static computeAndPublish(e){const t=O.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const c of i)c<a&&(a=c),c>o&&(o=c);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,O.publish(e,n))}static publish(e,t){const r=O.resolveBindOwner(e.fragment);if(!r){m.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);C.setBindingData(i,n,{skipFragments:a,reflectToAttribute:!1,kind:"nonSupply",sequence:w.nextSequence()}).catch(o=>{m.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};O.THRESHOLD=0,O.DEFAULT_ROOT_MARGIN="0px",O.registrations=new Map;let ye=O;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(),w.setPendingMutationFlusher(()=>{U.flushPendingMutations()});const e=new He;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 K.wait(),document.body.setAttribute("data-haori-ready",""),U.observe(document.head),U.observe(document.body),ve.syncTree(document.body),Se.syncTree(document.body),ye.syncTree(document.body)}finally{U._initialIntakes=null,e.release()}B.ready(yt)}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=>w.peek(t)!==null)}static isStaleExternalRemoval(e,t){const r=w.peek(t)?.getParent()??null;return r===null||r.getTarget()===e.target?!1:r.getTarget().closest(`[${l.prefix}external]`)!==null}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.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(n=>!U.isBindAttributeRecord(n));r.length>0&&U.processMutations(r,w.nextSequence()),i.length>0&&Promise.resolve().then(()=>{U.processMutations(i)})}}static isBindAttributeRecord(e){return e.type==="attributes"&&e.attributeName===`${l.prefix}bind`}static processMutations(e,t){for(const r of e)try{if(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(ge)&&(r.attributeName==="disabled"||r.attributeName===ge))break;if(r.attributeName&&(r.attributeName===`${l.prefix}if-false`||r.attributeName==="style"&&i.hasAttribute(`${l.prefix}if-false`))){r.attributeName==="style"&&w.reassertHiddenDisplay(i);break}if(r.attributeName&&C.isAliasedAttributeReflection(i,r.attributeName))break;const n=C.setAttribute(i,r.attributeName,i.getAttribute(r.attributeName),!0,t);U._initialIntakes?.push(n),ve.syncElement(i),Se.syncElement(i),ye.syncElement(i);break}case"childList":{Array.from(r.removedNodes).forEach(i=>{U.isStaleExternalRemoval(r,i)||(ve.cleanupTree(i),Se.cleanupTree(i),ye.cleanupTree(i),C.removeNode(i))}),Array.from(r.addedNodes).forEach(i=>{if(!(i.parentElement instanceof Element))return;const n=C.addNode(i.parentElement,i);U._initialIntakes?.push(n),ve.syncTree(i),Se.syncTree(i),ye.syncTree(i)}),r.target instanceof Element&&ye.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 xe=U;te.setMutationCapture(b=>xe.captureMutations(b));document.readyState==="loading"?document.addEventListener("DOMContentLoaded",xe.init):xe.init();const jt=()=>pe.waitForRenders(),Kt=pe.enhancers;exports.Core=C;exports.Enhance=te;exports.Env=l;exports.Form=x;exports.Fragment=I;exports.Haori=pe;exports.Log=m;exports.Queue=K;exports.default=pe;exports.enhancers=Kt;exports.version=yt;exports.waitForRenders=jt;
|
|
32
32
|
//# sourceMappingURL=haori.cjs.js.map
|