haori 0.6.2 → 0.8.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.
Files changed (47) hide show
  1. package/dist/haori.cjs.js +11 -11
  2. package/dist/haori.cjs.js.map +1 -1
  3. package/dist/haori.es.js +751 -650
  4. package/dist/haori.es.js.map +1 -1
  5. package/dist/haori.iife.js +11 -11
  6. package/dist/haori.iife.js.map +1 -1
  7. package/dist/index.d.ts +46 -2
  8. package/dist/package.json +1 -1
  9. package/dist/src/core.d.ts +45 -1
  10. package/dist/src/core.d.ts.map +1 -1
  11. package/dist/src/core.js +103 -10
  12. package/dist/src/core.js.map +1 -1
  13. package/dist/src/event.d.ts +12 -0
  14. package/dist/src/event.d.ts.map +1 -1
  15. package/dist/src/event.js +14 -0
  16. package/dist/src/event.js.map +1 -1
  17. package/dist/src/index.d.ts +1 -1
  18. package/dist/src/index.d.ts.map +1 -1
  19. package/dist/src/index.js +1 -1
  20. package/dist/src/index.js.map +1 -1
  21. package/dist/src/procedure.d.ts +7 -0
  22. package/dist/src/procedure.d.ts.map +1 -1
  23. package/dist/src/procedure.js +58 -4
  24. package/dist/src/procedure.js.map +1 -1
  25. package/dist/tests/data-bind-arg-reeval.test.d.ts +2 -0
  26. package/dist/tests/data-bind-arg-reeval.test.d.ts.map +1 -0
  27. package/dist/tests/data-bind-arg-reeval.test.js +119 -0
  28. package/dist/tests/data-bind-arg-reeval.test.js.map +1 -0
  29. package/dist/tests/data-bind-merge.test.d.ts +2 -0
  30. package/dist/tests/data-bind-merge.test.d.ts.map +1 -0
  31. package/dist/tests/data-bind-merge.test.js +86 -0
  32. package/dist/tests/data-bind-merge.test.js.map +1 -0
  33. package/dist/tests/data-if-falsy.test.d.ts +2 -0
  34. package/dist/tests/data-if-falsy.test.d.ts.map +1 -0
  35. package/dist/tests/data-if-falsy.test.js +73 -0
  36. package/dist/tests/data-if-falsy.test.js.map +1 -0
  37. package/dist/tests/data-load-on-show.test.d.ts +2 -0
  38. package/dist/tests/data-load-on-show.test.d.ts.map +1 -0
  39. package/dist/tests/data-load-on-show.test.js +98 -0
  40. package/dist/tests/data-load-on-show.test.js.map +1 -0
  41. package/dist/tests/each-update-event.test.d.ts +2 -0
  42. package/dist/tests/each-update-event.test.d.ts.map +1 -0
  43. package/dist/tests/each-update-event.test.js +83 -0
  44. package/dist/tests/each-update-event.test.js.map +1 -0
  45. package/dist/tests/procedure-action-operations.test.js +128 -0
  46. package/dist/tests/procedure-action-operations.test.js.map +1 -1
  47. package/package.json +1 -1
