haori 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +2 -1
- package/README.md +2 -1
- package/dist/haori.cjs.js +2 -2
- package/dist/haori.cjs.js.map +1 -1
- package/dist/haori.es.js +23 -3
- package/dist/haori.es.js.map +1 -1
- package/dist/haori.iife.js +2 -2
- package/dist/haori.iife.js.map +1 -1
- package/dist/index.d.ts +13 -1
- package/dist/package.json +1 -1
- package/dist/src/fragment.d.ts +12 -0
- package/dist/src/fragment.d.ts.map +1 -1
- package/dist/src/fragment.js +25 -2
- package/dist/src/fragment.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/tests/data-form-container.test.js +2 -1
- package/dist/tests/data-form-container.test.js.map +1 -1
- package/dist/tests/form-number-type.test.d.ts +2 -0
- package/dist/tests/form-number-type.test.d.ts.map +1 -0
- package/dist/tests/form-number-type.test.js +83 -0
- package/dist/tests/form-number-type.test.js.map +1 -0
- package/dist/tests/form.test.js +7 -6
- package/dist/tests/form.test.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量なライブラリです。JavaScript をほとんど書かずに、データバインディング、条件分岐、繰り返し処理、フォームの双方向バインディング、サーバー通信などを HTML 属性で宣言できます。
|
|
4
4
|
|
|
5
|
-
バージョン: 0.
|
|
5
|
+
バージョン: 0.13.0
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -28,6 +28,7 @@ Haori.js は、HTML 属性を中心にして動的な UI を実現する軽量
|
|
|
28
28
|
- 繰り返し表示(`data-each`)
|
|
29
29
|
- フォーム双方向バインディング(`name` 属性による自動バインド)
|
|
30
30
|
- `value="true"` を付けたチェックボックスの boolean 対応(チェック時 `true`、未チェック時 `false`)
|
|
31
|
+
- `type="number"` 入力の数値型対応(バインド・送信時に数値。空・数値化できない値は `null`)
|
|
31
32
|
- イベント駆動アクション(`data-click-*`・`data-change-*`・`data-load-*`・`data-intersect-*`)
|
|
32
33
|
- サーバー通信(`data-fetch`)
|
|
33
34
|
- HTML インポート(`data-import`)
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Haori.js is a lightweight, HTML-first UI library that enables dynamic user interfaces primarily through HTML attributes. It lets you declare data bindings, conditional rendering, list rendering, form two-way binding, server fetches, and HTML imports without writing much JavaScript.
|
|
4
4
|
|
|
5
|
-
Version: 0.
|
|
5
|
+
Version: 0.13.0
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -28,6 +28,7 @@ Contents
|
|
|
28
28
|
- List rendering via `data-each`
|
|
29
29
|
- Two-way form binding (automatic binding based on `name` attributes)
|
|
30
30
|
- Boolean checkbox support with `value="true"` (`true` when checked, `false` when unchecked)
|
|
31
|
+
- `type="number"` inputs are bound and submitted as numbers (empty / non-numeric values become `null`)
|
|
31
32
|
- Event-driven actions via `data-click-*`, `data-change-*`, `data-load-*`, `data-intersect-*`
|
|
32
33
|
- Server fetches via `data-fetch`
|
|
33
34
|
- HTML imports via `data-import`
|
package/dist/haori.cjs.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
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,d=t[s-3]||null;if(this.startsObjectKey(o,i,c,d)&&(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 h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=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}};I.MAX_IDENTIFIER_RECOVERY_COUNT=8,I.BUILTIN_NAMESPACE="haori",I.BUILTIN_HELPERS={...Ae},I.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,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 X=I;class oe{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 oe.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const ue=class ue{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)}};ue.ASYNC_QUEUE=new oe;let x=ue;class W{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return x.waitForIdle()}static dialog(e){return x.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 x.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return x.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return x.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 x.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 x.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)}static date(e,t){return fe(e,t)}static number(e,t){return pe(e,t)}static range(e,t,r){return ge(e,t,r)}static pages(e,t,r){return me(e,t,r)}}const Se=["addErrorMessage","clearMessages"];function he(){const e=globalThis.window?.Haori;return Se.every(r=>typeof e?.[r]=="function")?e:W}class S{static getValues(e){const t={};return S.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())S.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())S.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={};S.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())S.getPartValues(n,t);return t}static setValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return S.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`),d=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!d||i){const h=t[String(a)];c&&Array.isArray(h)&&r!==null?n.push(S.applyFragmentValue(e,h[r]??null,s)):typeof h>"u"||(typeof h=="string"||typeof h=="number"||typeof h=="boolean"||h===null?n.push(S.applyFragmentValue(e,h,s)):n.push(S.applyFragmentValue(e,String(h),s)))}}else if(o){const h=t[String(o)];if(h&&typeof h=="object")for(const g of e.getChildElementFragments())n.push(S.setPartValues(g,h,null,i,s))}else if(c){const h=t[String(c)];if(Array.isArray(h)){const g=e.getChildElementFragments();for(let v=0;v<g.length;v++){const T=g[v];h.length>v?n.push(S.setPartValues(T,h[v],v,i,s)):n.push(S.setPartValues(T,{},v,i,s))}}}else for(const h of e.getChildElementFragments())n.push(S.setPartValues(h,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){S.clearValues(e),await Promise.all([S.clearMessages(e),S.clearEachClones(e)]),await x.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())S.clearValues(t)}static clearMessages(e){return he().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return S.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=he(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=S.findFragmentsByKey(e,t);return c.forEach(d=>{s.push(o(d.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return S.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(...S.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),d=Number(c);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));d<h.length&&r.push(...S.findFragmentByKeyParts(h[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...S.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 N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.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:N.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:N.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;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(n,t,r);return}const s=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.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=N.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=N.now();return{value:e(),durationMs:N.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(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let Q=N;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 le(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 x.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 x.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 x.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 Z(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,x.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,x.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 x.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 Z(e,r);if(s){const U=this.attributeMap.get(e);if(U&&(U.isEvaluate||U.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,x.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,d=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:g,T=!n.isForceEvaluation()&&(t!==e||d||h?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&g===""),b=n.isForceEvaluation()?r:h?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=T||b===null||b===!1?null:String(b),A=e!==t&&a.getAttribute(e)!==r,F=m===null?a.hasAttribute(t):a.getAttribute(t)!==m,M=y&&m!==null&&a.value!==m;return!A&&!F&&!M?(y&&m!==null&&(this.value=m),Promise.resolve()):(this.skipMutationAttributes=!0,x.enqueue(()=>{A&&a.setAttribute(e,r),m===null?a.removeAttribute(t):(F&&a.setAttribute(t,m),y&&(this.value=m,M&&(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 x.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 d=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),d=v.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,x.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(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")):x.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 le extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new le(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,x.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ee=class ee{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ee.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 d=Q.measure(()=>X.evaluateDetailed(c.text,e)),h=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||h.unresolvedReference,s.push(h.value)}else s.push(c.text)}catch(d){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,d),n.push({expression:c.text,durationMs:0}),s.push("")}}),Q.record(t,n,a),{results:s,hasUnresolvedReference:o}}};ee.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=ee;const te=class te extends j{constructor(e,t){super(t),this.forceEvaluation=te.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}};te.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let Z=te;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 d=t?.[c],h=r[c];d!==h&&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 Te=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],we="__haoriHistoryState__",ie="data-haori-click-lock";function se(){const e=globalThis.window?.Haori;return Te.every(r=>typeof e?.[r]=="function")?e:W}const De=new Set(["GET","HEAD","OPTIONS"]);function Re(E){return De.has(E.toUpperCase())}function Fe(E,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?E.append(t,""):Array.isArray(r)?r.forEach(i=>{E.append(t,String(i))}):typeof r=="object"||typeof r=="function"?E.append(t,JSON.stringify(r)):E.append(t,String(r)))}function Ne(E,e){const t=new URL(E,window.location.href),r=new URLSearchParams(t.search);return Fe(r,e),t.search=r.toString(),t.toString()}function Me(E){return E==null?null:typeof E=="string"?E:E instanceof URLSearchParams?E.toString():E instanceof FormData?Array.from(E.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(E)}function xe(E,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:E,method:String(e.method||"GET").toUpperCase(),headers:r,body:Me(e.body||null)})}const f=class f{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 f.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=X.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"?f.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return f.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=X.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,f.isJsonStringContext(e,o)?f.stringifyJsonTemplateStringContent(c.value):f.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return f.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(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=f.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=f.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(f.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(f.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(f.attrName(t,"confirm")).replace(/\\n/g,`
|
|
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.BUILTIN_NAMESPACE="haori",I.BUILTIN_HELPERS={...Ae},I.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,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 X=I;class oe{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 oe.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const ue=class ue{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)}};ue.ASYNC_QUEUE=new oe;let x=ue;class W{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return x.waitForIdle()}static dialog(e){return x.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 x.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return x.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return x.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 x.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 x.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)}static date(e,t){return fe(e,t)}static number(e,t){return pe(e,t)}static range(e,t,r){return ge(e,t,r)}static pages(e,t,r){return me(e,t,r)}}const Se=["addErrorMessage","clearMessages"];function he(){const e=globalThis.window?.Haori;return Se.every(r=>typeof e?.[r]=="function")?e:W}class S{static getValues(e){const t={};return S.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())S.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())S.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={};S.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())S.getPartValues(n,t);return t}static setValues(e,t,r=!1){return S.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return S.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`),d=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!d||i){const h=t[String(a)];c&&Array.isArray(h)&&r!==null?n.push(S.applyFragmentValue(e,h[r]??null,s)):typeof h>"u"||(typeof h=="string"||typeof h=="number"||typeof h=="boolean"||h===null?n.push(S.applyFragmentValue(e,h,s)):n.push(S.applyFragmentValue(e,String(h),s)))}}else if(o){const h=t[String(o)];if(h&&typeof h=="object")for(const g of e.getChildElementFragments())n.push(S.setPartValues(g,h,null,i,s))}else if(c){const h=t[String(c)];if(Array.isArray(h)){const g=e.getChildElementFragments();for(let v=0;v<g.length;v++){const T=g[v];h.length>v?n.push(S.setPartValues(T,h[v],v,i,s)):n.push(S.setPartValues(T,{},v,i,s))}}}else for(const h of e.getChildElementFragments())n.push(S.setPartValues(h,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){S.clearValues(e),await Promise.all([S.clearMessages(e),S.clearEachClones(e)]),await x.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())S.clearValues(t)}static clearMessages(e){return he().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return S.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=he(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=S.findFragmentsByKey(e,t);return c.forEach(d=>{s.push(o(d.getTarget()))}),c.length===0&&s.push(o(e.getTarget())),Promise.all(s).then(()=>{})}static findFragmentsByKey(e,t){return S.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(...S.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),d=Number(c);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));d<h.length&&r.push(...S.findFragmentByKeyParts(h[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...S.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 N=class N{static reset(){N.ELEMENT_STORES.clear(),N.ensureGlobalAccess()}static snapshot(){return N.ensureGlobalAccess(),[...N.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:N.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:N.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;N.ensureGlobalAccess();const i=N.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=N.getOrCreateCounter(i.attributes,e.rawName,e.template);N.updateCounter(n,t,r);return}const s=N.getOrCreateCounter(i.texts,String(e.childIndex),e.template);N.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!B.isEnabled())return;const e=globalThis;e[N.GLOBAL_KEY]===void 0&&(e[N.GLOBAL_KEY]={reset:()=>N.reset(),snapshot:()=>N.snapshot()})}static getOrCreateElementStore(e){const t=N.createElementId(e),r=N.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return N.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=N.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=N.now();return{value:e(),durationMs:N.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(" > ")}};N.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",N.ELEMENT_STORES=new Map;let Q=N;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 le(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 x.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 x.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 x.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 Z(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,x.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=this.normalizeValueForElement(r,e),this.skipChangeValue=!0,x.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}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}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=this.normalizeValueForElement(e,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 x.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 Z(e,r);if(s){const U=this.attributeMap.get(e);if(U&&(U.isEvaluate||U.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,x.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,d=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:g,T=!n.isForceEvaluation()&&(t!==e||d||h?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&g===""),b=n.isForceEvaluation()?r:h?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=T||b===null||b===!1?null:String(b),A=e!==t&&a.getAttribute(e)!==r,F=m===null?a.hasAttribute(t):a.getAttribute(t)!==m,M=y&&m!==null&&a.value!==m;return!A&&!F&&!M?(y&&m!==null&&(this.value=m),Promise.resolve()):(this.skipMutationAttributes=!0,x.enqueue(()=>{A&&a.setAttribute(e,r),m===null?a.removeAttribute(t):(F&&a.setAttribute(t,m),y&&(this.value=m,M&&(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 x.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 d=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),d=v.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,x.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(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")):x.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 le extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new le(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,x.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ee=class ee{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ee.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 d=Q.measure(()=>X.evaluateDetailed(c.text,e)),h=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||h.unresolvedReference,s.push(h.value)}else s.push(c.text)}catch(d){p.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,d),n.push({expression:c.text,durationMs:0}),s.push("")}}),Q.record(t,n,a),{results:s,hasUnresolvedReference:o}}};ee.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=ee;const te=class te extends j{constructor(e,t){super(t),this.forceEvaluation=te.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}};te.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let Z=te;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 d=t?.[c],h=r[c];d!==h&&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 Te=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],we="__haoriHistoryState__",ie="data-haori-click-lock";function se(){const e=globalThis.window?.Haori;return Te.every(r=>typeof e?.[r]=="function")?e:W}const De=new Set(["GET","HEAD","OPTIONS"]);function Re(E){return De.has(E.toUpperCase())}function Fe(E,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?E.append(t,""):Array.isArray(r)?r.forEach(i=>{E.append(t,String(i))}):typeof r=="object"||typeof r=="function"?E.append(t,JSON.stringify(r)):E.append(t,String(r)))}function Ne(E,e){const t=new URL(E,window.location.href),r=new URLSearchParams(t.search);return Fe(r,e),t.search=r.toString(),t.toString()}function Me(E){return E==null?null:typeof E=="string"?E:E instanceof URLSearchParams?E.toString():E instanceof FormData?Array.from(E.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(E)}function xe(E,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:E,method:String(e.method||"GET").toUpperCase(),headers:r,body:Me(e.body||null)})}const f=class f{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 f.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=X.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"?f.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return f.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(f.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=X.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,f.isJsonStringContext(e,o)?f.stringifyJsonTemplateStringContent(c.value):f.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return f.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(f.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=f.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=f.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(f.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(f.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(f.attrName(t,"confirm")).replace(/\\n/g,`
|
|
7
7
|
`)),e.hasAttribute(f.attrName(t,"data"))&&(r.dataAttrName=f.attrName(t,"data")),e.hasAttribute(f.attrName(t,"form"))){const y=e.getRawAttribute(f.attrName(t,"form"));if(y){const m=document.body.querySelector(y);m!==null?r.formFragment=S.getFormFragment(w.get(m)):p.error("Haori",`Form element not found: ${y} (${f.attrName(t,"form")})`)}else r.formFragment=S.getFormFragment(e)}else t==="change"&&(r.formFragment=S.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
9
|
${y}
|
|
@@ -16,5 +16,5 @@ ${m}
|
|
|
16
16
|
`)}catch(A){p.error("Haori",`Invalid after script: ${A}`)}}if(e.hasAttribute(f.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(f.attrName(t,"dialog")).replace(/\\n/g,`
|
|
17
17
|
`)),e.hasAttribute(f.attrName(t,"toast"))){r.toastMessage=e.getAttribute(f.attrName(t,"toast"));const m=e.getRawAttribute(f.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(m);r.toastLevel=F?m:null}if(e.hasAttribute(f.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(f.attrName(t,"redirect"))),e.hasAttribute(f.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(f.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(f.attrName(t,"scroll"))),e.hasAttribute(f.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(f.attrName(t,"history"))),e.hasAttribute(f.attrName(t,"history-data"))&&(r.historyDataAttrName=f.attrName(t,"history-data")),e.hasAttribute(f.attrName(t,"history-form"))){const m=e.getRawAttribute(f.attrName(t,"history-form"));if(m){const A=document.body.querySelector(m);A!==null?r.historyFormFragment=S.getFormFragment(w.get(A)):p.error("Haori",`Form element not found: ${m} (${f.attrName(t,"history-form")})`)}else r.historyFormFragment=S.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(m=>{const A=f.attrName(t,m);if(!e.hasAttribute(A))return;const F=e.getRawAttribute(A),M=[];if(F?(document.body.querySelectorAll(F).forEach($=>{const K=w.get($);K&&M.push(K)}),M.length===0&&p.error("Haori",`Element not found: ${F} (${A})`)):M.push(e),M.length>0)switch(m){case"reset-before":r.resetBeforeFragments=M;break;case"reset":r.resetFragments=M;break;case"refetch":r.refetchFragments=M;break;case"click":r.clickFragments=M;break;case"copy":r.copyFragments=M;break;case"open":r.openFragments=M;break;case"close":r.closeFragments=M;break}});const y=f.attrName(t,"copy-source");if(e.hasAttribute(y)){const m=e.getRawAttribute(y);if(m){const A=document.body.querySelector(m);if(A!==null){const F=w.get(A);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(f.attrName(null,"data",!0))&&(r.dataAttrName=f.attrName(null,"data",!0)),e.hasAttribute(f.attrName(null,"form",!0)))){const b=e.getRawAttribute(f.attrName(null,"form",!0));if(b){const y=document.body.querySelector(b);y!==null?r.formFragment=S.getFormFragment(w.get(y)):p.error("Haori",`Form element not found: ${b} (${f.attrName(null,"fetch-form",!0)})`)}else r.formFragment=S.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){f.isElementFragment(e)?(this.options=f.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static resolveAutoFetchSignature(e){return new f(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 d=this.options.targetFragment?.getTarget()??null;try{this.options.runScript.call(d,this.domEvent)===!1&&this.domEvent&&this.domEvent.preventDefault()}catch(h){p.error("Haori",`Run script execution error: ${h}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>S.reset(d))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let s=r.url,n=r.options;if(this.options.beforeCallback){const d=this.options.beforeCallback(s||null,n||null);if(d!=null){if(d===!1||typeof d=="object"&&d.stop)return!1;typeof d=="object"&&(s="fetchUrl"in d?d.fetchUrl:s,n="fetchOptions"in d?d.fetchOptions:n)}}const a=Object.keys(i).length>0;if(s){const d={...n||{}},h=r.requestedMethod,g=r.effectiveMethod,v=r.transportMode==="query-get",T=r.queryString;if(v&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:h,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&s){const b=performance.now(),y={runtime:l.runtime,requestedMethod:h,effectiveMethod:g,transportMode:v?"query-get":"http",...v?{queryString:T}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),s,d,a?i:void 0,y),fetch(s,d).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,d).then(b=>this.handleFetchResult(b,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,h=d.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),h.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const v=d.getBindingData();Object.assign(v,i),await P.setBindingData(h,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(f.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(ie))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return f.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(ie,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(f.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(ie),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=se();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=>S.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new f(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[d,h]of Object.entries(c))h!=null&&(Array.isArray(h)?h.forEach(g=>a.searchParams.append(d,String(g))):typeof h=="object"?a.searchParams.set(d,JSON.stringify(h)):a.searchParams.set(d,String(h)))};i&&o(t),s&&o(r),history.pushState({[we]:!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=S.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await se().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(`
|
|
18
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(`
|
|
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 S.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):se().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"?S.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?S.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,S.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=f.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"&&!Re(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=Ne(i,t));else if(Object.keys(t).length>0){const h=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){n.delete("Content-Type");const g=new FormData;for(const[v,T]of Object.entries(t))T==null?g.append(v,""):T instanceof Blob?g.append(v,T):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[v,T]of Object.entries(t))T!==void 0&&(T===null?g.append(v,""):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let d;return o&&(d=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:d,transportMode:o?"query-get":"http",signature:xe(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?S.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return S.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(S.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()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let q=f;class Pe{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Ie{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),Ie.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return x.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(d=>{const h=w.get(d);h instanceof C?c.push(u.scan(h.getTarget())):h instanceof L&&c.push(u.evaluateText(h))}),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 d=s.getAttribute(`${l.prefix}url-arg`),h=Pe.readParams();if(d===null)a.push(u.setBindingData(e,h));else{const g=s.getRawBindingData()||{};g[String(d)]=h,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(d=>{if(d)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(()=>S.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 d=c.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},n=(c,d,h,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(d),kind:h,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=S.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,d=!1,h=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}h=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,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(()=>{d&&h!==null&&e.setDeriveSubtreeSignature(h)}))}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=X.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 h=w.get(c);h instanceof C&&(r=h.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const d=w.get(c);d instanceof C&&e.getChildren().includes(d)&&(e.removeChild(d),d.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((A,F)=>{const M=u.createListKey(A,s?String(s):null,F);o.push(M),a.set(M,{item:A,itemIndex:F})});const c=new Set(o),d=[];let h=e.getChildren().filter(A=>A instanceof C).filter(A=>!A.hasAttribute(`${l.prefix}each-before`)&&!A.hasAttribute(`${l.prefix}each-after`));const g=h.map(A=>A.getListKey());h=h.filter(A=>c.has(String(A.getListKey()))?!0:(d.push(A.remove()),!1));const v=h.map(A=>A.getListKey()),T=new Map;h.forEach(A=>{const F=A.getListKey();F!==null&&!T.has(F)&&T.set(F,A)});const b=e.getChildElementFragments().slice(),y=b.filter(A=>A.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((A,F)=>{const{item:M,itemIndex:U}=a.get(A);let $;const K=T.get(A);if(K)$=K,m=m.then(()=>u.updateRowFragment($,M,i,U,n?String(n):null,A).then(k=>{if(k)return u.evaluateAll($)}));else{$=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment($,M,i,U,n?String(n):null,A).then(()=>{const be=b[k]??null;return e.insertBefore($,be).then(()=>{b.splice(k,0,$)}).then(()=>u.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>m).then(()=>{const A=o.filter(k=>k!==null),F=v.filter(k=>k!==null),M=new Set(F),U=A.filter(k=>!M.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,A)})}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 re=class re{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[re.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;r.hasAttribute(`data-${t}-prevent`)&&e.preventDefault();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}};re.HISTORY_STATE_KEY="__haoriHistoryState__";let ae=re;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 d=D.registrations.get(e);d&&c.forEach(h=>{!h.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new q(d.fragment,"intersect").runWithResult().then(g=>{g&&d.once&&(d.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 J=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 x.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ae().start(),J.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),J.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{J.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),J.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 _=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",_.init):_.init();const Ce=()=>W.waitForRenders(),ke="0.12.0";exports.Core=P;exports.Env=l;exports.Form=S;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=x;exports.default=W;exports.version=ke;exports.waitForRenders=Ce;
|
|
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 S.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):se().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"?S.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?S.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,S.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=f.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"&&!Re(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=Ne(i,t));else if(Object.keys(t).length>0){const h=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){n.delete("Content-Type");const g=new FormData;for(const[v,T]of Object.entries(t))T==null?g.append(v,""):T instanceof Blob?g.append(v,T):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[v,T]of Object.entries(t))T!==void 0&&(T===null?g.append(v,""):Array.isArray(T)?T.forEach(b=>g.append(v,String(b))):typeof T=="object"?g.append(v,JSON.stringify(T)):g.append(v,String(T)));s.body=g}else n.set("Content-Type","application/json"),s.body=JSON.stringify(t)}s.headers=n;let d;return o&&(d=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:d,transportMode:o?"query-get":"http",signature:xe(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?S.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?f.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return S.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(S.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()}};f.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,f.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,f.RUNNING_CLICK_TARGETS=new WeakSet;let q=f;class Pe{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Ie{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),Ie.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return x.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(d=>{const h=w.get(d);h instanceof C?c.push(u.scan(h.getTarget())):h instanceof L&&c.push(u.evaluateText(h))}),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 d=s.getAttribute(`${l.prefix}url-arg`),h=Pe.readParams();if(d===null)a.push(u.setBindingData(e,h));else{const g=s.getRawBindingData()||{};g[String(d)]=h,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(d=>{if(d)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(()=>S.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 d=c.getTarget();return d.id?`#${d.id}`:d.tagName.toLowerCase()},n=(c,d,h,g)=>{if(c)for(const v of Object.keys(c))v in i||(i[v]={value:c[v],source:s(d),kind:h,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=S.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,d=!1,h=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}h=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,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(()=>{d&&h!==null&&e.setDeriveSubtreeSignature(h)}))}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=X.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 h=w.get(c);h instanceof C&&(r=h.clone(),u.markFreshInitializationSkippable(r),e.setTemplate(r),n=!0)}const d=w.get(c);d instanceof C&&e.getChildren().includes(d)&&(e.removeChild(d),d.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((A,F)=>{const M=u.createListKey(A,s?String(s):null,F);o.push(M),a.set(M,{item:A,itemIndex:F})});const c=new Set(o),d=[];let h=e.getChildren().filter(A=>A instanceof C).filter(A=>!A.hasAttribute(`${l.prefix}each-before`)&&!A.hasAttribute(`${l.prefix}each-after`));const g=h.map(A=>A.getListKey());h=h.filter(A=>c.has(String(A.getListKey()))?!0:(d.push(A.remove()),!1));const v=h.map(A=>A.getListKey()),T=new Map;h.forEach(A=>{const F=A.getListKey();F!==null&&!T.has(F)&&T.set(F,A)});const b=e.getChildElementFragments().slice(),y=b.filter(A=>A.hasAttribute(`${l.prefix}each-before`)).length;let m=Promise.resolve();return o.forEach((A,F)=>{const{item:M,itemIndex:U}=a.get(A);let $;const K=T.get(A);if(K)$=K,m=m.then(()=>u.updateRowFragment($,M,i,U,n?String(n):null,A).then(k=>{if(k)return u.evaluateAll($)}));else{$=r.clone();const k=y+F;m=m.then(()=>u.updateRowFragment($,M,i,U,n?String(n):null,A).then(()=>{const be=b[k]??null;return e.insertBefore($,be).then(()=>{b.splice(k,0,$)}).then(()=>u.initializeFreshEachRow($))}))}}),Promise.all(d).then(()=>m).then(()=>{const A=o.filter(k=>k!==null),F=v.filter(k=>k!==null),M=new Set(F),U=A.filter(k=>!M.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,A)})}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 re=class re{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[re.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;r.hasAttribute(`data-${t}-prevent`)&&e.preventDefault();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}};re.HISTORY_STATE_KEY="__haoriHistoryState__";let ae=re;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 d=D.registrations.get(e);d&&c.forEach(h=>{!h.isIntersecting||d.running||D.isDisabled(d.fragment)||(d.running=!0,new q(d.fragment,"intersect").runWithResult().then(g=>{g&&d.once&&(d.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 J=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 x.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ae().start(),J.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),J.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{J.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),J.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 _=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",_.init):_.init();const Ce=()=>W.waitForRenders(),ke="0.13.0";exports.Core=P;exports.Env=l;exports.Form=S;exports.Fragment=w;exports.Haori=W;exports.Log=p;exports.Queue=x;exports.default=W;exports.version=ke;exports.waitForRenders=Ce;
|
|
20
20
|
//# sourceMappingURL=haori.cjs.js.map
|