haori 0.10.1 → 0.11.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.10.0
5
+ バージョン: 0.11.1
6
6
 
7
7
  ---
8
8
 
@@ -111,6 +111,7 @@ Haori.mount(document.body, {items: [{name: 'りんご'}, {name: 'みかん'}]});
111
111
  - `data-click-*`・`data-change-*`・`data-load-*`・`data-intersect-*` は、それぞれクリック・フォーム変更・要素ロード・ビューポート交差を契機に処理(fetch、bind、copy、ダイアログ操作など)を宣言します。`data-load-*` は `data-if` 要素が非表示→表示へ遷移した(`haori:show`)タイミングでも発火するため、ネイティブの `load` が発生しない `<button>` などでも利用できます。
112
112
  - `data-click-copy-source` — `data-click-copy` のコピー元要素を明示指定します(既定は `data-click-form` のフォーム、無ければイベント発火元の binding)。
113
113
  - `data-click-no-disabled` / `data-click-defer` — 他ライブラリとの併用補助です。`no-disabled` はクリック手続き実行中に `disabled` 属性を付与せず実行します(Bootstrap collapse など disabled 要素を無視するライブラリ・CSS が動作し続けます。多重実行は内部マーカーで防止)。`defer` はクリック手続きを次フレーム(`requestAnimationFrame`/`setTimeout(0)`)で実行し、他ライブラリの同期 click ハンドラを先に完了させます。遅延後は `preventDefault()` できないため、`<a href>` や `type="submit"` への `defer` 併用は避けてください。
114
+ - `data-{event}-run`(例: `data-click-run`・`data-change-run`)— フェッチを伴わず任意の JavaScript をイベント時に実行します。属性値は `new Function` で実 JS として実行され(`-before-run`/`-after-run` と同方式)、`{{...}}` はレンダリング時に展開、`event` が引数で渡されます。本体が `false` を返すと `event.preventDefault()` を呼びます(`onclick="return false"` の慣習)。**セキュリティ**: 展開後の `{{...}}` は実行コードへ結合されるため、信頼できる値(数値 index・自前採番 ID 等)のみを入れてください。API レスポンスやユーザー入力などの信頼できない文字列を入れると任意コード実行(XSS)になり得ます。信頼できない値は `data-bind` 経由で渡し、呼び出す関数の内部で参照してください。
114
115
 
115
116
  ライフサイクルイベント:
116
117
 
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.10.0
5
+ Version: 0.11.1
6
6
 
7
7
  ---
8
8
 
@@ -111,6 +111,7 @@ Event-driven actions:
111
111
  - `data-click-*`, `data-change-*`, `data-load-*`, `data-intersect-*` declare actions (fetch, bind, copy, dialog control, etc.) triggered by click, form change, element load, and viewport intersection respectively. `data-load-*` also fires when a `data-if` element transitions from hidden to shown (the `haori:show` timing), so it works on elements like `<button>` that never receive a native `load` event.