package/dist/haori.cjs.js CHANGED
@@ -1,17 +1,17 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const q=class q{static isEnabled(){return q.devMode}static enable(){q.devMode=!0}static disable(){q.devMode=!1}static set(e){q.devMode=e}};q.devMode=!1;let H=q;const se="embedded";function ue(S){return S==="embedded"||S==="demo"}function he(S){return S===null?null:ue(S)?S:se}const $=class ${static get runtime(){return $._runtime}static setRuntime(e){$._runtime=ue(e)?e:se}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||$._prefix;$._prefix=r.endsWith("-")?r:r+"-";const i=he(e.getAttribute("data-runtime"));i!==null&&($._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${$._prefix}dev`)){H.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){H.set(!0);return}H.set(!1)}catch{}}static get prefix(){return $._prefix}};$._prefix="data-",$._runtime=se;let l=$;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class m{static info(e,...t){H.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){H.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const P=class P{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
- `)}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return m.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e))return m.warn("[Haori]",e,"Expression contains dangerous patterns"),{value:null,unresolvedReference:!1};if(this.containsForbiddenKeys(t))return m.warn("[Haori]",t,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,r))return m.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i={...t},s=this.canAttemptMissingIdentifierRecovery(e);for(let n=0;n<=this.MAX_IDENTIFIER_RECOVERY_COUNT;n+=1){const a=this.prepareEvaluator(e,i);if(a.compileFailed||a.evaluator===null)return{value:null,unresolvedReference:!1};try{const o=[],c=this.wrapBoundValues(i);return a.bindKeys.forEach(d=>{o.push(c[d])}),{value:this.withBlockedPropertyAccess(()=>a.evaluator(...o)),unresolvedReference:!1}}catch(o){if(s&&o instanceof ReferenceError){const c=this.extractMissingIdentifier(o);if(c!==null&&this.canRecoverMissingIdentifier(c,i)){i[c]=void 0;continue}}return m.error("[Haori]","Expression evaluation error:",e,o),o instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return m.error("[Haori]","Failed to recover missing identifiers:",e,i),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t){const r=Object.keys(t).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${e}:${r.join(",")}`;let s=this.EXPRESSION_CACHE.get(i)||null;if(s!==null)return{bindKeys:r,evaluator:s,compileFailed:!1};const n=this.buildAssignments(r),a=n?`"use strict";
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const z=class z{static isEnabled(){return z.devMode}static enable(){z.devMode=!0}static disable(){z.devMode=!1}static set(e){z.devMode=e}};z.devMode=!1;let L=z;const se="embedded";function ue(S){return S==="embedded"||S==="demo"}function he(S){return S===null?null:ue(S)?S:se}const $=class ${static get runtime(){return $._runtime}static setRuntime(e){$._runtime=ue(e)?e:se}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||$._prefix;$._prefix=r.endsWith("-")?r:r+"-";const i=he(e.getAttribute("data-runtime"));i!==null&&($._runtime=i)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${$._prefix}dev`)){L.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){L.set(!0);return}L.set(!1)}catch{}}static get prefix(){return $._prefix}};$._prefix="data-",$._runtime=se;let l=$;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect();class p{static info(e,...t){L.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){L.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const I=class I{static getForbiddenBindingValues(){const e=globalThis,t=[e,e.window,e.document,e.navigator,e.history,e.localStorage,e.sessionStorage,e.fetch,e.Function,e.setTimeout,e.setInterval,e.requestAnimationFrame,e.alert,e.confirm,e.prompt];return e.window?.location&&t.push(e.window.location),t.filter(r=>r!=null)}static getForbiddenBindingValueSet(){return new Set(this.getForbiddenBindingValues())}static scheduleForbiddenBindingValueCacheReset(){this.forbiddenBindingValueCacheResetScheduled||(this.forbiddenBindingValueCacheResetScheduled=!0,queueMicrotask(()=>{this.forbiddenBindingValueCache=new WeakMap,this.forbiddenBindingValueCacheResetScheduled=!1}))}static buildAssignments(e){const t=new Set(e);return this.FORBIDDEN_NAMES.filter(r=>!t.has(r)).map(r=>`const ${r} = undefined`).join(`;
2
+ `)}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return p.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e))return p.warn("[Haori]",e,"Expression contains dangerous patterns"),{value:null,unresolvedReference:!1};if(this.containsForbiddenKeys(t))return p.warn("[Haori]",t,"Binded values contain forbidden keys"),{value:null,unresolvedReference:!1};const r=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,r))return p.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const i={...t},s=this.canAttemptMissingIdentifierRecovery(e);for(let n=0;n<=this.MAX_IDENTIFIER_RECOVERY_COUNT;n+=1){const a=this.prepareEvaluator(e,i);if(a.compileFailed||a.evaluator===null)return{value:null,unresolvedReference:!1};try{const o=[],c=this.wrapBoundValues(i);return a.bindKeys.forEach(d=>{o.push(c[d])}),{value:this.withBlockedPropertyAccess(()=>a.evaluator(...o)),unresolvedReference:!1}}catch(o){if(s&&o instanceof ReferenceError){const c=this.extractMissingIdentifier(o);if(c!==null&&this.canRecoverMissingIdentifier(c,i)){i[c]=void 0;continue}}return p.error("[Haori]","Expression evaluation error:",e,o),o instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return p.error("[Haori]","Failed to recover missing identifiers:",e,i),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t){const r=Object.keys(t).filter(o=>!this.FORBIDDEN_BINDING_NAMES.has(o)).sort(),i=`${e}:${r.join(",")}`;let s=this.EXPRESSION_CACHE.get(i)||null;if(s!==null)return{bindKeys:r,evaluator:s,compileFailed:!1};const n=this.buildAssignments(r),a=n?`"use strict";
3
3
  ${n};
4
4
  return (${e});`:`"use strict";
5
- return (${e});`;try{return s=new Function(...r,a),this.EXPRESSION_CACHE.set(i,s),{bindKeys:r,evaluator:s,compileFailed:!1}}catch(o){return m.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 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 f=this.startsMemberAccess(i)?"member":"array";r.push(f);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=n}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<e.length;){const n=e[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return null;if(n==='"'||n==="'"){const o=this.readStringToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,s));if(a){t.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(i.has(n)){t.push({type:"operator",value:n,position:s}),s+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const s=e[i];if(s==="\\"){i+=2;continue}if(s===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};P.MAX_IDENTIFIER_RECOVERY_COUNT=8,P.forbiddenBindingValueCache=new WeakMap,P.forbiddenBindingValueCacheResetScheduled=!1,P.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"],P.STRICT_FORBIDDEN_NAMES=["eval","arguments"],P.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),P.FORBIDDEN_BINDING_NAMES=new Set([...P.FORBIDDEN_NAMES.filter(e=>!P.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...P.STRICT_FORBIDDEN_NAMES]),P.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),P.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),P.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"]),P.EXPRESSION_CACHE=new Map;let W=P;class de{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),m.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){m.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}}const oe=class oe{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}};oe.ASYNC_QUEUE=new de;let N=oe;class Y{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static dialog(e){return N.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 N.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return N.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return N.enqueue(()=>{e instanceof HTMLDialogElement?e.close():m.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return Y.addMessage(e,t,"error")}static addMessage(e,t,r){return N.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 N.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}}const fe=["addErrorMessage","clearMessages"];function le(){const e=globalThis.window?.Haori;return fe.every(r=>typeof e?.[r]=="function")?e:Y}class E{static getValues(e){const t={};return E.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&&m.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())E.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())E.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&m.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={};E.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())E.getPartValues(n,t);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return E.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 f=t[String(a)];c&&Array.isArray(f)&&r!==null?n.push(E.applyFragmentValue(e,f[r]??null,s)):typeof f>"u"||(typeof f=="string"||typeof f=="number"||typeof f=="boolean"||f===null?n.push(E.applyFragmentValue(e,f,s)):n.push(E.applyFragmentValue(e,String(f),s)))}}else if(o){const f=t[String(o)];if(f&&typeof f=="object")for(const b of e.getChildElementFragments())n.push(E.setPartValues(b,f,null,i,s))}else if(c){const f=t[String(c)];if(Array.isArray(f)){const b=e.getChildElementFragments();for(let v=0;v<b.length;v++){const p=b[v];f.length>v?n.push(E.setPartValues(p,f[v],v,i,s)):n.push(E.setPartValues(p,{},v,i,s))}}}else for(const f of e.getChildElementFragments())n.push(E.setPartValues(f,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await N.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 x.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())E.clearValues(t)}static clearMessages(e){return le().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=le(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=E.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 E.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(...E.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))m.error("Haori",`Invalid index: ${i}`);else{const f=e.getChildElementFragments().filter(b=>b.hasAttribute(`${l.prefix}row`));d<f.length&&r.push(...E.findFragmentByKeyParts(f[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t))});return r}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const r=e.getParent();return r?this.getFormFragment(r):null}}const F=class F{static reset(){F.ELEMENT_STORES.clear(),F.ensureGlobalAccess()}static snapshot(){return F.ensureGlobalAccess(),[...F.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:F.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:F.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(!H.isEnabled()||!e||t.length===0)return;F.ensureGlobalAccess();const i=F.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const n=F.getOrCreateCounter(i.attributes,e.rawName,e.template);F.updateCounter(n,t,r);return}const s=F.getOrCreateCounter(i.texts,String(e.childIndex),e.template);F.updateCounter(s,t,r)}static ensureGlobalAccess(){if(!H.isEnabled())return;const e=globalThis;e[F.GLOBAL_KEY]===void 0&&(e[F.GLOBAL_KEY]={reset:()=>F.reset(),snapshot:()=>F.snapshot()})}static getOrCreateElementStore(e){const t=F.createElementId(e),r=F.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return F.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=F.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=F.now();return{value:e(),durationMs:F.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(" > ")}};F.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",F.ELEMENT_STORES=new Map;let X=F;const K=class K{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,K.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(K.FRAGMENT_CACHE.has(e))return K.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new L(e);break;case Node.COMMENT_NODE:t=new ae(e);break;default:return m.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 N.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 N.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 N.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),K.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};K.FRAGMENT_CACHE=new WeakMap;let R=K;const V=class V extends R{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Q(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=R.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){m.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new V(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.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,N.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,N.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})):(m.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 N.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new Q(e,r);if(s){const B=this.attributeMap.get(e);if(B&&(B.isEvaluate||B.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,N.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()),f=n.isSingleExpression(),b=j.joinEvaluateResults(o.results),v=o.results.length===1?o.results[0]:b,p=!n.isForceEvaluation()&&(t!==e||d||f?o.hasUnresolvedReference||v===null||v===void 0||v===!1:c&&b===""),g=n.isForceEvaluation()?r:f?v:b,D=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),A=p||g===null||g===!1?null:String(g),y=e!==t&&a.getAttribute(e)!==r,C=A===null?a.hasAttribute(t):a.getAttribute(t)!==A,k=D&&A!==null&&a.value!==A;return!y&&!C&&!k?(D&&A!==null&&(this.value=A),Promise.resolve()):(this.skipMutationAttributes=!0,N.enqueue(()=>{y&&a.setAttribute(e,r),A===null?a.removeAttribute(t):(C&&a.setAttribute(t,A),D&&(this.value=A,k&&(a.value=A)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return N.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=R.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 m.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return m.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=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 b;if(n?a!==-1&&a<o?b=o-1:b=o:b=this.children.indexOf(t),b===-1){const v=this.resolveInsertionPointFromDom(t,!1);v===null?(m.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(b,0,e)}e.setParent(this),e.setMounted(this.mounted);const f=this.skipMutationNodes;return this.skipMutationNodes=!0,N.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=f})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(m.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}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 M=V;class L extends R{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")):N.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 ae extends R{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new ae(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,N.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const _=class _{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(_.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(m.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const d=X.measure(()=>W.evaluateDetailed(c.text,e)),f=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||f.unresolvedReference,s.push(f.value)}else s.push(c.text)}catch(d){m.error("[Haori]",`Error evaluating ${i} expression: ${c.text}`,d),n.push({expression:c.text,durationMs:0}),s.push("")}}),X.record(t,n,a),{results:s,hasUnresolvedReference:o}}};_.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=_;const ee=class ee extends j{constructor(e,t){super(t),this.forceEvaluation=ee.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(m.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ee.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let Q=ee;class w{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){w.dispatch(document,"ready",{version:e})}static render(e){w.dispatch(e,"render",{target:e})}static importStart(e,t){w.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){w.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){w.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],f=r[c];d!==f&&s.push(c)}w.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static eachUpdate(e,t,r,i){w.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){w.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){w.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){w.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){w.dispatch(e,"show",{visible:!0})}static hide(e){w.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){w.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){w.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){w.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const pe=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],ge="__haoriHistoryState__",re="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return pe.every(r=>typeof e?.[r]=="function")?e:Y}const me=new Set(["GET","HEAD","OPTIONS"]);function be(S){return me.has(S.toUpperCase())}function ve(S,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?S.append(t,""):Array.isArray(r)?r.forEach(i=>{S.append(t,String(i))}):typeof r=="object"||typeof r=="function"?S.append(t,JSON.stringify(r)):S.append(t,String(r)))}function ye(S,e){const t=new URL(S,window.location.href),r=new URLSearchParams(t.search);return ve(r,e),t.search=r.toString(),t.toString()}function Ee(S){return S==null?null:typeof S=="string"?S:S instanceof URLSearchParams?S.toString():S instanceof FormData?Array.from(S.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(S)}function Ae(S,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:S,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ee(e.body||null)})}const h=class h{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 h.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(h.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=W.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"?h.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return h.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(h.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=W.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,h.isJsonStringContext(e,o)?h.stringifyJsonTemplateStringContent(c.value):h.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return h.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(h.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:x.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=h.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=h.resolveDataParamStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(o.value),hasUnresolvedReference:n||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(h.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(h.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(h.attrName(t,"confirm")).replace(/\\n/g,`
7
- `)),e.hasAttribute(h.attrName(t,"data"))&&(r.dataAttrName=h.attrName(t,"data")),e.hasAttribute(h.attrName(t,"form"))){const p=e.getRawAttribute(h.attrName(t,"form"));if(p){const g=document.body.querySelector(p);g!==null?r.formFragment=E.getFormFragment(R.get(g)):m.error("Haori",`Form element not found: ${p} (${h.attrName(t,"form")})`)}else r.formFragment=E.getFormFragment(e)}else t==="change"&&(r.formFragment=E.getFormFragment(e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const p=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
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 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 f=this.startsMemberAccess(i)?"member":"array";r.push(f);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=n}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let s=0;for(;s<e.length;){const n=e[s];if(/\s/.test(n)){s+=1;continue}if(n==="/"&&(e[s+1]==="/"||e[s+1]==="*"))return null;if(n==='"'||n==="'"){const o=this.readStringToken(e,s);if(o===null)return null;t.push(o.token),s=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,s));if(a){t.push({type:"operator",value:a,position:s}),s+=a.length;continue}if(/[0-9]/.test(n)){const o=this.readNumberToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(/[A-Za-z_$]/.test(n)){const o=this.readIdentifierToken(e,s);t.push(o.token),s=o.nextIndex;continue}if(i.has(n)){t.push({type:"operator",value:n,position:s}),s+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const s=e[i];if(s==="\\"){i+=2;continue}if(s===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
6
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,s])=>{r[i]=this.wrapBoundValue(s,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const s=new Proxy(r,{get:(n,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const c=Reflect.get(n,a,o);return typeof a=="symbol"?c:this.wrapBoundValue(c,t)},has:(n,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(n,a),getOwnPropertyDescriptor:(n,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(n,a)},apply:(n,a,o)=>{const c=Reflect.apply(n,a,o);return this.isIteratorLike(c)?c:this.wrapBoundValue(c,t)},construct:(n,a,o)=>this.wrapBoundValue(Reflect.construct(n,a,o),t)});return t.set(r,s),s}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:s})=>{Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:s,descriptor:n})=>{n!==void 0&&Object.defineProperty(i,s,n)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){if(!e||typeof e!="object")return!1;for(const t of Object.keys(e))if(this.FORBIDDEN_BINDING_NAMES.has(t))return!0;return!1}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const s of Object.values(e)){if(typeof s=="function"){if(r.has(s))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(s,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};I.MAX_IDENTIFIER_RECOVERY_COUNT=8,I.forbiddenBindingValueCache=new WeakMap,I.forbiddenBindingValueCacheResetScheduled=!1,I.FORBIDDEN_NAMES=["window","self","globalThis","frames","parent","top","Function","setTimeout","setInterval","requestAnimationFrame","alert","confirm","prompt","fetch","XMLHttpRequest","Reflect","constructor","__proto__","prototype","Object","document","location","navigator","localStorage","sessionStorage","IndexedDB","history"],I.STRICT_FORBIDDEN_NAMES=["eval","arguments"],I.REBINDABLE_FORBIDDEN_NAMES=new Set(["location"]),I.FORBIDDEN_BINDING_NAMES=new Set([...I.FORBIDDEN_NAMES.filter(e=>!I.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...I.STRICT_FORBIDDEN_NAMES]),I.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),I.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),I.DISALLOWED_KEYWORDS=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","finally","for","function","if","import","in","instanceof","let","new","return","switch","this","throw","try","typeof","var","void","while","with","yield"]),I.EXPRESSION_CACHE=new Map;let Y=I;class de{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)}}const oe=class oe{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}};oe.ASYNC_QUEUE=new de;let M=oe;class J{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static dialog(e){return M.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return M.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.showModal():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return M.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return J.addMessage(e,t,"error")}static addMessage(e,t,r){return M.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return M.enqueue(()=>{e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})},!0)}}const fe=["addErrorMessage","clearMessages"];function le(){const e=globalThis.window?.Haori;return fe.every(r=>typeof e?.[r]=="function")?e:J}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static getPartValues(e,t){const r=e.getAttribute("name"),i=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`);if(r){s?Array.isArray(t[String(r)])?t[String(r)].push(e.getValue()):t[String(r)]=[e.getValue()]:t[String(r)]=e.getValue(),i&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const n of e.getChildElementFragments())A.getPartValues(n,t)}else if(i){const n={};for(const a of e.getChildElementFragments())A.getPartValues(a,n);Object.keys(n).length>0&&(t[String(i)]=n),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const n=[];for(const a of e.getChildElementFragments()){const o={};A.getPartValues(a,o),Object.keys(o).length>0&&n.push(o)}n.length>0&&(t[String(s)]=n)}else for(const n of e.getChildElementFragments())A.getPartValues(n,t);return t}static setValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!0)}static syncValues(e,t,r=!1){return A.setPartValues(e,t,null,r,!1)}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,s=!0){const n=[],a=e.getAttribute("name"),o=e.getAttribute(`${l.prefix}form-object`),c=e.getAttribute(`${l.prefix}form-list`),d=e.getAttribute(`${l.prefix}form-detach`);if(a){if(!d||i){const f=t[String(a)];c&&Array.isArray(f)&&r!==null?n.push(A.applyFragmentValue(e,f[r]??null,s)):typeof f>"u"||(typeof f=="string"||typeof f=="number"||typeof f=="boolean"||f===null?n.push(A.applyFragmentValue(e,f,s)):n.push(A.applyFragmentValue(e,String(f),s)))}}else if(o){const f=t[String(o)];if(f&&typeof f=="object")for(const g of e.getChildElementFragments())n.push(A.setPartValues(g,f,null,i,s))}else if(c){const f=t[String(c)];if(Array.isArray(f)){const g=e.getChildElementFragments();for(let y=0;y<g.length;y++){const T=g[y];f.length>y?n.push(A.setPartValues(T,f[y],y,i,s)):n.push(A.setPartValues(T,{},y,i,s))}}}else for(const f of e.getChildElementFragments())n.push(A.setPartValues(f,t,null,i,s));return Promise.all(n).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.clearEachClones(e)]),await M.enqueue(()=>{const t=e.getTarget();if(t instanceof HTMLFormElement)t.reset();else{const r=t.parentElement;if(r){const i=t.nextElementSibling,s=document.createElement("form");s.appendChild(t),s.reset(),r.insertBefore(t,i)}}}),await P.evaluateAll(e)}static clearEachClones(e){const t=[],r=s=>{if(s.hasAttribute(`${l.prefix}each`))for(const n of s.getChildElementFragments()){const a=n.hasAttribute(`${l.prefix}each-before`),o=n.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(n.remove())}},i=s=>{r(s);for(const n of s.getChildElementFragments())i(n)};r(e);for(const s of e.getChildElementFragments())i(s);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())A.clearValues(t)}static clearMessages(e){return le().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const s=[],n=le(),a=n.addMessage,o=d=>typeof a=="function"?a.call(n,d,r,i):n.addErrorMessage(d,r),c=A.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 A.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&e.getAttribute("name")===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const s=e.getAttribute(`${l.prefix}form-list`),n=i.lastIndexOf("["),a=i.lastIndexOf("]");if(n!==-1&&a!==-1&&n<a){const o=i.substring(0,n);if(s===o){const c=i.substring(n+1,a),d=Number(c);if(isNaN(d))p.error("Haori",`Invalid index: ${i}`);else{const f=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));d<f.length&&r.push(...A.findFragmentByKeyParts(f[d],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,t))});return r}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)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(!L.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(!L.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 X=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 H(e);break;case Node.COMMENT_NODE:t=new ae(e);break;default:return p.warn("[Haori]","Unsupported node type:",e.nodeType),null}return t}isSkipMutationNodes(){return this.skipMutationNodes}unmount(){if(!this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return M.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return M.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),G.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};G.FRAGMENT_CACHE=new WeakMap;let w=G;const V=class V extends w{constructor(e){super(e),this.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],this.children=[],this.attributeMap=new Map,this.bindingData=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.syncValue(),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new Q(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=w.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof V)}pushChild(e){this.children.push(e),e.setParent(this)}removeChild(e){const t=this.children.indexOf(e);if(t<0){p.warn("[Haori]","Child fragment not found.",e);return}this.children.splice(t,1),e.setParent(null)}clone(){const e=new V(this.target.cloneNode(!1));return this.attributeMap.forEach((t,r)=>{e.attributeMap.set(r,t)}),this.children.forEach(t=>{const r=t.clone();e.getTarget().appendChild(r.getTarget()),e.pushChild(r)}),e.mounted=!1,e.bindingData=this.bindingData,e.derivedBindingData=this.derivedBindingData,e.clearBindingDataCache(),e.visible=!0,e.display=this.display,e.displayPriority=this.displayPriority,e.template=this.template,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.children.forEach(e=>{e instanceof V&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof V&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),s=r.type==="checkbox"&&i==="true";let n;return s?n=e===!0||e==="true":i==="false"?n=e===!1:n=i===String(e),this.value=s?n:n?e:null,r.checked===n?Promise.resolve():(this.skipChangeValue=!0,M.enqueue(()=>{r.checked=n,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else return r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?(this.value=e,this.skipChangeValue=!0,M.enqueue(()=>{r.value=e===null?"":String(e),t&&((r instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})):(p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve())}getValue(){return this.value}clearValue(){this.value=null}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else this.value=e.value;else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(this.value=e.value)}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return M.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,s=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const n=new Q(e,r);if(s){const U=this.attributeMap.get(e);if(U&&(U.isEvaluate||U.isForceEvaluation())&&!n.isEvaluate&&!n.isForceEvaluation())return this.skipMutationAttributes=!0,M.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,n);const a=this.getTarget(),o=n.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),c=n.isEvaluate||n.isRawEvaluate,d=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),f=n.isSingleExpression(),g=j.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:g,T=!n.isForceEvaluation()&&(t!==e||d||f?o.hasUnresolvedReference||y===null||y===void 0||y===!1:c&&g===""),m=n.isForceEvaluation()?r:f?y:g,b=i&&n.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),E=T||m===null||m===!1?null:String(m),v=e!==t&&a.getAttribute(e)!==r,F=E===null?a.hasAttribute(t):a.getAttribute(t)!==E,x=b&&E!==null&&a.value!==E;return!v&&!F&&!x?(b&&E!==null&&(this.value=E),Promise.resolve()):(this.skipMutationAttributes=!0,M.enqueue(()=>{v&&a.setAttribute(e,r),E===null?a.removeAttribute(t):(F&&a.setAttribute(t,E),b&&(this.value=E,x&&(a.value=E)))}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return M.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:j.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let s=t?r.nextSibling:r;for(;s!==null;){const n=w.get(s);if(n!==null){const a=this.children.indexOf(n);if(a!==-1)return{index:a,referenceNode:i}}s=s.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let s=this.parent;for(;s;)i.add(s),s=s.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const n=e.getParent()===this;let a=-1,o=-1;n&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const c=e.getParent();c!==null&&c.removeChild(e);let 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 y=this.resolveInsertionPointFromDom(t,!1);y===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(y.index,0,e),d=y.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const f=this.skipMutationNodes;return this.skipMutationNodes=!0,M.enqueue(()=>{this.target.insertBefore(e.getTarget(),d)}).finally(()=>{this.skipMutationNodes=f})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(p.warn("[Haori]","Reference child not found in children.",t),this.insertBefore(e,null)):this.insertBefore(e,this.children[i.index]||null,i.referenceNode)}return this.insertBefore(e,this.children[r+1]||null)}getPrevious(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<=0?null:t[r-1]}getNext(){const e=this.getParent();if(e===null)return null;const t=e.getChildElementFragments(),r=t.indexOf(this);return r<0||r+1>=t.length?null:t[r+1]}isVisible(){return this.visible}hide(){if(!this.visible)return Promise.resolve();this.visible=!1;const e=this.getTarget();return this.display=e.style.getPropertyValue("display"),this.displayPriority=e.style.getPropertyPriority("display"),e.style.setProperty("display","none","important"),e.setAttribute(`${l.prefix}if-false`,""),Promise.resolve()}show(){if(this.visible)return Promise.resolve();const e=this.getTarget();return this.display===null||this.display===""?e.style.removeProperty("display"):e.style.setProperty("display",this.display,this.displayPriority??""),this.display=null,this.displayPriority=null,e.removeAttribute(`${l.prefix}if-false`),this.visible=!0,Promise.resolve()}closestByAttribute(e){if(this.hasAttribute(e))return this;const t=this.getParent();return t===null?null:t.closestByAttribute(e)}};V.BOOLEAN_ATTRIBUTES=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","hidden","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]);let C=V;class H 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 H(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new j(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):M.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=j.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class ae extends w{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new ae(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,M.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const _=class _{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(_.PLACEHOLDER_REGEX)];let r=0,i=!1,s=!1;for(const n of t){n.index>r&&this.contents.push({text:e.slice(r,n.index),type:0});const a={text:n[1]??n[2],type:n[1]?2:1};i=!0,s=s||a.type===2,this.contents.push(a),r=n.index+n[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=s,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(p.error("[Haori]","Raw expressions are not allowed in multi-content expressions."),this.contents[e].type=1)}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){return!this.isEvaluate&&!this.isRawEvaluate?{results:this.contents.map(r=>r.text),hasUnresolvedReference:!1}:this.evaluateWithProfile(e,t,r=>r.type===1||r.type===2,"text")}evaluateWithProfile(e,t,r,i){const s=[],n=[];let a=0,o=!1;return this.contents.forEach(c=>{try{if(r(c)){const d=X.measure(()=>Y.evaluateDetailed(c.text,e)),f=d.value;a+=d.durationMs,n.push({expression:c.text,durationMs:d.durationMs}),o=o||f.unresolvedReference,s.push(f.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("")}}),X.record(t,n,a),{results:s,hasUnresolvedReference:o}}};_.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let j=_;const ee=class ee extends j{constructor(e,t){super(t),this.forceEvaluation=ee.FORCE_EVALUATION_ATTRIBUTES.includes(e)}isForceEvaluation(){return this.forceEvaluation}evaluate(e,t){return this.evaluateDetailed(e,t).results}evaluateDetailed(e,t){if(!this.isEvaluate&&!this.forceEvaluation)return{results:this.contents.map(i=>i.text),hasUnresolvedReference:!1};const r=this.evaluateWithProfile(e,t,i=>this.forceEvaluation&&i.type===0||i.type===1||i.type===2,"attribute");return this.forceEvaluation&&r.results.length>1?(p.error("[Haori]","each or if expressions must have a single content.",r.results),{results:[r.results[0]],hasUnresolvedReference:r.hasUnresolvedReference}):r}};ee.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let Q=ee;class R{static dispatch(e,t,r,i){const s=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(s)}static ready(e){R.dispatch(document,"ready",{version:e})}static render(e){R.dispatch(e,"render",{target:e})}static importStart(e,t){R.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){R.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){R.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const s=[],n=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...n,...a]);for(const c of o){const d=t?.[c],f=r[c];d!==f&&s.push(c)}R.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:s,reason:i})}static bindComplete(e,t=null,r="other"){R.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){R.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){R.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){R.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){R.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){R.dispatch(e,"show",{visible:!0})}static hide(e){R.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,s){R.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...s})}static fetchEnd(e,t,r,i){R.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,s){R.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:s?performance.now()-s:void 0})}}const pe=["addErrorMessage","closeDialog","confirm","dialog","openDialog","toast"],ge="__haoriHistoryState__",re="data-haori-click-lock";function ie(){const e=globalThis.window?.Haori;return pe.every(r=>typeof e?.[r]=="function")?e:J}const me=new Set(["GET","HEAD","OPTIONS"]);function be(S){return me.has(S.toUpperCase())}function ve(S,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?S.append(t,""):Array.isArray(r)?r.forEach(i=>{S.append(t,String(i))}):typeof r=="object"||typeof r=="function"?S.append(t,JSON.stringify(r)):S.append(t,String(r)))}function ye(S,e){const t=new URL(S,window.location.href),r=new URLSearchParams(t.search);return ve(r,e),t.search=r.toString(),t.toString()}function Ee(S){return S==null?null:typeof S=="string"?S:S instanceof URLSearchParams?S.toString():S instanceof FormData?Array.from(S.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(S)}function Ae(S,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[s])=>i.localeCompare(s));return JSON.stringify({url:S,method:String(e.method||"GET").toUpperCase(),headers:r,body:Ee(e.body||null)})}const h=class h{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 h.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(h.DATA_PLACEHOLDER_REGEX,(s,n,a)=>{const o=Y.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"?h.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return h.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(h.DATA_PLACEHOLDER_REGEX,(s,n,a,o)=>{const c=Y.evaluateDetailed(n??a??"",t);return r=r||c.unresolvedReference,h.isJsonStringContext(e,o)?h.stringifyJsonTemplateStringContent(c.value):h.stringifyJsonTemplateValue(c.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return h.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(h.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(s),hasUnresolvedReference:n};if(a.startsWith("{")||a.startsWith("[")){const c=h.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(c.value),hasUnresolvedReference:n||c.hasUnresolvedReference}}const o=h.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(h.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(h.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(h.attrName(t,"confirm")).replace(/\\n/g,`
7
+ `)),e.hasAttribute(h.attrName(t,"data"))&&(r.dataAttrName=h.attrName(t,"data")),e.hasAttribute(h.attrName(t,"form"))){const m=e.getRawAttribute(h.attrName(t,"form"));if(m){const b=document.body.querySelector(m);b!==null?r.formFragment=A.getFormFragment(w.get(b)):p.error("Haori",`Form element not found: ${m} (${h.attrName(t,"form")})`)}else r.formFragment=A.getFormFragment(e)}else t==="change"&&(r.formFragment=A.getFormFragment(e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const m=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
8
8
  "use strict";
9
- ${p}
10
- `)}catch(g){m.error("Haori",`Invalid before script: ${g}`)}}}const i=h.attrName(t,"fetch"),s=e.hasAttribute(i);if(s){const p=e.getAttributeEvaluation(i);p&&(r.fetchHasUnresolvedReference=p.hasUnresolvedReference,r.fetchUrl=p.hasUnresolvedReference?null:p.value)}const n={};if(t){const p=h.attrName(t,"fetch-method");if(e.hasAttribute(p)){const g=e.getAttributeEvaluation(p);g?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=g?.value}}else{const p=h.attrName(null,"method",!0);if(e.hasAttribute(p)){const g=e.getAttributeEvaluation(p);g?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=g?.value}}if(t){const p=h.attrName(t,"fetch-headers");if(e.hasAttribute(p)){const g=e.getRawAttribute(p);try{n.headers=x.parseDataBind(g)}catch(D){m.error("Haori",`Invalid fetch headers: ${D}`)}}}else{const p=h.attrName(null,"headers",!0);if(e.hasAttribute(p)){const g=e.getRawAttribute(p);try{n.headers=x.parseDataBind(g)}catch(D){m.error("Haori",`Invalid fetch headers: ${D}`)}}}if(t){const p=h.attrName(t,"fetch-content-type");if(e.hasAttribute(p)){const g=e.getAttributeEvaluation(p);g?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":g?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let g=!1;n.headers&&typeof n.headers=="object"&&(g="Content-Type"in n.headers),g||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const p=h.attrName(null,"content-type",!0);if(e.hasAttribute(p)){const g=e.getAttributeEvaluation(p);g?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":g?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let g=!1;n.headers&&typeof n.headers=="object"&&(g="Content-Type"in n.headers),g||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(n).length>0&&(r.fetchOptions=n);const a=t?h.attrName(t,"bind"):h.attrName(null,"bind",!0);if(e.hasAttribute(a)){const p=e.getRawAttribute(a);if(p){const g=document.body.querySelectorAll(p);g.length>0?(r.bindFragments=[],g.forEach(D=>{const A=R.get(D);A&&r.bindFragments.push(A)})):m.error("Haori",`Bind element not found: ${p} (${a})`)}}const o=h.attrName(t,"bind-arg"),c=h.attrName(null,"arg",!0),d=h.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(c)?r.bindArg=e.getRawAttribute(c):e.hasAttribute(d)&&(r.bindArg=e.getRawAttribute(d));const f=t?h.attrName(t,"bind-params"):h.attrName(null,"bind-params",!0);if(e.hasAttribute(f)){const p=e.getRawAttribute(f);r.bindParams=p.split("&").map(g=>g.trim())}const b=t?h.attrName(t,"bind-append"):h.attrName(null,"bind-append",!0);if(e.hasAttribute(b)){const p=e.getRawAttribute(b);r.bindAppendParams=p.split("&").map(g=>g.trim()).filter(Boolean)}const v=t?h.attrName(t,"copy-params"):null;if(v&&e.hasAttribute(v)){const p=e.getRawAttribute(v);r.copyParams=p.split("&").map(g=>g.trim()).filter(Boolean)}if(t){if(e.hasAttribute(h.attrName(t,"adjust"))){const g=e.getRawAttribute(h.attrName(t,"adjust"));if(g){const D=document.body.querySelectorAll(g);D.length>0?(r.adjustFragments=[],D.forEach(A=>{const y=R.get(A);y&&r.adjustFragments.push(y)})):m.error("Haori",`Adjust element not found: ${g} (${h.attrName(t,"adjust")})`)}if(e.hasAttribute(h.attrName(t,"adjust-value"))){const D=e.getRawAttribute(h.attrName(t,"adjust-value")),A=Number(D);isNaN(A)||(r.adjustValue=A)}}if(e.hasAttribute(h.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(h.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(h.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(h.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const g=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
9
+ ${m}
10
+ `)}catch(b){p.error("Haori",`Invalid before script: ${b}`)}}}const i=h.attrName(t,"fetch"),s=e.hasAttribute(i);if(s){const m=e.getAttributeEvaluation(i);m&&(r.fetchHasUnresolvedReference=m.hasUnresolvedReference,r.fetchUrl=m.hasUnresolvedReference?null:m.value)}const n={};if(t){const m=h.attrName(t,"fetch-method");if(e.hasAttribute(m)){const b=e.getAttributeEvaluation(m);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=b?.value}}else{const m=h.attrName(null,"method",!0);if(e.hasAttribute(m)){const b=e.getAttributeEvaluation(m);b?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:n.method=b?.value}}if(t){const m=h.attrName(t,"fetch-headers");if(e.hasAttribute(m)){const b=e.getRawAttribute(m);try{n.headers=P.parseDataBind(b)}catch(E){p.error("Haori",`Invalid fetch headers: ${E}`)}}}else{const m=h.attrName(null,"headers",!0);if(e.hasAttribute(m)){const b=e.getRawAttribute(m);try{n.headers=P.parseDataBind(b)}catch(E){p.error("Haori",`Invalid fetch headers: ${E}`)}}}if(t){const m=h.attrName(t,"fetch-content-type");if(e.hasAttribute(m)){const b=e.getAttributeEvaluation(m);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":b?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let b=!1;n.headers&&typeof n.headers=="object"&&(b="Content-Type"in n.headers),b||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const m=h.attrName(null,"content-type",!0);if(e.hasAttribute(m)){const b=e.getAttributeEvaluation(m);b?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),n.headers={...n.headers,"Content-Type":b?.value}}else if(n.method&&n.method!=="GET"&&n.method!=="HEAD"&&n.method!=="OPTIONS"){let b=!1;n.headers&&typeof n.headers=="object"&&(b="Content-Type"in n.headers),b||(n.headers={...n.headers,"Content-Type":"application/json"})}else n.method&&(n.method==="GET"||n.method==="HEAD"||n.method==="OPTIONS")&&(n.headers={...n.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(n).length>0&&(r.fetchOptions=n);const a=t?h.attrName(t,"bind"):h.attrName(null,"bind",!0);if(e.hasAttribute(a)){const m=e.getRawAttribute(a);if(m){const b=document.body.querySelectorAll(m);b.length>0?(r.bindFragments=[],b.forEach(E=>{const v=w.get(E);v&&r.bindFragments.push(v)})):p.error("Haori",`Bind element not found: ${m} (${a})`)}}const o=h.attrName(t,"bind-arg"),c=h.attrName(null,"arg",!0),d=h.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(c)?r.bindArg=e.getRawAttribute(c):e.hasAttribute(d)&&(r.bindArg=e.getRawAttribute(d));const f=t?h.attrName(t,"bind-params"):h.attrName(null,"bind-params",!0);if(e.hasAttribute(f)){const m=e.getRawAttribute(f);r.bindParams=m.split("&").map(b=>b.trim())}const g=t?h.attrName(t,"bind-append"):h.attrName(null,"bind-append",!0);if(e.hasAttribute(g)){const m=e.getRawAttribute(g);r.bindAppendParams=m.split("&").map(b=>b.trim()).filter(Boolean)}const y=t?h.attrName(t,"bind-merge"):h.attrName(null,"bind-merge",!0);e.hasAttribute(y)&&(r.bindMerge=!0);const T=t?h.attrName(t,"copy-params"):null;if(T&&e.hasAttribute(T)){const m=e.getRawAttribute(T);r.copyParams=m.split("&").map(b=>b.trim()).filter(Boolean)}if(t){if(e.hasAttribute(h.attrName(t,"adjust"))){const E=e.getRawAttribute(h.attrName(t,"adjust"));if(E){const v=document.body.querySelectorAll(E);v.length>0?(r.adjustFragments=[],v.forEach(F=>{const x=w.get(F);x&&r.adjustFragments.push(x)})):p.error("Haori",`Adjust element not found: ${E} (${h.attrName(t,"adjust")})`)}if(e.hasAttribute(h.attrName(t,"adjust-value"))){const v=e.getRawAttribute(h.attrName(t,"adjust-value")),F=Number(v);isNaN(F)||(r.adjustValue=F)}}if(e.hasAttribute(h.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(h.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(h.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(h.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const E=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
11
11
  "use strict";
12
- ${g}
13
- `)}catch(D){m.error("Haori",`Invalid after script: ${D}`)}}if(e.hasAttribute(h.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(h.attrName(t,"dialog")).replace(/\\n/g,`
14
- `)),e.hasAttribute(h.attrName(t,"toast"))){r.toastMessage=e.getAttribute(h.attrName(t,"toast"));const g=e.getRawAttribute(h.attrName(t,"toast-level")),A=["info","warning","error","success"].includes(g);r.toastLevel=A?g:null}if(e.hasAttribute(h.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(h.attrName(t,"redirect"))),e.hasAttribute(h.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(h.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(h.attrName(t,"scroll"))),e.hasAttribute(h.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(h.attrName(t,"history"))),e.hasAttribute(h.attrName(t,"history-data"))&&(r.historyDataAttrName=h.attrName(t,"history-data")),e.hasAttribute(h.attrName(t,"history-form"))){const g=e.getRawAttribute(h.attrName(t,"history-form"));if(g){const D=document.body.querySelector(g);D!==null?r.historyFormFragment=E.getFormFragment(R.get(D)):m.error("Haori",`Form element not found: ${g} (${h.attrName(t,"history-form")})`)}else r.historyFormFragment=E.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(g=>{const D=h.attrName(t,g);if(!e.hasAttribute(D))return;const A=e.getRawAttribute(D),y=[];if(A?(document.body.querySelectorAll(A).forEach(k=>{const B=R.get(k);B&&y.push(B)}),y.length===0&&m.error("Haori",`Element not found: ${A} (${D})`)):y.push(e),y.length>0)switch(g){case"reset-before":r.resetBeforeFragments=y;break;case"reset":r.resetFragments=y;break;case"refetch":r.refetchFragments=y;break;case"click":r.clickFragments=y;break;case"copy":r.copyFragments=y;break;case"open":r.openFragments=y;break;case"close":r.closeFragments=y;break}})}if(!t&&(e.hasAttribute(h.attrName(null,"data",!0))&&(r.dataAttrName=h.attrName(null,"data",!0)),e.hasAttribute(h.attrName(null,"form",!0)))){const p=e.getRawAttribute(h.attrName(null,"form",!0));if(p){const g=document.body.querySelector(p);g!==null?r.formFragment=E.getFormFragment(R.get(g)):m.error("Haori",`Form element not found: ${p} (${h.attrName(null,"fetch-form",!0)})`)}else r.formFragment=E.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){h.isElementFragment(e)?(this.options=h.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null)}static resolveAutoFetchSignature(e){return new h(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1||!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>E.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||{}},f=r.requestedMethod,b=r.effectiveMethod,v=r.transportMode==="query-get",p=r.queryString;if(v&&m.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:f,effectiveMethod:b,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:p}),this.options.targetFragment&&s){const g=performance.now(),D={runtime:l.runtime,requestedMethod:f,effectiveMethod:b,transportMode:v?"query-get":"http",...v?{queryString:p}:{}};return w.fetchStart(this.options.targetFragment.getTarget(),s,d,a?i:void 0,D),fetch(s,d).then(A=>this.handleFetchResult(A,s||void 0,g)).catch(A=>{throw s&&w.fetchError(this.options.targetFragment.getTarget(),s,A),A})}return fetch(s,d).then(g=>this.handleFetchResult(g,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,f=d.getTarget(),b=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&b.add(this.options.targetFragment),f.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const v=d.getBindingData();Object.assign(v,i),await x.setBindingData(f,v,b)}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();return h.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(re)?!1:(h.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(re,""),t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!0})}releaseExecutionLock(e){e&&(h.RUNNING_CLICK_TARGETS.delete(e.target),e.appliedDisabledAttribute&&(e.target.removeAttribute("disabled"),e.target.removeAttribute(re)))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return this.options.targetFragment&&t&&w.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&&w.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=>E.reset(a))),await this.copy();const n=[];return this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new h(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0&&this.options.clickFragments.forEach(a=>{const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}),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)):m.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)):m.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();m.error("Haori",c);return}const o=c=>{for(const[d,f]of Object.entries(c))f!=null&&(Array.isArray(f)?f.forEach(b=>a.searchParams.append(d,String(b))):typeof f=="object"?a.searchParams.set(d,JSON.stringify(f)):a.searchParams.set(d,String(f)))};i&&o(t),s&&o(r),history.pushState({[ge]:!0},"",a.toString())}catch(n){m.error("Haori",`history.pushState failed: ${n}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=E.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await ie().addErrorMessage(a,n)},i=()=>{if(!this.options.scrollOnError)return;const n=t?t.getTarget():document.body;(n.getAttribute("data-message-level")==="error"?n:n.parentElement?.getAttribute("data-message-level")==="error"?n.parentElement:n.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const n=await e.json(),a=[];if(n&&typeof n=="object"){if(typeof n.message=="string"&&a.push({message:n.message}),Array.isArray(n.messages))for(const o of n.messages)typeof o=="string"&&a.push({message:o});if(n.errors&&typeof n.errors=="object")for(const[o,c]of Object.entries(n.errors))Array.isArray(c)?a.push({key:o,message:c.join(`
12
+ ${E}
13
+ `)}catch(v){p.error("Haori",`Invalid after script: ${v}`)}}if(e.hasAttribute(h.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(h.attrName(t,"dialog")).replace(/\\n/g,`
14
+ `)),e.hasAttribute(h.attrName(t,"toast"))){r.toastMessage=e.getAttribute(h.attrName(t,"toast"));const E=e.getRawAttribute(h.attrName(t,"toast-level")),F=["info","warning","error","success"].includes(E);r.toastLevel=F?E:null}if(e.hasAttribute(h.attrName(t,"redirect"))&&(r.redirectUrl=e.getAttribute(h.attrName(t,"redirect"))),e.hasAttribute(h.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(h.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(h.attrName(t,"scroll"))),e.hasAttribute(h.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(h.attrName(t,"history"))),e.hasAttribute(h.attrName(t,"history-data"))&&(r.historyDataAttrName=h.attrName(t,"history-data")),e.hasAttribute(h.attrName(t,"history-form"))){const E=e.getRawAttribute(h.attrName(t,"history-form"));if(E){const v=document.body.querySelector(E);v!==null?r.historyFormFragment=A.getFormFragment(w.get(v)):p.error("Haori",`Form element not found: ${E} (${h.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(E=>{const v=h.attrName(t,E);if(!e.hasAttribute(v))return;const F=e.getRawAttribute(v),x=[];if(F?(document.body.querySelectorAll(F).forEach(B=>{const K=w.get(B);K&&x.push(K)}),x.length===0&&p.error("Haori",`Element not found: ${F} (${v})`)):x.push(e),x.length>0)switch(E){case"reset-before":r.resetBeforeFragments=x;break;case"reset":r.resetFragments=x;break;case"refetch":r.refetchFragments=x;break;case"click":r.clickFragments=x;break;case"copy":r.copyFragments=x;break;case"open":r.openFragments=x;break;case"close":r.closeFragments=x;break}});const b=h.attrName(t,"copy-source");if(e.hasAttribute(b)){const E=e.getRawAttribute(b);if(E){const v=document.body.querySelector(E);if(v!==null){const F=w.get(v);F?r.copySourceFragment=F:p.error("Haori",`Element is not managed by Haori: ${E} (${b})`)}else p.error("Haori",`Element not found: ${E} (${b})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(h.attrName(null,"data",!0))&&(r.dataAttrName=h.attrName(null,"data",!0)),e.hasAttribute(h.attrName(null,"form",!0)))){const m=e.getRawAttribute(h.attrName(null,"form",!0));if(m){const b=document.body.querySelector(m);b!==null?r.formFragment=A.getFormFragment(w.get(b)):p.error("Haori",`Form element not found: ${m} (${h.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}return s&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e]),r}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}constructor(e,t=null){h.isElementFragment(e)?(this.options=h.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null)}static resolveAutoFetchSignature(e){return new h(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1||!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(d=>A.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||{}},f=r.requestedMethod,g=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:"query-get",url:s,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&s){const m=performance.now(),b={runtime:l.runtime,requestedMethod:f,effectiveMethod:g,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return R.fetchStart(this.options.targetFragment.getTarget(),s,d,a?i:void 0,b),fetch(s,d).then(E=>this.handleFetchResult(E,s||void 0,m)).catch(E=>{throw s&&R.fetchError(this.options.targetFragment.getTarget(),s,E),E})}return fetch(s,d).then(m=>this.handleFetchResult(m,s||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const d=this.options.formFragment,f=d.getTarget(),g=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&g.add(this.options.targetFragment),f.setAttribute(`${l.prefix}bind`,JSON.stringify(i));const y=d.getBindingData();Object.assign(y,i),await P.setBindingData(f,y,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();return h.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(re)?!1:(h.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(re,""),t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!0})}releaseExecutionLock(e){e&&(h.RUNNING_CLICK_TARGETS.delete(e.target),e.appliedDisabledAttribute&&(e.target.removeAttribute("disabled"),e.target.removeAttribute(re)))}async handleFetchResult(e,t,r){const i=ie();if(!e.ok)return this.options.targetFragment&&t&&R.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),!1;if(this.options.targetFragment&&t&&r&&R.fetchEnd(this.options.targetFragment.getTarget(),t,e.status,r),this.options.afterCallback){const a=this.options.afterCallback(e);if(a!=null){if(a===!1||typeof a=="object"&&a.stop)return!1;typeof a=="object"&&"response"in a&&(e="response"in a?a.response:e)}}const s=[];s.push(this.bindResult(e)),s.push(this.adjust()),s.push(this.addRow()),s.push(this.removeRow()),s.push(this.movePrevRow()),s.push(this.moveNextRow()),await Promise.all(s),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const n=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{n.push(new h(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,f]of Object.entries(c))f!=null&&(Array.isArray(f)?f.forEach(g=>a.searchParams.append(d,String(g))):typeof f=="object"?a.searchParams.set(d,JSON.stringify(f)):a.searchParams.set(d,String(f)))};i&&o(t),s&&o(r),history.pushState({[ge]:!0},"",a.toString())}catch(n){p.error("Haori",`history.pushState failed: ${n}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=A.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=async n=>{const a=t?t.getTarget():document.body;await ie().addErrorMessage(a,n)},i=()=>{if(!this.options.scrollOnError)return;const n=t?t.getTarget():document.body;(n.getAttribute("data-message-level")==="error"?n:n.parentElement?.getAttribute("data-message-level")==="error"?n.parentElement:n.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const n=await e.json(),a=[];if(n&&typeof n=="object"){if(typeof n.message=="string"&&a.push({message:n.message}),Array.isArray(n.messages))for(const o of n.messages)typeof o=="string"&&a.push({message:o});if(n.errors&&typeof n.errors=="object")for(const[o,c]of Object.entries(n.errors))Array.isArray(c)?a.push({key:o,message:c.join(`
15
15
  `)}):typeof c=="string"?a.push({key:o,message:c}):c!=null&&a.push({key:o,message:String(c)});if(a.length===0)for(const[o,c]of Object.entries(n))o==="message"||o==="messages"||o==="errors"||(Array.isArray(c)?a.push({key:o,message:c.join(`
16
- `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await E.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n=s.getBindingData(),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(x.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return m.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);i.push(x.setBindingData(s.getTarget(),n))})}return Promise.all(i).then(()=>{})})}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 x.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.formFragment?E.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,E.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=h.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const b=new FormData;for(const[v,p]of Object.entries(t))p==null?b.append(v,""):p instanceof Blob?b.append(v,p):Array.isArray(p)?p.forEach(g=>b.append(v,String(g))):typeof p=="object"?b.append(v,JSON.stringify(p)):b.append(v,String(p));s.body=b}else if(/application\/x-www-form-urlencoded/i.test(f)){const b=new URLSearchParams;for(const[v,p]of Object.entries(t))p!==void 0&&(p===null?b.append(v,""):Array.isArray(p)?p.forEach(g=>b.append(v,String(g))):typeof p=="object"?b.append(v,JSON.stringify(p)):b.append(v,String(p)));s.body=b}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:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=h.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?E.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?h.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return E.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 m.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(m.error("Haori","Row fragment not found."),null)}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(x.evaluateAll(r)),t.push(E.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()}};h.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,h.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,h.RUNNING_CLICK_TARGETS=new WeakSet;let z=h;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class De{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw m.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 m.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw m.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:(m.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return m.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=R.get(e);return r instanceof M?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 M?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 M&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=z.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 z(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`,""),w.importStart(t,s),De.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return N.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),w.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(d=>{const f=R.get(d);f instanceof M?c.push(u.scan(f.getTarget())):f instanceof L&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),w.importError(t,s,a),m.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=R.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 M?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`)&&(r===!1||r===void 0||r===null||Number.isNaN(r))?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const s=R.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`),f=Se.readParams();if(d===null)a.push(u.setBindingData(e,f));else{const b=s.getRawBindingData()||{};b[String(d)]=f,a.push(u.setBindingData(e,b))}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=R.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(()=>E.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),w.bindChange(e,s,t,"manual"),n.then(()=>{})}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return m.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,s]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(s):r[i]=[r[i],s]:r[i]=s;return r}}static addNode(e,t){const r=R.get(e);if(r.isSkipMutationNodes())return;const i=R.get(t.nextSibling),s=R.get(t);s&&(r.insertBefore(s,i),s instanceof M?u.scan(s.getTarget()):s instanceof L&&u.evaluateText(s))}static removeNode(e){const t=R.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=R.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=R.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=E.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,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const b=u.createDeriveInputSignature(e,a,o);b===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==b&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(b)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const b=[];return e.getChildren().forEach(v=>{if(v instanceof M){if(u.canSkipUnchangedNestedEach(v))return;b.push(u.evaluateAll(v,t))}else v instanceof L&&b.push(u.evaluateText(v))}),Promise.all(b).then(()=>{})}).then(()=>{d&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=W.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 evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(r===!1||r===void 0||r===null||Number.isNaN(r))t.push(e.hide().then(()=>{w.hide(e.getTarget())}));else{const i=[];e.getChildren().forEach(s=>{s instanceof M?i.push(s.isMounted()?u.evaluateAll(s):u.scan(s.getTarget())):s instanceof L&&i.push(u.evaluateText(s))}),t.push(e.show().then(()=>{w.show(e.getTarget())})),t.push(Promise.all(i).then(()=>{}))}return Promise.all(t).then(()=>{})}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();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;return e.getChildren().forEach(a=>{if(!n&&a instanceof M){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)}}),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:(m.error("[Haori]","Invalid each attribute:",r),null)}static canSkipUnchangedNestedEach(e){if(!e.hasAttribute(`${l.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${l.prefix}derive`)||t?.closestByAttribute(`${l.prefix}derive-name`)||t?.closestByAttribute(`${l.prefix}if`)||t?.closestByAttribute(`${l.prefix}fetch`)||t?.closestByAttribute(`${l.prefix}import`)||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 M?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(!H.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 M).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),m.info("[Haori][derive-profile]",{reason:t,hostId:r.hostId,signatureComputeTotal:r.signatureComputeTotal,signatureComputeFromEvaluateAll:r.signatureComputeFromEvaluateAll,signatureComputeFromRefresh:r.signatureComputeFromRefresh,skipHitCount:r.skipHitCount,skipMissCount:r.skipMissCount,skipIneligibleCount:r.skipIneligibleCount}))}static hasNonEachDynamicElementState(e){const t=new Set([`${l.prefix}each`,`${l.prefix}each-key`,`${l.prefix}each-arg`,`${l.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${l.prefix}attr-`)||i.startsWith(l.prefix))return!0;const 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 M?!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 m.error("[Haori]","Template is not set for each element."),Promise.resolve();let i=e.getAttribute(`${l.prefix}each-index`);i&&(i=String(i));const s=e.getAttribute(`${l.prefix}each-key`),n=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((y,C)=>{const k=u.createListKey(y,s?String(s):null,C);o.push(k),a.set(k,{item:y,itemIndex:C})});const c=new Set(o),d=[];let f=e.getChildren().filter(y=>y instanceof M).filter(y=>!y.hasAttribute(`${l.prefix}each-before`)&&!y.hasAttribute(`${l.prefix}each-after`));const b=f.map(y=>y.getListKey());f=f.filter(y=>c.has(String(y.getListKey()))?!0:(d.push(y.remove()),!1));const v=f.map(y=>y.getListKey()),p=new Map;f.forEach(y=>{const C=y.getListKey();C!==null&&!p.has(C)&&p.set(C,y)});const g=e.getChildElementFragments().slice(),D=g.filter(y=>y.hasAttribute(`${l.prefix}each-before`)).length;let A=Promise.resolve();return o.forEach((y,C)=>{const{item:k,itemIndex:B}=a.get(y);let U;const J=p.get(y);if(J)U=J,A=A.then(()=>u.updateRowFragment(U,k,i,B,n?String(n):null,y).then(I=>{if(I)return u.evaluateAll(U)}));else{U=r.clone();const I=D+C;A=A.then(()=>u.updateRowFragment(U,k,i,B,n?String(n):null,y).then(()=>{const ce=g[I]??null;return e.insertBefore(U,ce).then(()=>{g.splice(I,0,U)}).then(()=>u.initializeFreshEachRow(U))}))}}),Promise.all(d).then(()=>A).then(()=>{const y=o.filter(I=>I!==null),C=v.filter(I=>I!==null),k=new Set(C),B=y.filter(I=>!k.has(I)),J=b.filter(I=>I!==null).filter(I=>!c.has(I));w.eachUpdate(e.getTarget(),B,J,y)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return m.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;let x=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=R.get(t);r&&new z(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate)}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=R.get(r);i&&(t==="change"&&i instanceof M&&i.syncValue(),new z(i,t).run().catch(s=>{m.error("[Haori]","Procedure execution error:",s)}))}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const T=class T{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)&&(T.isHtmlElement(e)&&T.syncElement(e),e.querySelectorAll("*").forEach(t=>{T.syncElement(t)}))}static syncElement(e){const t=T.registrations.get(e),r=R.get(e);if(!r||!T.shouldObserve(r)){t&&(t.observer.disconnect(),T.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=T.resolveRoot(r),s=T.resolveRootMargin(r),n=T.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&T.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),T.registrations.delete(e));const o=new IntersectionObserver(c=>{const d=T.registrations.get(e);d&&c.forEach(f=>{!f.isIntersecting||d.running||T.isDisabled(d.fragment)||(d.running=!0,new z(d.fragment,"intersect").runWithResult().then(b=>{b&&d.once&&(d.observer.disconnect(),T.registrations.delete(e))}).catch(b=>{m.error("[Haori]","Intersect procedure execution error:",b)}).finally(()=>{const b=T.registrations.get(e);b&&(b.running=!1)}))})},{root:i,rootMargin:s,threshold:n});o.observe(e),T.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(T.isHtmlElement(e)){const t=T.registrations.get(e);t&&(t.observer.disconnect(),T.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=T.registrations.get(t);r&&(r.observer.disconnect(),T.registrations.delete(t))})}static disconnectAll(){T.registrations.forEach(e=>{e.observer.disconnect()}),T.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!T.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 T.isHtmlElement(i)?i:(m.error("[Haori]",`Intersect root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${l.prefix}intersect-threshold`,r=e.getAttribute(t),i=typeof r=="number"?r:Number.parseFloat(String(r??0));return Number.isNaN(i)?0:Math.min(1,Math.max(0,i))}static isDisabled(e){const t=`${l.prefix}intersect-disabled`,r=e.getAttribute(t);if(r===null||r===!1)return!1;if(typeof r=="boolean")return r;const i=String(r).trim().toLowerCase();return i!==""&&i!=="false"&&i!=="0"}static sameThreshold(e,t){return e.length===1&&e[0]===t}};T.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),T.registrations=new Map;let G=T;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([x.scan(document.head),x.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&m.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&m.error("[Haori]","Failed to build body fragment:",r.reason),await N.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),G.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&&x.isAliasedAttributeReflection(s,i.attributeName))break;x.setAttribute(s,i.attributeName,s.getAttribute(i.attributeName),!0),G.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{G.cleanupTree(s),x.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(x.addNode(s.parentElement,s),G.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.changeText(i.target,i.target.textContent):m.warn("[Haori]","Unsupported character data type:",i.target);break}default:m.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){m.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const Te="0.4.13";exports.Core=x;exports.Env=l;exports.Form=E;exports.Fragment=R;exports.Haori=Y;exports.Log=m;exports.Queue=N;exports.default=Y;exports.version=Te;
16
+ `)}):typeof c=="string"&&a.push({key:o,message:c}))}if(a.length===0)return await r(`${e.status} ${e.statusText}`),i(),!1;for(const o of a)o.key&&t?await A.addErrorMessage(t,o.key,o.message):await r(o.message);return i(),!1}catch{}try{const n=await e.text();n&&n.trim().length>0?await r(n.trim()):await r(`${e.status} ${e.statusText}`)}catch{await r(`${e.status} ${e.statusText}`)}return i(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):ie().confirm(e)}bindResult(e){return!this.options.bindFragments||this.options.bindFragments.length===0?Promise.resolve():(e.headers.get("Content-Type")?.includes("application/json")?e.json():e.text()).then(r=>{if(this.options.bindParams){const s={};this.options.bindParams.forEach(n=>{r&&typeof r=="object"&&n in r&&(s[n]=r[n])}),r=s}const i=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const n=s.getBindingData(),a=this.options.bindArg;if(r&&typeof r=="object"&&!Array.isArray(r)){const o=n[a],c=o&&typeof o=="object"&&!Array.isArray(o)?o:{};n[a]=this.mergeAppendBindingData(s,r,c)}else n[a]=r;i.push(P.setBindingData(s.getTarget(),n))});else{if(typeof r=="string")return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."));this.options.bindFragments.forEach(s=>{const n=this.mergeAppendBindingData(s,r),a=this.options.bindMerge?{...s.getRawBindingData()??{},...n}:n;i.push(P.setBindingData(s.getTarget(),a))})}return Promise.all(i).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(n=>{R.bindComplete(n.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},s=r;for(const n of this.options.bindAppendParams){const a=i[n],o=s[n];Array.isArray(o)&&Array.isArray(a)&&(i[n]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const s={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),s)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?A.getValues(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?A.getValues(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;if(this.options.formFragment&&Object.assign(e,A.getValues(this.options.formFragment)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const r=h.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||r.hasUnresolvedReference,r.value&&Object.assign(e,r.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{signature:e.signature,hasUnresolvedReference:e.hasUnresolvedReference}}prepareFetchRequest(){const e=this.buildPayloadResolution(),t=e.payload,r=!!this.options.fetchHasUnresolvedReference||e.hasUnresolvedReference;if(!this.options.fetchUrl||r)return{url:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const s={...this.options.fetchOptions||{}},n=new Headers(s.headers||void 0),a=(s.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!be(a),c=o?"GET":a;if(s.method=c,c==="GET"||c==="HEAD"||c==="OPTIONS")Object.keys(t).length>0&&(i=ye(i,t));else if(Object.keys(t).length>0){const f=n.get("Content-Type")||"";if(/multipart\/form-data/i.test(f)){n.delete("Content-Type");const g=new FormData;for(const[y,T]of Object.entries(t))T==null?g.append(y,""):T instanceof Blob?g.append(y,T):Array.isArray(T)?T.forEach(m=>g.append(y,String(m))):typeof T=="object"?g.append(y,JSON.stringify(T)):g.append(y,String(T));s.body=g}else if(/application\/x-www-form-urlencoded/i.test(f)){const g=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?g.append(y,""):Array.isArray(T)?T.forEach(m=>g.append(y,String(m))):typeof T=="object"?g.append(y,JSON.stringify(T)):g.append(y,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:Ae(i,s)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=h.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?A.getValues(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?h.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return A.getValues(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(n=>{const a=n.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(n=>{n in e&&(r.has(n)||(i[n]=e[n]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let s=Number(i);isNaN(s)&&(s=0),s+=e,t.push(r.setValue(String(s)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${l.prefix}row`);return e||(p.error("Haori","Row fragment not found."),null)}addRow(){if(this.options.rowAdd!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=[],r=e.clone();return t.push(e.getParent().insertAfter(r,e)),t.push(P.evaluateAll(r)),t.push(A.reset(r)),Promise.all(t).then(()=>{})}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getParent();return t&&t.getChildElementFragments().filter(i=>!i.hasAttribute(`${l.prefix}each-before`)&&!i.hasAttribute(`${l.prefix}each-after`)).length<=1?Promise.resolve():e.remove()}movePrevRow(){if(this.options.rowMovePrev!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getPrevious();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertBefore(e,t):Promise.resolve()}moveNextRow(){if(this.options.rowMoveNext!==!0)return Promise.resolve();const e=this.getRowFragment();if(!e)return Promise.reject(new Error("Row fragment not found."));const t=e.getNext();if(!t)return Promise.resolve();const r=e.getParent();return r?r.insertAfter(e,t):Promise.resolve()}};h.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,h.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,h.RUNNING_CLICK_TARGETS=new WeakSet;let q=h;class Se{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,s)=>{e[s]=i}),e}}class Te{static async load(e,t){let r;try{r=await fetch(e,t)}catch(s){throw p.error("[Haori]","Failed to fetch import source:",e,s),new Error(`Failed to fetch: ${e}`)}if(!r.ok){const s=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,s),new Error(`Failed to load ${e}: ${s}`)}let i;try{i=await r.text()}catch(s){throw p.error("[Haori]","Failed to read response text:",e,s),new Error(`Failed to read response from: ${e}`)}try{const n=new DOMParser().parseFromString(i,"text/html");return n&&n.body?n.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(s){return p.error("[Haori]","Failed to parse imported HTML:",e,s),i}}}const u=class u{static isDeferredAttributeName(e){return u.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!u.isEvaluateAllExcludedAttributeName(e)&&u.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=w.get(e);return r instanceof C?r.hasAttribute(`${l.prefix}${u.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);u.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>u.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof C?t.push(u.evaluateAll(r)):r instanceof H&&t.push(u.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=u.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return u.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=u.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return u.REACTIVE_IMPORT_STATES.set(e,r),r}static reevaluateReactiveSpecialAttributes(e,t=new Set){if(t.has(e))return Promise.resolve();const r=[];return e.hasAttribute(`${l.prefix}fetch`)&&r.push(u.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(u.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof C&&r.push(u.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=u.getReactiveFetchState(t),i=q.resolveAutoFetchSignature(e);return r.running?((i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve()):i.hasUnresolvedReference||i.signature===null?(r.lastSignature=null,Promise.resolve()):r.lastSignature===i.signature?Promise.resolve():(r.lastSignature=i.signature,r.running=!0,new q(e,null).runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedFetch(e)}))}static executeManagedImport(e){const t=e.getTarget(),r=u.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),s=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return s!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(s===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===s)return Promise.resolve();r.lastUrl=s,r.running=!0;const n=performance.now();return t.setAttribute(`${l.prefix}importing`,""),R.importStart(t,s),Te.load(s).then(a=>{const o=new TextEncoder().encode(a).length;return M.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),R.importEnd(t,s,o,n),!document.body.hasAttribute("data-haori-ready")){const c=[];return t.childNodes.forEach(d=>{const f=w.get(d);f instanceof C?c.push(u.scan(f.getTarget())):f instanceof H&&c.push(u.evaluateText(f))}),Promise.all(c).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),R.importError(t,s,a),p.error("[Haori]","Failed to import HTML:",s,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,u.executeManagedImport(e)})}static scan(e){const t=w.get(e);return t?u.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return u.initializeElementFragment(e,!0).then(()=>{u.needsScheduledEvaluateAll(e)&&u.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return u.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():u.initializeElementAttributes(e).then(()=>{if(u.shouldSkipChildInitialization(e,t)){u.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof C?r.push(u.initializeElementFragment(i,t)):i instanceof H&&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`),f=Se.readParams();if(d===null)a.push(u.setBindingData(e,f));else{const g=s.getRawBindingData()||{};g[String(d)]=f,a.push(u.setBindingData(e,g))}break}}return r===null?a.push(s.removeAttribute(t)):a.push(s.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return s.setDeriveInputSignature(c),o.then(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(()=>A.syncValues(i,o))}return n=n.then(()=>u.evaluateAll(i,r)),n=n.then(()=>u.reevaluateReactiveSpecialAttributes(i,r)),R.bindChange(e,s,t,"manual"),n.then(()=>{})}static 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 H&&u.evaluateText(s))}static removeNode(e){const t=w.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=w.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=w.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const s=u.getFormFragment(r);if(s){const n=A.getValues(s),a=s.getAttribute(`${l.prefix}form-arg`);let o;a?(o=s.getRawBindingData(),o||(o={}),o[String(a)]=n):o=n,i.push(u.setBindingData(s.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?u.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=u.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),s=e.hasAttribute(`${l.prefix}if`),n=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let c=!1,d=!1,f=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=u.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>u.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return s&&(r=r.then(()=>u.evaluateIf(e))),n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>u.evaluateEach(e))):s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!u.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),u.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}f=u.createDescendantBindingSignature(e,"evaluateAll"),d=!0,c=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===f,u.logDerivedSubtreeProfileSnapshot(e,c?"skip-hit":"skip-miss")})),r.then(()=>{if(c)return;const g=[];return e.getChildren().forEach(y=>{if(y instanceof C){if(u.canSkipUnchangedNestedEach(y))return;g.push(u.evaluateAll(y,t))}else y instanceof H&&g.push(u.evaluateText(y))}),Promise.all(g).then(()=>{})}).then(()=>{d&&f!==null&&e.setDeriveSubtreeSignature(f)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),s=typeof r=="string"?r.trim():"";if(!t||s==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const n=Y.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 evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(u.isHiddenIfCondition(r))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 H&&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},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,Promise.resolve()):(t.running=!0,u.performEachUpdate(e).catch(r=>{throw r}).finally(()=>{t.running=!1,t.rerunRequested&&(t.rerunRequested=!1,u.evaluateEach(e))}))}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;return 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)}}),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(!L.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 H&&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 H?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((v,F)=>{const x=u.createListKey(v,s?String(s):null,F);o.push(x),a.set(x,{item:v,itemIndex:F})});const c=new Set(o),d=[];let f=e.getChildren().filter(v=>v instanceof C).filter(v=>!v.hasAttribute(`${l.prefix}each-before`)&&!v.hasAttribute(`${l.prefix}each-after`));const g=f.map(v=>v.getListKey());f=f.filter(v=>c.has(String(v.getListKey()))?!0:(d.push(v.remove()),!1));const y=f.map(v=>v.getListKey()),T=new Map;f.forEach(v=>{const F=v.getListKey();F!==null&&!T.has(F)&&T.set(F,v)});const m=e.getChildElementFragments().slice(),b=m.filter(v=>v.hasAttribute(`${l.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((v,F)=>{const{item:x,itemIndex:U}=a.get(v);let B;const K=T.get(v);if(K)B=K,E=E.then(()=>u.updateRowFragment(B,x,i,U,n?String(n):null,v).then(k=>{if(k)return u.evaluateAll(B)}));else{B=r.clone();const k=b+F;E=E.then(()=>u.updateRowFragment(B,x,i,U,n?String(n):null,v).then(()=>{const ce=m[k]??null;return e.insertBefore(B,ce).then(()=>{m.splice(k,0,B)}).then(()=>u.initializeFreshEachRow(B))}))}}),Promise.all(d).then(()=>E).then(()=>{const v=o.filter(k=>k!==null),F=y.filter(k=>k!==null),x=new Set(F),U=v.filter(k=>!x.has(k)),K=g.filter(k=>k!==null).filter(k=>!c.has(k));R.eachUpdate(e.getTarget(),U,K,v)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const s=e[t];s==null?i=`__index_${r}`:typeof s=="object"?i=JSON.stringify(s):i=String(s)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,s,n){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),s&&(a={[s]:a});else if(s)a={[s]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,c=u.createBindingSignature({listKey:n,bindingData:o});return e.getListKey()===n&&e.getRenderSignature()===c?Promise.resolve(!1):(e.setListKey(n),e.setRenderSignature(c),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,n).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&u.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${l.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(s=>u.createBindingSignature(s,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const s=e;return`{${Object.keys(s).sort().map(n=>`${JSON.stringify(n)}:${u.createBindingSignature(s[n],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{u.evaluateAll(e)},100)}};u.ATTRIBUTE_ALIAS_SUFFIX="attr-",u.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],u.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],u.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],u.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,u.REACTIVE_FETCH_STATES=new WeakMap,u.REACTIVE_IMPORT_STATES=new WeakMap,u.DERIVE_SUBTREE_PROFILES=new WeakMap,u.EACH_UPDATE_STATES=new WeakMap;let P=u;const te=class te{constructor(e=document){this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{const t=document.documentElement,r=w.get(t);r&&new q(r,"load").run()},this.onPopstate=t=>{const r=t.state;!r||r[te.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}start(){this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate)}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate)}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(!r)return;const i=w.get(r);i&&(t==="change"&&i instanceof C&&i.syncValue(),new q(i,t).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)}))}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){let t=e;for(;t;){if(t.getAttributeNames().some(r=>r.startsWith("data-click-")))return t;t=t.parentElement}return null}};te.HISTORY_STATE_KEY="__haoriHistoryState__";let ne=te;const D=class D{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(D.isHtmlElement(e)&&D.syncElement(e),e.querySelectorAll("*").forEach(t=>{D.syncElement(t)}))}static syncElement(e){const t=D.registrations.get(e),r=w.get(e);if(!r||!D.shouldObserve(r)){t&&(t.observer.disconnect(),D.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=D.resolveRoot(r),s=D.resolveRootMargin(r),n=D.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===s&&D.sameThreshold(t.observer.thresholds,n)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(c=>{const d=D.registrations.get(e);d&&c.forEach(f=>{!f.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 W=D;const O=class O{static disconnectMutationObservers(){O._mutationObservers.forEach(e=>{e.disconnect()}),O._mutationObservers.length=0}static async init(){if(O._initialized)return;O._initialized=!0,O.disconnectMutationObservers();const e=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[t,r]=e;t.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",t.reason),r.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",r.reason),await M.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),new ne().start(),W.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),W.syncElement(s);break}case"childList":{Array.from(i.removedNodes).forEach(s=>{W.cleanupTree(s),P.removeNode(s)}),Array.from(i.addedNodes).forEach(s=>{s.parentElement instanceof Element&&(P.addNode(s.parentElement,s),W.syncTree(s))});break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?P.changeText(i.target,i.target.textContent):p.warn("[Haori]","Unsupported character data type:",i.target);break}default:p.warn("[Haori]","Unknown mutation type:",i.type);continue}}catch(s){p.error("[Haori]","Error processing mutation:",s)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[];let Z=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Z.init):Z.init();const De="0.8.0";exports.Core=P;exports.Env=l;exports.Form=A;exports.Fragment=w;exports.Haori=J;exports.Log=p;exports.Queue=M;exports.default=J;exports.version=De;
17
17
  //# sourceMappingURL=haori.cjs.js.map