haori 0.30.0 → 0.30.1

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量なライブラリです。JavaScript をほとんど書かずに、データバインディング、条件分岐、繰り返し処理、フォームの双方向バインディング、サーバー通信などを HTML 属性で宣言できます。
4
4
 
5
- バージョン: 0.30.0
5
+ バージョン: 0.30.1
6
6
 
7
7
  ---
8
8
 
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.30.0
5
+ Version: 0.30.1
6
6
 
7
7
  ---
8
8
 
package/dist/haori.cjs.js CHANGED
@@ -4,7 +4,7 @@ let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIden
4
4
  ${h};
5
5
  return (${y});${p}`:`"use strict";
6
6
  return (${y});${p}`;try{return f=new Function(...n,R),this.EXPRESSION_CACHE.set(u,f),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:f,compileFailed:!1}}catch(A){return o.length>0?(g.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(g.error("[Haori]","Failed to compile expression:",e,A),this.compileFailedExpressions.add(e),{bindKeys:n,evaluator:null,compileFailed:!0})}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,u=t[n-2]||null,f=t[n-3]||null;if(this.startsObjectKey(o,i,u,f)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
7
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};N.MAX_IDENTIFIER_RECOVERY_COUNT=8,N.BUILTIN_NAMESPACE="haori",N.BUILTIN_HELPERS={...ut},N.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,N.BUILTIN_DATA_PROPERTY="data",N.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,N.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,N.usableBindingKeyCache=new Map,N.loggedUnusableBindingKeys=new Set,N.compileFailedExpressions=new Set,N.forbiddenBindingValueCache=new WeakMap,N.forbiddenBindingValueCacheResetScheduled=!1,N.loggedForbiddenKeySignatures=new Set,N.loggedForbiddenKeyResetScheduled=!1,N.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],N.STRICT_FORBIDDEN_NAMES=["eval","arguments"],N.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),N.FORBIDDEN_BINDING_NAMES=new Set([...N.FORBIDDEN_NAMES.filter(e=>!N.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...N.STRICT_FORBIDDEN_NAMES]),N.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),N.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),N.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),N.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),N.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),N.EXPRESSION_CACHE=new Map,N.FREE_IDENTIFIER_CACHE=new Map,N.OPTIONAL_CHAIN_CACHE=new Map,N.FORBIDDEN_NAME_PATTERNS=N.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),N.FORBIDDEN_IDENTIFIER_CACHE=new Map,N.pendingUnresolvedIdentifiers=new Set,N.unresolvedReportScheduled=!1,N.loggedBlockedIdentifierExpressions=new Set;let G=N;const ae="data-haori-if-disabled",ke="input, select, textarea, button, fieldset",O=class O{static reset(){O.ELEMENT_STORES.clear(),O.ensureGlobalAccess()}static snapshot(){return O.ensureGlobalAccess(),[...O.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!W.isEnabled()||!e||t.length===0)return;O.ensureGlobalAccess();const i=O.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=O.getOrCreateCounter(i.attributes,e.rawName,e.template);O.updateCounter(s,t,r);return}const n=O.getOrCreateCounter(i.texts,String(e.childIndex),e.template);O.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!W.isEnabled())return;const e=globalThis;e[O.GLOBAL_KEY]===void 0&&(e[O.GLOBAL_KEY]={reset:()=>O.reset(),snapshot:()=>O.snapshot()})}static getOrCreateElementStore(e){const t=O.createElementId(e),r=O.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return O.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=O.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=O.now();return{value:e(),durationMs:O.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};O.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",O.ELEMENT_STORES=new Map;let fe=O;const te=class te{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,te.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(te.FRAGMENT_CACHE.has(e))return te.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new F(e);break;case Node.TEXT_NODE:t=new K(e);break;case Node.COMMENT_NODE:t=new Me(e);break;default:return g.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return $.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return $.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return $.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),te.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};te.FRAGMENT_CACHE=new WeakMap;let T=te;const H=class H extends T{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.userEditSequence=0,this.authoritativeValueSequence=0,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new pe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof H)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){g.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new H(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof H&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof H&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&r.type==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():$.enqueue(()=>{r.value=""})):(g.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,$.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,$.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,$.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&H.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return g.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}static currentUserEditSequence(){return H.userEditCounter}markUserEdit(){H.userEditCounter+=1,this.userEditSequence=H.userEditCounter}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=H.userEditCounter){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e)}static warnUnresolvedAttribute(e,t,r,i){if(!W.isEnabled())return;const n=`${e} ${r}`;H.loggedUnresolvedAttributes.has(n)||(H.loggedUnresolvedAttributes.add(n),g.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=T.get(t);return r instanceof H?r.hasPendingUserEdit():!1}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?H.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=T.get(t);r instanceof H&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!0,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return $.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new pe(e,r);if(n){const we=this.attributeMap.get(e);if(we&&(we.isEvaluate||we.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,$.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),u=s.isEvaluate||s.isRawEvaluate,f=e===t&&H.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=s.isSingleExpression(),p=Q.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||f||h?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&p==="");R&&o.hasUnresolvedReference&&H.warnUnresolvedAttribute(e,t,r,a);const A=s.isForceEvaluation()?r:h?y:p,C=i&&s.isEvaluate&&t==="value"&&H.isValuePropertyTarget(a),w=a.getRootNode(),S=C&&(a===w.activeElement||this.hasPendingUserEdit()),b=R||A===null||A===!1?null:String(A),D=e!==t&&a.getAttribute(e)!==r,M=b===null?a.hasAttribute(t):a.getAttribute(t)!==b,L=b===null?"":b,B=C&&!S&&a.value!==L,z=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),U=t==="selected"&&a instanceof HTMLOptionElement,Z=w.activeElement,Ae=Z!==null&&(z&&a===Z||U&&a.closest("select")===Z)||(z||U)&&this.hasPendingCheckableUserEdit(U),le=b!==null,Se=z&&!Ae&&a.checked!==le,ue=U&&!Ae&&a.selected!==le;return!D&&!M&&!B&&!Se&&!ue?(C&&!S&&(this.value=this.normalizeValueForElement(a,L)),(z||U)&&!Ae&&this.syncCheckableValueFromDom(U),Promise.resolve()):(this.skipMutationAttributes=!0,$.enqueue(()=>{D&&a.setAttribute(e,r),b===null?a.removeAttribute(t):M&&(a.setAttribute(t,b),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(b)),C&&!S&&(this.value=this.normalizeValueForElement(a,L),B&&(a.value=L)),Se&&(a.checked=le),ue&&(a.selected=le),(Se||ue)&&this.syncCheckableValueFromDom(ue)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return $.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Q.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return g.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return g.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const u=e.getParent();u!==null&&u.removeChild(e);let f=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(g.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),f=y.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,$.enqueue(()=>{this.target.insertBefore(e.getTarget(),f)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(g.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),H.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(ke)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(ke)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){H.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(ae,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){H.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(ae)&&(e.removeAttribute(ae),e.removeAttribute("disabled"))})}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};H.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),H.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],H.userEditCounter=0,H.loggedUnresolvedAttributes=new Set;let F=H;class K extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Q(this.text)}clone(){const e=new K(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Q(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):$.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=Q.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class Me extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Me(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,$.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const be=class be{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(be.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(g.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const f=fe.measure(()=>G.evaluateDetailed(u.text,e)),h=f.value;a+=f.durationMs,s.push({expression:u.text,durationMs:f.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(u.text)}catch(f){g.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,f),s.push({expression:u.text,durationMs:0}),n.push("")}}),fe.record(t,s,a),{results:n,hasUnresolvedReference:o}}};be.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Q=be;const ye=class ye extends Q{constructor(e,t){super(t),this.forceEvaluation=ye.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(g.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ye.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let pe=ye;class X{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return $.waitForIdle()}static dialog(e){return $.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return $.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return $.enqueue(()=>{e instanceof HTMLDialogElement?(X.clearMessagesSync(e),e.showModal()):g.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return $.enqueue(()=>{e instanceof HTMLDialogElement?e.close():g.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return X.addMessage(e,t,"error")}static addMessage(e,t,r){return $.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return $.enqueue(()=>{X.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return Ee(e,t,r)}static now(e,t){return Ve(e,t)}static today(e,t,r){return je(e,t,r)}static number(e,t){return qe(e,t)}static range(e,t,r){return We(e,t,r)}static pages(e,t,r){return Ke(e,t,r)}static monthAdd(e,t){return ve(e,t)}static monthRange(e,t){return ze(e,t)}static pageSummary(e,t){return Ge(e,t)}static findBy(e,t,r){return Ye(e,t,r)}static sum(e,t){return Xe(e,t)}static distinct(e,t){return Qe(e,t)}static groupBy(e,t){return Ze(e,t)}}const ct=["addErrorMessage","clearMessages"],Pe="data-haori-group-name";function Be(){const e=globalThis.window?.Haori;return ct.every(r=>typeof e?.[r]=="function")?e:X}const v=class v{static getValues(e){const t={};return v.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(v.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(v.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){g.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Pe))return;const i=v.resolveGroupScope(e),n=`${String(t)}--haori${v.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Pe,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=v.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(v.groupScopeSequence+=1,v.GROUP_SCOPE_IDS.set(e,v.groupScopeSequence),v.groupScopeSequence)}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?v.hasDeclarativeBinding(e,"checked"):F.isValuePropertyTarget(t)?v.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?v.hasDeclarativeSelectedOption(t):!1:!1}static clearDeclarativeStateFromDom(e){if(v.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof F&&v.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=T.get(t);if(r instanceof F&&v.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return v.getPartValues(e,{},t)}static getPartValues(e,t,r=null){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return t;const i=v.resolveFieldName(e),n=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`),a=e.hasAttribute(`${l.prefix}form-list`),o=r!==null&&e.getUserEditSequence()<=r;if(i){if(a&&o)Array.isArray(t[String(i)])?t[String(i)].push(null):t[String(i)]=[null];else if(!o)if(a){const u=v.resolveCollectedValue(e),f=v.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(i)])?t[String(i)].push(...f):t[String(i)]=f}else if(v.isGroupedCheckable(e)){const u=e.getTarget(),h=(u instanceof HTMLInputElement?u.checked:!0)?e.getValue():null,p=String(i);h===null?p in t||(t[p]=null):t[p]===null||t[p]===void 0?t[p]=h:Array.isArray(t[p])?t[p].push(h):t[p]=[t[p],h]}else t[String(i)]=v.resolveCollectedValue(e);n&&g.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())v.getPartValues(u,t,r)}else if(n){const u={};for(const f of e.getChildElementFragments())v.getPartValues(f,u,r);Object.keys(u).length>0&&(t[String(n)]=u),s&&g.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const u=[];let f=!1;for(const h of e.getChildElementFragments()){const p={};v.getPartValues(h,p,r),Object.keys(p).length>0?(f=!0,u.push(p)):r!==null&&u.push({})}(r===null||f)&&(t[String(s)]=u)}else for(const u of e.getChildElementFragments())v.getPartValues(u,t,r);return t}static setValues(e,t,r=!1){return v.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1){return v.setPartValues(e,t,r,!1)}static syncRowValues(e,t){return v.setPartValues(e,t,!1,!1,!0)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=t[String(r)];return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(v.INITIAL_RESTORED_FORMS.has(i))continue;const n=T.get(i);if(!(n instanceof F))continue;const s=n.getRawBindingData();s&&(v.INITIAL_RESTORED_FORMS.add(i),r.push(v.syncValues(n,v.resolveSyncValues(n,s))))}return Promise.all(r).then(()=>{})}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map){const a=[],o=v.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),f=e.getAttribute(`${l.prefix}form-list`),h=e.hasAttribute(`${l.prefix}form-list`),p=e.getAttribute(`${l.prefix}form-detach`);if(o){if(!p||r){const y=t[String(o)],A=n&&typeof y>"u"&&!v.isDeclarativeStateBound(e)?null:y;if(v.isFileInput(e))return(A===null||A==="")&&a.push(v.applyFragmentValue(e,null,i)),Promise.all(a).then(()=>{});if(h&&Array.isArray(A)&&!v.isGroupedCheckable(e)&&!v.isMultipleSelect(e)){const C=String(o),w=s.get(C)??0;s.set(C,w+1),a.push(v.applyFragmentValue(e,A[w]??null,i))}else typeof A>"u"||(Array.isArray(A)&&v.isGroupedCheckable(e)||Array.isArray(A)&&v.isMultipleSelect(e)||typeof A=="string"||typeof A=="number"||typeof A=="boolean"||A===null?a.push(v.applyFragmentValue(e,A,i)):a.push(v.applyFragmentValue(e,String(A),i)))}}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const R=new Map;for(const A of e.getChildElementFragments())a.push(v.setPartValues(A,y,r,i,n,R))}}else if(f){const y=t[String(f)];if(Array.isArray(y)){const R=e.getChildElementFragments();for(let A=0;A<R.length;A++){const C=R[A];y.length>A?a.push(v.setPartValues(C,y[A],r,i,n,new Map)):a.push(v.setPartValues(C,{},r,i,n,new Map))}}}else for(const y of e.getChildElementFragments())a.push(v.setPartValues(y,t,r,i,n,s));return Promise.all(a).then(()=>{})}static async reset(e){k.clearUserEditMarks(e),v.clearValues(e),await Promise.all([v.clearMessages(e),v.clearEachClones(e)]),await $.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}v.clearDeclarativeStateFromDom(e)});const t=v.collectBindingTargetForms(e);for(const r of t){const i=v.getInitialBindingData(r);i===null&&r.getRawBindingData()===null||await k.setBindingData(r.getTarget(),i??{})}v.syncValuesFromDom(e),await k.evaluateAll(e);for(const r of t){const i=v.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=v.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await k.setBindingData(r.getTarget(),a)}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:k.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())v.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof F&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())v.clearValues(t)}static clearMessages(e){return Be().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return v.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Be(),a=s.addMessage,o=f=>typeof a=="function"?a.call(s,f,r,i):s.addErrorMessage(f,r),u=v.findFragmentsByKey(e,t);return u.forEach(f=>{n.push(o(f.getTarget()))}),u.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return v.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&v.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...v.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),f=Number(u);if(isNaN(f))g.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));f<h.length&&r.push(...v.findFragmentByKeyParts(h[f],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...v.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};v.INITIAL_RESTORED_FORMS=new WeakSet,v.GROUP_SCOPE_IDS=new WeakMap,v.groupScopeSequence=0;let V=v;class x{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){x.dispatch(document,"ready",{version:e})}static importStart(e,t){x.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){x.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){x.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const f=t?.[u],h=r[u];f!==h&&n.push(u)}x.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){x.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){x.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){x.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){x.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){x.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){x.dispatch(e,"show",{visible:!0})}static hide(e){x.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){x.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){x.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){x.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){x.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){x.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const dt={401:"unauthorized-redirect",403:"forbidden-redirect"};function ht(d,e){return d.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=G.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function ft(d,e){const t=d.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(d),i=r instanceof F?r.getBindingData():{},n=ht(t,i);return n===""?null:n}function pt(d,e,t){const r=d.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function _e(d){const e=dt[d];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=ft(i,t);if(n===null)continue;const s=pt(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class et{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const gt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],mt="__haoriHistoryState__",Te="data-haori-click-lock";function de(){const e=globalThis.window?.Haori;return gt.every(r=>typeof e?.[r]=="function")?e:X}const bt=new Set(["GET","HEAD","OPTIONS"]);function De(d){return bt.has(d.toUpperCase())}function yt(d,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{d.append(t,re(i))}):d.append(t,re(r)))}function re(d){if(d==null)return"";if(typeof d=="object"||typeof d=="function")try{return JSON.stringify(d)??""}catch{return""}return String(d)}function tt(d,e){const t=new URL(d,window.location.href),r=new URLSearchParams(t.search);return yt(r,e),t.search=r.toString(),t.toString()}function Et(d){if(d==null)return{payload:{},dropped:!1};if(typeof d=="string"){const e=d.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:$e(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(d instanceof URLSearchParams)return{payload:$e(d),dropped:!1};if(typeof FormData<"u"&&d instanceof FormData){const e={};let t=!1;for(const[r,i]of d.entries()){if(typeof i!="string"){t=!0;continue}rt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function $e(d){const e={};for(const[t,r]of d.entries())rt(e,t,r);return e}function rt(d,e,t){const r=d[e];r===void 0?d[e]=t:Array.isArray(r)?r.push(t):d[e]=[r,t]}function ge(d,e){if(Array.isArray(e)){const t=Array.isArray(d)?d.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=ge(t[n],i),r=!0))}),r?t:d}if(e!==null&&typeof e=="object"){const t=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};for(const[r,i]of Object.entries(e))t[r]=ge(t[r],i);return t}return e}function vt(d){const e=d?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function At(d,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||De(r))return{url:d,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Et(t.body);let s=d;Object.keys(i).length>0&&(s=tt(s,i)),n&&g.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function St(d){return d==null?null:typeof d=="string"?d:d instanceof URLSearchParams?d.toString():d instanceof FormData?Array.from(d.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(d)}function oe(d){return d instanceof Blob?!0:Array.isArray(d)?d.some(oe):d!==null&&typeof d=="object"?Object.values(d).some(oe):!1}function wt(d){return Object.values(d).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&oe(t)):oe(e))}function he(d){return Fe(V.getValues(d))}function Fe(d){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(d))t[r]=e(i);return t}function Tt(d,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:d,method:String(e.method||"GET").toUpperCase(),headers:r,body:St(e.body||null)})}const m=class m{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,m.isElementFragment(e)?(this.options=m.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return m.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=G.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?m.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return m.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=G.evaluateDetailed(s??a??"",t);return r=r||u.unresolvedReference,m.isJsonStringContext(e,o)?m.stringifyJsonTemplateStringContent(u.value):m.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return m.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(m.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:k.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=m.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=m.resolveDataParamStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(m.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(m.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(m.attrName(t,"confirm")).replace(/\\n/g,`
7
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};N.MAX_IDENTIFIER_RECOVERY_COUNT=8,N.BUILTIN_NAMESPACE="haori",N.BUILTIN_HELPERS={...ut},N.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,N.BUILTIN_DATA_PROPERTY="data",N.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,N.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,N.usableBindingKeyCache=new Map,N.loggedUnusableBindingKeys=new Set,N.compileFailedExpressions=new Set,N.forbiddenBindingValueCache=new WeakMap,N.forbiddenBindingValueCacheResetScheduled=!1,N.loggedForbiddenKeySignatures=new Set,N.loggedForbiddenKeyResetScheduled=!1,N.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],N.STRICT_FORBIDDEN_NAMES=["eval","arguments"],N.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),N.FORBIDDEN_BINDING_NAMES=new Set([...N.FORBIDDEN_NAMES.filter(e=>!N.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...N.STRICT_FORBIDDEN_NAMES]),N.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),N.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),N.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),N.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),N.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),N.EXPRESSION_CACHE=new Map,N.FREE_IDENTIFIER_CACHE=new Map,N.OPTIONAL_CHAIN_CACHE=new Map,N.FORBIDDEN_NAME_PATTERNS=N.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),N.FORBIDDEN_IDENTIFIER_CACHE=new Map,N.pendingUnresolvedIdentifiers=new Set,N.unresolvedReportScheduled=!1,N.loggedBlockedIdentifierExpressions=new Set;let G=N;const ae="data-haori-if-disabled",ke="input, select, textarea, button, fieldset",O=class O{static reset(){O.ELEMENT_STORES.clear(),O.ensureGlobalAccess()}static snapshot(){return O.ensureGlobalAccess(),[...O.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!W.isEnabled()||!e||t.length===0)return;O.ensureGlobalAccess();const i=O.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=O.getOrCreateCounter(i.attributes,e.rawName,e.template);O.updateCounter(s,t,r);return}const n=O.getOrCreateCounter(i.texts,String(e.childIndex),e.template);O.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!W.isEnabled())return;const e=globalThis;e[O.GLOBAL_KEY]===void 0&&(e[O.GLOBAL_KEY]={reset:()=>O.reset(),snapshot:()=>O.snapshot()})}static getOrCreateElementStore(e){const t=O.createElementId(e),r=O.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return O.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=O.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=O.now();return{value:e(),durationMs:O.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};O.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",O.ELEMENT_STORES=new Map;let fe=O;const te=class te{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,te.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(te.FRAGMENT_CACHE.has(e))return te.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new F(e);break;case Node.TEXT_NODE:t=new K(e);break;case Node.COMMENT_NODE:t=new Me(e);break;default:return g.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return $.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return $.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return $.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),te.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};te.FRAGMENT_CACHE=new WeakMap;let T=te;const H=class H extends T{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.userEditSequence=0,this.authoritativeValueSequence=0,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new pe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof H)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){g.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new H(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof H&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof H&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&r.type==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():$.enqueue(()=>{r.value=""})):(g.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,$.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,$.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,$.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&H.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return g.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}static currentUserEditSequence(){return H.userEditCounter}markUserEdit(){H.userEditCounter+=1,this.userEditSequence=H.userEditCounter}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=H.userEditCounter){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e)}static warnUnresolvedAttribute(e,t,r,i){if(!W.isEnabled())return;const n=`${e} ${r}`;H.loggedUnresolvedAttributes.has(n)||(H.loggedUnresolvedAttributes.add(n),g.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=T.get(t);return r instanceof H?r.hasPendingUserEdit():!1}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?H.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=T.get(t);r instanceof H&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!0,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e);const r=this.getTarget(),i=r.hasAttribute(e),n=t!==e&&r.hasAttribute(t);return!i&&!n?Promise.resolve():(this.skipMutationAttributes=!0,$.enqueue(()=>{i&&r.removeAttribute(e),n&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1}))}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new pe(e,r);if(n){const we=this.attributeMap.get(e);if(we&&(we.isEvaluate||we.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,$.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),u=s.isEvaluate||s.isRawEvaluate,f=e===t&&H.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=s.isSingleExpression(),p=Q.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||f||h?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&p==="");R&&o.hasUnresolvedReference&&H.warnUnresolvedAttribute(e,t,r,a);const A=s.isForceEvaluation()?r:h?y:p,C=i&&s.isEvaluate&&t==="value"&&H.isValuePropertyTarget(a),w=a.getRootNode(),S=C&&(a===w.activeElement||this.hasPendingUserEdit()),b=R||A===null||A===!1?null:String(A),D=e!==t&&a.getAttribute(e)!==r,M=b===null?a.hasAttribute(t):a.getAttribute(t)!==b,L=b===null?"":b,B=C&&!S&&a.value!==L,z=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),U=t==="selected"&&a instanceof HTMLOptionElement,Z=w.activeElement,Ae=Z!==null&&(z&&a===Z||U&&a.closest("select")===Z)||(z||U)&&this.hasPendingCheckableUserEdit(U),le=b!==null,Se=z&&!Ae&&a.checked!==le,ue=U&&!Ae&&a.selected!==le;return!D&&!M&&!B&&!Se&&!ue?(C&&!S&&(this.value=this.normalizeValueForElement(a,L)),(z||U)&&!Ae&&this.syncCheckableValueFromDom(U),Promise.resolve()):(this.skipMutationAttributes=!0,$.enqueue(()=>{D&&a.setAttribute(e,r),b===null?a.removeAttribute(t):M&&(a.setAttribute(t,b),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(b)),C&&!S&&(this.value=this.normalizeValueForElement(a,L),B&&(a.value=L)),Se&&(a.checked=le),ue&&(a.selected=le),(Se||ue)&&this.syncCheckableValueFromDom(ue)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();return t.hasAttribute(e)?(this.skipMutationAttributes=!0,$.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})):Promise.resolve()}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Q.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return g.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return g.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const u=e.getParent();u!==null&&u.removeChild(e);let f=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(g.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),f=y.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,$.enqueue(()=>{this.target.insertBefore(e.getTarget(),f)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(g.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),H.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(ke)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(ke)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){H.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(ae,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){H.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(ae)&&(e.removeAttribute(ae),e.removeAttribute("disabled"))})}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};H.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),H.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],H.userEditCounter=0,H.loggedUnresolvedAttributes=new Set;let F=H;class K extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Q(this.text)}clone(){const e=new K(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Q(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):$.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=Q.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class Me extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Me(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,$.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const be=class be{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(be.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(g.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const f=fe.measure(()=>G.evaluateDetailed(u.text,e)),h=f.value;a+=f.durationMs,s.push({expression:u.text,durationMs:f.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(u.text)}catch(f){g.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,f),s.push({expression:u.text,durationMs:0}),n.push("")}}),fe.record(t,s,a),{results:n,hasUnresolvedReference:o}}};be.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Q=be;const ye=class ye extends Q{constructor(e,t){super(t),this.forceEvaluation=ye.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(g.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ye.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let pe=ye;class X{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return $.waitForIdle()}static dialog(e){return $.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return $.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return $.enqueue(()=>{e instanceof HTMLDialogElement?(X.clearMessagesSync(e),e.showModal()):g.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return $.enqueue(()=>{e instanceof HTMLDialogElement?e.close():g.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return X.addMessage(e,t,"error")}static addMessage(e,t,r){return $.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return $.enqueue(()=>{X.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return Ee(e,t,r)}static now(e,t){return Ve(e,t)}static today(e,t,r){return je(e,t,r)}static number(e,t){return qe(e,t)}static range(e,t,r){return We(e,t,r)}static pages(e,t,r){return Ke(e,t,r)}static monthAdd(e,t){return ve(e,t)}static monthRange(e,t){return ze(e,t)}static pageSummary(e,t){return Ge(e,t)}static findBy(e,t,r){return Ye(e,t,r)}static sum(e,t){return Xe(e,t)}static distinct(e,t){return Qe(e,t)}static groupBy(e,t){return Ze(e,t)}}const ct=["addErrorMessage","clearMessages"],Pe="data-haori-group-name";function Be(){const e=globalThis.window?.Haori;return ct.every(r=>typeof e?.[r]=="function")?e:X}const v=class v{static getValues(e){const t={};return v.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(v.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(v.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){g.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Pe))return;const i=v.resolveGroupScope(e),n=`${String(t)}--haori${v.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Pe,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=v.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(v.groupScopeSequence+=1,v.GROUP_SCOPE_IDS.set(e,v.groupScopeSequence),v.groupScopeSequence)}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?v.hasDeclarativeBinding(e,"checked"):F.isValuePropertyTarget(t)?v.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?v.hasDeclarativeSelectedOption(t):!1:!1}static clearDeclarativeStateFromDom(e){if(v.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof F&&v.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=T.get(t);if(r instanceof F&&v.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return v.getPartValues(e,{},t)}static getPartValues(e,t,r=null){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return t;const i=v.resolveFieldName(e),n=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`),a=e.hasAttribute(`${l.prefix}form-list`),o=r!==null&&e.getUserEditSequence()<=r;if(i){if(a&&o)Array.isArray(t[String(i)])?t[String(i)].push(null):t[String(i)]=[null];else if(!o)if(a){const u=v.resolveCollectedValue(e),f=v.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(i)])?t[String(i)].push(...f):t[String(i)]=f}else if(v.isGroupedCheckable(e)){const u=e.getTarget(),h=(u instanceof HTMLInputElement?u.checked:!0)?e.getValue():null,p=String(i);h===null?p in t||(t[p]=null):t[p]===null||t[p]===void 0?t[p]=h:Array.isArray(t[p])?t[p].push(h):t[p]=[t[p],h]}else t[String(i)]=v.resolveCollectedValue(e);n&&g.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())v.getPartValues(u,t,r)}else if(n){const u={};for(const f of e.getChildElementFragments())v.getPartValues(f,u,r);Object.keys(u).length>0&&(t[String(n)]=u),s&&g.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const u=[];let f=!1;for(const h of e.getChildElementFragments()){const p={};v.getPartValues(h,p,r),Object.keys(p).length>0?(f=!0,u.push(p)):r!==null&&u.push({})}(r===null||f)&&(t[String(s)]=u)}else for(const u of e.getChildElementFragments())v.getPartValues(u,t,r);return t}static setValues(e,t,r=!1){return v.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1){return v.setPartValues(e,t,r,!1)}static syncRowValues(e,t){return v.setPartValues(e,t,!1,!1,!0)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=t[String(r)];return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(v.INITIAL_RESTORED_FORMS.has(i))continue;const n=T.get(i);if(!(n instanceof F))continue;const s=n.getRawBindingData();s&&(v.INITIAL_RESTORED_FORMS.add(i),r.push(v.syncValues(n,v.resolveSyncValues(n,s))))}return Promise.all(r).then(()=>{})}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map){const a=[],o=v.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),f=e.getAttribute(`${l.prefix}form-list`),h=e.hasAttribute(`${l.prefix}form-list`),p=e.getAttribute(`${l.prefix}form-detach`);if(o){if(!p||r){const y=t[String(o)],A=n&&typeof y>"u"&&!v.isDeclarativeStateBound(e)?null:y;if(v.isFileInput(e))return(A===null||A==="")&&a.push(v.applyFragmentValue(e,null,i)),Promise.all(a).then(()=>{});if(h&&Array.isArray(A)&&!v.isGroupedCheckable(e)&&!v.isMultipleSelect(e)){const C=String(o),w=s.get(C)??0;s.set(C,w+1),a.push(v.applyFragmentValue(e,A[w]??null,i))}else typeof A>"u"||(Array.isArray(A)&&v.isGroupedCheckable(e)||Array.isArray(A)&&v.isMultipleSelect(e)||typeof A=="string"||typeof A=="number"||typeof A=="boolean"||A===null?a.push(v.applyFragmentValue(e,A,i)):a.push(v.applyFragmentValue(e,String(A),i)))}}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const R=new Map;for(const A of e.getChildElementFragments())a.push(v.setPartValues(A,y,r,i,n,R))}}else if(f){const y=t[String(f)];if(Array.isArray(y)){const R=e.getChildElementFragments();for(let A=0;A<R.length;A++){const C=R[A];y.length>A?a.push(v.setPartValues(C,y[A],r,i,n,new Map)):a.push(v.setPartValues(C,{},r,i,n,new Map))}}}else for(const y of e.getChildElementFragments())a.push(v.setPartValues(y,t,r,i,n,s));return Promise.all(a).then(()=>{})}static async reset(e){k.clearUserEditMarks(e),v.clearValues(e),await Promise.all([v.clearMessages(e),v.clearEachClones(e)]),await $.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}v.clearDeclarativeStateFromDom(e)});const t=v.collectBindingTargetForms(e);for(const r of t){const i=v.getInitialBindingData(r);i===null&&r.getRawBindingData()===null||await k.setBindingData(r.getTarget(),i??{})}v.syncValuesFromDom(e),await k.evaluateAll(e);for(const r of t){const i=v.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=v.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await k.setBindingData(r.getTarget(),a)}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:k.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())v.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof F&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())v.clearValues(t)}static clearMessages(e){return Be().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return v.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Be(),a=s.addMessage,o=f=>typeof a=="function"?a.call(s,f,r,i):s.addErrorMessage(f,r),u=v.findFragmentsByKey(e,t);return u.forEach(f=>{n.push(o(f.getTarget()))}),u.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return v.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&v.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...v.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),f=Number(u);if(isNaN(f))g.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));f<h.length&&r.push(...v.findFragmentByKeyParts(h[f],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...v.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};v.INITIAL_RESTORED_FORMS=new WeakSet,v.GROUP_SCOPE_IDS=new WeakMap,v.groupScopeSequence=0;let V=v;class x{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){x.dispatch(document,"ready",{version:e})}static importStart(e,t){x.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){x.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){x.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const f=t?.[u],h=r[u];f!==h&&n.push(u)}x.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){x.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){x.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){x.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){x.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){x.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){x.dispatch(e,"show",{visible:!0})}static hide(e){x.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){x.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){x.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){x.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){x.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){x.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const dt={401:"unauthorized-redirect",403:"forbidden-redirect"};function ht(d,e){return d.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=G.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function ft(d,e){const t=d.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(d),i=r instanceof F?r.getBindingData():{},n=ht(t,i);return n===""?null:n}function pt(d,e,t){const r=d.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function _e(d){const e=dt[d];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=ft(i,t);if(n===null)continue;const s=pt(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class et{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const gt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],mt="__haoriHistoryState__",Te="data-haori-click-lock";function de(){const e=globalThis.window?.Haori;return gt.every(r=>typeof e?.[r]=="function")?e:X}const bt=new Set(["GET","HEAD","OPTIONS"]);function De(d){return bt.has(d.toUpperCase())}function yt(d,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{d.append(t,re(i))}):d.append(t,re(r)))}function re(d){if(d==null)return"";if(typeof d=="object"||typeof d=="function")try{return JSON.stringify(d)??""}catch{return""}return String(d)}function tt(d,e){const t=new URL(d,window.location.href),r=new URLSearchParams(t.search);return yt(r,e),t.search=r.toString(),t.toString()}function Et(d){if(d==null)return{payload:{},dropped:!1};if(typeof d=="string"){const e=d.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:$e(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(d instanceof URLSearchParams)return{payload:$e(d),dropped:!1};if(typeof FormData<"u"&&d instanceof FormData){const e={};let t=!1;for(const[r,i]of d.entries()){if(typeof i!="string"){t=!0;continue}rt(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function $e(d){const e={};for(const[t,r]of d.entries())rt(e,t,r);return e}function rt(d,e,t){const r=d[e];r===void 0?d[e]=t:Array.isArray(r)?r.push(t):d[e]=[r,t]}function ge(d,e){if(Array.isArray(e)){const t=Array.isArray(d)?d.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=ge(t[n],i),r=!0))}),r?t:d}if(e!==null&&typeof e=="object"){const t=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};for(const[r,i]of Object.entries(e))t[r]=ge(t[r],i);return t}return e}function vt(d){const e=d?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function At(d,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||De(r))return{url:d,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=Et(t.body);let s=d;Object.keys(i).length>0&&(s=tt(s,i)),n&&g.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function St(d){return d==null?null:typeof d=="string"?d:d instanceof URLSearchParams?d.toString():d instanceof FormData?Array.from(d.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(d)}function oe(d){return d instanceof Blob?!0:Array.isArray(d)?d.some(oe):d!==null&&typeof d=="object"?Object.values(d).some(oe):!1}function wt(d){return Object.values(d).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&oe(t)):oe(e))}function he(d){return Fe(V.getValues(d))}function Fe(d){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(d))t[r]=e(i);return t}function Tt(d,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:d,method:String(e.method||"GET").toUpperCase(),headers:r,body:St(e.body||null)})}const m=class m{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,m.isElementFragment(e)?(this.options=m.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return m.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=G.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?m.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return m.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=G.evaluateDetailed(s??a??"",t);return r=r||u.unresolvedReference,m.isJsonStringContext(e,o)?m.stringifyJsonTemplateStringContent(u.value):m.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return m.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(m.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:k.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=m.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=m.resolveDataParamStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(m.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(m.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(m.attrName(t,"confirm")).replace(/\\n/g,`
8
8
  `)),e.hasAttribute(m.attrName(t,"data"))&&(r.dataAttrName=m.attrName(t,"data")),e.hasAttribute(m.attrName(t,"form"))){const S=e.getRawAttribute(m.attrName(t,"form"));if(S){const b=document.body.querySelector(S);b!==null?r.formFragment=V.getFormFragment(T.get(b)):g.error("Haori",`Form element not found: ${S} (${m.attrName(t,"form")})`)}else r.formFragment=V.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=V.getFormFragment(e),r.formFragment===null&&m.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const S=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
9
9
  "use strict";
10
10
  ${S}
@@ -24,5 +24,5 @@ ${r}
24
24
  );`)}catch{try{i=new Function(`"use strict";
25
25
  ${r}
26
26
  `)}catch(n){g.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){g.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${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"&&(c.EACH_RENDERED_CHANGE_WARNED.has(r)||(c.EACH_RENDERED_CHANGE_WARNED.add(r),g.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),c.countEachRenderedRows(e)!==0){if(!n){if(c.EACH_RENDERED_CHANGE_FIRED.has(r))return;c.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){g.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=c.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=c.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof F){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof F&&(r=h.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const f=T.get(u);f instanceof F&&e.getChildren().includes(f)&&(e.removeChild(f),f.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?c.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(c.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=>c.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:(g.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`)||c.hasNonEachDynamicElementState(e)||!c.isRowLocalEachTemplate(e))return!1;const r=c.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),n=c.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=c.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(!c.areExpressionsRowLocal(c.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(c.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!c.areExpressionsRowLocal([s],t))return!1;continue}if(!c.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))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 F){if(!c.isRowLocalSubtree(i,r))return!1}else if(i instanceof K){const n=i.getRawText();if(n.includes("{{")&&!c.areExpressionsRowLocal(c.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=G.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:!c.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof F?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return c.recordDerivedSubtreeSignatureComputation(e,t),c.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:c.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!c.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(c.createDescendantBindingSignature(e,"refresh")),c.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!W.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=c.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:c.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.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=c.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 u=o.getChildren().filter(f=>f instanceof F).findIndex(f=>f===r);n+=`:nth-child(${u+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${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 K&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof F?!c.markFreshInitializationSkippable(n):n instanceof K?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 g.error("[Haori]","Template is not set for each element."),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=new Map,o=[];t.forEach((b,D)=>{const M=c.createListKey(b,n?String(n):null,D);o.push(M),a.set(M,{item:b,itemIndex:D})});const u=new Set(o),f=[];let h=e.getChildren().filter(b=>b instanceof F).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const p=h.map(b=>b.getListKey()),y=new Set;h=h.filter(b=>u.has(String(b.getListKey()))?!0:(y.add(b),f.push(b.remove()),!1));const R=h.map(b=>b.getListKey()),A=new Map;h.forEach(b=>{const D=b.getListKey();D!==null&&!A.has(D)&&A.set(D,b)});const C=e.getChildElementFragments().filter(b=>!y.has(b)),w=C.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let S=Promise.resolve();return o.forEach((b,D)=>{const{item:M,itemIndex:L}=a.get(b);let B;const z=A.get(b);if(z){B=z;const U=w+D;S=S.then(()=>c.updateRowFragment(B,M,i,L,s?String(s):null,b).then(Z=>c.repositionEachRow(e,B,C,U).then(()=>{if(Z)return c.clearUserEditMarks(B),c.evaluateAll(B).then(()=>c.applyRowFormValues(e,B,M))})))}else{B=r.clone();const U=w+D;S=S.then(()=>c.updateRowFragment(B,M,i,L,s?String(s):null,b).then(()=>{const Z=C[U]??null;return e.insertBefore(B,Z).then(()=>{C.splice(U,0,B)}).then(()=>c.initializeFreshEachRow(B)).then(()=>c.applyRowFormValues(e,B,M))}))}}),Promise.all(f).then(()=>S).then(()=>{const b=o.filter(U=>U!==null),D=R.filter(U=>U!==null),M=new Set(D),L=b.filter(U=>!M.has(U)),z=p.filter(U=>U!==null).filter(U=>!u.has(U));x.eachUpdate(e.getTarget(),L,z,b)})}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve();r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():V.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===u?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(u),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()&&c.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=>c.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)}:${c.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{c.evaluateAll(e)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),c.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"]),c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap,c.EACH_RENDERED_CHANGE_FIRED=new WeakSet,c.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let k=c;const se=class se{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[se.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=T.get(e);t&&new Y(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){g.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate))}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(se.BUILTIN_EVENT_NAMES.has(e)){g.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof F&&new Y(n,"on",t).run().catch(s=>{g.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)))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=T.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof F&&(i.syncValue(),i.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=T.get(a);o instanceof F&&(o.syncValue(),o.markUserEdit())}}const n=()=>{new Y(i,t,r).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}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}};se.HISTORY_STATE_KEY="__haoriHistoryState__",se.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ie=se;const P=class P{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)&&(P.isHtmlElement(e)&&P.syncElement(e),e.querySelectorAll("*").forEach(t=>{P.syncElement(t)}))}static syncElement(e){const t=P.registrations.get(e),r=T.get(e);if(!r||!P.shouldObserve(r)){t&&(t.observer.disconnect(),P.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=P.resolveRoot(r),n=P.resolveRootMargin(r),s=P.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&P.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),P.registrations.delete(e));const o=new IntersectionObserver(u=>{const f=P.registrations.get(e);f&&u.forEach(h=>{!h.isIntersecting||f.running||P.isDisabled(f.fragment)||(f.running=!0,new Y(f.fragment,"intersect").runWithResult().then(p=>{p&&f.once&&(f.observer.disconnect(),P.registrations.delete(e))}).catch(p=>{g.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=P.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),P.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(P.isHtmlElement(e)){const t=P.registrations.get(e);t&&(t.observer.disconnect(),P.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=P.registrations.get(t);r&&(r.observer.disconnect(),P.registrations.delete(t))})}static disconnectAll(){P.registrations.forEach(e=>{e.observer.disconnect()}),P.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!P.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=document.querySelector(r);return P.isHtmlElement(i)?i:(g.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}};P.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),P.registrations=new Map;let ie=P;const E=class E{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(E.isHtmlElement(e)&&E.syncElement(e),e.querySelectorAll("*").forEach(t=>{E.syncElement(t)}))}static syncElement(e){const t=E.registrations.get(e);if(!t&&!E.hasPollAttribute(e))return;const r=T.get(e);if(!(r instanceof F)||!E.shouldObserve(r)){t&&E.teardown(e,t);return}const i=E.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}E.teardown(e,t)}E.startPolling(e,r,i)}static cleanupTree(e){if(E.isHtmlElement(e)){const t=E.registrations.get(e);t&&E.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=E.registrations.get(t);r&&E.teardown(t,r)})}static disconnectAll(){E.registrations.forEach(e=>{E.clearTimers(e)}),E.registrations.clear(),E.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",E.visibilityListener),E.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)?!E.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(`
27
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:E.resolveInterval(t),timeoutMs:E.resolveTimeout(t),errorLimit:E.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};E.registrations.set(e,i),E.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{E.handleTimeout(e)},i.timeoutMs)),E.injectState(i),E.tick(e)}static async tick(e){const t=E.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await E.stop(e,t,"detached");return}const r=E.isHidden(e)||E.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await E.injectState(t)),r){E.schedule(e,t);return}if(E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new Y(t.fragment,"poll").runWithResult()}catch(n){g.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(E.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await E.stop(e,t,"error");return}if(await E.restoreStateIfCleared(t),i&&E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}E.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{E.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=E.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&x.pollTimeout(e,t.count,E.elapsed(t)),await E.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,E.clearTimers(t),r==="detached"){E.registrations.delete(e);return}await E.injectState(t),e.isConnected&&x.pollStop(e,r,t.count,E.elapsed(t))}}static teardown(e,t){E.clearTimers(t),E.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(E.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(E.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),E.tick(t))})};E.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=E.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:E.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return k.setBindingData(n,s,new Set,!1,!1,null)})).then(()=>{})}static async restoreStateIfCleared(e){E.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await E.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=document.querySelectorAll(i);if(n.length===0)return g.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=T.get(a);o instanceof F&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return E.DEFAULT_INTERVAL_MS;const r=E.toNumber(e.getAttribute(t));return r===null?(g.warn("[Haori]",`${t} は数値で指定してください。既定値 ${E.DEFAULT_INTERVAL_MS}ms を使用します。`),E.DEFAULT_INTERVAL_MS):r<E.MIN_INTERVAL_MS?(g.warn("[Haori]",`${t} の下限は ${E.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),E.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<=0?(g.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<1?(g.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?E.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?(g.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):E.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}};E.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),E.DEFAULT_INTERVAL_MS=5e3,E.MIN_INTERVAL_MS=100,E.registrations=new Map,E.visibilityListener=null;let ne=E;function Dt(d){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>d()):Promise.resolve().then(d)}const I=class I{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)&&(I.isHtmlElement(e)&&I.syncElement(e),e.querySelectorAll("*").forEach(t=>{I.syncElement(t)}))}static syncElement(e){const t=I.registrations.get(e),r=T.get(e);if(!(r instanceof F)||!I.shouldObserve(r)){t&&(t.observer.disconnect(),I.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=I.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),I.registrations.delete(e)),g.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=I.resolveRoot(r),s=I.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,I.refreshRows(t);return}t&&(t.observer.disconnect(),I.registrations.delete(e));const a=new IntersectionObserver(u=>{const f=I.registrations.get(e);if(!f)return;let h=!1;u.forEach(p=>{const y=p.target;f.observedRows.has(y)&&(p.isIntersecting?f.visibleRows.has(y)||(f.visibleRows.add(y),h=!0):f.visibleRows.delete(y)&&(h=!0))}),h&&I.scheduleCompute(f)},{root:n,rootMargin:s,threshold:I.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};I.registrations.set(e,o),I.refreshRows(o)}static cleanupTree(e){if(I.isHtmlElement(e)){const t=I.registrations.get(e);t&&(t.observer.disconnect(),I.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=I.registrations.get(t);r&&(r.observer.disconnect(),I.registrations.delete(t))})}static disconnectAll(){I.registrations.forEach(e=>{e.observer.disconnect()}),I.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=document.querySelector(r);return I.isHtmlElement(i)?i:(g.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===""?I.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof F&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=I.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));I.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Dt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();I.registrations.get(t)===e&&I.computeAndPublish(e)}))}static computeAndPublish(e){const t=I.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 u of i)u<a&&(a=u),u>o&&(o=u);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,I.publish(e,n))}static publish(e,t){const r=I.resolveBindOwner(e.fragment);if(!r){g.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);k.setBindingData(i,n,a,!1,!1,null).catch(o=>{g.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}};I.THRESHOLD=0,I.DEFAULT_ROOT_MARGIN="0px",I.registrations=new Map;let _=I;const q=class q{static disconnectMutationObservers(){q._mutationObservers.forEach(e=>{e.disconnect()}),q._mutationObservers.length=0}static async init(){if(q._initialized)return;q._initialized=!0,q.disconnectMutationObservers();const e=new Ie;q._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([k.scan(document.head),k.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",i.reason),await $.wait(),document.body.setAttribute("data-haori-ready",""),q.observe(document.head),q.observe(document.body),ie.syncTree(document.body),ne.syncTree(document.body),_.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return q._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(q.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&n.hasAttribute(ae)&&(i.attributeName==="disabled"||i.attributeName===ae)||i.attributeName&&k.isAliasedAttributeReflection(n,i.attributeName))break;k.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ie.syncElement(n),ne.syncElement(n),_.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ie.cleanupTree(n),ne.cleanupTree(n),_.cleanupTree(n),k.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(k.addNode(n.parentElement,n),ie.syncTree(n),ne.syncTree(n),_.syncTree(n))}),i.target instanceof Element&&_.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?k.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),q._mutationObservers.push(t)}};q._initialized=!1,q._mutationObservers=[],q._dispatcher=null;let me=q;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",me.init):me.init();const Ft=()=>X.waitForRenders(),It="0.30.0";exports.Core=k;exports.Env=l;exports.Form=V;exports.Fragment=T;exports.Haori=X;exports.Log=g;exports.Queue=$;exports.default=X;exports.version=It;exports.waitForRenders=Ft;
27
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:E.resolveInterval(t),timeoutMs:E.resolveTimeout(t),errorLimit:E.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};E.registrations.set(e,i),E.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{E.handleTimeout(e)},i.timeoutMs)),E.injectState(i),E.tick(e)}static async tick(e){const t=E.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await E.stop(e,t,"detached");return}const r=E.isHidden(e)||E.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await E.injectState(t)),r){E.schedule(e,t);return}if(E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new Y(t.fragment,"poll").runWithResult()}catch(n){g.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(E.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await E.stop(e,t,"error");return}if(await E.restoreStateIfCleared(t),i&&E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}E.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{E.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=E.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&x.pollTimeout(e,t.count,E.elapsed(t)),await E.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,E.clearTimers(t),r==="detached"){E.registrations.delete(e);return}await E.injectState(t),e.isConnected&&x.pollStop(e,r,t.count,E.elapsed(t))}}static teardown(e,t){E.clearTimers(t),E.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(E.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(E.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),E.tick(t))})};E.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=E.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:E.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return k.setBindingData(n,s,new Set,!1,!1,null)})).then(()=>{})}static async restoreStateIfCleared(e){E.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await E.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=document.querySelectorAll(i);if(n.length===0)return g.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=T.get(a);o instanceof F&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return E.DEFAULT_INTERVAL_MS;const r=E.toNumber(e.getAttribute(t));return r===null?(g.warn("[Haori]",`${t} は数値で指定してください。既定値 ${E.DEFAULT_INTERVAL_MS}ms を使用します。`),E.DEFAULT_INTERVAL_MS):r<E.MIN_INTERVAL_MS?(g.warn("[Haori]",`${t} の下限は ${E.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),E.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<=0?(g.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<1?(g.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?E.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?(g.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):E.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}};E.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),E.DEFAULT_INTERVAL_MS=5e3,E.MIN_INTERVAL_MS=100,E.registrations=new Map,E.visibilityListener=null;let ne=E;function Dt(d){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>d()):Promise.resolve().then(d)}const I=class I{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)&&(I.isHtmlElement(e)&&I.syncElement(e),e.querySelectorAll("*").forEach(t=>{I.syncElement(t)}))}static syncElement(e){const t=I.registrations.get(e),r=T.get(e);if(!(r instanceof F)||!I.shouldObserve(r)){t&&(t.observer.disconnect(),I.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=I.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),I.registrations.delete(e)),g.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=I.resolveRoot(r),s=I.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,I.refreshRows(t);return}t&&(t.observer.disconnect(),I.registrations.delete(e));const a=new IntersectionObserver(u=>{const f=I.registrations.get(e);if(!f)return;let h=!1;u.forEach(p=>{const y=p.target;f.observedRows.has(y)&&(p.isIntersecting?f.visibleRows.has(y)||(f.visibleRows.add(y),h=!0):f.visibleRows.delete(y)&&(h=!0))}),h&&I.scheduleCompute(f)},{root:n,rootMargin:s,threshold:I.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};I.registrations.set(e,o),I.refreshRows(o)}static cleanupTree(e){if(I.isHtmlElement(e)){const t=I.registrations.get(e);t&&(t.observer.disconnect(),I.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=I.registrations.get(t);r&&(r.observer.disconnect(),I.registrations.delete(t))})}static disconnectAll(){I.registrations.forEach(e=>{e.observer.disconnect()}),I.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=document.querySelector(r);return I.isHtmlElement(i)?i:(g.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===""?I.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof F&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=I.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));I.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Dt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();I.registrations.get(t)===e&&I.computeAndPublish(e)}))}static computeAndPublish(e){const t=I.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 u of i)u<a&&(a=u),u>o&&(o=u);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,I.publish(e,n))}static publish(e,t){const r=I.resolveBindOwner(e.fragment);if(!r){g.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);k.setBindingData(i,n,a,!1,!1,null).catch(o=>{g.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}};I.THRESHOLD=0,I.DEFAULT_ROOT_MARGIN="0px",I.registrations=new Map;let _=I;const q=class q{static disconnectMutationObservers(){q._mutationObservers.forEach(e=>{e.disconnect()}),q._mutationObservers.length=0}static async init(){if(q._initialized)return;q._initialized=!0,q.disconnectMutationObservers();const e=new Ie;q._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([k.scan(document.head),k.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",i.reason),await $.wait(),document.body.setAttribute("data-haori-ready",""),q.observe(document.head),q.observe(document.body),ie.syncTree(document.body),ne.syncTree(document.body),_.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return q._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(q.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&n.hasAttribute(ae)&&(i.attributeName==="disabled"||i.attributeName===ae)||i.attributeName&&k.isAliasedAttributeReflection(n,i.attributeName))break;k.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ie.syncElement(n),ne.syncElement(n),_.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ie.cleanupTree(n),ne.cleanupTree(n),_.cleanupTree(n),k.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(k.addNode(n.parentElement,n),ie.syncTree(n),ne.syncTree(n),_.syncTree(n))}),i.target instanceof Element&&_.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?k.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),q._mutationObservers.push(t)}};q._initialized=!1,q._mutationObservers=[],q._dispatcher=null;let me=q;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",me.init):me.init();const Ft=()=>X.waitForRenders(),It="0.30.1";exports.Core=k;exports.Env=l;exports.Form=V;exports.Fragment=T;exports.Haori=X;exports.Log=g;exports.Queue=$;exports.default=X;exports.version=It;exports.waitForRenders=Ft;
28
28
  //# sourceMappingURL=haori.cjs.js.map
package/dist/haori.es.js CHANGED
@@ -2829,6 +2829,9 @@ const H = class H extends R {
2829
2829
  /**
2830
2830
  * data-attr-* の生属性と反映先属性を同時に削除します。
2831
2831
  *
2832
+ * DOM に残っている属性だけを削除対象にします。すでに無い属性はキューへ積まず、
2833
+ * 内部の属性マップの更新だけを行います(後続の書き込みを消さないため)。
2834
+ *
2832
2835
  * @param rawName 生の属性名
2833
2836
  * @param targetName 反映先の属性名
2834
2837
  * @returns 属性削除の Promise
@@ -2836,13 +2839,13 @@ const H = class H extends R {
2836
2839
  removeAliasedAttribute(e, t) {
2837
2840
  if (this.skipMutationAttributes)
2838
2841
  return Promise.resolve();
2839
- this.attributeMap.delete(e), this.skipMutationAttributes = !0;
2840
- const r = this.getTarget();
2841
- return L.enqueue(() => {
2842
- r.removeAttribute(e), t !== e && r.removeAttribute(t);
2842
+ this.attributeMap.delete(e);
2843
+ const r = this.getTarget(), i = r.hasAttribute(e), n = t !== e && r.hasAttribute(t);
2844
+ return !i && !n ? Promise.resolve() : (this.skipMutationAttributes = !0, L.enqueue(() => {
2845
+ i && r.removeAttribute(e), n && r.removeAttribute(t);
2843
2846
  }).finally(() => {
2844
2847
  this.skipMutationAttributes = !1;
2845
- });
2848
+ }));
2846
2849
  }
2847
2850
  /**
2848
2851
  * 生の属性値を保持しつつ、必要に応じて別名属性へ評価結果を反映します。
@@ -2897,19 +2900,23 @@ const H = class H extends R {
2897
2900
  /**
2898
2901
  * 属性の値を削除します。
2899
2902
  *
2903
+ * DOM に属性が無い場合はキューへ削除タスクを積まず、内部の属性マップの更新だけを
2904
+ * 行います。キュー待ちの削除が、その間に他の経路(優先実行の直接書き込みなど)で
2905
+ * 書き込まれた値を消してしまうのを防ぐためです。
2906
+ *
2900
2907
  * @param name 属性名
2901
2908
  * @returns 属性の削除のPromise
2902
2909
  */
2903
2910
  removeAttribute(e) {
2904
2911
  if (this.skipMutationAttributes)
2905
2912
  return Promise.resolve();
2906
- this.attributeMap.delete(e), this.skipMutationAttributes = !0;
2913
+ this.attributeMap.delete(e);
2907
2914
  const t = this.getTarget();
2908
- return L.enqueue(() => {
2915
+ return t.hasAttribute(e) ? (this.skipMutationAttributes = !0, L.enqueue(() => {
2909
2916
  t.removeAttribute(e);
2910
2917
  }).finally(() => {
2911
2918
  this.skipMutationAttributes = !1;
2912
- });
2919
+ })) : Promise.resolve();
2913
2920
  }
2914
2921
  /**
2915
2922
  * 属性の評価された値を取得します。
@@ -9878,7 +9885,7 @@ const q = class q {
9878
9885
  q._initialized = !1, q._mutationObservers = [], q._dispatcher = null;
9879
9886
  let me = q;
9880
9887
  document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", me.init) : me.init();
9881
- const Ft = () => te.waitForRenders(), It = "0.30.0";
9888
+ const Ft = () => te.waitForRenders(), It = "0.30.1";
9882
9889
  export {
9883
9890
  P as Core,
9884
9891
  l as Env,
@@ -4,7 +4,7 @@ let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIden
4
4
  ${h};
5
5
  return (${y});${p}`:`"use strict";
6
6
  return (${y});${p}`;try{return f=new Function(...n,R),this.EXPRESSION_CACHE.set(u,f),this.compileFailedExpressions.delete(e),{bindKeys:n,evaluator:f,compileFailed:!1}}catch(A){return o.length>0?(g.warn("[Haori]","Failed to shadow undeclared identifier(s): "+o.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(g.error("[Haori]","Failed to compile expression:",e,A),this.compileFailedExpressions.add(e),{bindKeys:n,evaluator:null,compileFailed:!0})}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,u=t[n-2]||null,f=t[n-3]||null;if(this.startsObjectKey(o,i,u,f)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
7
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};N.MAX_IDENTIFIER_RECOVERY_COUNT=8,N.BUILTIN_NAMESPACE="haori",N.BUILTIN_HELPERS={...ct},N.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,N.BUILTIN_DATA_PROPERTY="data",N.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,N.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,N.usableBindingKeyCache=new Map,N.loggedUnusableBindingKeys=new Set,N.compileFailedExpressions=new Set,N.forbiddenBindingValueCache=new WeakMap,N.forbiddenBindingValueCacheResetScheduled=!1,N.loggedForbiddenKeySignatures=new Set,N.loggedForbiddenKeyResetScheduled=!1,N.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],N.STRICT_FORBIDDEN_NAMES=["eval","arguments"],N.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),N.FORBIDDEN_BINDING_NAMES=new Set([...N.FORBIDDEN_NAMES.filter(e=>!N.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...N.STRICT_FORBIDDEN_NAMES]),N.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),N.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),N.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),N.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),N.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),N.EXPRESSION_CACHE=new Map,N.FREE_IDENTIFIER_CACHE=new Map,N.OPTIONAL_CHAIN_CACHE=new Map,N.FORBIDDEN_NAME_PATTERNS=N.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),N.FORBIDDEN_IDENTIFIER_CACHE=new Map,N.pendingUnresolvedIdentifiers=new Set,N.unresolvedReportScheduled=!1,N.loggedBlockedIdentifierExpressions=new Set;let Y=N;const oe="data-haori-if-disabled",Je="input, select, textarea, button, fieldset",O=class O{static reset(){O.ELEMENT_STORES.clear(),O.ensureGlobalAccess()}static snapshot(){return O.ensureGlobalAccess(),[...O.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!W.isEnabled()||!e||t.length===0)return;O.ensureGlobalAccess();const i=O.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=O.getOrCreateCounter(i.attributes,e.rawName,e.template);O.updateCounter(s,t,r);return}const n=O.getOrCreateCounter(i.texts,String(e.childIndex),e.template);O.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!W.isEnabled())return;const e=globalThis;e[O.GLOBAL_KEY]===void 0&&(e[O.GLOBAL_KEY]={reset:()=>O.reset(),snapshot:()=>O.snapshot()})}static getOrCreateElementStore(e){const t=O.createElementId(e),r=O.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return O.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=O.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=O.now();return{value:e(),durationMs:O.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};O.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",O.ELEMENT_STORES=new Map;let he=O;const te=class te{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,te.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(te.FRAGMENT_CACHE.has(e))return te.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new F(e);break;case Node.TEXT_NODE:t=new z(e);break;case Node.COMMENT_NODE:t=new Te(e);break;default:return g.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return B.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),te.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};te.FRAGMENT_CACHE=new WeakMap;let T=te;const H=class H extends T{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.userEditSequence=0,this.authoritativeValueSequence=0,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new fe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof H)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){g.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new H(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof H&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof H&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&r.type==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():B.enqueue(()=>{r.value=""})):(g.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,B.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,B.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,B.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&H.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return g.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}static currentUserEditSequence(){return H.userEditCounter}markUserEdit(){H.userEditCounter+=1,this.userEditSequence=H.userEditCounter}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=H.userEditCounter){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e)}static warnUnresolvedAttribute(e,t,r,i){if(!W.isEnabled())return;const n=`${e} ${r}`;H.loggedUnresolvedAttributes.has(n)||(H.loggedUnresolvedAttributes.add(n),g.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=T.get(t);return r instanceof H?r.hasPendingUserEdit():!1}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?H.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=T.get(t);r instanceof H&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!0,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return B.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new fe(e,r);if(n){const Ce=this.attributeMap.get(e);if(Ce&&(Ce.isEvaluate||Ce.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,B.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),u=s.isEvaluate||s.isRawEvaluate,f=e===t&&H.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=s.isSingleExpression(),p=Z.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||f||h?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&p==="");R&&o.hasUnresolvedReference&&H.warnUnresolvedAttribute(e,t,r,a);const A=s.isForceEvaluation()?r:h?y:p,C=i&&s.isEvaluate&&t==="value"&&H.isValuePropertyTarget(a),w=a.getRootNode(),S=C&&(a===w.activeElement||this.hasPendingUserEdit()),b=R||A===null||A===!1?null:String(A),D=e!==t&&a.getAttribute(e)!==r,M=b===null?a.hasAttribute(t):a.getAttribute(t)!==b,L=b===null?"":b,$=C&&!S&&a.value!==L,G=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),U=t==="selected"&&a instanceof HTMLOptionElement,re=w.activeElement,Me=re!==null&&(G&&a===re||U&&a.closest("select")===re)||(G||U)&&this.hasPendingCheckableUserEdit(U),ve=b!==null,xe=G&&!Me&&a.checked!==ve,Ae=U&&!Me&&a.selected!==ve;return!D&&!M&&!$&&!xe&&!Ae?(C&&!S&&(this.value=this.normalizeValueForElement(a,L)),(G||U)&&!Me&&this.syncCheckableValueFromDom(U),Promise.resolve()):(this.skipMutationAttributes=!0,B.enqueue(()=>{D&&a.setAttribute(e,r),b===null?a.removeAttribute(t):M&&(a.setAttribute(t,b),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(b)),C&&!S&&(this.value=this.normalizeValueForElement(a,L),$&&(a.value=L)),xe&&(a.checked=ve),Ae&&(a.selected=ve),(xe||Ae)&&this.syncCheckableValueFromDom(Ae)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return B.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Z.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return g.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return g.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const u=e.getParent();u!==null&&u.removeChild(e);let f=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(g.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),f=y.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,B.enqueue(()=>{this.target.insertBefore(e.getTarget(),f)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(g.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),H.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Je)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(Je)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){H.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(oe,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){H.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(oe)&&(e.removeAttribute(oe),e.removeAttribute("disabled"))})}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};H.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),H.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],H.userEditCounter=0,H.loggedUnresolvedAttributes=new Set;let F=H;class z extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Z(this.text)}clone(){const e=new z(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Z(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):B.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=Z.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class Te extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Te(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,B.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ye=class ye{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ye.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(g.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const f=he.measure(()=>Y.evaluateDetailed(u.text,e)),h=f.value;a+=f.durationMs,s.push({expression:u.text,durationMs:f.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(u.text)}catch(f){g.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,f),s.push({expression:u.text,durationMs:0}),n.push("")}}),he.record(t,s,a),{results:n,hasUnresolvedReference:o}}};ye.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Z=ye;const Ee=class Ee extends Z{constructor(e,t){super(t),this.forceEvaluation=Ee.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(g.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Ee.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let fe=Ee;class J{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return B.waitForIdle()}static dialog(e){return B.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return B.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?(J.clearMessagesSync(e),e.showModal()):g.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?e.close():g.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return J.addMessage(e,t,"error")}static addMessage(e,t,r){return B.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return B.enqueue(()=>{J.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return ue(e,t,r)}static now(e,t){return Oe(e,t)}static today(e,t,r){return He(e,t,r)}static number(e,t){return Ue(e,t)}static range(e,t,r){return Ve(e,t,r)}static pages(e,t,r){return je(e,t,r)}static monthAdd(e,t){return de(e,t)}static monthRange(e,t){return qe(e,t)}static pageSummary(e,t){return We(e,t)}static findBy(e,t,r){return Ke(e,t,r)}static sum(e,t){return ze(e,t)}static distinct(e,t){return Ye(e,t)}static groupBy(e,t){return Xe(e,t)}}const dt=["addErrorMessage","clearMessages"],Qe="data-haori-group-name";function Ze(){const e=globalThis.window?.Haori;return dt.every(r=>typeof e?.[r]=="function")?e:J}const v=class v{static getValues(e){const t={};return v.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(v.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(v.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){g.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Qe))return;const i=v.resolveGroupScope(e),n=`${String(t)}--haori${v.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Qe,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=v.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(v.groupScopeSequence+=1,v.GROUP_SCOPE_IDS.set(e,v.groupScopeSequence),v.groupScopeSequence)}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?v.hasDeclarativeBinding(e,"checked"):F.isValuePropertyTarget(t)?v.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?v.hasDeclarativeSelectedOption(t):!1:!1}static clearDeclarativeStateFromDom(e){if(v.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof F&&v.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=T.get(t);if(r instanceof F&&v.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return v.getPartValues(e,{},t)}static getPartValues(e,t,r=null){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return t;const i=v.resolveFieldName(e),n=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`),a=e.hasAttribute(`${l.prefix}form-list`),o=r!==null&&e.getUserEditSequence()<=r;if(i){if(a&&o)Array.isArray(t[String(i)])?t[String(i)].push(null):t[String(i)]=[null];else if(!o)if(a){const u=v.resolveCollectedValue(e),f=v.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(i)])?t[String(i)].push(...f):t[String(i)]=f}else if(v.isGroupedCheckable(e)){const u=e.getTarget(),h=(u instanceof HTMLInputElement?u.checked:!0)?e.getValue():null,p=String(i);h===null?p in t||(t[p]=null):t[p]===null||t[p]===void 0?t[p]=h:Array.isArray(t[p])?t[p].push(h):t[p]=[t[p],h]}else t[String(i)]=v.resolveCollectedValue(e);n&&g.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())v.getPartValues(u,t,r)}else if(n){const u={};for(const f of e.getChildElementFragments())v.getPartValues(f,u,r);Object.keys(u).length>0&&(t[String(n)]=u),s&&g.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const u=[];let f=!1;for(const h of e.getChildElementFragments()){const p={};v.getPartValues(h,p,r),Object.keys(p).length>0?(f=!0,u.push(p)):r!==null&&u.push({})}(r===null||f)&&(t[String(s)]=u)}else for(const u of e.getChildElementFragments())v.getPartValues(u,t,r);return t}static setValues(e,t,r=!1){return v.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1){return v.setPartValues(e,t,r,!1)}static syncRowValues(e,t){return v.setPartValues(e,t,!1,!1,!0)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=t[String(r)];return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(v.INITIAL_RESTORED_FORMS.has(i))continue;const n=T.get(i);if(!(n instanceof F))continue;const s=n.getRawBindingData();s&&(v.INITIAL_RESTORED_FORMS.add(i),r.push(v.syncValues(n,v.resolveSyncValues(n,s))))}return Promise.all(r).then(()=>{})}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map){const a=[],o=v.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),f=e.getAttribute(`${l.prefix}form-list`),h=e.hasAttribute(`${l.prefix}form-list`),p=e.getAttribute(`${l.prefix}form-detach`);if(o){if(!p||r){const y=t[String(o)],A=n&&typeof y>"u"&&!v.isDeclarativeStateBound(e)?null:y;if(v.isFileInput(e))return(A===null||A==="")&&a.push(v.applyFragmentValue(e,null,i)),Promise.all(a).then(()=>{});if(h&&Array.isArray(A)&&!v.isGroupedCheckable(e)&&!v.isMultipleSelect(e)){const C=String(o),w=s.get(C)??0;s.set(C,w+1),a.push(v.applyFragmentValue(e,A[w]??null,i))}else typeof A>"u"||(Array.isArray(A)&&v.isGroupedCheckable(e)||Array.isArray(A)&&v.isMultipleSelect(e)||typeof A=="string"||typeof A=="number"||typeof A=="boolean"||A===null?a.push(v.applyFragmentValue(e,A,i)):a.push(v.applyFragmentValue(e,String(A),i)))}}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const R=new Map;for(const A of e.getChildElementFragments())a.push(v.setPartValues(A,y,r,i,n,R))}}else if(f){const y=t[String(f)];if(Array.isArray(y)){const R=e.getChildElementFragments();for(let A=0;A<R.length;A++){const C=R[A];y.length>A?a.push(v.setPartValues(C,y[A],r,i,n,new Map)):a.push(v.setPartValues(C,{},r,i,n,new Map))}}}else for(const y of e.getChildElementFragments())a.push(v.setPartValues(y,t,r,i,n,s));return Promise.all(a).then(()=>{})}static async reset(e){k.clearUserEditMarks(e),v.clearValues(e),await Promise.all([v.clearMessages(e),v.clearEachClones(e)]),await B.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}v.clearDeclarativeStateFromDom(e)});const t=v.collectBindingTargetForms(e);for(const r of t){const i=v.getInitialBindingData(r);i===null&&r.getRawBindingData()===null||await k.setBindingData(r.getTarget(),i??{})}v.syncValuesFromDom(e),await k.evaluateAll(e);for(const r of t){const i=v.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=v.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await k.setBindingData(r.getTarget(),a)}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:k.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())v.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof F&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())v.clearValues(t)}static clearMessages(e){return Ze().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return v.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ze(),a=s.addMessage,o=f=>typeof a=="function"?a.call(s,f,r,i):s.addErrorMessage(f,r),u=v.findFragmentsByKey(e,t);return u.forEach(f=>{n.push(o(f.getTarget()))}),u.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return v.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&v.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...v.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),f=Number(u);if(isNaN(f))g.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));f<h.length&&r.push(...v.findFragmentByKeyParts(h[f],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...v.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};v.INITIAL_RESTORED_FORMS=new WeakSet,v.GROUP_SCOPE_IDS=new WeakMap,v.groupScopeSequence=0;let V=v;class x{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){x.dispatch(document,"ready",{version:e})}static importStart(e,t){x.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){x.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){x.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const f=t?.[u],h=r[u];f!==h&&n.push(u)}x.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){x.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){x.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){x.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){x.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){x.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){x.dispatch(e,"show",{visible:!0})}static hide(e){x.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){x.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){x.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){x.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){x.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){x.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const ht={401:"unauthorized-redirect",403:"forbidden-redirect"};function ft(d,e){return d.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function pt(d,e){const t=d.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(d),i=r instanceof F?r.getBindingData():{},n=ft(t,i);return n===""?null:n}function gt(d,e,t){const r=d.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function _e(d){const e=ht[d];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=pt(i,t);if(n===null)continue;const s=gt(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class et{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],bt="__haoriHistoryState__",Re="data-haori-click-lock";function pe(){const e=globalThis.window?.Haori;return mt.every(r=>typeof e?.[r]=="function")?e:J}const yt=new Set(["GET","HEAD","OPTIONS"]);function De(d){return yt.has(d.toUpperCase())}function Et(d,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{d.append(t,ie(i))}):d.append(t,ie(r)))}function ie(d){if(d==null)return"";if(typeof d=="object"||typeof d=="function")try{return JSON.stringify(d)??""}catch{return""}return String(d)}function tt(d,e){const t=new URL(d,window.location.href),r=new URLSearchParams(t.search);return Et(r,e),t.search=r.toString(),t.toString()}function vt(d){if(d==null)return{payload:{},dropped:!1};if(typeof d=="string"){const e=d.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:rt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(d instanceof URLSearchParams)return{payload:rt(d),dropped:!1};if(typeof FormData<"u"&&d instanceof FormData){const e={};let t=!1;for(const[r,i]of d.entries()){if(typeof i!="string"){t=!0;continue}it(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function rt(d){const e={};for(const[t,r]of d.entries())it(e,t,r);return e}function it(d,e,t){const r=d[e];r===void 0?d[e]=t:Array.isArray(r)?r.push(t):d[e]=[r,t]}function ge(d,e){if(Array.isArray(e)){const t=Array.isArray(d)?d.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=ge(t[n],i),r=!0))}),r?t:d}if(e!==null&&typeof e=="object"){const t=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};for(const[r,i]of Object.entries(e))t[r]=ge(t[r],i);return t}return e}function At(d){const e=d?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function St(d,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||De(r))return{url:d,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=vt(t.body);let s=d;Object.keys(i).length>0&&(s=tt(s,i)),n&&g.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function wt(d){return d==null?null:typeof d=="string"?d:d instanceof URLSearchParams?d.toString():d instanceof FormData?Array.from(d.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(d)}function le(d){return d instanceof Blob?!0:Array.isArray(d)?d.some(le):d!==null&&typeof d=="object"?Object.values(d).some(le):!1}function Tt(d){return Object.values(d).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&le(t)):le(e))}function me(d){return Fe(V.getValues(d))}function Fe(d){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(d))t[r]=e(i);return t}function Rt(d,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:d,method:String(e.method||"GET").toUpperCase(),headers:r,body:wt(e.body||null)})}const m=class m{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,m.isElementFragment(e)?(this.options=m.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return m.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=Y.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?m.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return m.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=Y.evaluateDetailed(s??a??"",t);return r=r||u.unresolvedReference,m.isJsonStringContext(e,o)?m.stringifyJsonTemplateStringContent(u.value):m.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return m.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(m.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:k.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=m.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=m.resolveDataParamStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(m.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(m.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(m.attrName(t,"confirm")).replace(/\\n/g,`
7
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};N.MAX_IDENTIFIER_RECOVERY_COUNT=8,N.BUILTIN_NAMESPACE="haori",N.BUILTIN_HELPERS={...ct},N.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,N.BUILTIN_DATA_PROPERTY="data",N.BUILTIN_DATA_REFERENCE_PATTERN=/(^|[^\w$.])haori\s*(\.\s*data(?![\w$])|\[)/,N.IDENTIFIER_NAME_PATTERN=/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u,N.usableBindingKeyCache=new Map,N.loggedUnusableBindingKeys=new Set,N.compileFailedExpressions=new Set,N.forbiddenBindingValueCache=new WeakMap,N.forbiddenBindingValueCacheResetScheduled=!1,N.loggedForbiddenKeySignatures=new Set,N.loggedForbiddenKeyResetScheduled=!1,N.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],N.STRICT_FORBIDDEN_NAMES=["eval","arguments"],N.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),N.FORBIDDEN_BINDING_NAMES=new Set([...N.FORBIDDEN_NAMES.filter(e=>!N.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...N.STRICT_FORBIDDEN_NAMES]),N.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),N.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),N.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),N.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),N.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),N.EXPRESSION_CACHE=new Map,N.FREE_IDENTIFIER_CACHE=new Map,N.OPTIONAL_CHAIN_CACHE=new Map,N.FORBIDDEN_NAME_PATTERNS=N.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),N.FORBIDDEN_IDENTIFIER_CACHE=new Map,N.pendingUnresolvedIdentifiers=new Set,N.unresolvedReportScheduled=!1,N.loggedBlockedIdentifierExpressions=new Set;let Y=N;const oe="data-haori-if-disabled",Je="input, select, textarea, button, fieldset",O=class O{static reset(){O.ELEMENT_STORES.clear(),O.ensureGlobalAccess()}static snapshot(){return O.ensureGlobalAccess(),[...O.ELEMENT_STORES.entries()].map(([e,t])=>({elementId:e,tagName:t.tagName,attributes:[...t.attributes.entries()].map(([r,i])=>({name:r,template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls),texts:[...t.texts.entries()].map(([r,i])=>({childIndex:Number(r),template:i.template,calls:i.calls,totalDurationMs:i.totalDurationMs,maxDurationMs:i.maxDurationMs,placeholders:O.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!W.isEnabled()||!e||t.length===0)return;O.ensureGlobalAccess();const i=O.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=O.getOrCreateCounter(i.attributes,e.rawName,e.template);O.updateCounter(s,t,r);return}const n=O.getOrCreateCounter(i.texts,String(e.childIndex),e.template);O.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!W.isEnabled())return;const e=globalThis;e[O.GLOBAL_KEY]===void 0&&(e[O.GLOBAL_KEY]={reset:()=>O.reset(),snapshot:()=>O.snapshot()})}static getOrCreateElementStore(e){const t=O.createElementId(e),r=O.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return O.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=O.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=O.now();return{value:e(),durationMs:O.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};O.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",O.ELEMENT_STORES=new Map;let he=O;const te=class te{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,te.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(te.FRAGMENT_CACHE.has(e))return te.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new F(e);break;case Node.TEXT_NODE:t=new z(e);break;case Node.COMMENT_NODE:t=new Te(e);break;default:return g.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return B.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),te.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};te.FRAGMENT_CACHE=new WeakMap;let T=te;const H=class H extends T{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.userEditSequence=0,this.authoritativeValueSequence=0,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new fe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof H)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){g.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new H(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf()),this.children.forEach(e=>{e instanceof H&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof H&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&r.type==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():B.enqueue(()=>{r.value=""})):(g.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,B.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,B.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,B.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&H.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return g.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}static currentUserEditSequence(){return H.userEditCounter}markUserEdit(){H.userEditCounter+=1,this.userEditSequence=H.userEditCounter}getUserEditSequence(){return this.userEditSequence}hasPendingUserEdit(){return this.userEditSequence>this.authoritativeValueSequence}clearUserEditMark(e=H.userEditCounter){e>this.authoritativeValueSequence&&(this.authoritativeValueSequence=e)}static warnUnresolvedAttribute(e,t,r,i){if(!W.isEnabled())return;const n=`${e} ${r}`;H.loggedUnresolvedAttributes.has(n)||(H.loggedUnresolvedAttributes.add(n),g.warn("[Haori]",`Attribute "${t}" was not applied because the expression has an unresolved reference; the attribute is removed and the synchronized value is emptied: ${e}="${r}"`,i))}hasPendingCheckableUserEdit(e){if(!e)return this.hasPendingUserEdit();const t=this.getTarget().closest("select");if(!t)return!1;const r=T.get(t);return r instanceof H?r.hasPendingUserEdit():!1}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?H.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=T.get(t);r instanceof H&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!0,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e);const r=this.getTarget(),i=r.hasAttribute(e),n=t!==e&&r.hasAttribute(t);return!i&&!n?Promise.resolve():(this.skipMutationAttributes=!0,B.enqueue(()=>{i&&r.removeAttribute(e),n&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1}))}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new fe(e,r);if(n){const Ce=this.attributeMap.get(e);if(Ce&&(Ce.isEvaluate||Ce.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,B.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),u=s.isEvaluate||s.isRawEvaluate,f=e===t&&H.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=s.isSingleExpression(),p=Z.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:p,R=!s.isForceEvaluation()&&(t!==e||f||h?o.hasUnresolvedReference||y===null||y===void 0||y===!1:u&&p==="");R&&o.hasUnresolvedReference&&H.warnUnresolvedAttribute(e,t,r,a);const A=s.isForceEvaluation()?r:h?y:p,C=i&&s.isEvaluate&&t==="value"&&H.isValuePropertyTarget(a),w=a.getRootNode(),S=C&&(a===w.activeElement||this.hasPendingUserEdit()),b=R||A===null||A===!1?null:String(A),D=e!==t&&a.getAttribute(e)!==r,M=b===null?a.hasAttribute(t):a.getAttribute(t)!==b,L=b===null?"":b,$=C&&!S&&a.value!==L,G=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),U=t==="selected"&&a instanceof HTMLOptionElement,re=w.activeElement,Me=re!==null&&(G&&a===re||U&&a.closest("select")===re)||(G||U)&&this.hasPendingCheckableUserEdit(U),ve=b!==null,xe=G&&!Me&&a.checked!==ve,Ae=U&&!Me&&a.selected!==ve;return!D&&!M&&!$&&!xe&&!Ae?(C&&!S&&(this.value=this.normalizeValueForElement(a,L)),(G||U)&&!Me&&this.syncCheckableValueFromDom(U),Promise.resolve()):(this.skipMutationAttributes=!0,B.enqueue(()=>{D&&a.setAttribute(e,r),b===null?a.removeAttribute(t):M&&(a.setAttribute(t,b),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(b)),C&&!S&&(this.value=this.normalizeValueForElement(a,L),$&&(a.value=L)),xe&&(a.checked=ve),Ae&&(a.selected=ve),(xe||Ae)&&this.syncCheckableValueFromDom(Ae)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e);const t=this.getTarget();return t.hasAttribute(e)?(this.skipMutationAttributes=!0,B.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})):Promise.resolve()}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Z.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return g.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return g.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const u=e.getParent();u!==null&&u.removeChild(e);let f=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let p;if(s?a!==-1&&a<o?p=o-1:p=o:p=this.children.indexOf(t),p===-1){const y=this.resolveInsertionPointFromDom(t,!1);y===null?(g.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),f=y.referenceNode)}else this.children.splice(p,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,B.enqueue(()=>{this.target.insertBefore(e.getTarget(),f)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(g.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),H.disableFormControlsInBranch(e),Promise.resolve()}static forEachFormControlInBranch(e,t){e.matches(Je)&&t(e);const r=i=>{Array.from(i.children).forEach(n=>{n.hasAttribute(`${l.prefix}if-false`)||(n instanceof HTMLElement&&n.matches(Je)&&t(n),r(n))})};r(e)}static disableFormControlsInBranch(e){H.forEachFormControlInBranch(e,t=>{t.hasAttribute("disabled")||(t.setAttribute(oe,""),t.setAttribute("disabled",""))})}restoreFormControlsDisabledByIf(){H.forEachFormControlInBranch(this.getTarget(),e=>{e.hasAttribute(oe)&&(e.removeAttribute(oe),e.removeAttribute("disabled"))})}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.restoreFormControlsDisabledByIf(),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};H.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),H.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],H.userEditCounter=0,H.loggedUnresolvedAttributes=new Set;let F=H;class z extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Z(this.text)}clone(){const e=new z(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Z(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):B.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=Z.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class Te extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Te(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,B.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ye=class ye{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ye.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(g.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const f=he.measure(()=>Y.evaluateDetailed(u.text,e)),h=f.value;a+=f.durationMs,s.push({expression:u.text,durationMs:f.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(u.text)}catch(f){g.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,f),s.push({expression:u.text,durationMs:0}),n.push("")}}),he.record(t,s,a),{results:n,hasUnresolvedReference:o}}};ye.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Z=ye;const Ee=class Ee extends Z{constructor(e,t){super(t),this.forceEvaluation=Ee.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(g.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};Ee.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let fe=Ee;class J{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return B.waitForIdle()}static dialog(e){return B.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return B.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?(J.clearMessagesSync(e),e.showModal()):g.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?e.close():g.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return J.addMessage(e,t,"error")}static addMessage(e,t,r){return B.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return B.enqueue(()=>{J.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return ue(e,t,r)}static now(e,t){return Oe(e,t)}static today(e,t,r){return He(e,t,r)}static number(e,t){return Ue(e,t)}static range(e,t,r){return Ve(e,t,r)}static pages(e,t,r){return je(e,t,r)}static monthAdd(e,t){return de(e,t)}static monthRange(e,t){return qe(e,t)}static pageSummary(e,t){return We(e,t)}static findBy(e,t,r){return Ke(e,t,r)}static sum(e,t){return ze(e,t)}static distinct(e,t){return Ye(e,t)}static groupBy(e,t){return Xe(e,t)}}const dt=["addErrorMessage","clearMessages"],Qe="data-haori-group-name";function Ze(){const e=globalThis.window?.Haori;return dt.every(r=>typeof e?.[r]=="function")?e:J}const v=class v{static getValues(e){const t={};return v.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(v.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(v.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){g.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Qe))return;const i=v.resolveGroupScope(e),n=`${String(t)}--haori${v.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Qe,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=v.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(v.groupScopeSequence+=1,v.GROUP_SCOPE_IDS.set(e,v.groupScopeSequence),v.groupScopeSequence)}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?v.hasDeclarativeBinding(e,"checked"):F.isValuePropertyTarget(t)?v.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?v.hasDeclarativeSelectedOption(t):!1:!1}static clearDeclarativeStateFromDom(e){if(v.isDeclarativeStateBound(e)){const t=e.getTarget();t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?t.checked=!1:t instanceof HTMLSelectElement?(Array.from(t.options).forEach(r=>{r.selected=!1}),t.selectedIndex=-1):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.value="")}e.getChildren().forEach(t=>{t instanceof F&&v.clearDeclarativeStateFromDom(t)})}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=T.get(t);if(r instanceof F&&v.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return v.getPartValues(e,{},t)}static getPartValues(e,t,r=null){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return t;const i=v.resolveFieldName(e),n=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`),a=e.hasAttribute(`${l.prefix}form-list`),o=r!==null&&e.getUserEditSequence()<=r;if(i){if(a&&o)Array.isArray(t[String(i)])?t[String(i)].push(null):t[String(i)]=[null];else if(!o)if(a){const u=v.resolveCollectedValue(e),f=v.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(i)])?t[String(i)].push(...f):t[String(i)]=f}else if(v.isGroupedCheckable(e)){const u=e.getTarget(),h=(u instanceof HTMLInputElement?u.checked:!0)?e.getValue():null,p=String(i);h===null?p in t||(t[p]=null):t[p]===null||t[p]===void 0?t[p]=h:Array.isArray(t[p])?t[p].push(h):t[p]=[t[p],h]}else t[String(i)]=v.resolveCollectedValue(e);n&&g.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())v.getPartValues(u,t,r)}else if(n){const u={};for(const f of e.getChildElementFragments())v.getPartValues(f,u,r);Object.keys(u).length>0&&(t[String(n)]=u),s&&g.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const u=[];let f=!1;for(const h of e.getChildElementFragments()){const p={};v.getPartValues(h,p,r),Object.keys(p).length>0?(f=!0,u.push(p)):r!==null&&u.push({})}(r===null||f)&&(t[String(s)]=u)}else for(const u of e.getChildElementFragments())v.getPartValues(u,t,r);return t}static setValues(e,t,r=!1){return v.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1){return v.setPartValues(e,t,r,!1)}static syncRowValues(e,t){return v.setPartValues(e,t,!1,!1,!0)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=t[String(r)];return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(v.INITIAL_RESTORED_FORMS.has(i))continue;const n=T.get(i);if(!(n instanceof F))continue;const s=n.getRawBindingData();s&&(v.INITIAL_RESTORED_FORMS.add(i),r.push(v.syncValues(n,v.resolveSyncValues(n,s))))}return Promise.all(r).then(()=>{})}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map){const a=[],o=v.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),f=e.getAttribute(`${l.prefix}form-list`),h=e.hasAttribute(`${l.prefix}form-list`),p=e.getAttribute(`${l.prefix}form-detach`);if(o){if(!p||r){const y=t[String(o)],A=n&&typeof y>"u"&&!v.isDeclarativeStateBound(e)?null:y;if(v.isFileInput(e))return(A===null||A==="")&&a.push(v.applyFragmentValue(e,null,i)),Promise.all(a).then(()=>{});if(h&&Array.isArray(A)&&!v.isGroupedCheckable(e)&&!v.isMultipleSelect(e)){const C=String(o),w=s.get(C)??0;s.set(C,w+1),a.push(v.applyFragmentValue(e,A[w]??null,i))}else typeof A>"u"||(Array.isArray(A)&&v.isGroupedCheckable(e)||Array.isArray(A)&&v.isMultipleSelect(e)||typeof A=="string"||typeof A=="number"||typeof A=="boolean"||A===null?a.push(v.applyFragmentValue(e,A,i)):a.push(v.applyFragmentValue(e,String(A),i)))}}else if(u){const y=t[String(u)];if(y&&typeof y=="object"){const R=new Map;for(const A of e.getChildElementFragments())a.push(v.setPartValues(A,y,r,i,n,R))}}else if(f){const y=t[String(f)];if(Array.isArray(y)){const R=e.getChildElementFragments();for(let A=0;A<R.length;A++){const C=R[A];y.length>A?a.push(v.setPartValues(C,y[A],r,i,n,new Map)):a.push(v.setPartValues(C,{},r,i,n,new Map))}}}else for(const y of e.getChildElementFragments())a.push(v.setPartValues(y,t,r,i,n,s));return Promise.all(a).then(()=>{})}static async reset(e){k.clearUserEditMarks(e),v.clearValues(e),await Promise.all([v.clearMessages(e),v.clearEachClones(e)]),await B.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}v.clearDeclarativeStateFromDom(e)});const t=v.collectBindingTargetForms(e);for(const r of t){const i=v.getInitialBindingData(r);i===null&&r.getRawBindingData()===null||await k.setBindingData(r.getTarget(),i??{})}v.syncValuesFromDom(e),await k.evaluateAll(e);for(const r of t){const i=v.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=v.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await k.setBindingData(r.getTarget(),a)}}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:k.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())v.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof F&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`)){for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}n.setEachInputSignature(null)}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())v.clearValues(t)}static clearMessages(e){return Ze().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return v.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Ze(),a=s.addMessage,o=f=>typeof a=="function"?a.call(s,f,r,i):s.addErrorMessage(f,r),u=v.findFragmentsByKey(e,t);return u.forEach(f=>{n.push(o(f.getTarget()))}),u.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return v.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&v.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...v.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),f=Number(u);if(isNaN(f))g.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(p=>p.hasAttribute(`${l.prefix}row`));f<h.length&&r.push(...v.findFragmentByKeyParts(h[f],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...v.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};v.INITIAL_RESTORED_FORMS=new WeakSet,v.GROUP_SCOPE_IDS=new WeakMap,v.groupScopeSequence=0;let V=v;class x{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){x.dispatch(document,"ready",{version:e})}static importStart(e,t){x.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){x.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){x.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const f=t?.[u],h=r[u];f!==h&&n.push(u)}x.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){x.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){x.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){x.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){x.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){x.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){x.dispatch(e,"show",{visible:!0})}static hide(e){x.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){x.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){x.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){x.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){x.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){x.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const ht={401:"unauthorized-redirect",403:"forbidden-redirect"};function ft(d,e){return d.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function pt(d,e){const t=d.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(d),i=r instanceof F?r.getBindingData():{},n=ft(t,i);return n===""?null:n}function gt(d,e,t){const r=d.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function _e(d){const e=ht[d];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=pt(i,t);if(n===null)continue;const s=gt(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class et{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const mt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],bt="__haoriHistoryState__",Re="data-haori-click-lock";function pe(){const e=globalThis.window?.Haori;return mt.every(r=>typeof e?.[r]=="function")?e:J}const yt=new Set(["GET","HEAD","OPTIONS"]);function De(d){return yt.has(d.toUpperCase())}function Et(d,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{d.append(t,ie(i))}):d.append(t,ie(r)))}function ie(d){if(d==null)return"";if(typeof d=="object"||typeof d=="function")try{return JSON.stringify(d)??""}catch{return""}return String(d)}function tt(d,e){const t=new URL(d,window.location.href),r=new URLSearchParams(t.search);return Et(r,e),t.search=r.toString(),t.toString()}function vt(d){if(d==null)return{payload:{},dropped:!1};if(typeof d=="string"){const e=d.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:rt(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(d instanceof URLSearchParams)return{payload:rt(d),dropped:!1};if(typeof FormData<"u"&&d instanceof FormData){const e={};let t=!1;for(const[r,i]of d.entries()){if(typeof i!="string"){t=!0;continue}it(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function rt(d){const e={};for(const[t,r]of d.entries())it(e,t,r);return e}function it(d,e,t){const r=d[e];r===void 0?d[e]=t:Array.isArray(r)?r.push(t):d[e]=[r,t]}function ge(d,e){if(Array.isArray(e)){const t=Array.isArray(d)?d.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=ge(t[n],i),r=!0))}),r?t:d}if(e!==null&&typeof e=="object"){const t=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};for(const[r,i]of Object.entries(e))t[r]=ge(t[r],i);return t}return e}function At(d){const e=d?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function St(d,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||De(r))return{url:d,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=vt(t.body);let s=d;Object.keys(i).length>0&&(s=tt(s,i)),n&&g.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function wt(d){return d==null?null:typeof d=="string"?d:d instanceof URLSearchParams?d.toString():d instanceof FormData?Array.from(d.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(d)}function le(d){return d instanceof Blob?!0:Array.isArray(d)?d.some(le):d!==null&&typeof d=="object"?Object.values(d).some(le):!1}function Tt(d){return Object.values(d).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&le(t)):le(e))}function me(d){return Fe(V.getValues(d))}function Fe(d){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(d))t[r]=e(i);return t}function Rt(d,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:d,method:String(e.method||"GET").toUpperCase(),headers:r,body:wt(e.body||null)})}const m=class m{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,this.twoWayCommitBind=!1,m.isElementFragment(e)?(this.options=m.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return m.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=Y.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?m.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return m.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=Y.evaluateDetailed(s??a??"",t);return r=r||u.unresolvedReference,m.isJsonStringContext(e,o)?m.stringifyJsonTemplateStringContent(u.value):m.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return m.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(m.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:k.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=m.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=m.resolveDataParamStringDetailed(r,e.getBindingData());return{value:k.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(m.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(m.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(m.attrName(t,"confirm")).replace(/\\n/g,`
8
8
  `)),e.hasAttribute(m.attrName(t,"data"))&&(r.dataAttrName=m.attrName(t,"data")),e.hasAttribute(m.attrName(t,"form"))){const S=e.getRawAttribute(m.attrName(t,"form"));if(S){const b=document.body.querySelector(S);b!==null?r.formFragment=V.getFormFragment(T.get(b)):g.error("Haori",`Form element not found: ${S} (${m.attrName(t,"form")})`)}else r.formFragment=V.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=V.getFormFragment(e),r.formFragment===null&&m.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const S=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
9
9
  "use strict";
10
10
  ${S}
@@ -24,5 +24,5 @@ ${r}
24
24
  );`)}catch{try{i=new Function(`"use strict";
25
25
  ${r}
26
26
  `)}catch(n){g.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){g.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${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"&&(c.EACH_RENDERED_CHANGE_WARNED.has(r)||(c.EACH_RENDERED_CHANGE_WARNED.add(r),g.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),c.countEachRenderedRows(e)!==0){if(!n){if(c.EACH_RENDERED_CHANGE_FIRED.has(r))return;c.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){g.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=c.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=c.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof F){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof F&&(r=h.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const f=T.get(u);f instanceof F&&e.getChildren().includes(f)&&(e.removeChild(f),f.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?c.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(c.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=>c.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:(g.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`)||c.hasNonEachDynamicElementState(e)||!c.isRowLocalEachTemplate(e))return!1;const r=c.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),n=c.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=c.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(!c.areExpressionsRowLocal(c.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(c.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!c.areExpressionsRowLocal([s],t))return!1;continue}if(!c.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))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 F){if(!c.isRowLocalSubtree(i,r))return!1}else if(i instanceof z){const n=i.getRawText();if(n.includes("{{")&&!c.areExpressionsRowLocal(c.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=Y.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:!c.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof F?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return c.recordDerivedSubtreeSignatureComputation(e,t),c.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:c.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!c.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(c.createDescendantBindingSignature(e,"refresh")),c.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!W.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=c.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:c.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.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=c.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 u=o.getChildren().filter(f=>f instanceof F).findIndex(f=>f===r);n+=`:nth-child(${u+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),g.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${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 z&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof F?!c.markFreshInitializationSkippable(n):n instanceof z?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 g.error("[Haori]","Template is not set for each element."),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=new Map,o=[];t.forEach((b,D)=>{const M=c.createListKey(b,n?String(n):null,D);o.push(M),a.set(M,{item:b,itemIndex:D})});const u=new Set(o),f=[];let h=e.getChildren().filter(b=>b instanceof F).filter(b=>!b.hasAttribute(`${l.prefix}each-before`)&&!b.hasAttribute(`${l.prefix}each-after`));const p=h.map(b=>b.getListKey()),y=new Set;h=h.filter(b=>u.has(String(b.getListKey()))?!0:(y.add(b),f.push(b.remove()),!1));const R=h.map(b=>b.getListKey()),A=new Map;h.forEach(b=>{const D=b.getListKey();D!==null&&!A.has(D)&&A.set(D,b)});const C=e.getChildElementFragments().filter(b=>!y.has(b)),w=C.filter(b=>b.hasAttribute(`${l.prefix}each-before`)).length;let S=Promise.resolve();return o.forEach((b,D)=>{const{item:M,itemIndex:L}=a.get(b);let $;const G=A.get(b);if(G){$=G;const U=w+D;S=S.then(()=>c.updateRowFragment($,M,i,L,s?String(s):null,b).then(re=>c.repositionEachRow(e,$,C,U).then(()=>{if(re)return c.clearUserEditMarks($),c.evaluateAll($).then(()=>c.applyRowFormValues(e,$,M))})))}else{$=r.clone();const U=w+D;S=S.then(()=>c.updateRowFragment($,M,i,L,s?String(s):null,b).then(()=>{const re=C[U]??null;return e.insertBefore($,re).then(()=>{C.splice(U,0,$)}).then(()=>c.initializeFreshEachRow($)).then(()=>c.applyRowFormValues(e,$,M))}))}}),Promise.all(f).then(()=>S).then(()=>{const b=o.filter(U=>U!==null),D=R.filter(U=>U!==null),M=new Set(D),L=b.filter(U=>!M.has(U)),G=p.filter(U=>U!==null).filter(U=>!u.has(U));x.eachUpdate(e.getTarget(),L,G,b)})}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve();r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():V.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return g.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===u?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(u),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()&&c.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=>c.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)}:${c.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{c.evaluateAll(e)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),c.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"]),c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap,c.EACH_RENDERED_CHANGE_FIRED=new WeakSet,c.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let k=c;const ae=class ae{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[ae.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=T.get(e);t&&new X(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){g.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate))}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ae.BUILTIN_EVENT_NAMES.has(e)){g.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof F&&new X(n,"on",t).run().catch(s=>{g.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)))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=T.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof F&&(i.syncValue(),i.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=T.get(a);o instanceof F&&(o.syncValue(),o.markUserEdit())}}const n=()=>{new X(i,t,r).run().catch(s=>{g.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}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}};ae.HISTORY_STATE_KEY="__haoriHistoryState__",ae.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ie=ae;const P=class P{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)&&(P.isHtmlElement(e)&&P.syncElement(e),e.querySelectorAll("*").forEach(t=>{P.syncElement(t)}))}static syncElement(e){const t=P.registrations.get(e),r=T.get(e);if(!r||!P.shouldObserve(r)){t&&(t.observer.disconnect(),P.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=P.resolveRoot(r),n=P.resolveRootMargin(r),s=P.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&P.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),P.registrations.delete(e));const o=new IntersectionObserver(u=>{const f=P.registrations.get(e);f&&u.forEach(h=>{!h.isIntersecting||f.running||P.isDisabled(f.fragment)||(f.running=!0,new X(f.fragment,"intersect").runWithResult().then(p=>{p&&f.once&&(f.observer.disconnect(),P.registrations.delete(e))}).catch(p=>{g.error("[Haori]","Intersect procedure execution error:",p)}).finally(()=>{const p=P.registrations.get(e);p&&(p.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),P.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(P.isHtmlElement(e)){const t=P.registrations.get(e);t&&(t.observer.disconnect(),P.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=P.registrations.get(t);r&&(r.observer.disconnect(),P.registrations.delete(t))})}static disconnectAll(){P.registrations.forEach(e=>{e.observer.disconnect()}),P.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!P.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=document.querySelector(r);return P.isHtmlElement(i)?i:(g.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}};P.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),P.registrations=new Map;let ne=P;const E=class E{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(E.isHtmlElement(e)&&E.syncElement(e),e.querySelectorAll("*").forEach(t=>{E.syncElement(t)}))}static syncElement(e){const t=E.registrations.get(e);if(!t&&!E.hasPollAttribute(e))return;const r=T.get(e);if(!(r instanceof F)||!E.shouldObserve(r)){t&&E.teardown(e,t);return}const i=E.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}E.teardown(e,t)}E.startPolling(e,r,i)}static cleanupTree(e){if(E.isHtmlElement(e)){const t=E.registrations.get(e);t&&E.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=E.registrations.get(t);r&&E.teardown(t,r)})}static disconnectAll(){E.registrations.forEach(e=>{E.clearTimers(e)}),E.registrations.clear(),E.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",E.visibilityListener),E.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)?!E.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(`
27
- `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:E.resolveInterval(t),timeoutMs:E.resolveTimeout(t),errorLimit:E.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};E.registrations.set(e,i),E.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{E.handleTimeout(e)},i.timeoutMs)),E.injectState(i),E.tick(e)}static async tick(e){const t=E.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await E.stop(e,t,"detached");return}const r=E.isHidden(e)||E.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await E.injectState(t)),r){E.schedule(e,t);return}if(E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new X(t.fragment,"poll").runWithResult()}catch(n){g.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(E.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await E.stop(e,t,"error");return}if(await E.restoreStateIfCleared(t),i&&E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}E.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{E.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=E.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&x.pollTimeout(e,t.count,E.elapsed(t)),await E.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,E.clearTimers(t),r==="detached"){E.registrations.delete(e);return}await E.injectState(t),e.isConnected&&x.pollStop(e,r,t.count,E.elapsed(t))}}static teardown(e,t){E.clearTimers(t),E.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(E.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(E.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),E.tick(t))})};E.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=E.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:E.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return k.setBindingData(n,s,new Set,!1,!1,null)})).then(()=>{})}static async restoreStateIfCleared(e){E.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await E.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=document.querySelectorAll(i);if(n.length===0)return g.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=T.get(a);o instanceof F&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return E.DEFAULT_INTERVAL_MS;const r=E.toNumber(e.getAttribute(t));return r===null?(g.warn("[Haori]",`${t} は数値で指定してください。既定値 ${E.DEFAULT_INTERVAL_MS}ms を使用します。`),E.DEFAULT_INTERVAL_MS):r<E.MIN_INTERVAL_MS?(g.warn("[Haori]",`${t} の下限は ${E.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),E.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<=0?(g.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<1?(g.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?E.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?(g.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):E.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}};E.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),E.DEFAULT_INTERVAL_MS=5e3,E.MIN_INTERVAL_MS=100,E.registrations=new Map,E.visibilityListener=null;let se=E;function Ft(d){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>d()):Promise.resolve().then(d)}const I=class I{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)&&(I.isHtmlElement(e)&&I.syncElement(e),e.querySelectorAll("*").forEach(t=>{I.syncElement(t)}))}static syncElement(e){const t=I.registrations.get(e),r=T.get(e);if(!(r instanceof F)||!I.shouldObserve(r)){t&&(t.observer.disconnect(),I.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=I.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),I.registrations.delete(e)),g.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=I.resolveRoot(r),s=I.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,I.refreshRows(t);return}t&&(t.observer.disconnect(),I.registrations.delete(e));const a=new IntersectionObserver(u=>{const f=I.registrations.get(e);if(!f)return;let h=!1;u.forEach(p=>{const y=p.target;f.observedRows.has(y)&&(p.isIntersecting?f.visibleRows.has(y)||(f.visibleRows.add(y),h=!0):f.visibleRows.delete(y)&&(h=!0))}),h&&I.scheduleCompute(f)},{root:n,rootMargin:s,threshold:I.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};I.registrations.set(e,o),I.refreshRows(o)}static cleanupTree(e){if(I.isHtmlElement(e)){const t=I.registrations.get(e);t&&(t.observer.disconnect(),I.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=I.registrations.get(t);r&&(r.observer.disconnect(),I.registrations.delete(t))})}static disconnectAll(){I.registrations.forEach(e=>{e.observer.disconnect()}),I.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=document.querySelector(r);return I.isHtmlElement(i)?i:(g.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===""?I.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof F&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=I.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));I.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Ft(()=>{e.scheduled=!1;const t=e.fragment.getTarget();I.registrations.get(t)===e&&I.computeAndPublish(e)}))}static computeAndPublish(e){const t=I.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 u of i)u<a&&(a=u),u>o&&(o=u);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,I.publish(e,n))}static publish(e,t){const r=I.resolveBindOwner(e.fragment);if(!r){g.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);k.setBindingData(i,n,a,!1,!1,null).catch(o=>{g.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}};I.THRESHOLD=0,I.DEFAULT_ROOT_MARGIN="0px",I.registrations=new Map;let _=I;const q=class q{static disconnectMutationObservers(){q._mutationObservers.forEach(e=>{e.disconnect()}),q._mutationObservers.length=0}static async init(){if(q._initialized)return;q._initialized=!0,q.disconnectMutationObservers();const e=new Ie;q._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([k.scan(document.head),k.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",i.reason),await B.wait(),document.body.setAttribute("data-haori-ready",""),q.observe(document.head),q.observe(document.body),ne.syncTree(document.body),se.syncTree(document.body),_.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return q._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(q.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&n.hasAttribute(oe)&&(i.attributeName==="disabled"||i.attributeName===oe)||i.attributeName&&k.isAliasedAttributeReflection(n,i.attributeName))break;k.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ne.syncElement(n),se.syncElement(n),_.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ne.cleanupTree(n),se.cleanupTree(n),_.cleanupTree(n),k.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(k.addNode(n.parentElement,n),ne.syncTree(n),se.syncTree(n),_.syncTree(n))}),i.target instanceof Element&&_.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?k.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),q._mutationObservers.push(t)}};q._initialized=!1,q._mutationObservers=[],q._dispatcher=null;let be=q;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be.init):be.init();const It=()=>J.waitForRenders(),Nt="0.30.0";return K.Core=k,K.Env=l,K.Form=V,K.Fragment=T,K.Haori=J,K.Log=g,K.Queue=B,K.default=J,K.version=Nt,K.waitForRenders=It,Object.defineProperties(K,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),K}({});
27
+ `)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:E.resolveInterval(t),timeoutMs:E.resolveTimeout(t),errorLimit:E.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};E.registrations.set(e,i),E.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{E.handleTimeout(e)},i.timeoutMs)),E.injectState(i),E.tick(e)}static async tick(e){const t=E.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await E.stop(e,t,"detached");return}const r=E.isHidden(e)||E.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await E.injectState(t)),r){E.schedule(e,t);return}if(E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new X(t.fragment,"poll").runWithResult()}catch(n){g.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(E.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await E.stop(e,t,"error");return}if(await E.restoreStateIfCleared(t),i&&E.isUntilSatisfied(t.fragment)){await E.stop(e,t,"until");return}E.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{E.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=E.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&x.pollTimeout(e,t.count,E.elapsed(t)),await E.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,E.clearTimers(t),r==="detached"){E.registrations.delete(e);return}await E.injectState(t),e.isConnected&&x.pollStop(e,r,t.count,E.elapsed(t))}}static teardown(e,t){E.clearTimers(t),E.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(E.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(E.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),E.tick(t))})};E.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=E.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:E.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return k.setBindingData(n,s,new Set,!1,!1,null)})).then(()=>{})}static async restoreStateIfCleared(e){E.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await E.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=document.querySelectorAll(i);if(n.length===0)return g.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=T.get(a);o instanceof F&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return E.DEFAULT_INTERVAL_MS;const r=E.toNumber(e.getAttribute(t));return r===null?(g.warn("[Haori]",`${t} は数値で指定してください。既定値 ${E.DEFAULT_INTERVAL_MS}ms を使用します。`),E.DEFAULT_INTERVAL_MS):r<E.MIN_INTERVAL_MS?(g.warn("[Haori]",`${t} の下限は ${E.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),E.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<=0?(g.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=E.toNumber(e.getAttribute(t));return r===null||r<1?(g.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?E.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?(g.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):E.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}};E.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),E.DEFAULT_INTERVAL_MS=5e3,E.MIN_INTERVAL_MS=100,E.registrations=new Map,E.visibilityListener=null;let se=E;function Ft(d){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>d()):Promise.resolve().then(d)}const I=class I{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)&&(I.isHtmlElement(e)&&I.syncElement(e),e.querySelectorAll("*").forEach(t=>{I.syncElement(t)}))}static syncElement(e){const t=I.registrations.get(e),r=T.get(e);if(!(r instanceof F)||!I.shouldObserve(r)){t&&(t.observer.disconnect(),I.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=I.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),I.registrations.delete(e)),g.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=I.resolveRoot(r),s=I.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,I.refreshRows(t);return}t&&(t.observer.disconnect(),I.registrations.delete(e));const a=new IntersectionObserver(u=>{const f=I.registrations.get(e);if(!f)return;let h=!1;u.forEach(p=>{const y=p.target;f.observedRows.has(y)&&(p.isIntersecting?f.visibleRows.has(y)||(f.visibleRows.add(y),h=!0):f.visibleRows.delete(y)&&(h=!0))}),h&&I.scheduleCompute(f)},{root:n,rootMargin:s,threshold:I.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};I.registrations.set(e,o),I.refreshRows(o)}static cleanupTree(e){if(I.isHtmlElement(e)){const t=I.registrations.get(e);t&&(t.observer.disconnect(),I.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=I.registrations.get(t);r&&(r.observer.disconnect(),I.registrations.delete(t))})}static disconnectAll(){I.registrations.forEach(e=>{e.observer.disconnect()}),I.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=document.querySelector(r);return I.isHtmlElement(i)?i:(g.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===""?I.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof F&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=I.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));I.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Ft(()=>{e.scheduled=!1;const t=e.fragment.getTarget();I.registrations.get(t)===e&&I.computeAndPublish(e)}))}static computeAndPublish(e){const t=I.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 u of i)u<a&&(a=u),u>o&&(o=u);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,I.publish(e,n))}static publish(e,t){const r=I.resolveBindOwner(e.fragment);if(!r){g.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);k.setBindingData(i,n,a,!1,!1,null).catch(o=>{g.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}};I.THRESHOLD=0,I.DEFAULT_ROOT_MARGIN="0px",I.registrations=new Map;let _=I;const q=class q{static disconnectMutationObservers(){q._mutationObservers.forEach(e=>{e.disconnect()}),q._mutationObservers.length=0}static async init(){if(q._initialized)return;q._initialized=!0,q.disconnectMutationObservers();const e=new Ie;q._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([k.scan(document.head),k.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&g.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&g.error("[Haori]","Failed to build body fragment:",i.reason),await B.wait(),document.body.setAttribute("data-haori-ready",""),q.observe(document.head),q.observe(document.body),ne.syncTree(document.body),se.syncTree(document.body),_.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return q._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(q.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&n.hasAttribute(oe)&&(i.attributeName==="disabled"||i.attributeName===oe)||i.attributeName&&k.isAliasedAttributeReflection(n,i.attributeName))break;k.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ne.syncElement(n),se.syncElement(n),_.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ne.cleanupTree(n),se.cleanupTree(n),_.cleanupTree(n),k.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(k.addNode(n.parentElement,n),ne.syncTree(n),se.syncTree(n),_.syncTree(n))}),i.target instanceof Element&&_.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?k.changeText(i.target,i.target.textContent):g.warn("[Haori]","Unsupported character data type:",i.target);break}default:g.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(n){g.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),q._mutationObservers.push(t)}};q._initialized=!1,q._mutationObservers=[],q._dispatcher=null;let be=q;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be.init):be.init();const It=()=>J.waitForRenders(),Nt="0.30.1";return K.Core=k,K.Env=l,K.Form=V,K.Fragment=T,K.Haori=J,K.Log=g,K.Queue=B,K.default=J,K.version=Nt,K.waitForRenders=It,Object.defineProperties(K,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),K}({});
28
28
  //# sourceMappingURL=haori.iife.js.map
package/dist/index.d.ts CHANGED
@@ -1295,6 +1295,9 @@ declare class ElementFragment extends Fragment {
1295
1295
  /**
1296
1296
  * data-attr-* の生属性と反映先属性を同時に削除します。
1297
1297
  *
1298
+ * DOM に残っている属性だけを削除対象にします。すでに無い属性はキューへ積まず、
1299
+ * 内部の属性マップの更新だけを行います(後続の書き込みを消さないため)。
1300
+ *
1298
1301
  * @param rawName 生の属性名
1299
1302
  * @param targetName 反映先の属性名
1300
1303
  * @returns 属性削除の Promise
@@ -1314,6 +1317,10 @@ declare class ElementFragment extends Fragment {
1314
1317
  /**
1315
1318
  * 属性の値を削除します。
1316
1319
  *
1320
+ * DOM に属性が無い場合はキューへ削除タスクを積まず、内部の属性マップの更新だけを
1321
+ * 行います。キュー待ちの削除が、その間に他の経路(優先実行の直接書き込みなど)で
1322
+ * 書き込まれた値を消してしまうのを防ぐためです。
1323
+ *
1317
1324
  * @param name 属性名
1318
1325
  * @returns 属性の削除のPromise
1319
1326
  */
@@ -2428,7 +2435,7 @@ declare class TextFragment extends Fragment {
2428
2435
  evaluate(): Promise<void>;
2429
2436
  }
2430
2437
 
2431
- export declare const version = "0.30.0";
2438
+ export declare const version = "0.30.1";
2432
2439
 
2433
2440
  /**
2434
2441
  * すべてのレンダリングタスク(追従投入分を含む)の完了を待ちます。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haori",
3
- "version": "0.30.0",
3
+ "version": "0.30.1",
4
4
  "description": "A lightweight HTML-first UI engine powered by declarative data bindings and expressions.",
5
5
  "scripts": {
6
6
  "dev": "vite",