112
112
  - `data-click-copy-source` — explicitly set the copy source element for `data-click-copy` (defaults to the form given by `data-click-form`, otherwise the event element's binding).
113
113
  - `data-click-no-disabled` / `data-click-defer` — coexistence helpers for other libraries. `no-disabled` runs the click procedure without adding the `disabled` attribute (so libraries/CSS that ignore disabled elements, e.g. Bootstrap collapse, keep working; double execution is still prevented internally). `defer` runs the click procedure on the next frame (`requestAnimationFrame`/`setTimeout(0)`) so other libraries' synchronous click handlers complete first. Avoid `defer` on `<a href>` / `type="submit"` because the deferred procedure cannot `preventDefault()` the default action.
114
+ - `data-{event}-run` (e.g. `data-click-run`, `data-change-run`) — run arbitrary JavaScript on the event without a fetch. The value is executed as real JS via `new Function` (like `-before-run`/`-after-run`), with `{{...}}` expanded at render time and `event` passed as an argument. Returning `false` calls `event.preventDefault()` (the `onclick="return false"` convention). **Security:** the expanded `{{...}}` is concatenated into executable code, so only interpolate trusted values (numeric indexes, IDs you control) — never untrusted strings (API/user input), which would run as code (XSS). Pass untrusted values via `data-bind` and read them inside the called function instead.
114
115
 
115
116
  Lifecycle events:
116
117
 
package/dist/haori.cjs.js CHANGED
@@ -1,17 +1,20 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const z=class z{static isEnabled(){return z.devMode}static enable(){z.devMode=!0}static disable(){z.devMode=!1}static set(e){z.devMode=e}};z.devMode=!1;let B=z;const se="embedded";function ce(T){return T==="embedded"||T==="demo"}function de(T){return T===null?null:ce(T)?T:se}const H=class H{static get runtime(){return H._runtime}static setRuntime(e){H._runtime=ce(e)?e:se}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||H._prefix;H._prefix=r.endsWith("-")?r:r+"-";const i=de(e.getAttribute("data-runtime"));i!==null&&(H._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${H._prefix}dev`)){B.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){B.set(!0);return}B.set(!1)}catch{}}static get prefix(){return H._prefix}};H._prefix="data-",H._runtime=se;let l=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class p{static info(e,...t){B.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){B.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const k=class k{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const z=class z{static isEnabled(){return z.devMode}static enable(){z.devMode=!0}static disable(){z.devMode=!1}static set(e){z.devMode=e}};z.devMode=!1;let $=z;const se="embedded";function ce(T){return T==="embedded"||T==="demo"}function de(T){return T===null?null:ce(T)?T:se}const H=class H{static get runtime(){return H._runtime}static setRuntime(e){H._runtime=ce(e)?e:se}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||H._prefix;H._prefix=r.endsWith("-")?r:r+"-";const i=de(e.getAttribute("data-runtime"));i!==null&&(H._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${H._prefix}dev`)){$.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){$.set(!0);return}$.set(!1)}catch{}}static get prefix(){return H._prefix}};H._prefix="data-",H._runtime=se;let l=H;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class p{static info(e,...t){$.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){$.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const I=class I{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
2
  `)}static detectForbiddenIdentifiers(e){return this.FORBIDDEN_NAMES.filter(t=>new RegExp(`(^|[^\\w$.])${t}(?![\\w$])`).test(e))}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return p.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const n=this.detectDisallowedKeywords(e);if(n.length>0){const a=n.some(o=>o==="function"||o==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";p.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+n.join(", ")+"."+a)}else p.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}if(this.containsForbiddenKeys(t))return p.warn("[Haori]",t,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,r))return p.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i={...t},s=this.canAttemptMissingIdentifierRecovery(e);for(let n=0;n<=this.MAX_IDENTIFIER_RECOVERY_COUNT;n+=1){const a=this.prepareEvaluator(e,i);if(a.compileFailed||a.evaluator===null)return{value:null,unresolvedReference:!1};try{const o=[],c=this.wrapBoundValues(i);return a.bindKeys.forEach(h=>{o.push(c[h])}),{value:this.withBlockedPropertyAccess(()=>a.evaluator(...o)),unresolvedReference:!1}}catch(o){if(s&&o instanceof ReferenceError){const h=this.extractMissingIdentifier(o);if(h!==null&&this.canRecoverMissingIdentifier(h,i)){i[h]=void 0;continue}}const c=this.detectForbiddenIdentifiers(e);return c.length>0&&p.warn("[Haori]","Expression references blocked identifier(s): "+c.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of this error). Use spread {...a, ...b} instead of Object.assign.",e),p.error("[Haori]","Expression evaluation error:",e,o),o instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return p.error("[Haori]","Failed to recover missing identifiers:",e,i),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t){const r=Object.keys(t).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${e}:${r.join(",")}`;let s=this.EXPRESSION_CACHE.get(i)||null;if(s!==null)return{bindKeys:r,evaluator:s,compileFailed:!1};const n=this.buildAssignments(r),a=n?`"use strict";
3
3
  ${n};
4
4
  return (${e});`:`"use strict";
5
5
  return (${e});`;try{return s=new Function(...r,a),this.EXPRESSION_CACHE.set(i,s),{bindKeys:r,evaluator:s,compileFailed:!1}}catch(o){return p.error("[Haori]","Failed to compile expression:",e,o),{bindKeys:r,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 s=0;s<t.length;s++){const n=t[s],a=t[s+1]||null,o=r[r.length-1]||null,c=t[s-2]||null,h=t[s-3]||null;if(this.startsObjectKey(o,i,c,h)&&(n.value==="["||n.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value)||n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value)))||n.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(n.value)||this.STRICT_FORBIDDEN_NAMES.includes(n.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(n.value))||o==="member"&&n.value!=="]"&&n.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(n.value))||n.value==="."&&a?.type!=="identifier"||n.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(n.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const f=this.startsMemberAccess(i)?"member":"array";r.push(f);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=n}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<e.length;){const n=e[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return null;if(n==='"'||n==="'"){const o=this.readStringToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,s));if(a){t.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(i.has(n)){t.push({type:"operator",value:n,position:s}),s+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const s=e[i];if(s==="\\"){i+=2;continue}if(s===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!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`
6
- `;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,s])=>{r[i]=this.wrapBoundValue(s,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 s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}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 s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};k.MAX_IDENTIFIER_RECOVERY_COUNT=8,k.forbiddenBindingValueCache=new WeakMap,k.forbiddenBindingValueCacheResetScheduled=!1,k.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"],k.STRICT_FORBIDDEN_NAMES=["eval","arguments"],k.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),k.FORBIDDEN_BINDING_NAMES=new Set([...k.FORBIDDEN_NAMES.filter(e=>!k.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...k.STRICT_FORBIDDEN_NAMES]),k.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),k.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),k.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"]),k.EXPRESSION_CACHE=new Map;let J=k;class ae{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:e,timestamp:performance.now(),promise:s,resolve:r,reject:i};return t?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ae.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const le=class le{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};le.ASYNC_QUEUE=new ae;let M=le;class W{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return M.waitForIdle()}static dialog(e){return M.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 M.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return W.addMessage(e,t,"error")}static addMessage(e,t,r){return M.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 M.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}}const fe=["addErrorMessage","clearMessages"];function ue(){const e=globalThis.window?.Haori;return fe.every(r=>typeof e?.[r]=="function")?e:W}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()]:t[String(r)]=e.getValue(),i&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())A.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())A.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of e.getChildElementFragments()){const o={};A.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(t[String(s)]=n)}else for(const n of e.getChildElementFragments())A.getPartValues(n,t);return t}static setValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!1)}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,s=!0){const n=[],a=e.getAttribute("name"),o=e.getAttribute(`${l.prefix}form-object`),c=e.getAttribute(`${l.prefix}form-list`),h=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!h||i){const f=t[String(a)];c&&Array.isArray(f)&&r!==null?n.push(A.applyFragmentValue(e,f[r]??null,s)):typeof f>"u"||(typeof f=="string"||typeof f=="number"||typeof f=="boolean"||f===null?n.push(A.applyFragmentValue(e,f,s)):n.push(A.applyFragmentValue(e,String(f),s)))}}else if(o){const f=t[String(o)];if(f&&typeof f=="object")for(const g of e.getChildElementFragments())n.push(A.setPartValues(g,f,null,i,s))}else if(c){const f=t[String(c)];if(Array.isArray(f)){const g=e.getChildElementFragments();for(let b=0;b<g.length;b++){const S=g[b];f.length>b?n.push(A.setPartValues(S,f[b],b,i,s)):n.push(A.setPartValues(S,{},b,i,s))}}}else for(const f of e.getChildElementFragments())n.push(A.setPartValues(f,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.clearEachClones(e)]),await M.enqueue(()=>{const t=e.getTarget();if(t instanceof HTMLFormElement)t.reset();else{const r=t.parentElement;if(r){const i=t.nextElementSibling,s=document.createElement("form");s.appendChild(t),s.reset(),r.insertBefore(t,i)}}}),await P.evaluateAll(e)}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())A.clearValues(t)}static clearMessages(e){return ue().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=ue(),a=n.addMessage,o=h=>typeof a=="function"?a.call(n,h,r,i):n.addErrorMessage(h,r),c=A.findFragmentsByKey(e,t);return c.forEach(h=>{s.push(o(h.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return A.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const c=i.substring(n+1,a),h=Number(c);if(isNaN(h))p.error("Haori",`Invalid index: ${i}`);else{const f=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));h<f.length&&r.push(...A.findFragmentByKeyParts(f[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,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}}const x=class x{static reset(){x.ELEMENT_STORES.clear(),x.ensureGlobalAccess()}static snapshot(){return x.ensureGlobalAccess(),[...x.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:x.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:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((s,n)=>s+n.calls,0)+e.texts.reduce((s,n)=>s+n.calls,0);return t.attributes.reduce((s,n)=>s+n.calls,0)+t.texts.reduce((s,n)=>s+n.calls,0)-r})}static record(e,t,r){if(!B.isEnabled()||!e||t.length===0)return;x.ensureGlobalAccess();const i=x.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=x.getOrCreateCounter(i.attributes,e.rawName,e.template);x.updateCounter(n,t,r);return}const s=x.getOrCreateCounter(i.texts,String(e.childIndex),e.template);x.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.isEnabled())return;const e=globalThis;e[x.GLOBAL_KEY]===void 0&&(e[x.GLOBAL_KEY]={reset:()=>x.reset(),snapshot:()=>x.snapshot()})}static getOrCreateElementStore(e){const t=x.createElementId(e),r=x.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return x.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const s={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,s),s}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const s=x.getOrCreatePlaceholder(e.placeholders,i.expression);s.calls+=1,s.totalDurationMs+=i.durationMs,s.maxDurationMs=Math.max(s.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=x.now();return{value:e(),durationMs:x.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const s=r.getAttribute("id")||"";if(s.trim()!==""){i+=`#${s.trim()}`,t.unshift(i);break}const n=r.getAttribute(`${l.prefix}derive-name`);n&&n.trim()!==""&&(i+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};x.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",x.ELEMENT_STORES=new Map;let X=x;const G=class G{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,G.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(G.FRAGMENT_CACHE.has(e))return G.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new C(e);break;case Node.TEXT_NODE:t=new L(e);break;case Node.COMMENT_NODE:t=new oe(e);break;default:return p.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 M.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 M.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 M.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),G.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};G.FRAGMENT_CACHE=new WeakMap;let w=G;const V=class V extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=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.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Q(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof V)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new V(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,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.children.forEach(e=>{e instanceof V&&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}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof V&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}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==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=e===!0||e==="true":i==="false"?n=e===!1:n=i===String(e),this.value=s?n:n?e:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=n,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=e,this.skipChangeValue=!0,M.enqueue(()=>{r.value=e===null?"":String(e),t&&((r instanceof HTMLInputElement&&this.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})):(p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}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 this.value=e.value;else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}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,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new Q(e,r);if(s){const U=this.attributeMap.get(e);if(U&&(U.isEvaluate||U.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,n);const a=this.getTarget(),o=n.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),c=n.isEvaluate||n.isRawEvaluate,h=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),f=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),b=o.results.length===1?o.results[0]:g,S=!n.isForceEvaluation()&&(t!==e||h||f?o.hasUnresolvedReference||b===null||b===void 0||b===!1:c&&g===""),m=n.isForceEvaluation()?r:f?b:g,v=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),E=S||m===null||m===!1?null:String(m),y=e!==t&&a.getAttribute(e)!==r,F=E===null?a.hasAttribute(t):a.getAttribute(t)!==E,N=v&&E!==null&&a.value!==E;return!y&&!F&&!N?(v&&E!==null&&(this.value=E),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{y&&a.setAttribute(e,r),E===null?a.removeAttribute(t):(F&&a.setAttribute(t,E),v&&(this.value=E,N&&(a.value=E)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return M.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:j.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let s=t?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=e.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(n?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const b=this.resolveInsertionPointFromDom(t,!1);b===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(b.index,0,e),h=b.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const f=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=f})}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?(p.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`,""),Promise.resolve()}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.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};V.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let C=V;class L extends w{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new j(this.text)}clone(){const e=new L(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}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new j(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.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=j.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 oe extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new oe(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,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const _=class _{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(_.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(p.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const h=X.measure(()=>J.evaluateDetailed(c.text,e)),f=h.value;a+=h.durationMs,n.push({expression:c.text,durationMs:h.durationMs}),o=o||f.unresolvedReference,s.push(f.value)}else s.push(c.text)}catch(h){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,h),n.push({expression:c.text,durationMs:0}),s.push("")}}),X.record(t,n,a),{results:s,hasUnresolvedReference:o}}};_.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=_;const ee=class ee extends j{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?(p.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 Q=ee;class R{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){R.dispatch(document,"ready",{version:e})}static render(e){R.dispatch(e,"render",{target:e})}static importStart(e,t){R.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){R.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){R.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const c of o){const h=t?.[c],f=r[c];h!==f&&s.push(c)}R.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){R.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){R.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){R.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){R.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){R.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){R.dispatch(e,"show",{visible:!0})}static hide(e){R.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){R.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){R.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){R.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const pe=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],ge="__haoriHistoryState__",re="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return pe.every(r=>typeof e?.[r]=="function")?e:W}const me=new Set(["GET","HEAD","OPTIONS"]);function be(T){return me.has(T.toUpperCase())}function ve(T,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?T.append(t,""):Array.isArray(r)?r.forEach(i=>{T.append(t,String(i))}):typeof r=="object"||typeof r=="function"?T.append(t,JSON.stringify(r)):T.append(t,String(r)))}function ye(T,e){const t=new URL(T,window.location.href),r=new URLSearchParams(t.search);return ve(r,e),t.search=r.toString(),t.toString()}function Ee(T){return T==null?null:typeof T=="string"?T:T instanceof URLSearchParams?T.toString():T instanceof FormData?Array.from(T.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(T)}function Ae(T,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:T,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ee(e.body||null)})}const d=class d{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 d.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(d.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=J.evaluateDetailed(n??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let s=0;s<t;s+=1){const n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?d.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return d.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(d.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=J.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,d.isJsonStringContext(e,o)?d.stringifyJsonTemplateStringContent(c.value):d.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return d.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),s=i?.value??null,n=i?.hasUnresolvedReference??!1;if(s&&typeof s=="object"&&!Array.isArray(s))return{value:s,hasUnresolvedReference:n};if(typeof s!="string"||r===null)return{value:null,hasUnresolvedReference:n};const a=r.trim();if(d.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=d.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=d.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(d.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(d.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(d.attrName(t,"confirm")).replace(/\\n/g,`
7
- `)),e.hasAttribute(d.attrName(t,"data"))&&(r.dataAttrName=d.attrName(t,"data")),e.hasAttribute(d.attrName(t,"form"))){const m=e.getRawAttribute(d.attrName(t,"form"));if(m){const v=document.body.querySelector(m);v!==null?r.formFragment=A.getFormFragment(w.get(v)):p.error("Haori",`Form element not found: ${m} (${d.attrName(t,"form")})`)}else r.formFragment=A.getFormFragment(e)}else t==="change"&&(r.formFragment=A.getFormFragment(e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const m=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
6
+ `;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,s])=>{r[i]=this.wrapBoundValue(s,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 s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}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 s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};I.MAX_IDENTIFIER_RECOVERY_COUNT=8,I.forbiddenBindingValueCache=new WeakMap,I.forbiddenBindingValueCacheResetScheduled=!1,I.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"],I.STRICT_FORBIDDEN_NAMES=["eval","arguments"],I.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),I.FORBIDDEN_BINDING_NAMES=new Set([...I.FORBIDDEN_NAMES.filter(e=>!I.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...I.STRICT_FORBIDDEN_NAMES]),I.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),I.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),I.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"]),I.EXPRESSION_CACHE=new Map;let J=I;class ae{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const s=new Promise((a,o)=>{r=a,i=o}),n={task:e,timestamp:performance.now(),promise:s,resolve:r,reject:i};return t?this.queue.unshift(n):this.queue.push(n),this.scheduleProcessing(),s}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await ae.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const le=class le{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};le.ASYNC_QUEUE=new ae;let M=le;class W{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return M.waitForIdle()}static dialog(e){return M.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 M.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return W.addMessage(e,t,"error")}static addMessage(e,t,r){return M.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 M.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}}const fe=["addErrorMessage","clearMessages"];function ue(){const e=globalThis.window?.Haori;return fe.every(r=>typeof e?.[r]=="function")?e:W}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()]:t[String(r)]=e.getValue(),i&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())A.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())A.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of e.getChildElementFragments()){const o={};A.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(t[String(s)]=n)}else for(const n of e.getChildElementFragments())A.getPartValues(n,t);return t}static setValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!1)}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,s=!0){const n=[],a=e.getAttribute("name"),o=e.getAttribute(`${l.prefix}form-object`),c=e.getAttribute(`${l.prefix}form-list`),h=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!h||i){const f=t[String(a)];c&&Array.isArray(f)&&r!==null?n.push(A.applyFragmentValue(e,f[r]??null,s)):typeof f>"u"||(typeof f=="string"||typeof f=="number"||typeof f=="boolean"||f===null?n.push(A.applyFragmentValue(e,f,s)):n.push(A.applyFragmentValue(e,String(f),s)))}}else if(o){const f=t[String(o)];if(f&&typeof f=="object")for(const g of e.getChildElementFragments())n.push(A.setPartValues(g,f,null,i,s))}else if(c){const f=t[String(c)];if(Array.isArray(f)){const g=e.getChildElementFragments();for(let v=0;v<g.length;v++){const S=g[v];f.length>v?n.push(A.setPartValues(S,f[v],v,i,s)):n.push(A.setPartValues(S,{},v,i,s))}}}else for(const f of e.getChildElementFragments())n.push(A.setPartValues(f,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.clearEachClones(e)]),await M.enqueue(()=>{const t=e.getTarget();if(t instanceof HTMLFormElement)t.reset();else{const r=t.parentElement;if(r){const i=t.nextElementSibling,s=document.createElement("form");s.appendChild(t),s.reset(),r.insertBefore(t,i)}}}),await P.evaluateAll(e)}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())A.clearValues(t)}static clearMessages(e){return ue().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=ue(),a=n.addMessage,o=h=>typeof a=="function"?a.call(n,h,r,i):n.addErrorMessage(h,r),c=A.findFragmentsByKey(e,t);return c.forEach(h=>{s.push(o(h.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return A.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const c=i.substring(n+1,a),h=Number(c);if(isNaN(h))p.error("Haori",`Invalid index: ${i}`);else{const f=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));h<f.length&&r.push(...A.findFragmentByKeyParts(f[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,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}}const x=class x{static reset(){x.ELEMENT_STORES.clear(),x.ensureGlobalAccess()}static snapshot(){return x.ensureGlobalAccess(),[...x.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:x.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:x.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((s,n)=>s+n.calls,0)+e.texts.reduce((s,n)=>s+n.calls,0);return t.attributes.reduce((s,n)=>s+n.calls,0)+t.texts.reduce((s,n)=>s+n.calls,0)-r})}static record(e,t,r){if(!$.isEnabled()||!e||t.length===0)return;x.ensureGlobalAccess();const i=x.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=x.getOrCreateCounter(i.attributes,e.rawName,e.template);x.updateCounter(n,t,r);return}const s=x.getOrCreateCounter(i.texts,String(e.childIndex),e.template);x.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!$.isEnabled())return;const e=globalThis;e[x.GLOBAL_KEY]===void 0&&(e[x.GLOBAL_KEY]={reset:()=>x.reset(),snapshot:()=>x.snapshot()})}static getOrCreateElementStore(e){const t=x.createElementId(e),r=x.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return x.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const s={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,s),s}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const s=x.getOrCreatePlaceholder(e.placeholders,i.expression);s.calls+=1,s.totalDurationMs+=i.durationMs,s.maxDurationMs=Math.max(s.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=x.now();return{value:e(),durationMs:x.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const s=r.getAttribute("id")||"";if(s.trim()!==""){i+=`#${s.trim()}`,t.unshift(i);break}const n=r.getAttribute(`${l.prefix}derive-name`);n&&n.trim()!==""&&(i+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};x.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",x.ELEMENT_STORES=new Map;let X=x;const G=class G{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,G.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(G.FRAGMENT_CACHE.has(e))return G.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new C(e);break;case Node.TEXT_NODE:t=new L(e);break;case Node.COMMENT_NODE:t=new oe(e);break;default:return p.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 M.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 M.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 M.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),G.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};G.FRAGMENT_CACHE=new WeakMap;let w=G;const V=class V extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=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.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Q(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof V)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new V(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,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.children.forEach(e=>{e instanceof V&&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}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof V&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}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==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=e===!0||e==="true":i==="false"?n=e===!1:n=i===String(e),this.value=s?n:n?e:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=n,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=e,this.skipChangeValue=!0,M.enqueue(()=>{r.value=e===null?"":String(e),t&&((r instanceof HTMLInputElement&&this.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})):(p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}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 this.value=e.value;else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}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,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new Q(e,r);if(s){const U=this.attributeMap.get(e);if(U&&(U.isEvaluate||U.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,n);const a=this.getTarget(),o=n.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),c=n.isEvaluate||n.isRawEvaluate,h=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),f=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:g,S=!n.isForceEvaluation()&&(t!==e||h||f?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&g===""),b=n.isForceEvaluation()?r:f?v:g,y=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),m=S||b===null||b===!1?null:String(b),E=e!==t&&a.getAttribute(e)!==r,F=m===null?a.hasAttribute(t):a.getAttribute(t)!==m,N=y&&m!==null&&a.value!==m;return!E&&!F&&!N?(y&&m!==null&&(this.value=m),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{E&&a.setAttribute(e,r),m===null?a.removeAttribute(t):(F&&a.setAttribute(t,m),y&&(this.value=m,N&&(a.value=m)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return M.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:j.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let s=t?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=e.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(n?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(v.index,0,e),h=v.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const f=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=f})}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?(p.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`,""),Promise.resolve()}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.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};V.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let C=V;class L extends w{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new j(this.text)}clone(){const e=new L(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}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new j(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.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=j.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 oe extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new oe(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,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const _=class _{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(_.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(p.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const h=X.measure(()=>J.evaluateDetailed(c.text,e)),f=h.value;a+=h.durationMs,n.push({expression:c.text,durationMs:h.durationMs}),o=o||f.unresolvedReference,s.push(f.value)}else s.push(c.text)}catch(h){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,h),n.push({expression:c.text,durationMs:0}),s.push("")}}),X.record(t,n,a),{results:s,hasUnresolvedReference:o}}};_.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=_;const ee=class ee extends j{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?(p.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 Q=ee;class R{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){R.dispatch(document,"ready",{version:e})}static render(e){R.dispatch(e,"render",{target:e})}static importStart(e,t){R.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){R.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){R.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const c of o){const h=t?.[c],f=r[c];h!==f&&s.push(c)}R.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){R.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){R.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){R.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){R.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){R.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){R.dispatch(e,"show",{visible:!0})}static hide(e){R.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){R.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){R.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){R.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const pe=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],ge="__haoriHistoryState__",re="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return pe.every(r=>typeof e?.[r]=="function")?e:W}const me=new Set(["GET","HEAD","OPTIONS"]);function be(T){return me.has(T.toUpperCase())}function ve(T,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?T.append(t,""):Array.isArray(r)?r.forEach(i=>{T.append(t,String(i))}):typeof r=="object"||typeof r=="function"?T.append(t,JSON.stringify(r)):T.append(t,String(r)))}function ye(T,e){const t=new URL(T,window.location.href),r=new URLSearchParams(t.search);return ve(r,e),t.search=r.toString(),t.toString()}function Ee(T){return T==null?null:typeof T=="string"?T:T instanceof URLSearchParams?T.toString():T instanceof FormData?Array.from(T.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(T)}function Ae(T,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:T,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ee(e.body||null)})}const d=class d{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 d.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(d.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=J.evaluateDetailed(n??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let s=0;s<t;s+=1){const n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?d.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return d.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(d.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=J.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,d.isJsonStringContext(e,o)?d.stringifyJsonTemplateStringContent(c.value):d.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return d.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),s=i?.value??null,n=i?.hasUnresolvedReference??!1;if(s&&typeof s=="object"&&!Array.isArray(s))return{value:s,hasUnresolvedReference:n};if(typeof s!="string"||r===null)return{value:null,hasUnresolvedReference:n};const a=r.trim();if(d.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=d.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=d.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(d.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(d.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(d.attrName(t,"confirm")).replace(/\\n/g,`
7
+ `)),e.hasAttribute(d.attrName(t,"data"))&&(r.dataAttrName=d.attrName(t,"data")),e.hasAttribute(d.attrName(t,"form"))){const y=e.getRawAttribute(d.attrName(t,"form"));if(y){const m=document.body.querySelector(y);m!==null?r.formFragment=A.getFormFragment(w.get(m)):p.error("Haori",`Form element not found: ${y} (${d.attrName(t,"form")})`)}else r.formFragment=A.getFormFragment(e)}else t==="change"&&(r.formFragment=A.getFormFragment(e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const y=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
- ${m}
10
- `)}catch(v){p.error("Haori",`Invalid before script: ${v}`)}}}const i=d.attrName(t,"fetch"),s=e.hasAttribute(i);if(s){const m=e.getAttributeEvaluation(i);m&&(r.fetchHasUnresolvedReference=m.hasUnresolvedReference,r.fetchUrl=m.hasUnresolvedReference?null:m.value)}const n={};if(t){const m=d.attrName(t,"fetch-method");if(e.hasAttribute(m)){const v=e.getAttributeEvaluation(m);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=v?.value}}else{const m=d.attrName(null,"method",!0);if(e.hasAttribute(m)){const v=e.getAttributeEvaluation(m);v?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=v?.value}}if(t){const m=d.attrName(t,"fetch-headers");if(e.hasAttribute(m)){const v=e.getRawAttribute(m);try{n.headers=P.parseDataBind(v)}catch(E){p.error("Haori",`Invalid fetch headers: ${E}`)}}}else{const m=d.attrName(null,"headers",!0);if(e.hasAttribute(m)){const v=e.getRawAttribute(m);try{n.headers=P.parseDataBind(v)}catch(E){p.error("Haori",`Invalid fetch headers: ${E}`)}}}if(t){const m=d.attrName(t,"fetch-content-type");if(e.hasAttribute(m)){const v=e.getAttributeEvaluation(m);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":v?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let v=!1;n.headers&&typeof n.headers=="object"&&(v="Content-Type"in n.headers),v||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const m=d.attrName(null,"content-type",!0);if(e.hasAttribute(m)){const v=e.getAttributeEvaluation(m);v?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":v?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let v=!1;n.headers&&typeof n.headers=="object"&&(v="Content-Type"in n.headers),v||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(n).length>0&&(r.fetchOptions=n);const a=t?d.attrName(t,"bind"):d.attrName(null,"bind",!0);if(e.hasAttribute(a)){const m=e.getRawAttribute(a);if(m){const v=document.body.querySelectorAll(m);v.length>0?(r.bindFragments=[],v.forEach(E=>{const y=w.get(E);y&&r.bindFragments.push(y)})):p.error("Haori",`Bind element not found: ${m} (${a})`)}}const o=d.attrName(t,"bind-arg"),c=d.attrName(null,"arg",!0),h=d.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(c)?r.bindArg=e.getRawAttribute(c):e.hasAttribute(h)&&(r.bindArg=e.getRawAttribute(h));const f=t?d.attrName(t,"bind-params"):d.attrName(null,"bind-params",!0);if(e.hasAttribute(f)){const m=e.getRawAttribute(f);r.bindParams=m.split("&").map(v=>v.trim())}const g=t?d.attrName(t,"bind-append"):d.attrName(null,"bind-append",!0);if(e.hasAttribute(g)){const m=e.getRawAttribute(g);r.bindAppendParams=m.split("&").map(v=>v.trim()).filter(Boolean)}const b=t?d.attrName(t,"bind-merge"):d.attrName(null,"bind-merge",!0);e.hasAttribute(b)&&(r.bindMerge=!0);const S=t?d.attrName(t,"copy-params"):null;if(S&&e.hasAttribute(S)){const m=e.getRawAttribute(S);r.copyParams=m.split("&").map(v=>v.trim()).filter(Boolean)}if(t){if(e.hasAttribute(d.attrName(t,"adjust"))){const E=e.getRawAttribute(d.attrName(t,"adjust"));if(E){const y=document.body.querySelectorAll(E);y.length>0?(r.adjustFragments=[],y.forEach(F=>{const N=w.get(F);N&&r.adjustFragments.push(N)})):p.error("Haori",`Adjust element not found: ${E} (${d.attrName(t,"adjust")})`)}if(e.hasAttribute(d.attrName(t,"adjust-value"))){const y=e.getRawAttribute(d.attrName(t,"adjust-value")),F=Number(y);isNaN(F)||(r.adjustValue=F)}}if(e.hasAttribute(d.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(d.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(d.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(d.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const E=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
9
+ ${y}
10
+ `)}catch(m){p.error("Haori",`Invalid before script: ${m}`)}}const b=d.attrName(t,"run");if(e.hasAttribute(b)){const y=String(e.getAttribute(b)??"");try{r.runScript=new Function("event",`
11
+ "use strict";
12
+ ${y}
13
+ `)}catch(m){p.error("Haori",`Invalid run script: ${m}`)}}}const i=d.attrName(t,"fetch"),s=e.hasAttribute(i);if(s){const b=e.getAttributeEvaluation(i);b&&(r.fetchHasUnresolvedReference=b.hasUnresolvedReference,r.fetchUrl=b.hasUnresolvedReference?null:b.value)}const n={};if(t){const b=d.attrName(t,"fetch-method");if(e.hasAttribute(b)){const y=e.getAttributeEvaluation(b);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=y?.value}}else{const b=d.attrName(null,"method",!0);if(e.hasAttribute(b)){const y=e.getAttributeEvaluation(b);y?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=y?.value}}if(t){const b=d.attrName(t,"fetch-headers");if(e.hasAttribute(b)){const y=e.getRawAttribute(b);try{n.headers=P.parseDataBind(y)}catch(m){p.error("Haori",`Invalid fetch headers: ${m}`)}}}else{const b=d.attrName(null,"headers",!0);if(e.hasAttribute(b)){const y=e.getRawAttribute(b);try{n.headers=P.parseDataBind(y)}catch(m){p.error("Haori",`Invalid fetch headers: ${m}`)}}}if(t){const b=d.attrName(t,"fetch-content-type");if(e.hasAttribute(b)){const y=e.getAttributeEvaluation(b);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":y?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let y=!1;n.headers&&typeof n.headers=="object"&&(y="Content-Type"in n.headers),y||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const b=d.attrName(null,"content-type",!0);if(e.hasAttribute(b)){const y=e.getAttributeEvaluation(b);y?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":y?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let y=!1;n.headers&&typeof n.headers=="object"&&(y="Content-Type"in n.headers),y||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(n).length>0&&(r.fetchOptions=n);const a=t?d.attrName(t,"bind"):d.attrName(null,"bind",!0);if(e.hasAttribute(a)){const b=e.getRawAttribute(a);if(b){const y=document.body.querySelectorAll(b);y.length>0?(r.bindFragments=[],y.forEach(m=>{const E=w.get(m);E&&r.bindFragments.push(E)})):p.error("Haori",`Bind element not found: ${b} (${a})`)}}const o=d.attrName(t,"bind-arg"),c=d.attrName(null,"arg",!0),h=d.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(c)?r.bindArg=e.getRawAttribute(c):e.hasAttribute(h)&&(r.bindArg=e.getRawAttribute(h));const f=t?d.attrName(t,"bind-params"):d.attrName(null,"bind-params",!0);if(e.hasAttribute(f)){const b=e.getRawAttribute(f);r.bindParams=b.split("&").map(y=>y.trim())}const g=t?d.attrName(t,"bind-append"):d.attrName(null,"bind-append",!0);if(e.hasAttribute(g)){const b=e.getRawAttribute(g);r.bindAppendParams=b.split("&").map(y=>y.trim()).filter(Boolean)}const v=t?d.attrName(t,"bind-merge"):d.attrName(null,"bind-merge",!0);e.hasAttribute(v)&&(r.bindMerge=!0);const S=t?d.attrName(t,"copy-params"):null;if(S&&e.hasAttribute(S)){const b=e.getRawAttribute(S);r.copyParams=b.split("&").map(y=>y.trim()).filter(Boolean)}if(t){if(e.hasAttribute(d.attrName(t,"adjust"))){const m=e.getRawAttribute(d.attrName(t,"adjust"));if(m){const E=document.body.querySelectorAll(m);E.length>0?(r.adjustFragments=[],E.forEach(F=>{const N=w.get(F);N&&r.adjustFragments.push(N)})):p.error("Haori",`Adjust element not found: ${m} (${d.attrName(t,"adjust")})`)}if(e.hasAttribute(d.attrName(t,"adjust-value"))){const E=e.getRawAttribute(d.attrName(t,"adjust-value")),F=Number(E);isNaN(F)||(r.adjustValue=F)}}if(e.hasAttribute(d.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(d.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(d.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(d.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const m=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
11
14
  "use strict";
12
- ${E}
13
- `)}catch(y){p.error("Haori",`Invalid after script: ${y}`)}}if(e.hasAttribute(d.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(d.attrName(t,"dialog")).replace(/\\n/g,`
14
- `)),e.hasAttribute(d.attrName(t,"toast"))){r.toastMessage=e.getAttribute(d.attrName(t,"toast"));const E=e.getRawAttribute(d.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(E);r.toastLevel=F?E:null}if(e.hasAttribute(d.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(d.attrName(t,"redirect"))),e.hasAttribute(d.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(d.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(d.attrName(t,"scroll"))),e.hasAttribute(d.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(d.attrName(t,"history"))),e.hasAttribute(d.attrName(t,"history-data"))&&(r.historyDataAttrName=d.attrName(t,"history-data")),e.hasAttribute(d.attrName(t,"history-form"))){const E=e.getRawAttribute(d.attrName(t,"history-form"));if(E){const y=document.body.querySelector(E);y!==null?r.historyFormFragment=A.getFormFragment(w.get(y)):p.error("Haori",`Form element not found: ${E} (${d.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(E=>{const y=d.attrName(t,E);if(!e.hasAttribute(y))return;const F=e.getRawAttribute(y),N=[];if(F?(document.body.querySelectorAll(F).forEach($=>{const K=w.get($);K&&N.push(K)}),N.length===0&&p.error("Haori",`Element not found: ${F} (${y})`)):N.push(e),N.length>0)switch(E){case"reset-before":r.resetBeforeFragments=N;break;case"reset":r.resetFragments=N;break;case"refetch":r.refetchFragments=N;break;case"click":r.clickFragments=N;break;case"copy":r.copyFragments=N;break;case"open":r.openFragments=N;break;case"close":r.closeFragments=N;break}});const v=d.attrName(t,"copy-source");if(e.hasAttribute(v)){const E=e.getRawAttribute(v);if(E){const y=document.body.querySelector(E);if(y!==null){const F=w.get(y);F?r.copySourceFragment=F:p.error("Haori",`Element is not managed by Haori: ${E} (${v})`)}else p.error("Haori",`Element not found: ${E} (${v})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(d.attrName(null,"data",!0))&&(r.dataAttrName=d.attrName(null,"data",!0)),e.hasAttribute(d.attrName(null,"form",!0)))){const m=e.getRawAttribute(d.attrName(null,"form",!0));if(m){const v=document.body.querySelector(m);v!==null?r.formFragment=A.getFormFragment(w.get(v)):p.error("Haori",`Form element not found: ${m} (${d.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e]),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}constructor(e,t=null){d.isElementFragment(e)?(this.options=d.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null)}static resolveAutoFetchSignature(e){return new d(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1||!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>A.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let s=r.url,n=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(s||null,n||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(s="fetchUrl"in h?h.fetchUrl:s,n="fetchOptions"in h?h.fetchOptions:n)}}const a=Object.keys(i).length>0;if(s){const h={...n||{}},f=r.requestedMethod,g=r.effectiveMethod,b=r.transportMode==="query-get",S=r.queryString;if(b&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:S}),this.options.targetFragment&&s){const m=performance.now(),v={runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:b?"query-get":"http",...b?{queryString:S}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),s,h,a?i:void 0,v),fetch(s,h).then(E=>this.handleFetchResult(E,s||void 0,m)).catch(E=>{throw s&&R.fetchError(this.options.targetFragment.getTarget(),s,E),E})}return fetch(s,h).then(m=>this.handleFetchResult(m,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,f=h.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),f.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const b=h.getBindingData();Object.assign(b,i),await P.setBindingData(f,b,g)}const o=a?i:{},c=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(c)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(d.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(re))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return d.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(re,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(d.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(re),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return this.options.targetFragment&&t&&R.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),!1;if(this.options.targetFragment&&t&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const s=[];s.push(this.bindResult(e)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new d(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await P.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.openDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,s=r!=null;if(!(!e&&!i&&!s))try{const n=e?this.options.historyUrl:window.location.pathname,a=new URL(n,window.location.href);if(a.origin!==window.location.origin){const c="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",c);return}const o=c=>{for(const[h,f]of Object.entries(c))f!=null&&(Array.isArray(f)?f.forEach(g=>a.searchParams.append(h,String(g))):typeof f=="object"?a.searchParams.set(h,JSON.stringify(f)):a.searchParams.set(h,String(f)))};i&&o(t),s&&o(r),history.pushState({[ge]:!0},"",a.toString())}catch(n){p.error("Haori",`history.pushState failed: ${n}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await ie().addErrorMessage(a,n)},i=()=>{if(!this.options.scrollOnError)return;const n=t?t.getTarget():document.body;(n.getAttribute("data-message-level")==="error"?n:n.parentElement?.getAttribute("data-message-level")==="error"?n.parentElement:n.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const n=await e.json(),a=[];if(n&&typeof n=="object"){if(typeof n.message=="string"&&a.push({message:n.message}),Array.isArray(n.messages))for(const o of n.messages)typeof o=="string"&&a.push({message:o});if(n.errors&&typeof n.errors=="object")for(const[o,c]of Object.entries(n.errors))Array.isArray(c)?a.push({key:o,message:c.join(`
15
+ ${m}
16
+ `)}catch(E){p.error("Haori",`Invalid after script: ${E}`)}}if(e.hasAttribute(d.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(d.attrName(t,"dialog")).replace(/\\n/g,`
17
+ `)),e.hasAttribute(d.attrName(t,"toast"))){r.toastMessage=e.getAttribute(d.attrName(t,"toast"));const m=e.getRawAttribute(d.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(m);r.toastLevel=F?m:null}if(e.hasAttribute(d.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(d.attrName(t,"redirect"))),e.hasAttribute(d.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(d.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(d.attrName(t,"scroll"))),e.hasAttribute(d.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(d.attrName(t,"history"))),e.hasAttribute(d.attrName(t,"history-data"))&&(r.historyDataAttrName=d.attrName(t,"history-data")),e.hasAttribute(d.attrName(t,"history-form"))){const m=e.getRawAttribute(d.attrName(t,"history-form"));if(m){const E=document.body.querySelector(m);E!==null?r.historyFormFragment=A.getFormFragment(w.get(E)):p.error("Haori",`Form element not found: ${m} (${d.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(m=>{const E=d.attrName(t,m);if(!e.hasAttribute(E))return;const F=e.getRawAttribute(E),N=[];if(F?(document.body.querySelectorAll(F).forEach(B=>{const K=w.get(B);K&&N.push(K)}),N.length===0&&p.error("Haori",`Element not found: ${F} (${E})`)):N.push(e),N.length>0)switch(m){case"reset-before":r.resetBeforeFragments=N;break;case"reset":r.resetFragments=N;break;case"refetch":r.refetchFragments=N;break;case"click":r.clickFragments=N;break;case"copy":r.copyFragments=N;break;case"open":r.openFragments=N;break;case"close":r.closeFragments=N;break}});const y=d.attrName(t,"copy-source");if(e.hasAttribute(y)){const m=e.getRawAttribute(y);if(m){const E=document.body.querySelector(m);if(E!==null){const F=w.get(E);F?r.copySourceFragment=F:p.error("Haori",`Element is not managed by Haori: ${m} (${y})`)}else p.error("Haori",`Element not found: ${m} (${y})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(d.attrName(null,"data",!0))&&(r.dataAttrName=d.attrName(null,"data",!0)),e.hasAttribute(d.attrName(null,"form",!0)))){const b=e.getRawAttribute(d.attrName(null,"form",!0));if(b){const y=document.body.querySelector(b);y!==null?r.formFragment=A.getFormFragment(w.get(y)):p.error("Haori",`Form element not found: ${b} (${d.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e]),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}constructor(e,t=null,r=null){d.isElementFragment(e)?(this.options=d.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(e){return new d(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(h,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(f){p.error("Haori",`Run script execution error: ${f}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>A.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let s=r.url,n=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(s||null,n||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(s="fetchUrl"in h?h.fetchUrl:s,n="fetchOptions"in h?h.fetchOptions:n)}}const a=Object.keys(i).length>0;if(s){const h={...n||{}},f=r.requestedMethod,g=r.effectiveMethod,v=r.transportMode==="query-get",S=r.queryString;if(v&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:S}),this.options.targetFragment&&s){const b=performance.now(),y={runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:v?"query-get":"http",...v?{queryString:S}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),s,h,a?i:void 0,y),fetch(s,h).then(m=>this.handleFetchResult(m,s||void 0,b)).catch(m=>{throw s&&R.fetchError(this.options.targetFragment.getTarget(),s,m),m})}return fetch(s,h).then(b=>this.handleFetchResult(b,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,f=h.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),f.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const v=h.getBindingData();Object.assign(v,i),await P.setBindingData(f,v,g)}const o=a?i:{},c=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(c)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(d.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(re))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return d.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(re,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(d.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(re),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return this.options.targetFragment&&t&&R.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),!1;if(this.options.targetFragment&&t&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const s=[];s.push(this.bindResult(e)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new d(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await P.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}return this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.openDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),this.options.closeFragments&&this.options.closeFragments.length>0&&this.options.closeFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?n.push(i.closeDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(n),this.options.dialogMessage&&await i.dialog(this.options.dialogMessage),this.options.toastMessage&&await i.toast(this.options.toastMessage,this.options.toastLevel??"info"),this.pushHistory(),this.options.scrollTarget&&document.querySelector(this.options.scrollTarget)?.scrollIntoView({behavior:"smooth",block:"nearest"}),this.options.redirectUrl&&(window.location.href=this.options.redirectUrl),!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,s=r!=null;if(!(!e&&!i&&!s))try{const n=e?this.options.historyUrl:window.location.pathname,a=new URL(n,window.location.href);if(a.origin!==window.location.origin){const c="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",c);return}const o=c=>{for(const[h,f]of Object.entries(c))f!=null&&(Array.isArray(f)?f.forEach(g=>a.searchParams.append(h,String(g))):typeof f=="object"?a.searchParams.set(h,JSON.stringify(f)):a.searchParams.set(h,String(f)))};i&&o(t),s&&o(r),history.pushState({[ge]:!0},"",a.toString())}catch(n){p.error("Haori",`history.pushState failed: ${n}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await ie().addErrorMessage(a,n)},i=()=>{if(!this.options.scrollOnError)return;const n=t?t.getTarget():document.body;(n.getAttribute("data-message-level")==="error"?n:n.parentElement?.getAttribute("data-message-level")==="error"?n.parentElement:n.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const n=await e.json(),a=[];if(n&&typeof n=="object"){if(typeof n.message=="string"&&a.push({message:n.message}),Array.isArray(n.messages))for(const o of n.messages)typeof o=="string"&&a.push({message:o});if(n.errors&&typeof n.errors=="object")for(const[o,c]of Object.entries(n.errors))Array.isArray(c)?a.push({key:o,message:c.join(`
15
18
  `)}):typeof c=="string"?a.push({key:o,message:c}):c!=null&&a.push({key:o,message:String(c)});if(a.length===0)for(const[o,c]of Object.entries(n))o==="message"||o==="messages"||o==="errors"||(Array.isArray(c)?a.push({key:o,message:c.join(`
16
- `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await A.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n={...s.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,c)}else n[a]=r;i.push(P.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r),a=this.options.bindMerge?{...s.getRawBindingData()??{},...n}:n;i.push(P.setBindingData(s.getTarget(),a))})}return Promise.all(i).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(n=>{R.bindComplete(n.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?A.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?A.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,A.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=d.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const g=new FormData;for(const[b,S]of Object.entries(t))S==null?g.append(b,""):S instanceof Blob?g.append(b,S):Array.isArray(S)?S.forEach(m=>g.append(b,String(m))):typeof S=="object"?g.append(b,JSON.stringify(S)):g.append(b,String(S));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(f)){const g=new URLSearchParams;for(const[b,S]of Object.entries(t))S!==void 0&&(S===null?g.append(b,""):Array.isArray(S)?S.forEach(m=>g.append(b,String(m))):typeof S=="object"?g.append(b,JSON.stringify(S)):g.append(b,String(S)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let h;return o&&(h=new URL(i,window.location.href).search||void 0,n.delete("Content-Type")),{url:i,options:s,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:h,transportMode:o?"query-get":"http",signature:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?A.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return A.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(n=>{const a=n.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};d.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,d.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,d.RUNNING_CLICK_TARGETS=new WeakSet;let q=d;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Te{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw p.error("[Haori]","Failed to fetch import source:",e,s),new Error(`Failed to fetch: ${e}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw p.error("[Haori]","Failed to read response text:",e,s),new Error(`Failed to read response from: ${e}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return p.error("[Haori]","Failed to parse imported HTML:",e,s),i}}}const u=class u{static isDeferredAttributeName(e){return u.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!u.isEvaluateAllExcludedAttributeName(e)&&u.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof C?r.hasAttribute(`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);u.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>u.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof C?t.push(u.evaluateAll(r)):r instanceof L&&t.push(u.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=u.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return u.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=u.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return u.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}fetch`)&&r.push(u.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(u.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof C&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new q(e,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedFetch(e)}))}static executeManagedImport(e){const t=e.getTarget(),r=u.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${l.prefix}importing`,""),R.importStart(t,s),Te.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),R.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(h=>{const f=w.get(h);f instanceof C?c.push(u.scan(f.getTarget())):f instanceof L&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),R.importError(t,s,a),p.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?u.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return u.initializeElementFragment(e,!0).then(()=>{u.needsScheduledEvaluateAll(e)&&u.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return u.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():u.initializeElementAttributes(e).then(()=>{if(u.shouldSkipChildInitialization(e,t)){u.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof C?r.push(u.initializeElementFragment(i,t)):i instanceof L&&r.push(u.evaluateText(i))}),Promise.all(r).then(()=>{u.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of u.PRIORITY_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}for(const i of e.getAttributeNames()){if(r.has(i)||u.isDeferredAttributeName(i))continue;const s=e.getRawAttribute(i);s!==null&&(t=t.then(()=>u.setAttribute(e.getTarget(),i,s)))}for(const i of u.DEFERRED_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&u.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const s=w.get(e),n=u.getAliasedAttributeName(t);if(n!==null)return r===null?s.removeAliasedAttribute(t,n):s.setAliasedAttribute(t,n,r,i);const a=[];let o=null,c=null;switch(t){case`${l.prefix}bind`:{r===null?(s.clearBindingDataCache(),s.setBindingData({})):s.setBindingData(u.parseDataBind(r));break}case`${l.prefix}derive`:c=u.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o=u.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:c=u.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),o=u.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(u.evaluateIf(s));break;case`${l.prefix}each`:a.push(u.evaluateEach(s));break;case`${l.prefix}fetch`:a.push(u.executeManagedFetch(s));break;case`${l.prefix}import`:typeof r=="string"&&a.push(u.executeManagedImport(s));break;case`${l.prefix}url-param`:{const h=s.getAttribute(`${l.prefix}url-arg`),f=Se.readParams();if(h===null)a.push(u.setBindingData(e,f));else{const g=s.getRawBindingData()||{};g[String(h)]=f,a.push(u.setBindingData(e,g))}break}}return r===null?a.push(s.removeAttribute(t)):a.push(s.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return s.setDeriveInputSignature(c),o.then(h=>{if(h)return u.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r=new Set){const i=w.get(e),s=i.getRawBindingData();i.setBindingData(t);let n=i.setAttribute(`${l.prefix}bind`,JSON.stringify(t));if(e.tagName==="FORM"){const a=i.getAttribute(`${l.prefix}form-arg`),o=a&&t[String(a)]&&typeof t[String(a)]=="object"&&!Array.isArray(t[String(a)])?t[String(a)]:a?{}:t;n=n.then(()=>A.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),R.bindChange(e,s,t,"manual"),n.then(()=>{})}static dumpScope(e){const t=w.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},s=c=>{const h=c.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},n=(c,h,f,g)=>{if(c)for(const b of Object.keys(c))b in i||(i[b]={value:c[b],source:s(h),kind:f,depth:g})};let a=t,o=0;for(;a;)a!==t&&n(a.getRawDerivedBindingData(),a,"derive",o),n(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return B.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=w.get(e);if(r.isSkipMutationNodes())return;const i=w.get(t.nextSibling),s=w.get(t);s&&(r.insertBefore(s,i),s instanceof C?u.scan(s.getTarget()):s instanceof L&&u.evaluateText(s))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=u.getFormFragment(r);if(s){const n=A.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(u.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?u.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=u.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),s=e.hasAttribute(`${l.prefix}if`),n=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,h=!1,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=u.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),h=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(b=>{if(b instanceof C){if(u.canSkipUnchangedNestedEach(b))return;g.push(u.evaluateAll(b,t))}else b instanceof L&&g.push(u.evaluateText(b))}),Promise.all(g).then(()=>{})}).then(()=>{h&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=J.evaluateDetailed(t,e.getBindingData());if(n.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[s]:n.value};return u.createBindingSignature(i)===u.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=u.dumpScope(e.getTarget()),i=new Set,s=t.match(/[A-Za-z_$][\w$]*/g)??[];let n=0;s.forEach(o=>{const c=t.indexOf(o,n);n=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(u.isHiddenIfCondition(r))B.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{R.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof C?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof L&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{R.show(e.getTarget()),i||u.triggerLoadOnShow(e)})),t.push(Promise.all(s).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=u.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},u.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=u.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):u.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await u.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=u.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`),s=u.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof C){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!n){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!n){const f=w.get(c);f instanceof C&&(r=f.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const h=w.get(c);h instanceof C&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}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:(p.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`)||u.hasNonEachDynamicElementState(e))return!1;const r=u.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),s=u.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}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:!u.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof C?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:u.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return u.recordDerivedSubtreeSignatureComputation(e,t),u.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:u.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(u.createDescendantBindingSignature(e,"refresh")),u.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!B.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=u.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:u.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return u.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let s=i.tagName.toLowerCase();if(i.id.trim()!==""){s+=`#${i.id.trim()}`,t.unshift(s);break}const n=r.getRawAttribute(`${l.prefix}derive-name`);typeof n=="string"&&n.trim()!==""&&(s+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(c=>c instanceof C).findIndex(c=>c===r);s+=`:nth-child(${o+1})`}t.unshift(s),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.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 s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof L&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof C?!u.markFreshInitializationSkippable(s):s instanceof L?s.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${l.prefix}each-key`),n=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((y,F)=>{const N=u.createListKey(y,s?String(s):null,F);o.push(N),a.set(N,{item:y,itemIndex:F})});const c=new Set(o),h=[];let f=e.getChildren().filter(y=>y instanceof C).filter(y=>!y.hasAttribute(`${l.prefix}each-before`)&&!y.hasAttribute(`${l.prefix}each-after`));const g=f.map(y=>y.getListKey());f=f.filter(y=>c.has(String(y.getListKey()))?!0:(h.push(y.remove()),!1));const b=f.map(y=>y.getListKey()),S=new Map;f.forEach(y=>{const F=y.getListKey();F!==null&&!S.has(F)&&S.set(F,y)});const m=e.getChildElementFragments().slice(),v=m.filter(y=>y.hasAttribute(`${l.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((y,F)=>{const{item:N,itemIndex:U}=a.get(y);let $;const K=S.get(y);if(K)$=K,E=E.then(()=>u.updateRowFragment($,N,i,U,n?String(n):null,y).then(I=>{if(I)return u.evaluateAll($)}));else{$=r.clone();const I=v+F;E=E.then(()=>u.updateRowFragment($,N,i,U,n?String(n):null,y).then(()=>{const he=m[I]??null;return e.insertBefore($,he).then(()=>{m.splice(I,0,$)}).then(()=>u.initializeFreshEachRow($))}))}}),Promise.all(h).then(()=>E).then(()=>{const y=o.filter(I=>I!==null),F=b.filter(I=>I!==null),N=new Set(F),U=y.filter(I=>!N.has(I)),K=g.filter(I=>I!==null).filter(I=>!c.has(I));R.eachUpdate(e.getTarget(),U,K,y)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,c=u.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&u.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(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(s=>u.createBindingSignature(s,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${u.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{u.evaluateAll(e)},100)}};u.ATTRIBUTE_ALIAS_SUFFIX="attr-",u.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],u.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],u.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,u.REACTIVE_FETCH_STATES=new WeakMap,u.REACTIVE_IMPORT_STATES=new WeakMap,u.DERIVE_SUBTREE_PROFILES=new WeakMap,u.EACH_UPDATE_STATES=new WeakMap;let P=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),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("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=w.get(r);if(!i)return;t==="change"&&i instanceof C&&i.syncValue();const s=()=>{new q(i,t).run().catch(n=>{p.error("[Haori]","Procedure execution error:",n)})};if(t==="click"&&r.hasAttribute("data-click-defer")){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}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){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const D=class D{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)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=w.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),s=D.resolveRootMargin(r),n=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&D.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(c=>{const h=D.registrations.get(e);h&&c.forEach(f=>{!f.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(g=>{g&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.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!D.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 D.isHtmlElement(i)?i:(p.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}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Y=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const s=i.target;if(i.attributeName&&s.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&P.isAliasedAttributeReflection(s,i.attributeName))break;P.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName),!0),Y.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Y.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Y.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){p.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const we=()=>W.waitForRenders(),De="0.10.1";exports.Core=P;exports.Env=l;exports.Form=A;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=M;exports.default=W;exports.version=De;exports.waitForRenders=we;
19
+ `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await A.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n={...s.getRawBindingData()??{}},a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,c)}else n[a]=r;i.push(P.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r),a=this.options.bindMerge?{...s.getRawBindingData()??{},...n}:n;i.push(P.setBindingData(s.getTarget(),a))})}return Promise.all(i).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(n=>{R.bindComplete(n.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?A.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?A.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,A.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=d.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const g=new FormData;for(const[v,S]of Object.entries(t))S==null?g.append(v,""):S instanceof Blob?g.append(v,S):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(f)){const g=new URLSearchParams;for(const[v,S]of Object.entries(t))S!==void 0&&(S===null?g.append(v,""):Array.isArray(S)?S.forEach(b=>g.append(v,String(b))):typeof S=="object"?g.append(v,JSON.stringify(S)):g.append(v,String(S)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let h;return o&&(h=new URL(i,window.location.href).search||void 0,n.delete("Content-Type")),{url:i,options:s,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:c,queryString:h,transportMode:o?"query-get":"http",signature:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?A.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?d.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return A.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(n=>{const a=n.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};d.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,d.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,d.RUNNING_CLICK_TARGETS=new WeakSet;let q=d;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Te{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw p.error("[Haori]","Failed to fetch import source:",e,s),new Error(`Failed to fetch: ${e}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw p.error("[Haori]","Failed to read response text:",e,s),new Error(`Failed to read response from: ${e}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return p.error("[Haori]","Failed to parse imported HTML:",e,s),i}}}const u=class u{static isDeferredAttributeName(e){return u.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!u.isEvaluateAllExcludedAttributeName(e)&&u.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof C?r.hasAttribute(`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);u.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>u.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof C?t.push(u.evaluateAll(r)):r instanceof L&&t.push(u.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=u.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return u.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=u.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return u.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}fetch`)&&r.push(u.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(u.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof C&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new q(e,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedFetch(e)}))}static executeManagedImport(e){const t=e.getTarget(),r=u.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${l.prefix}importing`,""),R.importStart(t,s),Te.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),R.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(h=>{const f=w.get(h);f instanceof C?c.push(u.scan(f.getTarget())):f instanceof L&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),R.importError(t,s,a),p.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?u.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return u.initializeElementFragment(e,!0).then(()=>{u.needsScheduledEvaluateAll(e)&&u.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return u.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():u.initializeElementAttributes(e).then(()=>{if(u.shouldSkipChildInitialization(e,t)){u.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof C?r.push(u.initializeElementFragment(i,t)):i instanceof L&&r.push(u.evaluateText(i))}),Promise.all(r).then(()=>{u.refreshDerivedSubtreeSignature(e)})})}static syncMountedState(e){if(e.getParent()?.isMounted()){e.setMounted(!0);return}const r=e.getTarget();if(r.parentNode&&document.body.contains(r)){e.setMounted(!0);return}e.setMounted(!1)}static initializeElementAttributes(e){let t=Promise.resolve();const r=new Set;for(const i of u.PRIORITY_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}for(const i of e.getAttributeNames()){if(r.has(i)||u.isDeferredAttributeName(i))continue;const s=e.getRawAttribute(i);s!==null&&(t=t.then(()=>u.setAttribute(e.getTarget(),i,s)))}for(const i of u.DEFERRED_ATTRIBUTE_SUFFIXES){const s=l.prefix+i;e.hasAttribute(s)&&(t=t.then(()=>u.setAttribute(e.getTarget(),s,e.getRawAttribute(s))),r.add(s))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&u.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const s=w.get(e),n=u.getAliasedAttributeName(t);if(n!==null)return r===null?s.removeAliasedAttribute(t,n):s.setAliasedAttribute(t,n,r,i);const a=[];let o=null,c=null;switch(t){case`${l.prefix}bind`:{r===null?(s.clearBindingDataCache(),s.setBindingData({})):s.setBindingData(u.parseDataBind(r));break}case`${l.prefix}derive`:c=u.createDeriveInputSignature(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),o=u.evaluateDerive(s,r,s.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:c=u.createDeriveInputSignature(s,s.getRawAttribute(`${l.prefix}derive`),r),o=u.evaluateDerive(s,s.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(u.evaluateIf(s));break;case`${l.prefix}each`:a.push(u.evaluateEach(s));break;case`${l.prefix}fetch`:a.push(u.executeManagedFetch(s));break;case`${l.prefix}import`:typeof r=="string"&&a.push(u.executeManagedImport(s));break;case`${l.prefix}url-param`:{const h=s.getAttribute(`${l.prefix}url-arg`),f=Se.readParams();if(h===null)a.push(u.setBindingData(e,f));else{const g=s.getRawBindingData()||{};g[String(h)]=f,a.push(u.setBindingData(e,g))}break}}return r===null?a.push(s.removeAttribute(t)):a.push(s.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return s.setDeriveInputSignature(c),o.then(h=>{if(h)return u.reevaluateChildren(s)})}).then(()=>{})}static setBindingData(e,t,r=new Set){const i=w.get(e),s=i.getRawBindingData();i.setBindingData(t);let n=i.setAttribute(`${l.prefix}bind`,JSON.stringify(t));if(e.tagName==="FORM"){const a=i.getAttribute(`${l.prefix}form-arg`),o=a&&t[String(a)]&&typeof t[String(a)]=="object"&&!Array.isArray(t[String(a)])?t[String(a)]:a?{}:t;n=n.then(()=>A.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),R.bindChange(e,s,t,"manual"),n.then(()=>{})}static dumpScope(e){const t=w.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},s=c=>{const h=c.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},n=(c,h,f,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(h),kind:f,depth:g})};let a=t,o=0;for(;a;)a!==t&&n(a.getRawDerivedBindingData(),a,"derive",o),n(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return $.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=w.get(e);if(r.isSkipMutationNodes())return;const i=w.get(t.nextSibling),s=w.get(t);s&&(r.insertBefore(s,i),s instanceof C?u.scan(s.getTarget()):s instanceof L&&u.evaluateText(s))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=u.getFormFragment(r);if(s){const n=A.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(u.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?u.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=u.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),s=e.hasAttribute(`${l.prefix}if`),n=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,h=!1,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=u.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),h=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(v=>{if(v instanceof C){if(u.canSkipUnchangedNestedEach(v))return;g.push(u.evaluateAll(v,t))}else v instanceof L&&g.push(u.evaluateText(v))}),Promise.all(g).then(()=>{})}).then(()=>{h&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=J.evaluateDetailed(t,e.getBindingData());if(n.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[s]:n.value};return u.createBindingSignature(i)===u.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=u.dumpScope(e.getTarget()),i=new Set,s=t.match(/[A-Za-z_$][\w$]*/g)??[];let n=0;s.forEach(o=>{const c=t.indexOf(o,n);n=c+o.length,!(c>0&&t[c-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(u.isHiddenIfCondition(r))$.isEnabled()&&u.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{R.hide(e.getTarget())}));else{const i=e.isVisible(),s=[];e.getChildren().forEach(n=>{n instanceof C?s.push(n.isMounted()?u.evaluateAll(n):u.scan(n.getTarget())):n instanceof L&&s.push(u.evaluateText(n))}),t.push(e.show().then(()=>{R.show(e.getTarget()),i||u.triggerLoadOnShow(e)})),t.push(Promise.all(s).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new q(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=u.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},u.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=u.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):u.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await u.performEachUpdate(e);while(t.rerunRequested);e.getTarget().setAttribute(`${l.prefix}each-done`,"")}finally{t.running=!1,t.settled=null}})();return t.settled=r,r}static performEachUpdate(e){const t=u.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`),s=u.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let n=!1;if(e.getChildren().forEach(a=>{if(!n&&a instanceof C){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!n){const a=e.getTarget();Array.from(a.children).filter(c=>!c.hasAttribute(`${l.prefix}each-before`)&&!c.hasAttribute(`${l.prefix}each-after`)).forEach(c=>{if(!n){const f=w.get(c);f instanceof C&&(r=f.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const h=w.get(c);h instanceof C&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),c.parentNode&&c.parentNode.removeChild(c)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}return e.getEachInputSignature()===s?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(s)})}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:(p.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`)||u.hasNonEachDynamicElementState(e))return!1;const r=u.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),s=u.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===s}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:!u.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof C?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:u.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return u.recordDerivedSubtreeSignatureComputation(e,t),u.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:u.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(u.createDescendantBindingSignature(e,"refresh")),u.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!$.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=u.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:u.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return u.DERIVE_SUBTREE_PROFILES.set(e,r),r}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let s=i.tagName.toLowerCase();if(i.id.trim()!==""){s+=`#${i.id.trim()}`,t.unshift(s);break}const n=r.getRawAttribute(`${l.prefix}derive-name`);typeof n=="string"&&n.trim()!==""&&(s+=`[${l.prefix}derive-name="${n.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(c=>c instanceof C).findIndex(c=>c===r);s+=`:nth-child(${o+1})`}t.unshift(s),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=u.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),p.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 s=e.getRawAttribute(i);return typeof s=="string"&&s.includes("{{")})?!0:e.getChildren().some(i=>i instanceof L&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(s=>u.isFreshInitializationDynamicAttribute(e,s)),r=e.getChildren().some(s=>s instanceof C?!u.markFreshInitializationSkippable(s):s instanceof L?s.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 p.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${l.prefix}each-key`),n=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((E,F)=>{const N=u.createListKey(E,s?String(s):null,F);o.push(N),a.set(N,{item:E,itemIndex:F})});const c=new Set(o),h=[];let f=e.getChildren().filter(E=>E instanceof C).filter(E=>!E.hasAttribute(`${l.prefix}each-before`)&&!E.hasAttribute(`${l.prefix}each-after`));const g=f.map(E=>E.getListKey());f=f.filter(E=>c.has(String(E.getListKey()))?!0:(h.push(E.remove()),!1));const v=f.map(E=>E.getListKey()),S=new Map;f.forEach(E=>{const F=E.getListKey();F!==null&&!S.has(F)&&S.set(F,E)});const b=e.getChildElementFragments().slice(),y=b.filter(E=>E.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((E,F)=>{const{item:N,itemIndex:U}=a.get(E);let B;const K=S.get(E);if(K)B=K,m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(k=>{if(k)return u.evaluateAll(B)}));else{B=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment(B,N,i,U,n?String(n):null,E).then(()=>{const he=b[k]??null;return e.insertBefore(B,he).then(()=>{b.splice(k,0,B)}).then(()=>u.initializeFreshEachRow(B))}))}}),Promise.all(h).then(()=>m).then(()=>{const E=o.filter(k=>k!==null),F=v.filter(k=>k!==null),N=new Set(F),U=E.filter(k=>!N.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,E)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,c=u.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&u.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(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(s=>u.createBindingSignature(s,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${u.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{u.evaluateAll(e)},100)}};u.ATTRIBUTE_ALIAS_SUFFIX="attr-",u.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],u.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],u.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,u.REACTIVE_FETCH_STATES=new WeakMap,u.REACTIVE_IMPORT_STATES=new WeakMap,u.DERIVE_SUBTREE_PROFILES=new WeakMap,u.EACH_UPDATE_STATES=new WeakMap;let P=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),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("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=w.get(r);if(!i)return;t==="change"&&i instanceof C&&i.syncValue();const s=()=>{new q(i,t,e).run().catch(n=>{p.error("[Haori]","Procedure execution error:",n)})};if(t==="click"&&r.hasAttribute("data-click-defer")){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>s()):setTimeout(s,0);return}s()}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){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const D=class D{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)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=w.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),s=D.resolveRootMargin(r),n=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&D.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(c=>{const h=D.registrations.get(e);h&&c.forEach(f=>{!f.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new q(h.fragment,"intersect").runWithResult().then(g=>{g&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=D.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),D.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(D.isHtmlElement(e)){const t=D.registrations.get(e);t&&(t.observer.disconnect(),D.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=D.registrations.get(t);r&&(r.observer.disconnect(),D.registrations.delete(t))})}static disconnectAll(){D.registrations.forEach(e=>{e.observer.disconnect()}),D.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!D.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 D.isHtmlElement(i)?i:(p.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}};D.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),D.registrations=new Map;let Y=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),Y.syncTree(document.body)}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{switch(i.type){case"attributes":{const s=i.target;if(i.attributeName&&s.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&P.isAliasedAttributeReflection(s,i.attributeName))break;P.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName),!0),Y.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{Y.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),Y.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){p.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const we=()=>W.waitForRenders(),De="0.11.1";exports.Core=P;exports.Env=l;exports.Form=A;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=M;exports.default=W;exports.version=De;exports.waitForRenders=we;
17
20
  //# sourceMappingURL=haori.cjs.js.map