haori 0.26.2 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +3 -1
- package/README.md +3 -1
- package/dist/haori.cjs.js +22 -20
- package/dist/haori.es.js +3417 -1637
- package/dist/haori.iife.js +22 -20
- package/dist/index.d.ts +368 -3
- package/package.json +1 -1
package/dist/haori.cjs.js
CHANGED
|
@@ -1,26 +1,28 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
2
|
-
`)}static detectForbiddenIdentifiers(e){
|
|
3
|
-
${s};
|
|
4
|
-
|
|
5
|
-
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,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const l=Reflect.get(s,a,o);return typeof a=="symbol"?l:this.wrapBoundValue(l,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const l=Reflect.apply(s,a,o);return this.isIteratorLike(l)?l:this.wrapBoundValue(l,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};$.MAX_IDENTIFIER_RECOVERY_COUNT=8,$.BUILTIN_NAMESPACE="haori",$.BUILTIN_HELPERS={...Xe},$.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,$.forbiddenBindingValueCache=new WeakMap,$.forbiddenBindingValueCacheResetScheduled=!1,$.loggedForbiddenKeySignatures=new Set,$.loggedForbiddenKeyResetScheduled=!1,$.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"],$.STRICT_FORBIDDEN_NAMES=["eval","arguments"],$.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),$.FORBIDDEN_BINDING_NAMES=new Set([...$.FORBIDDEN_NAMES.filter(e=>!$.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...$.STRICT_FORBIDDEN_NAMES]),$.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),$.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),$.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"]),$.EXPRESSION_CACHE=new Map;let Y=$;class Ae{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Ae.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const we=class we{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};we.ASYNC_QUEUE=new Ae;let k=we;const P=class P{static reset(){P.ELEMENT_STORES.clear(),P.ensureGlobalAccess()}static snapshot(){return P.ensureGlobalAccess(),[...P.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:P.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:P.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!U.isEnabled()||!e||t.length===0)return;P.ensureGlobalAccess();const i=P.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=P.getOrCreateCounter(i.attributes,e.rawName,e.template);P.updateCounter(s,t,r);return}const n=P.getOrCreateCounter(i.texts,String(e.childIndex),e.template);P.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!U.isEnabled())return;const e=globalThis;e[P.GLOBAL_KEY]===void 0&&(e[P.GLOBAL_KEY]={reset:()=>P.reset(),snapshot:()=>P.snapshot()})}static getOrCreateElementStore(e){const t=P.createElementId(e),r=P.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return P.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=P.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=P.now();return{value:e(),durationMs:P.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${u.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};P.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",P.ELEMENT_STORES=new Map;let oe=P;const Z=class Z{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,Z.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(Z.FRAGMENT_CACHE.has(e))return Z.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new M(e);break;case Node.TEXT_NODE:t=new j(e);break;case Node.COMMENT_NODE:t=new Se(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 k.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 k.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 k.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),Z.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};Z.FRAGMENT_CACHE=new WeakMap;let S=Z;const q=class q extends S{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.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.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.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${u.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new le(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=S.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof q)}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 q(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(`${u.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${u.prefix}if-false`)),this.children.forEach(e=>{e instanceof q&&e.normalizeClonedVisibilityState()})}remove(e=!0){const t=[];return this.children.forEach(r=>{t.push(r.remove(!1))}),this.children.length=0,this.attributeMap.clear(),this.bindingData=null,this.bindingDataCache=null,this.derivedBindingData=null,this.descendantBindingDataCache=null,this.template&&(t.push(this.template.remove(!1)),this.template=null),this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,t.push(super.remove(e)),Promise.all(t).then(()=>{})}getTarget(){return this.target}getBindingData(){return this.bindingDataCache?this.bindingDataCache:(this.bindingDataCache={},this.parent&&Object.assign(this.bindingDataCache,this.parent.getDescendantBindingData()),this.bindingData&&Object.assign(this.bindingDataCache,this.bindingData),this.bindingDataCache)}getDescendantBindingData(){return this.descendantBindingDataCache?this.descendantBindingDataCache:(this.descendantBindingDataCache={...this.getBindingData()},this.derivedBindingData&&Object.assign(this.descendantBindingDataCache,this.derivedBindingData),this.descendantBindingDataCache)}getRawBindingData(){return this.bindingData}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof q&&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==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():k.enqueue(()=>{r.value=""})):(p.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,k.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,k.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,k.enqueue(()=>{r.value=i===null?"":String(i),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})}else return p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=S.get(t);r instanceof q&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!1,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return k.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new le(e,r);if(n){const me=this.attributeMap.get(e);if(me&&(me.isEvaluate||me.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,k.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),l=s.isEvaluate||s.isRawEvaluate,h=e===t&&q.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),c=s.isSingleExpression(),m=J.joinEvaluateResults(o.results),y=o.results.length===1?o.results[0]:m,T=!s.isForceEvaluation()&&(t!==e||h||c?o.hasUnresolvedReference||y===null||y===void 0||y===!1:l&&m===""),I=s.isForceEvaluation()?r:c?y:m,H=i&&s.isEvaluate&&t==="value"&&(a instanceof HTMLInputElement&&this.INPUT_EVENT_TYPES.includes(a.type)||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement),E=a.getRootNode(),b=H&&a===E.activeElement,v=T||I===null||I===!1?null:String(I),R=e!==t&&a.getAttribute(e)!==r,C=v===null?a.hasAttribute(t):a.getAttribute(t)!==v,F=H&&!b&&v!==null&&a.value!==v,L=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),B=t==="selected"&&a instanceof HTMLOptionElement,z=E.activeElement,ge=z!==null&&(L&&a===z||B&&a.closest("select")===z),re=v!==null,pe=L&&!ge&&a.checked!==re,ie=B&&!ge&&a.selected!==re;return!R&&!C&&!F&&!pe&&!ie?(H&&!b&&v!==null&&(this.value=this.normalizeValueForElement(a,v)),(L||B)&&!ge&&this.syncCheckableValueFromDom(B),Promise.resolve()):(this.skipMutationAttributes=!0,k.enqueue(()=>{R&&a.setAttribute(e,r),v===null?a.removeAttribute(t):(C&&(a.setAttribute(t,v),t===`${u.prefix}bind`&&this.recordSelfWrittenBind(v)),H&&!b&&(this.value=this.normalizeValueForElement(a,v),F&&(a.value=v))),pe&&(a.checked=re),ie&&(a.selected=re),(pe||ie)&&this.syncCheckableValueFromDom(ie)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return k.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 n=t?r.nextSibling:r;for(;n!==null;){const s=S.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const l=e.getParent();l!==null&&l.removeChild(e);let h=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let m;if(s?a!==-1&&a<o?m=o-1:m=o:m=this.children.indexOf(t),m===-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),h=y.referenceNode)}else this.children.splice(m,0,e)}e.setParent(this),e.setMounted(this.mounted);const c=this.skipMutationNodes;return this.skipMutationNodes=!0,k.enqueue(()=>{this.target.insertBefore(e.getTarget(),h)}).finally(()=>{this.skipMutationNodes=c})}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(`${u.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(`${u.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)}};q.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=q;class j extends S{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new J(this.text)}clone(){const e=new j(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")):k.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 Se extends S{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Se(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,k.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const ce=class ce{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(ce.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(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 n=[],s=[];let a=0,o=!1;return this.contents.forEach(l=>{try{if(r(l)){const h=oe.measure(()=>Y.evaluateDetailed(l.text,e)),c=h.value;a+=h.durationMs,s.push({expression:l.text,durationMs:h.durationMs}),o=o||c.unresolvedReference,n.push(c.value)}else n.push(l.text)}catch(h){p.error("[Haori]",`Error evaluating ${i} expression: ${l.text}`,h),s.push({expression:l.text,durationMs:0}),n.push("")}}),oe.record(t,s,a),{results:n,hasUnresolvedReference:o}}};ce.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let J=ce;const he=class he extends J{constructor(e,t){super(t),this.forceEvaluation=he.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}};he.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let le=he;class W{static get runtime(){return u.runtime}static setRuntime(e){u.setRuntime(e)}static waitForRenders(){return k.waitForIdle()}static dialog(e){return k.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 k.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return k.enqueue(()=>{e instanceof HTMLDialogElement?(W.clearMessagesSync(e),e.showModal()):p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return k.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return W.addMessage(e,t,"error")}static addMessage(e,t,r){return k.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 k.enqueue(()=>{W.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return de(e,t,r)}static now(e,t){return xe(e,t)}static today(e,t,r){return ke(e,t,r)}static number(e,t){return Pe(e,t)}static range(e,t,r){return Ie(e,t,r)}static pages(e,t,r){return Ce(e,t,r)}static monthAdd(e,t){return fe(e,t)}static monthRange(e,t){return Be(e,t)}static pageSummary(e,t){return $e(e,t)}static findBy(e,t,r){return Oe(e,t,r)}static sum(e,t){return He(e,t)}static distinct(e,t){return Ue(e,t)}static groupBy(e,t){return Ve(e,t)}}const Qe=["addErrorMessage","clearMessages"];function Re(){const e=globalThis.window?.Haori;return Qe.every(r=>typeof e?.[r]=="function")?e:W}class A{static getValues(e){const t={};return A.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(A.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(A.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getPartValues(e,t){if(e.getTarget().hasAttribute(`${u.prefix}if-false`))return t;const r=e.getAttribute("name"),i=e.getAttribute(`${u.prefix}form-object`),n=e.getAttribute(`${u.prefix}form-list`);if(r){if(n){const s=A.resolveCollectedValue(e),a=A.isFileInput(e)&&Array.isArray(s)?s:[s];Array.isArray(t[String(r)])?t[String(r)].push(...a):t[String(r)]=a}else if(A.isGroupedCheckable(e)){const s=e.getTarget(),o=(s instanceof HTMLInputElement?s.checked:!0)?e.getValue():null,l=String(r);o===null?l in t||(t[l]=null):t[l]===null||t[l]===void 0?t[l]=o:Array.isArray(t[l])?t[l].push(o):t[l]=[t[l],o]}else t[String(r)]=A.resolveCollectedValue(e);i&&p.warn("Haori",`Element cannot have both ${u.prefix}form-object and name attributes.`);for(const s of e.getChildElementFragments())A.getPartValues(s,t)}else if(i){const s={};for(const a of e.getChildElementFragments())A.getPartValues(a,s);Object.keys(s).length>0&&(t[String(i)]=s),n&&p.warn("Haori",`Element cannot have both ${u.prefix}form-list and ${u.prefix}form-object attributes.`)}else if(n){const s=[];for(const a of e.getChildElementFragments()){const o={};A.getPartValues(a,o),Object.keys(o).length>0&&s.push(o)}s.length>0&&(t[String(n)]=s)}else for(const s of e.getChildElementFragments())A.getPartValues(s,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 isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=null,i=!1,n=!0){const s=[],a=e.getAttribute("name"),o=e.getAttribute(`${u.prefix}form-object`),l=e.getAttribute(`${u.prefix}form-list`),h=e.getAttribute(`${u.prefix}form-detach`);if(a){if(!h||i){const c=t[String(a)];if(A.isFileInput(e))return(c===null||c==="")&&s.push(A.applyFragmentValue(e,null,n)),Promise.all(s).then(()=>{});l&&Array.isArray(c)&&r!==null?s.push(A.applyFragmentValue(e,c[r]??null,n)):typeof c>"u"||(Array.isArray(c)&&A.isGroupedCheckable(e)||Array.isArray(c)&&A.isMultipleSelect(e)||typeof c=="string"||typeof c=="number"||typeof c=="boolean"||c===null?s.push(A.applyFragmentValue(e,c,n)):s.push(A.applyFragmentValue(e,String(c),n)))}}else if(o){const c=t[String(o)];if(c&&typeof c=="object")for(const m of e.getChildElementFragments())s.push(A.setPartValues(m,c,null,i,n))}else if(l){const c=t[String(l)];if(Array.isArray(c)){const m=e.getChildElementFragments();for(let y=0;y<m.length;y++){const T=m[y];c.length>y?s.push(A.setPartValues(T,c[y],y,i,n)):s.push(A.setPartValues(T,{},y,i,n))}}}else for(const c of e.getChildElementFragments())s.push(A.setPartValues(c,t,null,i,n));return Promise.all(s).then(()=>{})}static async reset(e){A.clearValues(e),await Promise.all([A.clearMessages(e),A.clearEachClones(e)]),await k.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const t=A.collectBindingTargetForms(e);for(const r of t){const i=A.getInitialBindingData(r);i&&await x.setBindingData(r.getTarget(),i)}A.syncValuesFromDom(e);for(const r of t){const i=A.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=A.getValues(r),s=r.getAttribute(`${u.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await x.setBindingData(r.getTarget(),a)}await x.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:x.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())A.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=S.get(n);s instanceof M&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${u.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${u.prefix}each-before`),o=s.hasAttribute(`${u.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())A.clearValues(t)}static clearMessages(e){return Re().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return A.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=Re(),a=s.addMessage,o=h=>typeof a=="function"?a.call(s,h,r,i):s.addErrorMessage(h,r),l=A.findFragmentsByKey(e,t);return l.forEach(h=>{n.push(o(h.getTarget()))}),l.length===0&&n.push(o(e.getTarget())),Promise.all(n).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(`${u.prefix}form-object`))t.length>1&&e.getAttribute(`${u.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...A.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${u.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${u.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const l=i.substring(s+1,a),h=Number(l);if(isNaN(h))p.error("Haori",`Invalid index: ${i}`);else{const c=e.getChildElementFragments().filter(m=>m.hasAttribute(`${u.prefix}row`));h<c.length&&r.push(...A.findFragmentByKeyParts(c[h],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...A.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${u.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}}class N{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){N.dispatch(document,"ready",{version:e})}static importStart(e,t){N.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){N.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){N.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const l of o){const h=t?.[l],c=r[l];h!==c&&n.push(l)}N.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){N.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){N.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){N.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){N.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){N.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){N.dispatch(e,"show",{visible:!0})}static hide(e){N.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){N.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){N.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){N.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}}const Ze={401:"unauthorized-redirect",403:"forbidden-redirect"};function _e(f,e){return f.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function et(f,e){const t=f.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=S.get(f),i=r instanceof M?r.getBindingData():{},n=_e(t,i);return n===""?null:n}function tt(f,e,t){const r=f.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,l=o.includes("?")?"&":"?";return`${o}${l}${n}${a}`}function je(f){const e=Ze[f];if(e===void 0||typeof document>"u")return!1;const t=`${u.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=et(i,t);if(n===null)continue;const s=tt(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class qe{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const rt=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],it="__haoriHistoryState__",be="data-haori-click-lock";function se(){const e=globalThis.window?.Haori;return rt.every(r=>typeof e?.[r]=="function")?e:W}const nt=new Set(["GET","HEAD","OPTIONS"]);function st(f){return nt.has(f.toUpperCase())}function at(f,e){for(const[t,r]of Object.entries(e))r!==void 0&&(r===null?f.append(t,""):Array.isArray(r)?r.forEach(i=>{f.append(t,String(i))}):typeof r=="object"||typeof r=="function"?f.append(t,JSON.stringify(r)):f.append(t,String(r)))}function ot(f,e){const t=new URL(f,window.location.href),r=new URLSearchParams(t.search);return at(r,e),t.search=r.toString(),t.toString()}function lt(f){return f==null?null:typeof f=="string"?f:f instanceof URLSearchParams?f.toString():f instanceof FormData?Array.from(f.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(f)}function te(f){return f instanceof Blob?!0:Array.isArray(f)?f.some(te):f!==null&&typeof f=="object"?Object.values(f).some(te):!1}function ut(f){return Object.values(f).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&te(t)):te(e))}function ae(f){return ve(A.getValues(f))}function ve(f){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(f))t[r]=e(i);return t}function ct(f,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:f,method:String(e.method||"GET").toUpperCase(),headers:r,body:lt(e.body||null)})}const g=class g{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,g.isElementFragment(e)?(this.options=g.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${u.prefix}${e}-${t}`:r?`${u.prefix}fetch-${t}`:`${u.prefix}${t}`}static resolveDataParamString(e,t){return g.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=Y.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?g.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return g.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(g.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const l=Y.evaluateDetailed(s??a??"",t);return r=r||l.unresolvedReference,g.isJsonStringContext(e,o)?g.stringifyJsonTemplateStringContent(l.value):g.stringifyJsonTemplateValue(l.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return g.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(g.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:x.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const l=g.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(l.value),hasUnresolvedReference:s||l.hasUnresolvedReference}}const o=g.resolveDataParamStringDetailed(r,e.getBindingData());return{value:x.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(g.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(g.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(g.attrName(t,"confirm")).replace(/\\n/g,`
|
|
7
|
-
`)),e.hasAttribute(g.attrName(t,"data"))&&(r.dataAttrName=g.attrName(t,"data")),e.hasAttribute(g.attrName(t,"form"))){const b=e.getRawAttribute(g.attrName(t,"form"));if(b){const v=document.body.querySelector(b);v!==null?r.formFragment=A.getFormFragment(S.get(v)):p.error("Haori",`Form element not found: ${b} (${g.attrName(t,"form")})`)}else r.formFragment=A.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=A.getFormFragment(e),r.formFragment===null&&g.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${u.prefix}${t}-before-run`)){const b=e.getRawAttribute(`${u.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const ee=class ee{static isEnabled(){return ee.devMode}static enable(){ee.devMode=!0}static disable(){ee.devMode=!1}static set(e){ee.devMode=e}};ee.devMode=!1;let W=ee;const Te="embedded";function Be(d){return d==="embedded"||d==="demo"}function tt(d){return d===null?null:Be(d)?d:Te}const j=class j{static get strictBind(){return j._strictBind}static setStrictBind(e){j._strictBind=e}static get runtime(){return j._runtime}static setRuntime(e){j._runtime=Be(e)?e:Te}static detect(){try{const e=document.currentScript||document.querySelector('script[src*="haori"]');if(e instanceof HTMLScriptElement){const r=e.getAttribute("data-prefix")||j._prefix;j._prefix=r.endsWith("-")?r:r+"-";const i=tt(e.getAttribute("data-runtime"));i!==null&&(j._runtime=i),j._strictBind=e.hasAttribute(`${j._prefix}strict-bind`)}if(e instanceof HTMLScriptElement&&e.hasAttribute(`${j._prefix}dev`)){W.set(!0);return}const t=window.location.hostname;if(t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t.endsWith(".local")){W.set(!0);return}W.set(!1)}catch{}}static get prefix(){return j._prefix}};j._prefix="data-",j._runtime=Te,j._strictBind=!1;let l=j;typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",l.detect):l.detect());class p{static info(e,...t){W.isEnabled()&&console.log&&console.log(e,...t)}static warn(e,...t){W.isEnabled()&&console.warn&&console.warn(e,...t)}static error(e,...t){console.error(e,...t)}}const $e="yyyy/MM/dd HH:mm",rt="en-US",xe=1e4;function J(d){return String(d).padStart(2,"0")}function Oe(d,e,t,r,i,n){return{yyyy:String(d).padStart(4,"0"),yy:J(d%100),MM:J(e),M:String(e),dd:J(t),d:String(t),HH:J(r),H:String(r),mm:J(i),ss:J(n)}}function Le(d,e){let t;try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(d)}catch{return null}const r={};for(const f of t)f.type!=="literal"&&(r[f.type]=f.value);const i=Number(r.year),n=Number(r.month),s=Number(r.day),a=Number(r.hour),o=Number(r.minute),u=Number(r.second);return!Number.isFinite(i)||!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(u)?null:Oe(i,n,s,a,o,u)}function ye(d,e=$e,t){if(d==null||d==="")return"";const r=d instanceof Date?d:new Date(d);if(Number.isNaN(r.getTime()))return"";let i;if(typeof t=="string"&&t.trim()!==""){if(i=Le(r,t.trim()),i===null)return""}else i=Oe(r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds());const n=i;return e.replace(/'([^']*)'|yyyy|yy|MM|dd|HH|mm|ss|M|d|H/g,(s,a)=>a!==void 0?a===""?"'":a:n[s])}const it="yyyy-MM-dd";function He(d=$e,e){return ye(new Date,d,e)}function Ue(d=0,e=it,t){const r=Number.isFinite(d)?Math.trunc(d):0,i=typeof t=="string"&&t.trim()!==""?t.trim():"";let n,s,a;if(i!==""){const u=Le(new Date,i);if(u===null)return"";n=Number(u.yyyy),s=Number(u.MM),a=Number(u.dd)}else{const u=new Date;n=u.getFullYear(),s=u.getMonth()+1,a=u.getDate()}const o=new Date(Date.UTC(n,s-1,a+r));return ye(o,e,"UTC")}function Ve(d,e){if(d==null)return"";let t;if(typeof d=="number")t=d;else{const i=String(d).trim();if(i==="")return"";t=Number(i)}if(!Number.isFinite(t))return"";const r={};if(e!==void 0&&Number.isFinite(e)){const i=Math.max(0,Math.trunc(e));r.minimumFractionDigits=i,r.maximumFractionDigits=i}return new Intl.NumberFormat(rt,r).format(t)}function je(d,e,t){let r,i,n;if(e===void 0?(r=0,i=d,n=1):(r=d,i=e,n=t===void 0?1:t),!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(n)||n===0)return[];r=Math.trunc(r),i=Math.trunc(i),n=Math.trunc(n);const s=[];if(n>0)for(let a=r;a<i&&s.length<xe;a+=n)s.push(a);else for(let a=r;a>i&&s.length<xe;a+=n)s.push(a);return s}function qe(d,e,t={}){const r=Math.trunc(Number(d));if(!Number.isFinite(r)||r<=0)return[];const i=Math.min(Math.max(Math.trunc(Number(e))||0,0),r-1),n=Math.max(0,Math.trunc(t.window??2)),s=Math.max(0,Math.trunc(t.boundary??1)),a=new Set;for(let h=0;h<s&&h<r;h+=1)a.add(h);for(let h=Math.max(0,r-s);h<r;h+=1)a.add(h);for(let h=Math.max(0,i-n);h<=Math.min(r-1,i+n);h+=1)a.add(h);const o=Array.from(a).sort((h,g)=>h-g),u=[];let f=null;for(const h of o){if(f!==null&&h-f>1)if(h-f===2){const g=f+1;u.push({page:g,label:g+1,active:g===i,ellipsis:!1})}else u.push({page:null,label:"…",active:!1,ellipsis:!0});u.push({page:h,label:h+1,active:h===i,ellipsis:!1}),f=h}return u}const nt=/^(\d{4})-(\d{1,2})$/,st=1200;function ue(d,e){const t=Number(d);return Number.isFinite(t)?Math.trunc(t):e}function ve(d,e){if(typeof d!="string")return"";const t=nt.exec(d.trim());if(!t)return"";const r=Number(t[1]),i=Number(t[2]);if(i<1||i>12)return"";const n=Number.isFinite(e)?Math.trunc(e):0,s=r*12+(i-1)+n,a=Math.floor(s/12),o=s-a*12+1;return`${String(a).padStart(4,"0")}-${J(o)}`}function at(d){if(typeof d=="string"&&d.trim()!=="")return ve(d,0);const e=new Date;return`${String(e.getFullYear()).padStart(4,"0")}-${J(e.getMonth()+1)}`}function We(d,e){const t=Math.trunc(Number(d));if(!Number.isFinite(t)||t<0)return[];const r=at(e);if(r==="")return[];const i=Math.min(t,st),n=[];for(let s=0;s<=i;s+=1){const a=ve(r,-s);n.push({targetMonth:a,label:a.replace(/-/g,"/")})}return n}function ze(d,e){const t={start:0,end:0,total:0,empty:!0};if(!d||typeof d!="object")return t;const r=d,i=ue(r.totalElements??r.totalCount,0);if(i<=0)return t;const n=Math.max(0,ue(r.number,0)),s=Math.max(0,ue(r.size,0)),a=n*s,o=Math.min(a+1,i);let u;if(e!==void 0&&Number.isFinite(e))u=Math.max(0,Math.trunc(e));else{const h=ue(r.numberOfElements,NaN);u=Number.isFinite(h)?h:Math.min(s,i-a)}const f=Math.min(a+u,i);return{start:o,end:Math.max(f,o),total:i,empty:!1}}function Ke(d,e,t){if(!Array.isArray(d)||d.length===0)return null;const r=String(t),i=d.find(n=>n!=null&&String(n[e])===r);return i===void 0?null:i}function Ge(d,e){if(!Array.isArray(d))return 0;let t=0;for(const r of d){const i=e==null?r:r?.[e];if(i==null||i==="")continue;const n=typeof i=="number"?i:Number(i);Number.isNaN(n)||(t+=n)}return t}function Ye(d,e){return e==null||d==null?String(d):String(d[e])}function Xe(d,e){if(!Array.isArray(d))return[];const t=new Set,r=[];for(const i of d){const n=Ye(i,e);t.has(n)||(t.add(n),r.push(i))}return r}function Je(d,e){if(!Array.isArray(d))return[];const t=new Map,r=[];for(const i of d){const n=Ye(i,e),s=t.get(n);if(s===void 0){const a=i==null?i:i[e];t.set(n,r.length),r.push({key:a,items:[i]})}else r[s].items.push(i)}return r}const ot=Object.freeze({date:ye,now:He,today:Ue,number:Ve,pages:qe,range:je,monthAdd:ve,monthRange:We,pageSummary:ze,findBy:Ke,sum:Ge,distinct:Xe,groupBy:Je});class Ne{constructor(){this.MAX_BUDGET=8,this.queue=[],this.processing=!1}enqueue(e,t=!1){let r,i;const n=new Promise((a,o)=>{r=a,i=o}),s={task:e,timestamp:performance.now(),promise:n,resolve:r,reject:i};return t?this.queue.unshift(s):this.queue.push(s),this.scheduleProcessing(),n}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{const e=performance.now();for(;this.queue.length>0;){const t=this.queue.shift();if(!t)return;try{const r=await t.task();t.resolve(r)}catch(r){t.reject(r),p.error("[Haori]",`Task ${t.timestamp} failed:`,r)}if(performance.now()-e>this.MAX_BUDGET)break}}catch(e){p.error("[Haori]","Error processing queue:",e)}finally{this.processing=!1,this.queue.length>0&&this.scheduleProcessing()}}}scheduleProcessing(){this.processing||(typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>{this.processQueue()}):setTimeout(()=>{this.processQueue()},16))}async wait(){if(this.queue.length===0&&!this.processing)return;const e=this.queue.map(t=>t.promise);e.length>0&&await Promise.allSettled(e)}async waitForIdle(e=1e3){let t=0,r=0;for(;t<2&&r<e;)this.processing||this.queue.length>0?(await this.wait(),t=0):t+=1,await Ne.nextTick(),r+=1}static nextTick(){return new Promise(e=>{typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>e()):setTimeout(e,0)})}}const Me=class Me{static enqueue(e,t=!1){return this.ASYNC_QUEUE.enqueue(e,t)}static wait(){return this.ASYNC_QUEUE.wait()}static waitForIdle(e=1e3){return this.ASYNC_QUEUE.waitForIdle(e)}};Me.ASYNC_QUEUE=new Ne;let B=Me;const x=class x{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 scheduleForbiddenKeyLogReset(){this.loggedForbiddenKeyResetScheduled||(this.loggedForbiddenKeyResetScheduled=!0,queueMicrotask(()=>{this.loggedForbiddenKeySignatures.clear(),this.loggedForbiddenKeyResetScheduled=!1}))}static getFreeIdentifiers(e){return this.extractFreeIdentifiers(e)}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 detectForbiddenIdentifiers(e){const t=this.FORBIDDEN_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.FORBIDDEN_NAME_PATTERNS.filter(i=>i.pattern.test(e)).map(i=>i.name);return this.FORBIDDEN_IDENTIFIER_CACHE.set(e,r),r}static extractFreeIdentifiers(e){const t=this.FREE_IDENTIFIER_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e),i=[];if(r!==null){let n=null;for(const s of r){const a=n?.value==="."||n?.value==="?.";s.type==="identifier"&&!a&&!this.NON_SHADOWABLE_IDENTIFIERS.has(s.value)&&!this.DISALLOWED_KEYWORDS.has(s.value)&&!this.STRICT_FORBIDDEN_NAMES.includes(s.value)&&/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s.value)&&!i.includes(s.value)&&i.push(s.value),n=s}}return this.FREE_IDENTIFIER_CACHE.set(e,i),i}static buildShadowDeclarations(e){return e.length===0?"":`
|
|
3
|
+
let ${e.join(", ")};`}static warnBlockedIdentifiers(e){if(this.loggedBlockedIdentifierExpressions.has(e))return;const t=this.detectForbiddenIdentifiers(e);t.length!==0&&(this.loggedBlockedIdentifierExpressions.add(e),p.warn("[Haori]","Expression references blocked identifier(s): "+t.join(", ")+". These are blocked in expressions and evaluate to undefined (often the cause of an empty result). Use spread {...a, ...b} instead of Object.assign.",e))}static startsCall(e){return e===null?!1:e.type==="identifier"?!this.NON_SHADOWABLE_IDENTIFIERS.has(e.value):e.value===")"||e.value==="]"}static toOptionalChainExpression(e){const t=this.OPTIONAL_CHAIN_CACHE.get(e);if(t!==void 0)return t;const r=this.tokenizeExpression(e);let i=e;if(r!==null){const n=[];let s=null;for(const a of r)a.type==="operator"&&s?.value!=="?."&&(a.value==="."?n.push({start:a.position,end:a.position+1,text:"?."}):(a.value==="["&&this.startsMemberAccess(s)||a.value==="("&&this.startsCall(s))&&n.push({start:a.position,end:a.position,text:"?."})),s=a;for(let a=n.length-1;a>=0;a-=1){const o=n[a];i=i.slice(0,o.start)+o.text+i.slice(o.end)}}return this.OPTIONAL_CHAIN_CACHE.set(e,i),i}static extractUninitializedIdentifiers(e,t){const r=String(e.message||""),i=t.filter(n=>["'",'"',"`"].some(s=>r.includes(`${s}${n}${s}`)));return i.length>0?i:t}static recordUnresolvedIdentifiers(e,t){if(e.length!==0){if(l.strictBind){p.error("[Haori]","Expression references key(s) that are not in the binding data: "+e.join(", ")+". The result is treated as an unresolved reference.",t);return}W.isEnabled()&&(e.forEach(r=>{this.pendingUnresolvedIdentifiers.add(r)}),this.scheduleUnresolvedIdentifierReport())}}static scheduleUnresolvedIdentifierReport(){this.unresolvedReportScheduled||(this.unresolvedReportScheduled=!0,B.waitForIdle().then(()=>{this.unresolvedReportScheduled=!1,this.reportUnresolvedIdentifiers()}))}static reportUnresolvedIdentifiers(){if(this.pendingUnresolvedIdentifiers.size===0)return;const e=Array.from(this.pendingUnresolvedIdentifiers);this.pendingUnresolvedIdentifiers.clear(),p.warn("[Haori]","Expression key(s) were never provided by any binding: "+e.join(", ")+". They are treated as unresolved references (rendered as empty). Check for typos if this is unexpected.")}static evaluateAsCondition(e,t,r){const i={...t};r.forEach(s=>{i[s]=void 0});const n=this.prepareEvaluator(e,i);if(!(n.compileFailed||n.evaluator===null))try{const s=this.wrapBoundValues(i),a=n.bindKeys.map(u=>s[u]),o=this.withBlockedPropertyAccess(()=>n.evaluator(...a));return typeof o=="boolean"?o:void 0}catch{return}}static pruneResolvedIdentifiers(e){this.pendingUnresolvedIdentifiers.size!==0&&this.pendingUnresolvedIdentifiers.forEach(t=>{t in e&&this.pendingUnresolvedIdentifiers.delete(t)})}static evaluate(e,t={}){return this.evaluateDetailed(e,t).value}static evaluateDetailed(e,t={}){if(this.scheduleForbiddenBindingValueCacheReset(),e.trim()==="")return p.warn("[Haori]",e,"Expression is empty"),{value:null,unresolvedReference:!1};if(this.containsDangerousPatterns(e)){const h=this.detectDisallowedKeywords(e);if(h.length>0){const g=h.some(b=>b==="function"||b==="return")?" Statement keywords are not allowed in expressions; use an arrow function such as `x => ({key: value})` instead of `function(x){ return {key: value}; }`.":" These are statement keywords and cannot be used in expressions.";p.warn("[Haori]",e,"Expression uses disallowed keyword(s): "+h.join(", ")+"."+g)}else p.warn("[Haori]",e,"Expression contains dangerous patterns");return{value:null,unresolvedReference:!1}}const r=this.collectForbiddenKeys(t);if(r.length>0){const h=r.join(",");this.loggedForbiddenKeySignatures.has(h)||(this.loggedForbiddenKeySignatures.add(h),this.scheduleForbiddenKeyLogReset(),p.error("[Haori]","Binding keys are reserved and ignored: "+r.join(", ")+". These collide with blocked global/prototype names and cannot be used as top-level binding keys; the remaining keys are still evaluated."))}const i=this.getForbiddenBindingValueSet();if(this.containsForbiddenBindingValues(t,new WeakSet,i))return p.warn("[Haori]",t,"Binded values contain forbidden values"),{value:null,unresolvedReference:!1};const n=e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,""),s=this.BUILTIN_REFERENCE_PATTERN.test(n);s&&this.BUILTIN_NAMESPACE in t&&p.warn("[Haori]",`Binding key "${this.BUILTIN_NAMESPACE}" is reserved for built-in helpers; the bound value is ignored in expressions.`);const a={};for(const h of Object.keys(t))this.FORBIDDEN_BINDING_NAMES.has(h)||(a[h]=t[h]);s&&(a[this.BUILTIN_NAMESPACE]=this.BUILTIN_HELPERS),this.pruneResolvedIdentifiers(a);const o=this.canAttemptMissingIdentifierRecovery(e),u=this.extractFreeIdentifiers(e).filter(h=>!(h in a)&&!this.FORBIDDEN_NAMES.includes(h)&&!this.ALLOWED_GLOBAL_IDENTIFIERS.has(h));o&&u.forEach(h=>{a[h]=void 0});const f=o?[]:u;for(let h=0;h<=this.MAX_IDENTIFIER_RECOVERY_COUNT;h+=1){const g=this.prepareEvaluator(e,a,f);if(g.compileFailed||g.evaluator===null)return{value:null,unresolvedReference:!1};try{const b=[],R=this.wrapBoundValues(a);g.bindKeys.forEach(k=>{b.push(R[k])});const S=this.withBlockedPropertyAccess(()=>g.evaluator(...b));return S===void 0&&this.warnBlockedIdentifiers(e),{value:S,unresolvedReference:S===void 0}}catch(b){if(o&&b instanceof ReferenceError){const R=this.extractMissingIdentifier(b);if(R!==null&&this.canRecoverMissingIdentifier(R,a)){a[R]=void 0;continue}}if(this.warnBlockedIdentifiers(e),b instanceof ReferenceError&&f.length>0){const R=this.evaluateAsCondition(e,a,f);return R!==void 0?{value:R,unresolvedReference:!1}:(this.recordUnresolvedIdentifiers(this.extractUninitializedIdentifiers(b,f),e),{value:void 0,unresolvedReference:!0})}return p.error("[Haori]","Expression evaluation error:",e,b),b instanceof ReferenceError?{value:void 0,unresolvedReference:!0}:{value:null,unresolvedReference:!1}}}return p.error("[Haori]","Failed to recover missing identifiers:",e,a),{value:void 0,unresolvedReference:!0}}static prepareEvaluator(e,t,r=[]){const i=Object.keys(t).filter(b=>!this.FORBIDDEN_BINDING_NAMES.has(b)).sort(),n=new Set(i),s=r.filter(b=>!n.has(b)),a=`${e}:${i.join(",")}:${s.join(",")}`;let o=this.EXPRESSION_CACHE.get(a)||null;if(o!==null)return{bindKeys:i,evaluator:o,compileFailed:!1};const u=this.buildAssignments(i),f=this.buildShadowDeclarations(s),h=this.toOptionalChainExpression(e),g=u?`"use strict";
|
|
4
|
+
${u};
|
|
5
|
+
return (${h});${f}`:`"use strict";
|
|
6
|
+
return (${h});${f}`;try{return o=new Function(...i,g),this.EXPRESSION_CACHE.set(a,o),{bindKeys:i,evaluator:o,compileFailed:!1}}catch(b){return s.length>0?(p.warn("[Haori]","Failed to shadow undeclared identifier(s): "+s.join(", ")+". Falling back to evaluation without shadowing.",e),this.prepareEvaluator(e,t,[])):(p.error("[Haori]","Failed to compile expression:",e,b),{bindKeys:i,evaluator:null,compileFailed:!0})}}static extractMissingIdentifier(e){return String(e.message||"").match(/^([A-Za-z_$][A-Za-z0-9_$]*) is not defined$/)?.[1]||null}static canRecoverMissingIdentifier(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?t[e]===void 0&&!(e in t):!1}static canAttemptMissingIdentifierRecovery(e){return e.includes("?.")||e.includes("??")||e.includes("||")||e.includes("&&")}static containsDangerousPatterns(e){return this.hasAllowedSyntax(e)?[/\beval\s*\(/,/\barguments\s*\[/,/\barguments\s*\./].some(r=>r.test(e)):!0}static detectDisallowedKeywords(e){const t=[];return this.DISALLOWED_KEYWORDS.forEach(r=>{new RegExp(`(^|[^\\w$.])${r}(?![\\w$])`).test(e)&&t.push(r)}),t}static hasAllowedSyntax(e){const t=this.tokenizeExpression(e);if(t===null||t.length===0)return!1;const r=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n],a=t[n+1]||null,o=r[r.length-1]||null,u=t[n-2]||null,f=t[n-3]||null;if(this.startsObjectKey(o,i,u,f)&&(s.value==="["||s.type==="identifier"&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value)||s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value)))||s.type==="identifier"&&(this.DISALLOWED_KEYWORDS.has(s.value)||this.STRICT_FORBIDDEN_NAMES.includes(s.value)||(i?.value==="."||i?.value==="?.")&&this.FORBIDDEN_PROPERTY_NAMES.has(s.value))||o==="member"&&s.value!=="]"&&s.type==="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(this.decodeStringLiteral(s.value))||s.value==="."&&a?.type!=="identifier"||s.value==="?."&&a?.type!=="identifier"&&a?.value!=="["&&a?.value!=="(")return!1;switch(s.value){case"(":r.push("paren");break;case")":{if(r.pop()!=="paren")return!1;break}case"[":{const h=this.startsMemberAccess(i)?"member":"array";r.push(h);break}case"{":r.push("object");break;case"]":{if(r.pop()===void 0)return!1;break}case"}":{if(r.pop()!=="object")return!1;break}}i=s}return r.length===0}static tokenizeExpression(e){const t=[],r=["===","!==","...","?.","&&","||",">=","<=","==","!=","=>"],i=new Set(["(",")","{","}","[","]",".",",","?",":","+","-","*","/","%","!",">","<"]);let n=0;for(;n<e.length;){const s=e[n];if(/\s/.test(s)){n+=1;continue}if(s==="/"&&(e[n+1]==="/"||e[n+1]==="*"))return null;if(s==='"'||s==="'"){const o=this.readStringToken(e,n);if(o===null)return null;t.push(o.token),n=o.nextIndex;continue}const a=r.find(o=>e.startsWith(o,n));if(a){t.push({type:"operator",value:a,position:n}),n+=a.length;continue}if(/[0-9]/.test(s)){const o=this.readNumberToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(/[A-Za-z_$]/.test(s)){const o=this.readIdentifierToken(e,n);t.push(o.token),n=o.nextIndex;continue}if(i.has(s)){t.push({type:"operator",value:s,position:n}),n+=1;continue}return null}return t}static readStringToken(e,t){const r=e[t];let i=t+1;for(;i<e.length;){const n=e[i];if(n==="\\"){i+=2;continue}if(n===r)return{token:{type:"string",value:e.slice(t,i+1),position:t},nextIndex:i+1};i+=1}return null}static readNumberToken(e,t){let r=t;for(;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;if(e[r]===".")for(r+=1;r<e.length&&/[0-9_]/.test(e[r]);)r+=1;return{token:{type:"number",value:e.slice(t,r),position:t},nextIndex:r}}static readIdentifierToken(e,t){let r=t;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{token:{type:"identifier",value:e.slice(t,r),position:t},nextIndex:r}}static startsMemberAccess(e){return e===null?!1:e.type==="identifier"||e.type==="number"?!0:e.value===")"||e.value==="]"||e.value==="?."}static startsObjectKey(e,t,r,i){return e!=="object"?!1:t?.value==="{"||t?.value===","||t?.type==="identifier"&&this.OBJECT_PROPERTY_MODIFIERS.has(t.value)&&(r?.value==="{"||r?.value===",")?!0:t?.value!=="*"?!1:r?.value==="{"||r?.value===","?!0:r?.type==="identifier"&&r.value==="async"&&(i?.value==="{"||i?.value===",")}static decodeStringLiteral(e){return e.slice(1,-1).replace(/\\u\{([0-9a-fA-F]+)\}/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\x([0-9a-fA-F]{2})/g,(t,r)=>String.fromCharCode(parseInt(r,16))).replace(/\\(["'\\bfnrtv0])/g,(t,r)=>{switch(r){case"b":return"\b";case"f":return"\f";case"n":return`
|
|
7
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return r}})}static wrapBoundValues(e){const t=new WeakMap,r={};return Object.entries(e).forEach(([i,n])=>{r[i]=this.wrapBoundValue(n,t)}),r}static wrapBoundValue(e,t){if(!this.shouldWrapValue(e))return e;const r=e,i=t.get(r);if(i!==void 0)return i;const n=new Proxy(r,{get:(s,a,o)=>{if(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a))return;const u=Reflect.get(s,a,o);return typeof a=="symbol"?u:this.wrapBoundValue(u,t)},has:(s,a)=>typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)?!1:Reflect.has(s,a),getOwnPropertyDescriptor:(s,a)=>{if(!(typeof a=="string"&&this.FORBIDDEN_PROPERTY_NAMES.has(a)))return Reflect.getOwnPropertyDescriptor(s,a)},apply:(s,a,o)=>{const u=Reflect.apply(s,a,o);return this.isIteratorLike(u)?u:this.wrapBoundValue(u,t)},construct:(s,a,o)=>this.wrapBoundValue(Reflect.construct(s,a,o),t)});return t.set(r,n),n}static shouldWrapValue(e){if(typeof e=="function")return!0;if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}static withBlockedPropertyAccess(e){const r=[{target:Object.prototype,property:"constructor"},{target:Function.prototype,property:"constructor"},{target:Object.prototype,property:"__proto__"}].map(i=>({...i,descriptor:Object.getOwnPropertyDescriptor(i.target,i.property)})).filter(i=>i.descriptor?.configurable===!0);r.forEach(({target:i,property:n})=>{Object.defineProperty(i,n,{configurable:!0,enumerable:!1,get:()=>{},set:()=>{}})});try{return e()}finally{r.forEach(({target:i,property:n,descriptor:s})=>{s!==void 0&&Object.defineProperty(i,n,s)})}}static isIteratorLike(e){return e===null||typeof e!="object"?!1:typeof e.next=="function"}static containsForbiddenKeys(e){return this.collectForbiddenKeys(e).length>0}static collectForbiddenKeys(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>this.FORBIDDEN_BINDING_NAMES.has(t))}static containsForbiddenBindingValues(e,t=new WeakSet,r=this.getForbiddenBindingValueSet()){if(!e||typeof e!="object")return!1;const i=this.forbiddenBindingValueCache.get(e);if(i!==void 0)return i;if(t.has(e))return!1;if(t.add(e),r.has(e))return this.forbiddenBindingValueCache.set(e,!0),!0;for(const n of Object.values(e)){if(typeof n=="function"){if(r.has(n))return this.forbiddenBindingValueCache.set(e,!0),!0;continue}if(this.containsForbiddenBindingValues(n,t,r))return this.forbiddenBindingValueCache.set(e,!0),!0}return this.forbiddenBindingValueCache.set(e,!1),!1}};x.MAX_IDENTIFIER_RECOVERY_COUNT=8,x.BUILTIN_NAMESPACE="haori",x.BUILTIN_HELPERS={...ot},x.BUILTIN_REFERENCE_PATTERN=/(^|[^\w$.])haori(?![\w$])/,x.forbiddenBindingValueCache=new WeakMap,x.forbiddenBindingValueCacheResetScheduled=!1,x.loggedForbiddenKeySignatures=new Set,x.loggedForbiddenKeyResetScheduled=!1,x.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"],x.STRICT_FORBIDDEN_NAMES=["eval","arguments"],x.REBINDABLE_FORBIDDEN_NAMES=new Set(["location","history","document","navigator","localStorage","sessionStorage","IndexedDB"]),x.FORBIDDEN_BINDING_NAMES=new Set([...x.FORBIDDEN_NAMES.filter(e=>!x.REBINDABLE_FORBIDDEN_NAMES.has(e)),"constructor","__proto__","prototype",...x.STRICT_FORBIDDEN_NAMES]),x.FORBIDDEN_PROPERTY_NAMES=new Set(["constructor","__proto__","prototype"]),x.OBJECT_PROPERTY_MODIFIERS=new Set(["get","set","async"]),x.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"]),x.NON_SHADOWABLE_IDENTIFIERS=new Set(["true","false","null","undefined","NaN","Infinity","enum","implements","interface","package","private","protected","public","static","super"]),x.ALLOWED_GLOBAL_IDENTIFIERS=new Set(["Math","JSON","Intl","Atomics","Array","String","Number","Boolean","Date","RegExp","Symbol","BigInt","Map","Set","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Promise","Proxy","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","parseInt","parseFloat","isNaN","isFinite","encodeURI","encodeURIComponent","decodeURI","decodeURIComponent"]),x.EXPRESSION_CACHE=new Map,x.FREE_IDENTIFIER_CACHE=new Map,x.OPTIONAL_CHAIN_CACHE=new Map,x.FORBIDDEN_NAME_PATTERNS=x.FORBIDDEN_NAMES.map(e=>({name:e,pattern:new RegExp(`(^|[^\\w$.])${e}(?![\\w$])`)})),x.FORBIDDEN_IDENTIFIER_CACHE=new Map,x.pendingUnresolvedIdentifiers=new Set,x.unresolvedReportScheduled=!1,x.loggedBlockedIdentifierExpressions=new Set;let Y=x;const L=class L{static reset(){L.ELEMENT_STORES.clear(),L.ensureGlobalAccess()}static snapshot(){return L.ensureGlobalAccess(),[...L.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:L.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:L.sortPlaceholders(i.placeholders)})).sort((r,i)=>i.calls-r.calls)})).sort((e,t)=>{const r=e.attributes.reduce((n,s)=>n+s.calls,0)+e.texts.reduce((n,s)=>n+s.calls,0);return t.attributes.reduce((n,s)=>n+s.calls,0)+t.texts.reduce((n,s)=>n+s.calls,0)-r})}static record(e,t,r){if(!W.isEnabled()||!e||t.length===0)return;L.ensureGlobalAccess();const i=L.getOrCreateElementStore(e.element);if(e.kind==="attribute"){const s=L.getOrCreateCounter(i.attributes,e.rawName,e.template);L.updateCounter(s,t,r);return}const n=L.getOrCreateCounter(i.texts,String(e.childIndex),e.template);L.updateCounter(n,t,r)}static ensureGlobalAccess(){if(!W.isEnabled())return;const e=globalThis;e[L.GLOBAL_KEY]===void 0&&(e[L.GLOBAL_KEY]={reset:()=>L.reset(),snapshot:()=>L.snapshot()})}static getOrCreateElementStore(e){const t=L.createElementId(e),r=L.ELEMENT_STORES.get(t);if(r)return r;const i={tagName:e.tagName.toLowerCase(),attributes:new Map,texts:new Map};return L.ELEMENT_STORES.set(t,i),i}static getOrCreateCounter(e,t,r){const i=e.get(t);if(i)return i;const n={template:r,calls:0,totalDurationMs:0,maxDurationMs:0,placeholders:new Map};return e.set(t,n),n}static getOrCreatePlaceholder(e,t){const r=e.get(t);if(r)return r;const i={calls:0,totalDurationMs:0,maxDurationMs:0};return e.set(t,i),i}static updateCounter(e,t,r){e.calls+=1,e.totalDurationMs+=r,e.maxDurationMs=Math.max(e.maxDurationMs,r),t.forEach(i=>{const n=L.getOrCreatePlaceholder(e.placeholders,i.expression);n.calls+=1,n.totalDurationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs)})}static sortPlaceholders(e){return[...e.entries()].map(([t,r])=>({expression:t,calls:r.calls,totalDurationMs:r.totalDurationMs,maxDurationMs:r.maxDurationMs})).sort((t,r)=>r.calls!==t.calls?r.calls-t.calls:r.totalDurationMs-t.totalDurationMs)}static now(){return globalThis.performance?.now()??Date.now()}static measure(e){const t=L.now();return{value:e(),durationMs:L.now()-t}}static createElementId(e){const t=[];let r=e;for(;r;){let i=r.tagName.toLowerCase();const n=r.getAttribute("id")||"";if(n.trim()!==""){i+=`#${n.trim()}`,t.unshift(i);break}const s=r.getAttribute(`${l.prefix}derive-name`);s&&s.trim()!==""&&(i+=`[${l.prefix}derive-name="${s.trim()}"]`);const a=r.parentElement;a&&(i+=`:nth-child(${[...a.children].indexOf(r)+1})`),t.unshift(i),r=a}return t.join(" > ")}};L.GLOBAL_KEY="__HAORI_EVALUATION_PROFILE__",L.ELEMENT_STORES=new Map;let he=L;const te=class te{constructor(e){this.parent=null,this.mounted=!1,this.skipMutationNodes=!1,this.target=e,te.FRAGMENT_CACHE.set(e,this)}static get(e){if(e==null)return null;if(te.FRAGMENT_CACHE.has(e))return te.FRAGMENT_CACHE.get(e);let t;switch(e.nodeType){case Node.ELEMENT_NODE:t=new N(e);break;case Node.TEXT_NODE:t=new z(e);break;case Node.COMMENT_NODE:t=new Ie(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 B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode===e.getTarget()&&e.getTarget().removeChild(this.target),this.mounted=!1}).finally(()=>{e.skipMutationNodes=t})}else{const e=this.target.parentNode;if(e)return B.enqueue(()=>{this.target.parentNode===e&&e.removeChild(this.target),this.mounted=!1});this.mounted=!1}return Promise.resolve()}mount(){if(this.mounted||this.skipMutationNodes)return Promise.resolve();if(this.parent){const e=this.parent,t=e.skipMutationNodes;return B.enqueue(()=>{e.skipMutationNodes=!0,this.target.parentNode!==e.getTarget()&&e.getTarget().appendChild(this.target),this.mounted=!0}).finally(()=>{e.skipMutationNodes=t})}return Promise.resolve()}isMounted(){return this.mounted}setMounted(e){this.mounted=e}remove(e=!0){return this.parent&&this.parent.removeChild(this),te.FRAGMENT_CACHE.delete(this.target),e?this.unmount():Promise.resolve()}getTarget(){return this.target}getParent(){return this.parent}setParent(e){this.parent=e}};te.FRAGMENT_CACHE=new WeakMap;let T=te;const V=class V extends T{constructor(e){super(e),this.children=[],this.attributeMap=new Map,this.bindingData=null,this.bindingWorkChain=Promise.resolve(),this.bindingWorkActive=0,this.initialBindAttribute=null,this.derivedBindingData=null,this.bindingDataCache=null,this.descendantBindingDataCache=null,this.visible=!0,this.display=null,this.displayPriority=null,this.template=null,this.rowLocalTemplate=null,this.listKey=null,this.renderSignature=null,this.eachInputSignature=null,this.deriveSubtreeSignature=null,this.deriveInputSignature=null,this.freshInitializationSkippable=!1,this.value=null,this.skipMutationAttributes=!1,this.skipChangeValue=!1,this.userEditSequence=0,this.selfWrittenBind=new Map,this.syncValue(),this.initialBindAttribute=e.getAttribute(`${l.prefix}bind`),e.getAttributeNames().forEach(t=>{const r=e.getAttribute(t);if(r!==null&&!this.attributeMap.has(t)){const i=new fe(t,r);this.attributeMap.set(t,i)}}),e.childNodes.forEach(t=>{const r=T.get(t);r.setParent(this),this.children.push(r)})}getChildren(){return this.children}getChildElementFragments(){return this.children.filter(e=>e instanceof 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.rowLocalTemplate=this.rowLocalTemplate,e.renderSignature=this.renderSignature,e.eachInputSignature=this.eachInputSignature,e.deriveSubtreeSignature=null,e.deriveInputSignature=null,e.freshInitializationSkippable=this.freshInitializationSkippable,e.normalizeClonedVisibilityState(),e}normalizeClonedVisibilityState(){(this.visible===!1||this.getTarget().style.display==="none"||this.getTarget().hasAttribute(`${l.prefix}if-false`))&&(this.visible=!0,this.display=null,this.displayPriority=null,this.getTarget().style.removeProperty("display"),this.getTarget().removeAttribute(`${l.prefix}if-false`)),this.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}recordSelfWrittenBind(e){this.selfWrittenBind.size>64&&this.selfWrittenBind.clear(),this.selfWrittenBind.set(e,(this.selfWrittenBind.get(e)??0)+1)}consumeSelfWrittenBind(e){const t=this.selfWrittenBind.get(e);return t===void 0?!1:(t<=1?this.selfWrittenBind.delete(e):this.selfWrittenBind.set(e,t-1),!0)}getRawDerivedBindingData(){return this.derivedBindingData}setBindingData(e){this.bindingData=e,this.clearBindingDataCache()}isExecutingBindingWork(){return this.bindingWorkActive>0}markBindingWorkStart(){this.bindingWorkActive++}markBindingWorkEnd(){this.bindingWorkActive>0&&this.bindingWorkActive--}enqueueBindingWork(e){const t=this.bindingWorkChain.then(e,e);return this.bindingWorkChain=t.then(()=>{},()=>{}),t}getInitialBindAttribute(){return this.initialBindAttribute}setDerivedBindingData(e){this.derivedBindingData=e,this.clearBindingDataCache()}setParent(e){this.parent!==e&&(this.parent=e,this.clearBindingDataCache())}clearBindingDataCache(){this.bindingDataCache=null,this.descendantBindingDataCache=null,this.children.forEach(e=>{e instanceof V&&e.clearBindingDataCache()})}getTemplate(){return this.template}setTemplate(e){this.template=e,this.rowLocalTemplate=null}getRowLocalTemplate(){return this.rowLocalTemplate}setRowLocalTemplate(e){this.rowLocalTemplate=e}setListKey(e){this.listKey=e}getListKey(){return this.listKey}getRenderSignature(){return this.renderSignature}setRenderSignature(e){this.renderSignature=e}getEachInputSignature(){return this.eachInputSignature}setEachInputSignature(e){this.eachInputSignature=e}getDeriveSubtreeSignature(){return this.deriveSubtreeSignature}setDeriveSubtreeSignature(e){this.deriveSubtreeSignature=e}getDeriveInputSignature(){return this.deriveInputSignature}setDeriveInputSignature(e){this.deriveInputSignature=e}isFreshInitializationSkippable(){return this.freshInitializationSkippable}setFreshInitializationSkippable(e){this.freshInitializationSkippable=e}setValue(e){return this.applyValue(e,!0)}syncBindingValue(e){return this.applyValue(e,!1)}applyValue(e,t){if(this.skipChangeValue||this.value===e)return Promise.resolve();const r=this.getTarget();if(r instanceof HTMLInputElement&&r.type==="file")return e===null||e===""?(this.value=null,r.value===""?Promise.resolve():B.enqueue(()=>{r.value=""})):(p.warn("[Haori]","A value cannot be assigned to input[type=file]; only clearing is supported.",r),Promise.resolve());if(r instanceof HTMLInputElement&&(r.type==="checkbox"||r.type==="radio")){const i=this.getAttribute("value"),n=r.type==="checkbox"&&i==="true";let s;return n?s=e===!0||e==="true":i==="false"?s=e===!1:Array.isArray(e)?s=e.map(String).includes(String(i)):s=i===String(e),n?this.value=s:s?Array.isArray(e)?this.value=String(i):this.value=e:this.value=null,r.checked===s?Promise.resolve():(this.skipChangeValue=!0,B.enqueue(()=>{r.checked=s,t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1}))}else if(r instanceof HTMLSelectElement&&r.multiple){const i=(Array.isArray(e)?e:e===null?[]:[e]).map(String);return this.value=i.slice(),this.skipChangeValue=!0,B.enqueue(()=>{let n=!1;Array.from(r.options).forEach(s=>{const a=i.includes(s.value);s.selected!==a&&(s.selected=a,n=!0)}),n&&t&&r.dispatchEvent(new Event("change",{bubbles:!0}))}).finally(()=>{this.skipChangeValue=!1})}else if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){const i=Array.isArray(e)?e.join(","):e;return this.value=this.normalizeValueForElement(r,i),this.skipChangeValue=!0,B.enqueue(()=>{r.value=i===null?"":String(i),t&&((r instanceof HTMLInputElement&&V.INPUT_EVENT_TYPES.includes(r.type)||r instanceof HTMLTextAreaElement)&&r.dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0})))}).finally(()=>{this.skipChangeValue=!1})}else return p.warn("[Haori]","setValue is not supported for this element type.",r),Promise.resolve()}getValue(){return this.value}static currentUserEditSequence(){return V.userEditCounter}markUserEdit(){V.userEditCounter+=1,this.userEditSequence=V.userEditCounter}getUserEditSequence(){return this.userEditSequence}clearValue(){this.value=null}normalizeValueForElement(e,t){if(e instanceof HTMLInputElement&&e.type==="number"){if(t===null||t==="")return null;const r=typeof t=="number"?t:Number(t);return Number.isNaN(r)?null:r}return t}static isValuePropertyTarget(e){return e instanceof HTMLInputElement?V.INPUT_EVENT_TYPES.includes(e.type)||e.type==="hidden":e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}syncValue(){const e=this.getTarget();if(e instanceof HTMLInputElement)if(e.type==="checkbox"||e.type==="radio"){const t=e.type==="checkbox"&&e.value==="true";if(e.checked){const r=e.value;t?this.value=!0:r==="false"?this.value=!1:this.value=r}else{const r=e.value;t?this.value=!1:r==="false"?this.value=!0:this.value=null}}else if(e.type==="file"){const t=e.files;this.value=t&&t.length>0?t[0].name:null}else this.value=this.normalizeValueForElement(e,e.value);else e instanceof HTMLTextAreaElement?this.value=e.value:e instanceof HTMLSelectElement&&(e.multiple?this.value=Array.from(e.selectedOptions).map(t=>t.value):this.value=e.value)}syncCheckableValueFromDom(e){if(!e){this.syncValue();return}const t=this.getTarget().closest("select");if(!t)return;const r=T.get(t);r instanceof V&&r.syncValue()}setAttribute(e,t,r=!1){return this.setAttributeInternal(e,e,t,!0,r)}setAliasedAttribute(e,t,r,i=!1){return this.setAttributeInternal(e,t,r,!0,i)}removeAliasedAttribute(e,t){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const r=this.getTarget();return B.enqueue(()=>{r.removeAttribute(e),t!==e&&r.removeAttribute(t)}).finally(()=>{this.skipMutationAttributes=!1})}setAttributeInternal(e,t,r,i,n=!1){if(this.skipMutationAttributes)return Promise.resolve();if(r===null)return e===t?this.removeAttribute(e):this.removeAliasedAttribute(e,t);const s=new fe(e,r);if(n){const Se=this.attributeMap.get(e);if(Se&&(Se.isEvaluate||Se.isForceEvaluation())&&!s.isEvaluate&&!s.isForceEvaluation())return this.skipMutationAttributes=!0,B.enqueue(()=>{}).finally(()=>{this.skipMutationAttributes=!1})}this.attributeMap.set(e,s);const a=this.getTarget(),o=s.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:a,rawName:e,template:r}),u=s.isEvaluate||s.isRawEvaluate,f=e===t&&V.BOOLEAN_ATTRIBUTES.has(t.toLowerCase()),h=s.isSingleExpression(),g=Q.joinEvaluateResults(o.results),b=o.results.length===1?o.results[0]:g,R=!s.isForceEvaluation()&&(t!==e||f||h?o.hasUnresolvedReference||b===null||b===void 0||b===!1:u&&g===""),S=s.isForceEvaluation()?r:h?b:g,k=i&&s.isEvaluate&&t==="value"&&V.isValuePropertyTarget(a),w=a.getRootNode(),A=k&&a===w.activeElement,y=R||S===null||S===!1?null:String(S),D=e!==t&&a.getAttribute(e)!==r,I=y===null?a.hasAttribute(t):a.getAttribute(t)!==y,$=y===null?"":y,O=k&&!A&&a.value!==$,K=t==="checked"&&a instanceof HTMLInputElement&&(a.type==="checkbox"||a.type==="radio"),U=t==="selected"&&a instanceof HTMLOptionElement,Z=w.activeElement,Ee=Z!==null&&(K&&a===Z||U&&a.closest("select")===Z),oe=y!==null,Ae=K&&!Ee&&a.checked!==oe,le=U&&!Ee&&a.selected!==oe;return!D&&!I&&!O&&!Ae&&!le?(k&&!A&&(this.value=this.normalizeValueForElement(a,$)),(K||U)&&!Ee&&this.syncCheckableValueFromDom(U),Promise.resolve()):(this.skipMutationAttributes=!0,B.enqueue(()=>{D&&a.setAttribute(e,r),y===null?a.removeAttribute(t):I&&(a.setAttribute(t,y),t===`${l.prefix}bind`&&this.recordSelfWrittenBind(y)),k&&!A&&(this.value=this.normalizeValueForElement(a,$),O&&(a.value=$)),Ae&&(a.checked=oe),le&&(a.selected=oe),(Ae||le)&&this.syncCheckableValueFromDom(le)}).finally(()=>{this.skipMutationAttributes=!1}))}removeAttribute(e){if(this.skipMutationAttributes)return Promise.resolve();this.attributeMap.delete(e),this.skipMutationAttributes=!0;const t=this.getTarget();return B.enqueue(()=>{t.removeAttribute(e)}).finally(()=>{this.skipMutationAttributes=!1})}getAttribute(e){return this.getAttributeEvaluation(e)?.value??null}getAttributeEvaluation(e){const t=this.attributeMap.get(e);if(t===void 0)return null;const r=t.evaluateDetailed(this.getBindingData(),{kind:"attribute",element:this.getTarget(),rawName:e,template:t.getValue()});return r.results.length===1?{value:r.results[0],hasUnresolvedReference:r.hasUnresolvedReference}:{value:Q.joinEvaluateResults(r.results),hasUnresolvedReference:r.hasUnresolvedReference}}getRawAttribute(e){const t=this.attributeMap.get(e);return t===void 0?null:t.getValue()}getAttributeNames(){return Array.from(this.attributeMap.keys())}hasAttribute(e){return this.attributeMap.has(e)}resolveInsertionPointFromDom(e,t){const r=e.getTarget();if(r.parentNode!==this.target)return null;const i=t?r.nextSibling:r;let n=t?r.nextSibling:r;for(;n!==null;){const s=T.get(n);if(s!==null){const a=this.children.indexOf(s);if(a!==-1)return{index:a,referenceNode:i}}n=n.nextSibling}return{index:this.children.length,referenceNode:i}}insertBefore(e,t,r){if(this.skipMutationNodes)return Promise.resolve();if(e===this)return p.error("[Haori]","Cannot insert element as child of itself"),Promise.reject(new Error("Self-insertion not allowed"));const i=new Set;let n=this.parent;for(;n;)i.add(n),n=n.getParent();if(i.has(e))return p.error("[Haori]","Cannot create circular reference"),Promise.reject(new Error("Circular reference detected"));const s=e.getParent()===this;let a=-1,o=-1;s&&(a=this.children.indexOf(e),t!==null&&(o=this.children.indexOf(t)));const u=e.getParent();u!==null&&u.removeChild(e);let f=r===void 0?t?.getTarget()||null:r;if(t===null)this.children.push(e);else{let g;if(s?a!==-1&&a<o?g=o-1:g=o:g=this.children.indexOf(t),g===-1){const b=this.resolveInsertionPointFromDom(t,!1);b===null?(p.warn("[Haori]","Reference child not found in children.",t),this.children.push(e)):(this.children.splice(b.index,0,e),f=b.referenceNode)}else this.children.splice(g,0,e)}e.setParent(this),e.setMounted(this.mounted);const h=this.skipMutationNodes;return this.skipMutationNodes=!0,B.enqueue(()=>{this.target.insertBefore(e.getTarget(),f)}).finally(()=>{this.skipMutationNodes=h})}insertAfter(e,t){if(t==null)return this.insertBefore(e,null);const r=this.children.indexOf(t);if(r===-1){const i=this.resolveInsertionPointFromDom(t,!0);return i===null?(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"]),V.INPUT_EVENT_TYPES=["text","password","email","url","tel","search","number","range","color","date","datetime-local","month","time","week"],V.userEditCounter=0;let N=V;class z extends T{constructor(e){super(e),this.skipMutation=!1,this.renderedText=null,this.text=e.textContent||"",this.contents=new Q(this.text)}clone(){const e=new z(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e.contents=this.contents,e.renderedText=this.renderedText,e}getTarget(){return this.target}hasDynamicContent(){return this.contents.isEvaluate||this.contents.isRawEvaluate}getRawText(){return this.text}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,this.contents=new Q(e),this.evaluate())}evaluate(){return this.contents.isRawEvaluate&&this.parent===null?Promise.reject(new Error("Parent fragment is required for raw evaluation")):B.enqueue(()=>{this.skipMutation=!0;let e=this.text;this.contents.isRawEvaluate?e=this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})[0]:this.contents.isEvaluate&&(e=Q.joinEvaluateResults(this.contents.evaluate(this.parent.getBindingData(),{kind:"text",element:this.parent.getTarget(),childIndex:this.parent.getChildren().indexOf(this),template:this.text})));const t=this.contents.isRawEvaluate?this.parent.getTarget().innerHTML:this.target.textContent||"";this.renderedText===e&&t===e||(this.contents.isRawEvaluate?this.parent.getTarget().innerHTML=e:this.target.textContent=e,this.renderedText=e)}).finally(()=>{this.skipMutation=!1})}}class Ie extends T{constructor(e){super(e),this.skipMutation=!1,this.text=e.textContent||""}clone(){const e=new Ie(this.target.cloneNode(!0));return e.mounted=!1,e.text=this.text,e}getTarget(){return this.target}setContent(e){return this.skipMutation||this.text===e?Promise.resolve():(this.text=e,B.enqueue(()=>{this.skipMutation=!0,this.target.textContent=this.text}).finally(()=>{this.skipMutation=!1}))}}const me=class me{constructor(e){this.contents=[],this.isEvaluate=!1,this.isRawEvaluate=!1,this.value=e;const t=[...e.matchAll(me.PLACEHOLDER_REGEX)];let r=0,i=!1,n=!1;for(const s of t){s.index>r&&this.contents.push({text:e.slice(r,s.index),type:0});const a={text:s[1]??s[2],type:s[1]?2:1};i=!0,n=n||a.type===2,this.contents.push(a),r=s.index+s[0].length}r<e.length&&this.contents.push({text:e.slice(r),type:0}),this.isEvaluate=i,this.isRawEvaluate=n,this.checkRawExpressions()}static joinEvaluateResults(e){return e===null||e.length===0?"":e.map(t=>t==null||t===!1||Number.isNaN(t)?"":typeof t!="string"?String(t):t).join("")}getValue(){return this.value}isSingleExpression(){return this.contents.length===1&&(this.contents[0].type===1||this.contents[0].type===2)}checkRawExpressions(){for(let e=0;e<this.contents.length;e++)this.contents[e].type===2&&this.contents.length>1&&(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 n=[],s=[];let a=0,o=!1;return this.contents.forEach(u=>{try{if(r(u)){const f=he.measure(()=>Y.evaluateDetailed(u.text,e)),h=f.value;a+=f.durationMs,s.push({expression:u.text,durationMs:f.durationMs}),o=o||h.unresolvedReference,n.push(h.value)}else n.push(u.text)}catch(f){p.error("[Haori]",`Error evaluating ${i} expression: ${u.text}`,f),s.push({expression:u.text,durationMs:0}),n.push("")}}),he.record(t,s,a),{results:n,hasUnresolvedReference:o}}};me.PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g;let Q=me;const be=class be extends Q{constructor(e,t){super(t),this.forceEvaluation=be.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}};be.FORCE_EVALUATION_ATTRIBUTES=["data-if","hor-if","data-each","hor-each","data-derive","hor-derive"];let fe=be;class X{static get runtime(){return l.runtime}static setRuntime(e){l.setRuntime(e)}static waitForRenders(){return B.waitForIdle()}static dialog(e){return B.enqueue(()=>{window.alert(e)},!0)}static async toast(e,t="info"){const r=document.createElement("div");r.className=`haori-toast haori-toast-${t}`,r.textContent=e,r.setAttribute("popover","manual"),r.setAttribute("role","status"),r.setAttribute("aria-live",t==="error"?"assertive":"polite"),document.body.appendChild(r),r.showPopover(),setTimeout(()=>{try{r.hidePopover()}finally{r.remove()}},3e3)}static confirm(e){return B.enqueue(()=>window.confirm(e),!0)}static openDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?(X.clearMessagesSync(e),e.showModal()):p.error("[Haori]","Element is not a dialog: ",e)},!0)}static closeDialog(e){return B.enqueue(()=>{e instanceof HTMLDialogElement?e.close():p.error("[Haori]","Element is not a dialog: ",e)},!0)}static addErrorMessage(e,t){return X.addMessage(e,t,"error")}static addMessage(e,t,r){return B.enqueue(()=>{const i=e instanceof HTMLFormElement?e:e.parentElement??e;i.setAttribute("data-message",t),r!==void 0?i.setAttribute("data-message-level",r):i.removeAttribute("data-message-level")},!0)}static clearMessages(e){return B.enqueue(()=>{X.clearMessagesSync(e)},!0)}static clearMessagesSync(e){e.removeAttribute("data-message"),e.removeAttribute("data-message-level"),e.querySelectorAll("[data-message]").forEach(t=>{t.removeAttribute("data-message"),t.removeAttribute("data-message-level")})}static date(e,t,r){return ye(e,t,r)}static now(e,t){return He(e,t)}static today(e,t,r){return Ue(e,t,r)}static number(e,t){return Ve(e,t)}static range(e,t,r){return je(e,t,r)}static pages(e,t,r){return qe(e,t,r)}static monthAdd(e,t){return ve(e,t)}static monthRange(e,t){return We(e,t)}static pageSummary(e,t){return ze(e,t)}static findBy(e,t,r){return Ke(e,t,r)}static sum(e,t){return Ge(e,t)}static distinct(e,t){return Xe(e,t)}static groupBy(e,t){return Je(e,t)}}const lt=["addErrorMessage","clearMessages"],Ce="data-haori-group-name";function ke(){const e=globalThis.window?.Haori;return lt.every(r=>typeof e?.[r]=="function")?e:X}const E=class E{static getValues(e){const t={};return E.getPartValues(e,t)}static resolveCollectedValue(e){const t=e.getTarget();if(E.isFileInput(e)){const r=t,i=r.files?Array.from(r.files):[];return r.multiple?i:i.length>0?i[0]:null}if(E.isBooleanCheckbox(e)){const r=t;return r.value==="false"?!r.checked:r.checked}return e.getValue()}static isBooleanCheckbox(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.value==="true"||t.value==="false")}static resolveFieldName(e){const t=e.getAttribute(`${l.prefix}form-name`);return t||e.getAttribute("name")}static prepareFormName(e){if(!e.hasAttribute(`${l.prefix}form-name`))return;const t=e.getAttribute(`${l.prefix}form-name`);if(!t){p.warn("Haori",`${l.prefix}form-name evaluated to an empty key; the field falls back to the name attribute or is not collected.`,e.getTarget());return}const r=e.getTarget();if(!(r instanceof HTMLInputElement)||r.type!=="radio"||r.hasAttribute("name")&&!r.hasAttribute(Ce))return;const i=E.resolveGroupScope(e),n=`${String(t)}--haori${E.resolveGroupScopeId(i)}`;if(r.getAttribute("name")!==n)return e.setAttribute(Ce,"").then(()=>e.setAttribute("name",n))}static resolveGroupScope(e){let t=e,r=t.getParent();for(;r!==null;){if(r.hasAttribute(`${l.prefix}form-list`))return t;if(r.getTarget()instanceof HTMLFormElement||r.hasAttribute(`${l.prefix}form`))return r;t=r,r=r.getParent()}return t}static resolveGroupScopeId(e){const t=E.GROUP_SCOPE_IDS.get(e);return t!==void 0?t:(E.groupScopeSequence+=1,E.GROUP_SCOPE_IDS.set(e,E.groupScopeSequence),E.groupScopeSequence)}static isDeclarativeStateBound(e){const t=e.getTarget();return t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio")?E.hasDeclarativeBinding(e,"checked"):N.isValuePropertyTarget(t)?E.hasDeclarativeBinding(e,"value")?!0:t instanceof HTMLSelectElement?E.hasDeclarativeSelectedOption(t):!1:!1}static hasDeclarativeBinding(e,t){if(e.hasAttribute(`${l.prefix}attr-${t}`))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static hasDeclarativeSelectedOption(e){for(const t of Array.from(e.options)){const r=T.get(t);if(r instanceof N&&E.hasDeclarativeBinding(r,"selected"))return!0}return!1}static isFileInput(e){const t=e.getTarget();return t instanceof HTMLInputElement&&t.type==="file"}static getValuesEditedAfter(e,t){return E.getPartValues(e,{},t)}static getPartValues(e,t,r=null){if(e.getTarget().hasAttribute(`${l.prefix}if-false`))return t;const i=E.resolveFieldName(e),n=e.getAttribute(`${l.prefix}form-object`),s=e.getAttribute(`${l.prefix}form-list`),a=e.hasAttribute(`${l.prefix}form-list`),o=r!==null&&e.getUserEditSequence()<=r;if(i){if(a&&o)Array.isArray(t[String(i)])?t[String(i)].push(null):t[String(i)]=[null];else if(!o)if(a){const u=E.resolveCollectedValue(e),f=E.isFileInput(e)&&Array.isArray(u)?u:[u];Array.isArray(t[String(i)])?t[String(i)].push(...f):t[String(i)]=f}else if(E.isGroupedCheckable(e)){const u=e.getTarget(),h=(u instanceof HTMLInputElement?u.checked:!0)?e.getValue():null,g=String(i);h===null?g in t||(t[g]=null):t[g]===null||t[g]===void 0?t[g]=h:Array.isArray(t[g])?t[g].push(h):t[g]=[t[g],h]}else t[String(i)]=E.resolveCollectedValue(e);n&&p.warn("Haori",`Element cannot have both ${l.prefix}form-object and name attributes.`);for(const u of e.getChildElementFragments())E.getPartValues(u,t,r)}else if(n){const u={};for(const f of e.getChildElementFragments())E.getPartValues(f,u,r);Object.keys(u).length>0&&(t[String(n)]=u),s&&p.warn("Haori",`Element cannot have both ${l.prefix}form-list and ${l.prefix}form-object attributes.`)}else if(s){const u=[];let f=!1;for(const h of e.getChildElementFragments()){const g={};E.getPartValues(h,g,r),Object.keys(g).length>0?(f=!0,u.push(g)):r!==null&&u.push({})}(r===null||f)&&(t[String(s)]=u)}else for(const u of e.getChildElementFragments())E.getPartValues(u,t,r);return t}static setValues(e,t,r=!1){return E.setPartValues(e,t,r,!0)}static syncValues(e,t,r=!1){return E.setPartValues(e,t,r,!1)}static syncRowValues(e,t){return E.setPartValues(e,t,!1,!1,!0)}static resolveSyncValues(e,t){const r=e.getAttribute(`${l.prefix}form-arg`);if(!r)return t;const i=t[String(r)];return i&&typeof i=="object"&&!Array.isArray(i)?i:{}}static restoreInitialValues(e){const t=[];e instanceof HTMLFormElement&&t.push(e),e.querySelectorAll("form").forEach(i=>{t.push(i)});const r=[];for(const i of t){if(E.INITIAL_RESTORED_FORMS.has(i))continue;const n=T.get(i);if(!(n instanceof N))continue;const s=n.getRawBindingData();s&&(E.INITIAL_RESTORED_FORMS.add(i),r.push(E.syncValues(n,E.resolveSyncValues(n,s))))}return Promise.all(r).then(()=>{})}static isGroupedCheckable(e){const t=e.getTarget();return t instanceof HTMLInputElement?t.type==="radio"?!0:t.type!=="checkbox"?!1:t.value!=="true"&&t.value!=="false":!1}static isMultipleSelect(e){const t=e.getTarget();return t instanceof HTMLSelectElement&&t.multiple}static applyFragmentValue(e,t,r){return r?e.setValue(t):e.syncBindingValue(t)}static setPartValues(e,t,r=!1,i=!0,n=!1,s=new Map){const a=[],o=E.resolveFieldName(e),u=e.getAttribute(`${l.prefix}form-object`),f=e.getAttribute(`${l.prefix}form-list`),h=e.hasAttribute(`${l.prefix}form-list`),g=e.getAttribute(`${l.prefix}form-detach`);if(o){if(!g||r){const b=t[String(o)],S=n&&typeof b>"u"&&!E.isDeclarativeStateBound(e)?null:b;if(E.isFileInput(e))return(S===null||S==="")&&a.push(E.applyFragmentValue(e,null,i)),Promise.all(a).then(()=>{});if(h&&Array.isArray(S)&&!E.isGroupedCheckable(e)&&!E.isMultipleSelect(e)){const k=String(o),w=s.get(k)??0;s.set(k,w+1),a.push(E.applyFragmentValue(e,S[w]??null,i))}else typeof S>"u"||(Array.isArray(S)&&E.isGroupedCheckable(e)||Array.isArray(S)&&E.isMultipleSelect(e)||typeof S=="string"||typeof S=="number"||typeof S=="boolean"||S===null?a.push(E.applyFragmentValue(e,S,i)):a.push(E.applyFragmentValue(e,String(S),i)))}}else if(u){const b=t[String(u)];if(b&&typeof b=="object"){const R=new Map;for(const S of e.getChildElementFragments())a.push(E.setPartValues(S,b,r,i,n,R))}}else if(f){const b=t[String(f)];if(Array.isArray(b)){const R=e.getChildElementFragments();for(let S=0;S<R.length;S++){const k=R[S];b.length>S?a.push(E.setPartValues(k,b[S],r,i,n,new Map)):a.push(E.setPartValues(k,{},r,i,n,new Map))}}}else for(const b of e.getChildElementFragments())a.push(E.setPartValues(b,t,r,i,n,s));return Promise.all(a).then(()=>{})}static async reset(e){E.clearValues(e),await Promise.all([E.clearMessages(e),E.clearEachClones(e)]),await B.enqueue(()=>{const r=e.getTarget();if(r instanceof HTMLFormElement)r.reset();else{r.querySelectorAll("form").forEach(n=>n.reset());const i=r.parentElement;if(i){const n=r.nextElementSibling,s=document.createElement("form");s.appendChild(r),s.reset(),i.insertBefore(r,n)}}});const t=E.collectBindingTargetForms(e);for(const r of t){const i=E.getInitialBindingData(r);i&&await P.setBindingData(r.getTarget(),i)}E.syncValuesFromDom(e);for(const r of t){const i=E.getInitialBindingData(r);if(r.getRawBindingData()===null&&i===null)continue;const n=E.getValues(r),s=r.getAttribute(`${l.prefix}form-arg`),a={...i||{}};s?a[String(s)]=n:Object.assign(a,n),await P.setBindingData(r.getTarget(),a)}await P.evaluateAll(e)}static getInitialBindingData(e){const t=e.getInitialBindAttribute();return t===null?null:P.parseDataBind(t)}static syncValuesFromDom(e){const t=e.getTarget();(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&e.syncValue();for(const r of e.getChildElementFragments())E.syncValuesFromDom(r)}static collectBindingTargetForms(e){const t=e.getTarget(),r=[];t instanceof HTMLFormElement?r.push(t):r.push(...Array.from(t.querySelectorAll("form")));const i=[];for(const n of r){const s=T.get(n);s instanceof N&&i.push(s)}return i}static clearEachClones(e){const t=[],r=n=>{if(n.hasAttribute(`${l.prefix}each`))for(const s of n.getChildElementFragments()){const a=s.hasAttribute(`${l.prefix}each-before`),o=s.hasAttribute(`${l.prefix}each-after`);!a&&!o&&t.push(s.remove())}},i=n=>{r(n);for(const s of n.getChildElementFragments())i(s)};r(e);for(const n of e.getChildElementFragments())i(n);return Promise.all(t).then(()=>{})}static clearValues(e){e.clearValue();for(const t of e.getChildElementFragments())E.clearValues(t)}static clearMessages(e){return ke().clearMessages(e.getTarget())}static addErrorMessage(e,t,r){return E.addMessage(e,t,r,"error")}static addMessage(e,t,r,i){const n=[],s=ke(),a=s.addMessage,o=f=>typeof a=="function"?a.call(s,f,r,i):s.addErrorMessage(f,r),u=E.findFragmentsByKey(e,t);return u.forEach(f=>{n.push(o(f.getTarget()))}),u.length===0&&n.push(o(e.getTarget())),Promise.all(n).then(()=>{})}static findFragmentsByKey(e,t){return E.findFragmentByKeyParts(e,t.split("."))}static findFragmentByKeyParts(e,t){const r=[],i=t[0];if(t.length==1&&E.resolveFieldName(e)===i&&r.push(e),e.hasAttribute(`${l.prefix}form-object`))t.length>1&&e.getAttribute(`${l.prefix}form-object`)===i&&e.getChildElementFragments().forEach(s=>{r.push(...E.findFragmentByKeyParts(s,t.slice(1)))});else if(e.hasAttribute(`${l.prefix}form-list`)){if(t.length>1){const n=e.getAttribute(`${l.prefix}form-list`),s=i.lastIndexOf("["),a=i.lastIndexOf("]");if(s!==-1&&a!==-1&&s<a){const o=i.substring(0,s);if(n===o){const u=i.substring(s+1,a),f=Number(u);if(isNaN(f))p.error("Haori",`Invalid index: ${i}`);else{const h=e.getChildElementFragments().filter(g=>g.hasAttribute(`${l.prefix}row`));f<h.length&&r.push(...E.findFragmentByKeyParts(h[f],t.slice(1)))}}}}}else e.getChildElementFragments().forEach(n=>{r.push(...E.findFragmentByKeyParts(n,t))});return r}static getFormFragment(e){const t=e.getTarget();if(t instanceof HTMLFormElement||t instanceof HTMLElement&&t.hasAttribute(`${l.prefix}form`))return e;const r=e.getParent();return r?this.getFormFragment(r):null}};E.INITIAL_RESTORED_FORMS=new WeakSet,E.GROUP_SCOPE_IDS=new WeakMap,E.groupScopeSequence=0;let H=E;class M{static dispatch(e,t,r,i){const n=new CustomEvent(`haori:${t}`,{bubbles:i?.bubbles??!0,cancelable:i?.cancelable??!1,composed:i?.composed??!0,detail:r});return e.dispatchEvent(n)}static ready(e){M.dispatch(document,"ready",{version:e})}static importStart(e,t){M.dispatch(e,"importstart",{url:t,startedAt:performance.now()})}static importEnd(e,t,r,i){M.dispatch(e,"importend",{url:t,bytes:r,durationMs:performance.now()-i})}static importError(e,t,r){M.dispatch(e,"importerror",{url:t,error:r})}static bindChange(e,t,r,i="other"){const n=[],s=new Set(Object.keys(t||{})),a=new Set(Object.keys(r)),o=new Set([...s,...a]);for(const u of o){const f=t?.[u],h=r[u];f!==h&&n.push(u)}M.dispatch(e,"bindchange",{previous:t||{},next:r,changedKeys:n,reason:i})}static bindComplete(e,t=null,r="other"){M.dispatch(e,"bindcomplete",{bindArg:t,reason:r})}static eachUpdate(e,t,r,i){M.dispatch(e,"eachupdate",{added:t,removed:r,order:i,total:i.length})}static rowAdd(e,t,r,i){M.dispatch(e,"rowadd",{key:t,index:r,item:i})}static rowRemove(e,t,r){M.dispatch(e,"rowremove",{key:t,index:r})}static rowMove(e,t,r,i){M.dispatch(e,"rowmove",{key:t,from:r,to:i})}static show(e){M.dispatch(e,"show",{visible:!0})}static hide(e){M.dispatch(e,"hide",{visible:!1})}static fetchStart(e,t,r,i,n){M.dispatch(e,"fetchstart",{url:t,options:r||{},payload:i,startedAt:performance.now(),...n})}static fetchEnd(e,t,r,i){M.dispatch(e,"fetchend",{url:t,status:r,durationMs:performance.now()-i})}static fetchError(e,t,r,i,n){M.dispatch(e,"fetcherror",{url:t,status:i,error:r,durationMs:n?performance.now()-n:void 0})}static pollTimeout(e,t,r){M.dispatch(e,"polltimeout",{count:t,elapsedMs:r})}static pollStop(e,t,r,i){M.dispatch(e,"pollstop",{reason:t,count:r,elapsedMs:i})}}const ut={401:"unauthorized-redirect",403:"forbidden-redirect"};function ct(d,e){return d.replace(/\{\{([\s\S]+?)\}\}/g,(t,r)=>{try{const i=Y.evaluate(String(r).trim(),e);return i==null?"":String(i)}catch{return""}})}function dt(d,e){const t=d.getAttribute(e);if(t===null||t==="")return null;if(!t.includes("{{"))return t;const r=T.get(d),i=r instanceof N?r.getBindingData():{},n=ct(t,i);return n===""?null:n}function ht(d,e,t){const r=d.getAttribute(`${e}-return-param`);if(r===null||r==="")return t;try{if(new URL(t,window.location.href).searchParams.has(r))return t}catch{return t}const i=window.location.pathname+window.location.search+window.location.hash,n=`${encodeURIComponent(r)}=${encodeURIComponent(i)}`,s=t.indexOf("#"),a=s>=0?t.slice(s):"",o=s>=0?t.slice(0,s):t,u=o.includes("?")?"&":"?";return`${o}${u}${n}${a}`}function Qe(d){const e=ut[d];if(e===void 0||typeof document>"u")return!1;const t=`${l.prefix}${e}`,r=[];document.body&&r.push(document.body),document.documentElement&&r.push(document.documentElement);for(const i of r){const n=dt(i,t);if(n===null)continue;const s=ht(i,t,n);try{if(new URL(s,window.location.href).href===window.location.href)return!1}catch{}return window.location.href=s,!0}return!1}class Ze{static readParams(){const e={},t=window.location.search;return new URLSearchParams(t).forEach((i,n)=>{e[n]=i}),e}static isSafeLocalPath(e){const t=e.trim();if(t===""||t[0]!=="/"||t[1]==="/"||t[1]==="\\")return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return!1}}}const ft=["addErrorMessage","clearMessages","closeDialog","confirm","dialog","openDialog","toast"],pt="__haoriHistoryState__",we="data-haori-click-lock";function ce(){const e=globalThis.window?.Haori;return ft.every(r=>typeof e?.[r]=="function")?e:X}const gt=new Set(["GET","HEAD","OPTIONS"]);function Re(d){return gt.has(d.toUpperCase())}function mt(d,e){for(const[t,r]of Object.entries(e))r!==void 0&&(Array.isArray(r)?r.forEach(i=>{d.append(t,re(i))}):d.append(t,re(r)))}function re(d){if(d==null)return"";if(typeof d=="object"||typeof d=="function")try{return JSON.stringify(d)??""}catch{return""}return String(d)}function _e(d,e){const t=new URL(d,window.location.href),r=new URLSearchParams(t.search);return mt(r,e),t.search=r.toString(),t.toString()}function bt(d){if(d==null)return{payload:{},dropped:!1};if(typeof d=="string"){const e=d.trim();if(e==="")return{payload:{},dropped:!1};if(e.startsWith("{")){try{const t=JSON.parse(e);if(t!==null&&typeof t=="object"&&!Array.isArray(t))return{payload:t,dropped:!1}}catch{}return{payload:{},dropped:!0}}return e.includes("=")?{payload:Pe(new URLSearchParams(e)),dropped:!1}:{payload:{},dropped:!0}}if(d instanceof URLSearchParams)return{payload:Pe(d),dropped:!1};if(typeof FormData<"u"&&d instanceof FormData){const e={};let t=!1;for(const[r,i]of d.entries()){if(typeof i!="string"){t=!0;continue}et(e,r,i)}return{payload:e,dropped:t}}return{payload:{},dropped:!0}}function Pe(d){const e={};for(const[t,r]of d.entries())et(e,t,r);return e}function et(d,e,t){const r=d[e];r===void 0?d[e]=t:Array.isArray(r)?r.push(t):d[e]=[r,t]}function pe(d,e){if(Array.isArray(e)){const t=Array.isArray(d)?d.slice():[];let r=!1;return e.forEach((i,n)=>{i!=null&&(typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0||(t[n]=pe(t[n],i),r=!0))}),r?t:d}if(e!==null&&typeof e=="object"){const t=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};for(const[r,i]of Object.entries(e))t[r]=pe(t[r],i);return t}return e}function yt(d){const e=d?.body;return e==null?!1:typeof e=="string"?e!=="":!0}function vt(d,e){const t={...e||{}},r=(t.method||"GET").toUpperCase();if(l.runtime!=="demo"||Re(r))return{url:d,options:t,requestedMethod:r,effectiveMethod:r,normalized:!1};const{payload:i,dropped:n}=bt(t.body);let s=d;Object.keys(i).length>0&&(s=_e(s,i)),n&&p.warn("Haori",`The ${r} body cannot be converted into a query string and is dropped by the demo runtime normalization. Send the values with ${l.prefix}{event}-data / ${l.prefix}{event}-form, or use the embedded runtime.`),delete t.body,t.method="GET";const a=new Headers(t.headers||void 0);return a.delete("Content-Type"),t.headers=a,{url:s,options:t,requestedMethod:r,effectiveMethod:"GET",normalized:!0,queryString:new URL(s,window.location.href).search||void 0}}function Et(d){return d==null?null:typeof d=="string"?d:d instanceof URLSearchParams?d.toString():d instanceof FormData?Array.from(d.entries()).map(([e,t])=>t instanceof File?[e,{type:"file",name:t.name,size:t.size,mimeType:t.type}]:[e,String(t)]):String(d)}function ae(d){return d instanceof Blob?!0:Array.isArray(d)?d.some(ae):d!==null&&typeof d=="object"?Object.values(d).some(ae):!1}function At(d){return Object.values(d).some(e=>e instanceof Blob?!1:Array.isArray(e)?e.some(t=>!(t instanceof Blob)&&ae(t)):ae(e))}function de(d){return De(H.getValues(d))}function De(d){const e=r=>{if(r instanceof File)return r.name;if(r instanceof Blob)return"";if(Array.isArray(r))return r.map(e);if(r!==null&&typeof r=="object"){const i={};for(const[n,s]of Object.entries(r))i[n]=e(s);return i}return r},t={};for(const[r,i]of Object.entries(d))t[r]=e(i);return t}function St(d,e){const t=new Headers(e.headers||void 0),r=Array.from(t.entries()).sort(([i],[n])=>i.localeCompare(n));return JSON.stringify({url:d,method:String(e.method||"GET").toUpperCase(),headers:r,body:Et(e.body||null)})}const m=class m{constructor(e,t=null,r=null){this.reentrantBind=!1,this.suppressEmptyReplaceBind=!1,this.requestUserEditSequence=null,m.isElementFragment(e)?(this.options=m.buildOptions(e,t),this.eventType=t):(this.options=e,this.eventType=null),this.domEvent=r}static attrName(e,t,r=!1){return e?`${l.prefix}${e}-${t}`:r?`${l.prefix}fetch-${t}`:`${l.prefix}${t}`}static resolveDataParamString(e,t){return m.resolveDataParamStringDetailed(e,t).value}static resolveDataParamStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a)=>{const o=Y.evaluateDetailed(s??a??"",t);return r=r||o.unresolvedReference,o.value===null||o.value===void 0||Number.isNaN(o.value)?"":typeof o.value=="object"?encodeURIComponent(JSON.stringify(o.value)):encodeURIComponent(String(o.value))}),hasUnresolvedReference:r}}static isJsonStringContext(e,t){let r=!1,i=!1;for(let n=0;n<t;n+=1){const s=e[n];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}s==='"'&&(r=!r)}return r}static stringifyJsonTemplateValue(e){if(e===void 0||Number.isNaN(e))return"null";try{return JSON.stringify(e)??JSON.stringify(String(e))}catch{return JSON.stringify(String(e))}}static stringifyJsonTemplateStringContent(e){if(e==null||Number.isNaN(e))return"";const t=typeof e=="object"?m.stringifyJsonTemplateValue(e):String(e);return JSON.stringify(t).slice(1,-1)}static resolveDataJsonString(e,t){return m.resolveDataJsonStringDetailed(e,t).value}static resolveDataJsonStringDetailed(e,t){let r=!1;return{value:e.replace(m.DATA_PLACEHOLDER_REGEX,(n,s,a,o)=>{const u=Y.evaluateDetailed(s??a??"",t);return r=r||u.unresolvedReference,m.isJsonStringContext(e,o)?m.stringifyJsonTemplateStringContent(u.value):m.stringifyJsonTemplateValue(u.value)}),hasUnresolvedReference:r}}static resolveDataAttribute(e,t){return m.resolveDataAttributeDetailed(e,t).value}static resolveDataAttributeDetailed(e,t){const r=e.getRawAttribute(t),i=e.getAttributeEvaluation(t),n=i?.value??null,s=i?.hasUnresolvedReference??!1;if(n&&typeof n=="object"&&!Array.isArray(n))return{value:n,hasUnresolvedReference:s};if(typeof n!="string"||r===null)return{value:null,hasUnresolvedReference:s};const a=r.trim();if(m.SINGLE_PLACEHOLDER_REGEX.test(a))return{value:P.parseDataBind(n),hasUnresolvedReference:s};if(a.startsWith("{")||a.startsWith("[")){const u=m.resolveDataJsonStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(u.value),hasUnresolvedReference:s||u.hasUnresolvedReference}}const o=m.resolveDataParamStringDetailed(r,e.getBindingData());return{value:P.parseDataBind(o.value),hasUnresolvedReference:s||o.hasUnresolvedReference}}static buildOptions(e,t){const r={targetFragment:e};if(t){if(e.hasAttribute(m.attrName(t,"validate"))&&(r.valid=!0),e.hasAttribute(m.attrName(t,"confirm"))&&(r.confirmMessage=e.getAttribute(m.attrName(t,"confirm")).replace(/\\n/g,`
|
|
8
|
+
`)),e.hasAttribute(m.attrName(t,"data"))&&(r.dataAttrName=m.attrName(t,"data")),e.hasAttribute(m.attrName(t,"form"))){const A=e.getRawAttribute(m.attrName(t,"form"));if(A){const y=document.body.querySelector(A);y!==null?r.formFragment=H.getFormFragment(T.get(y)):p.error("Haori",`Form element not found: ${A} (${m.attrName(t,"form")})`)}else r.formFragment=H.getFormFragment(e)}else(t==="change"||t==="input")&&(r.formFragment=H.getFormFragment(e),r.formFragment===null&&m.isNamedInputFragment(e)&&(r.selfValueFragment=e));if(e.hasAttribute(`${l.prefix}${t}-before-run`)){const A=e.getRawAttribute(`${l.prefix}${t}-before-run`);try{r.beforeCallback=new Function("fetchUrl","fetchOptions",`
|
|
8
9
|
"use strict";
|
|
9
|
-
${
|
|
10
|
-
`)}catch(
|
|
11
|
-
${
|
|
12
|
-
);`)}catch{try{
|
|
13
|
-
${
|
|
14
|
-
`)}catch(
|
|
10
|
+
${A}
|
|
11
|
+
`)}catch(y){p.error("Haori",`Invalid before script: ${y}`)}}const w=m.attrName(t,"run");if(e.hasAttribute(w)){const A=String(e.getAttribute(w)??"");let y=null;try{y=new Function("event",`"use strict"; return (
|
|
12
|
+
${A}
|
|
13
|
+
);`)}catch{try{y=new Function("event",`"use strict";
|
|
14
|
+
${A}
|
|
15
|
+
`)}catch(D){p.error("Haori",`Invalid run script: ${D}`)}}y&&(r.runScript=y)}}const i=m.attrName(t,"fetch"),n=e.hasAttribute(i);if(n){const w=e.getAttributeEvaluation(i);w&&(r.fetchHasUnresolvedReference=w.hasUnresolvedReference,r.fetchUrl=w.hasUnresolvedReference?null:w.value)}const s={};if(t){const w=m.attrName(t,"fetch-method");if(e.hasAttribute(w)){const A=e.getAttributeEvaluation(w);A?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=A?.value}}else{const w=m.attrName(null,"method",!0);if(e.hasAttribute(w)){const A=e.getAttributeEvaluation(w);A?.hasUnresolvedReference?r.fetchHasUnresolvedReference=!0:s.method=A?.value}}if(t){const w=m.attrName(t,"fetch-headers");if(e.hasAttribute(w)){const A=e.getRawAttribute(w);try{s.headers=P.parseDataBind(A)}catch(y){p.error("Haori",`Invalid fetch headers: ${y}`)}}}else{const w=m.attrName(null,"headers",!0);if(e.hasAttribute(w)){const A=e.getRawAttribute(w);try{s.headers=P.parseDataBind(A)}catch(y){p.error("Haori",`Invalid fetch headers: ${y}`)}}}if(t){const w=m.attrName(t,"fetch-content-type");if(e.hasAttribute(w)){const A=e.getAttributeEvaluation(w);A?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":A?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let A=!1;s.headers&&typeof s.headers=="object"&&(A="Content-Type"in s.headers),A||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}else{const w=m.attrName(null,"content-type",!0);if(e.hasAttribute(w)){const A=e.getAttributeEvaluation(w);A?.hasUnresolvedReference&&(r.fetchHasUnresolvedReference=!0),s.headers={...s.headers,"Content-Type":A?.value}}else if(s.method&&s.method!=="GET"&&s.method!=="HEAD"&&s.method!=="OPTIONS"){let A=!1;s.headers&&typeof s.headers=="object"&&(A="Content-Type"in s.headers),A||(s.headers={...s.headers,"Content-Type":"application/json"})}else s.method&&(s.method==="GET"||s.method==="HEAD"||s.method==="OPTIONS")&&(s.headers={...s.headers,"Content-Type":"application/x-www-form-urlencoded"})}Object.keys(s).length>0&&(r.fetchOptions=s);const a=t?m.attrName(t,"bind"):m.attrName(null,"bind",!0);if(e.hasAttribute(a)){const w=e.getRawAttribute(a);if(w){const A=document.body.querySelectorAll(w);A.length>0?(r.bindFragments=[],A.forEach(y=>{const D=T.get(y);D&&r.bindFragments.push(D)})):p.error("Haori",`Bind element not found: ${w} (${a})`)}}const o=m.attrName(t,"bind-arg"),u=m.attrName(null,"arg",!0),f=m.attrName(null,"bind-arg",!0);t?e.hasAttribute(o)&&(r.bindArg=e.getRawAttribute(o)):e.hasAttribute(u)?r.bindArg=e.getRawAttribute(u):e.hasAttribute(f)&&(r.bindArg=e.getRawAttribute(f));const h=t?m.attrName(t,"bind-params"):m.attrName(null,"bind-params",!0);if(e.hasAttribute(h)){const w=e.getRawAttribute(h);r.bindParams=w.split("&").map(A=>A.trim())}const g=t?m.attrName(t,"bind-append"):m.attrName(null,"bind-append",!0);if(e.hasAttribute(g)){const w=e.getRawAttribute(g);r.bindAppendParams=w.split("&").map(A=>A.trim()).filter(Boolean)}const b=t?m.attrName(t,"bind-merge"):m.attrName(null,"bind-merge",!0);e.hasAttribute(b)&&(r.bindMerge=!0);const R=t?m.attrName(t,"bind-transform"):m.attrName(null,"bind-transform",!0);e.hasAttribute(R)&&(r.bindTransform=e.getRawAttribute(R));const S=t?m.attrName(t,"copy-params"):null;if(S&&e.hasAttribute(S)){const w=e.getRawAttribute(S);r.copyParams=w.split("&").map(A=>A.trim()).filter(Boolean)}if(t){if(e.hasAttribute(m.attrName(t,"adjust"))){const y=e.getRawAttribute(m.attrName(t,"adjust"));if(y){const D=document.body.querySelectorAll(y);D.length>0?(r.adjustFragments=[],D.forEach(I=>{const $=T.get(I);$&&r.adjustFragments.push($)})):p.error("Haori",`Adjust element not found: ${y} (${m.attrName(t,"adjust")})`)}if(e.hasAttribute(m.attrName(t,"adjust-value"))){const D=e.getRawAttribute(m.attrName(t,"adjust-value")),I=Number(D);isNaN(I)||(r.adjustValue=I)}}if(e.hasAttribute(m.attrName(t,"row-add"))&&(r.rowAdd=!0),e.hasAttribute(m.attrName(t,"row-remove"))&&(r.rowRemove=!0),e.hasAttribute(m.attrName(t,"row-prev"))&&(r.rowMovePrev=!0),e.hasAttribute(m.attrName(t,"row-next"))&&(r.rowMoveNext=!0),e.hasAttribute(`${l.prefix}${t}-after-run`)){const y=e.getRawAttribute(`${l.prefix}${t}-after-run`);try{r.afterCallback=new Function("response",`
|
|
15
16
|
"use strict";
|
|
16
|
-
${
|
|
17
|
-
`)}catch(
|
|
18
|
-
`)),e.hasAttribute(g.attrName(t,"toast"))){r.toastMessage=e.getAttribute(g.attrName(t,"toast"));const v=e.getRawAttribute(g.attrName(t,"toast-level")),C=["info","warning","error","success"].includes(v);r.toastLevel=C?v:null}if(e.hasAttribute(g.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(g.attrName(t,"redirect"));const v=g.attrName(t,"redirect-return-param");e.hasAttribute(v)&&(r.redirectReturnParam=e.getAttribute(v))}if(e.hasAttribute(g.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(g.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(g.attrName(t,"scroll"))),e.hasAttribute(g.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(g.attrName(t,"history"))),e.hasAttribute(g.attrName(t,"history-data"))&&(r.historyDataAttrName=g.attrName(t,"history-data")),e.hasAttribute(g.attrName(t,"history-form"))){const v=e.getRawAttribute(g.attrName(t,"history-form"));if(v){const R=document.body.querySelector(v);R!==null?r.historyFormFragment=A.getFormFragment(S.get(R)):p.error("Haori",`Form element not found: ${v} (${g.attrName(t,"history-form")})`)}else r.historyFormFragment=A.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(v=>{const R=g.attrName(t,v);if(!e.hasAttribute(R))return;const C=e.getRawAttribute(R),F=[];if(C)document.body.querySelectorAll(C).forEach(B=>{const z=S.get(B);z&&F.push(z)}),F.length===0&&p.error("Haori",`Element not found: ${C} (${R})`);else if(v==="open"||v==="close"){const L=e.getTarget().closest("dialog");L?F.push(S.get(L)):p.error("Haori",`Ancestor <dialog> not found (${R})`)}else F.push(e);if(F.length>0)switch(v){case"reset-before":r.resetBeforeFragments=F;break;case"reset":r.resetFragments=F;break;case"refetch":r.refetchFragments=F;break;case"click":r.clickFragments=F;break;case"copy":r.copyFragments=F;break;case"open":r.openFragments=F;break;case"close":r.closeFragments=F;break}});const b=g.attrName(t,"copy-source");if(e.hasAttribute(b)){const v=e.getRawAttribute(b);if(v){const R=document.body.querySelector(v);if(R!==null){const C=S.get(R);C?r.copySourceFragment=C:p.error("Haori",`Element is not managed by Haori: ${v} (${b})`)}else p.error("Haori",`Element not found: ${v} (${b})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(g.attrName(null,"data",!0))&&(r.dataAttrName=g.attrName(null,"data",!0)),e.hasAttribute(g.attrName(null,"form",!0)))){const E=e.getRawAttribute(g.attrName(null,"form",!0));if(E){const b=document.body.querySelector(E);b!==null?r.formFragment=A.getFormFragment(S.get(b)):p.error("Haori",`Form element not found: ${E} (${g.attrName(null,"fetch-form",!0)})`)}else r.formFragment=A.getFormFragment(e)}const H=t?g.attrName(t,"fetch-state"):g.attrName(null,"state",!0);if(e.hasAttribute(H)){const E=e.getRawAttribute(H),b=[];E?(document.body.querySelectorAll(E).forEach(R=>{const C=S.get(R);C&&b.push(C)}),b.length===0&&p.error("Haori",`Element not found: ${E} (${H})`)):b.push(e),b.length>0&&(r.fetchStateFragments=b)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null:!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new g(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const h=this.options.targetFragment?.getTarget()??null;try{const c=this.options.runScript.call(h,this.domEvent);c===!1&&this.domEvent&&this.domEvent.preventDefault(),c!=null&&typeof c.then=="function"&&await c}catch(c){p.error("Haori",`Run script execution error: ${c}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(h=>A.reset(h))),this.captureHistorySnapshots());const r=this.prepareFetchRequest(),i=r.payload;let n=r.url,s=r.options;if(this.options.beforeCallback){const h=this.options.beforeCallback(n||null,s||null);if(h!=null){if(h===!1||typeof h=="object"&&h.stop)return!1;typeof h=="object"&&(n="fetchUrl"in h?h.fetchUrl:n,s="fetchOptions"in h?h.fetchOptions:s)}}const a=Object.keys(i).length>0;if(n){const h={...s||{}},c=r.requestedMethod,m=r.effectiveMethod,y=r.transportMode==="query-get",T=r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:"query-get",url:n,payload:a?i:void 0,queryString:T}),this.options.targetFragment&&n){const I=performance.now(),H={runtime:u.runtime,requestedMethod:c,effectiveMethod:m,transportMode:y?"query-get":"http",...y?{queryString:T}:{}};return N.fetchStart(this.options.targetFragment.getTarget(),n,h,a?i:void 0,H),await this.injectFetchState("loading"),fetch(n,h).then(E=>this.handleFetchResult(E,n||void 0,I)).catch(async E=>{throw n&&N.fetchError(this.options.targetFragment.getTarget(),n,E),await this.injectFetchState("error",null,E instanceof Error?E.message:String(E)),E})}return fetch(n,h).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&a){const h=this.options.formFragment,c=h.getTarget(),m=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&m.add(this.options.targetFragment);const y=h.getBindingData();Object.assign(y,ve(i)),await x.setBindingData(c,y,m)}this.suppressEmptyReplaceBind=!a&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input");const o=a?ve(i):{},l=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(l)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(g.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(be))return!1;const r=t.hasAttribute(`${u.prefix}click-no-disabled`);return g.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(be,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(g.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(be),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=se();if(!e.ok)return je(e.status)||(this.options.targetFragment&&t&&N.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&N.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 n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>A.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new g(a,null).run())}),this.options.clickFragments&&this.options.clickFragments.length>0)for(const a of this.options.clickFragments){await x.evaluateAll(a);const o=a.getTarget();typeof o.click=="function"?o.click():o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.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?s.push(i.closeDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),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){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const h=new URLSearchParams(window.location.search).get(o);if(h!==null){const c=h.trim();qe.isSafeLocalPath(c)?a=c:p.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${h}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const l="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",l);return}const o=l=>{for(const[h,c]of Object.entries(l))c!=null&&(Array.isArray(c)?c.forEach(m=>a.searchParams.append(h,String(m))):typeof c=="object"?a.searchParams.set(h,JSON.stringify(c)):a.searchParams.set(h,String(c)))};i&&o(t),n&&o(r),history.pushState({[it]:!0},"",a.toString())}catch(s){p.error("Haori",`history.pushState failed: ${s}`)}}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=t?t.getTarget():document.body;await se().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await se().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const l=new Map,h=[];for(const c of a)if(c&&typeof c=="object"&&!Array.isArray(c)){const m=c.key,y=c.message,T=typeof m=="string"&&m.length>0?m:null,I=typeof y=="string"?y:y!=null?String(y):"";if(I.length===0)continue;if(T!==null){const H=l.get(T)??[];H.push(I),l.set(T,H)}else h.push(I)}else typeof c=="string"&&c.length>0&&h.push(c);for(const[c,m]of l)o.push({key:c,message:m.join(`
|
|
19
|
-
`)});for(const
|
|
20
|
-
`)}):typeof
|
|
21
|
-
`)}):typeof h=="string"&&o.push({key:l,message:h}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const l of o)l.key&&t?await A.addErrorMessage(t,l.key,l.message):await i(l.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!0;const t=this.findFirstInvalid(e);return t===null?!0:(t.reportValidity(),t.focus(),this.options.scrollOnError&&t.scrollIntoView({behavior:"smooth",block:"nearest"}),!1)}findFirstInvalid(e){let t=null;for(const r of e.getChildElementFragments().reverse()){const i=this.findFirstInvalid(r);i!==null&&(t=i)}return this.checkOne(e)?t:e.getTarget()}checkOne(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.checkValidity():!0}confirm(){const e=this.options.confirmMessage;return e==null?Promise.resolve(!0):se().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=Y.evaluate(this.options.bindTransform,{response:i})}catch(s){p.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${u.prefix}${this.eventType}-form.`);return}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const l=a[o],h=l&&typeof l=="object"&&!Array.isArray(l)?l:{};a[o]=this.mergeAppendBindingData(s,i,h)}else a[o]=i;n.push(x.setBindingData(s.getTarget(),a,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(x.setBindingData(s.getTarget(),o,new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{N.bindComplete(a.getTarget(),s)})})})}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return x.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?ae(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?ae(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,A.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=g.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{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 n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=u.runtime==="demo"&&!st(a),l=o?"GET":a;if(n.method=l,Object.keys(t).length>0&&te(t)){const c=s.get("Content-Type")||"";l!=="GET"&&l!=="HEAD"&&l!=="OPTIONS"&&/multipart\/form-data/i.test(c)?ut(t)&&p.warn("Haori",`A File value nested under ${u.prefix}form-object / ${u.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${u.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(l==="GET"||l==="HEAD"||l==="OPTIONS")Object.keys(t).length>0&&(i=ot(i,t));else if(Object.keys(t).length>0){const c=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(c)){s.delete("Content-Type");const m=new FormData;for(const[y,T]of Object.entries(t))T==null?m.append(y,""):T instanceof Blob?m.append(y,T):Array.isArray(T)?T.forEach(I=>{I instanceof Blob?m.append(y,I):m.append(y,String(I))}):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T));n.body=m}else if(/application\/x-www-form-urlencoded/i.test(c)){const m=new URLSearchParams;for(const[y,T]of Object.entries(t))T!==void 0&&(T===null?m.append(y,""):Array.isArray(T)?T.forEach(I=>m.append(y,String(I))):typeof T=="object"?m.append(y,JSON.stringify(T)):m.append(y,String(T)));n.body=m}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let h;return o&&(h=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:l,queryString:h,transportMode:o?"query-get":"http",signature:ct(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?ae(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?g.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return ae(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return p.error("Haori","Target fragment is not specified for row operation."),null;const e=this.options.targetFragment.closestByAttribute(`${u.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(x.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(`${u.prefix}each-before`)&&!i.hasAttribute(`${u.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()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return x.setBindingData(a,o,new Set,!1,!1)}))}};g.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,g.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,g.RUNNING_CLICK_TARGETS=new WeakSet;let K=g;class ht{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){je(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const d=class d{static isDeferredAttributeName(e){return d.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${u.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!d.isEvaluateAllExcludedAttributeName(e)&&d.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${u.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=S.get(e);return r instanceof M?r.hasAttribute(`${u.prefix}${d.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);d.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>d.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof M?t.push(d.evaluateAll(r)):r instanceof j&&t.push(d.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=d.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return d.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=d.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return d.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(`${u.prefix}fetch`)&&r.push(d.executeManagedFetch(e)),e.hasAttribute(`${u.prefix}import`)&&r.push(d.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof M&&r.push(d.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=d.getReactiveFetchState(t),i=K.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new K(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=d.getReactiveImportState(t),i=e.getAttributeEvaluation(`${u.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${u.prefix}importing`,""),N.importStart(t,n),ht.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return k.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${u.prefix}importing`),N.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const l=[];return t.childNodes.forEach(h=>{const c=S.get(h);c instanceof M?l.push(d.scan(c.getTarget())):c instanceof j&&l.push(d.evaluateText(c))}),Promise.all(l).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${u.prefix}importing`),N.importError(t,n,a),p.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,d.executeManagedImport(e)})}static scan(e){const t=S.get(e);return t?d.initializeElementFragment(t,!1):Promise.resolve()}static initializeFreshEachRow(e){return d.initializeElementFragment(e,!0).then(()=>{d.needsScheduledEvaluateAll(e)&&d.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return d.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():d.initializeElementAttributes(e).then(()=>{if(d.shouldSkipChildInitialization(e,t)){d.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof M?r.push(d.initializeElementFragment(i,t)):i instanceof j&&r.push(d.evaluateText(i))}),Promise.all(r).then(()=>{d.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 d.PRIORITY_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||d.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>d.setAttribute(e.getTarget(),i,n)))}for(const i of d.DEFERRED_ATTRIBUTE_SUFFIXES){const n=u.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>d.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>{})}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${u.prefix}if`);return e.hasAttribute(`${u.prefix}if`)&&d.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${u.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=S.get(e),s=d.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,l=null;switch(t){case`${u.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof M&&n.consumeSelfWrittenBind(r))break;n.setBindingData(d.parseDataBind(r))}break}case`${u.prefix}derive`:l=d.createDeriveInputSignature(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),o=d.evaluateDerive(n,r,n.getRawAttribute(`${u.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${u.prefix}derive-name`:l=d.createDeriveInputSignature(n,n.getRawAttribute(`${u.prefix}derive`),r),o=d.evaluateDerive(n,n.getRawAttribute(`${u.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${u.prefix}if`:a.push(d.evaluateIf(n));break;case`${u.prefix}each`:a.push(d.evaluateEach(n));break;case`${u.prefix}fetch`:a.push(d.executeManagedFetch(n));break;case`${u.prefix}import`:typeof r=="string"&&a.push(d.executeManagedImport(n));break;case`${u.prefix}url-param`:{const h=n.getAttribute(`${u.prefix}url-arg`),c=qe.readParams();if(h===null)a.push(d.setBindingData(e,c,new Set,!0));else{const m=n.getRawBindingData()||{};m[String(h)]=c,a.push(d.setBindingData(e,m,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(l),o.then(h=>{if(h)return d.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=S.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&N.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const l=s.getRawBindingData()??t;let h=n?s.setAttribute(`${u.prefix}bind`,JSON.stringify(l)):Promise.resolve();return e.tagName==="FORM"&&(h=h.then(()=>{const c=s.getRawBindingData()??t,m=s.getAttribute(`${u.prefix}form-arg`),y=m&&c[String(m)]&&typeof c[String(m)]=="object"&&!Array.isArray(c[String(m)])?c[String(m)]:m?{}:c;return A.syncValues(s,y)})),h=h.then(()=>d.evaluateAll(s,r)),h=h.then(()=>d.reevaluateReactiveSpecialAttributes(s,r)),h.then(()=>s.markBindingWorkEnd(),c=>{throw s.markBindingWorkEnd(),c})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=S.get(e);return r instanceof M?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=S.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=l=>{const h=l.getTarget();return h.id?`#${h.id}`:h.tagName.toLowerCase()},s=(l,h,c,m)=>{if(l)for(const y of Object.keys(l))y in i||(i[y]={value:l[y],source:n(h),kind:c,depth:m})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return U.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=S.get(e);if(r.isSkipMutationNodes())return;const i=S.get(t.nextSibling),n=S.get(t);n&&(r.insertBefore(n,i),n instanceof M?d.scan(n.getTarget()):n instanceof j&&d.evaluateText(n))}static removeNode(e){const t=S.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=S.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=S.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=d.getFormFragment(r);if(n){const s=A.getValues(n),a=n.getAttribute(`${u.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(d.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?d.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=d.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${u.prefix}derive`),n=e.hasAttribute(`${u.prefix}if`),s=e.hasAttribute(`${u.prefix}each`),a=e.getRawAttribute(`${u.prefix}derive`),o=e.getRawAttribute(`${u.prefix}derive-name`);let l=!1,h=!1,c=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const m=d.createDeriveInputSignature(e,a,o);m===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==m&&(r=r.then(()=>d.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(m)})))}return n&&(r=r.then(()=>d.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>d.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}c=d.createDescendantBindingSignature(e,"evaluateAll"),h=!0,l=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===c,d.logDerivedSubtreeProfileSnapshot(e,l?"skip-hit":"skip-miss")})),r.then(()=>{if(l)return;const m=[];return e.getChildren().forEach(y=>{if(y instanceof M){if(d.canSkipUnchangedNestedEach(y))return;m.push(d.evaluateAll(y,t))}else y instanceof j&&m.push(d.evaluateText(y))}),Promise.all(m).then(()=>{})}).then(()=>{h&&c!==null&&e.setDeriveSubtreeSignature(c)}))}static evaluateDerive(e,t=e.getRawAttribute(`${u.prefix}derive`),r=e.getRawAttribute(`${u.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=Y.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return d.createBindingSignature(i)===d.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${u.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=d.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const l=t.indexOf(o,s);s=l+o.length,!(l>0&&t[l-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${u.prefix}if`);if(d.isHiddenIfCondition(r))U.isEnabled()&&d.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{N.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof M?n.push(s.isMounted()?d.evaluateAll(s):d.scan(s.getTarget())):s instanceof j&&n.push(d.evaluateText(s))}),t.push(e.show().then(()=>{N.show(e.getTarget()),i||d.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${u.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new K(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=d.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},d.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=d.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):d.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${u.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await d.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${u.prefix}each-done`,""),d.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}d.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${u.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
17
|
+
${y}
|
|
18
|
+
`)}catch(D){p.error("Haori",`Invalid after script: ${D}`)}}if(e.hasAttribute(m.attrName(t,"dialog"))&&(r.dialogMessage=e.getAttribute(m.attrName(t,"dialog")).replace(/\\n/g,`
|
|
19
|
+
`)),e.hasAttribute(m.attrName(t,"toast"))){r.toastMessage=e.getAttribute(m.attrName(t,"toast"));const y=e.getRawAttribute(m.attrName(t,"toast-level")),I=["info","warning","error","success"].includes(y);r.toastLevel=I?y:null}if(e.hasAttribute(m.attrName(t,"redirect"))){r.redirectUrl=e.getAttribute(m.attrName(t,"redirect"));const y=m.attrName(t,"redirect-return-param");e.hasAttribute(y)&&(r.redirectReturnParam=e.getAttribute(y))}if(e.hasAttribute(m.attrName(t,"scroll-error"))&&(r.scrollOnError=!0),e.hasAttribute(m.attrName(t,"scroll"))&&(r.scrollTarget=e.getAttribute(m.attrName(t,"scroll"))),e.hasAttribute(m.attrName(t,"history"))&&(r.historyUrl=e.getAttribute(m.attrName(t,"history"))),e.hasAttribute(m.attrName(t,"history-data"))&&(r.historyDataAttrName=m.attrName(t,"history-data")),e.hasAttribute(m.attrName(t,"history-form"))){const y=e.getRawAttribute(m.attrName(t,"history-form"));if(y){const D=document.body.querySelector(y);D!==null?r.historyFormFragment=H.getFormFragment(T.get(D)):p.error("Haori",`Form element not found: ${y} (${m.attrName(t,"history-form")})`)}else r.historyFormFragment=H.getFormFragment(e)}["reset-before","reset","refetch","click","copy","open","close"].forEach(y=>{const D=m.attrName(t,y);if(!e.hasAttribute(D))return;const I=e.getRawAttribute(D),$=[];if(I)document.body.querySelectorAll(I).forEach(K=>{const U=T.get(K);U&&$.push(U)}),$.length===0&&p.error("Haori",`Element not found: ${I} (${D})`);else if(y==="open"||y==="close"){const O=e.getTarget().closest("dialog");O?$.push(T.get(O)):p.error("Haori",`Ancestor <dialog> not found (${D})`)}else $.push(e);if($.length>0)switch(y){case"reset-before":r.resetBeforeFragments=$;break;case"reset":r.resetFragments=$;break;case"refetch":r.refetchFragments=$;break;case"click":r.clickFragments=$;break;case"copy":r.copyFragments=$;break;case"open":r.openFragments=$;break;case"close":r.closeFragments=$;break}});const A=m.attrName(t,"copy-source");if(e.hasAttribute(A)){const y=e.getRawAttribute(A);if(y){const D=document.body.querySelector(y);if(D!==null){const I=T.get(D);I?r.copySourceFragment=I:p.error("Haori",`Element is not managed by Haori: ${y} (${A})`)}else p.error("Haori",`Element not found: ${y} (${A})`)}else r.copySourceFragment=e}}if(!t&&(e.hasAttribute(m.attrName(null,"data",!0))&&(r.dataAttrName=m.attrName(null,"data",!0)),e.hasAttribute(m.attrName(null,"form",!0)))){const w=e.getRawAttribute(m.attrName(null,"form",!0));if(w){const A=document.body.querySelector(w);A!==null?r.formFragment=H.getFormFragment(T.get(A)):p.error("Haori",`Form element not found: ${w} (${m.attrName(null,"fetch-form",!0)})`)}else r.formFragment=H.getFormFragment(e)}const k=t?m.attrName(t,"fetch-state"):m.attrName(null,"state",!0);if(e.hasAttribute(k)){const w=e.getRawAttribute(k),A=[];w?(document.body.querySelectorAll(w).forEach(D=>{const I=T.get(D);I&&A.push(I)}),A.length===0&&p.error("Haori",`Element not found: ${w} (${k})`)):A.push(e),A.length>0&&(r.fetchStateFragments=A)}return n&&(!r.bindFragments||r.bindFragments.length===0)&&(r.bindFragments=[e],r.defaultSelfBind=!0),r}static isNamedInputFragment(e){const t=e.getTarget();return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.getAttribute("name")!==null||e.hasAttribute(`${l.prefix}form-name`):!1}static isElementFragment(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.getTarget=="function"&&typeof t.getChildElementFragments=="function"}static resolveAutoFetchSignature(e){return new m(e,null).resolveFetchSignature()}run(){return this.runWithResult().then(()=>{})}markReentrantBind(){this.reentrantBind=!0}runWithResult(){return this.execute()}async execute(){const e=this.acquireExecutionLock();if(e===!1)return!1;try{if(Object.keys(this.options).length===0||this.options.formFragment&&this.validate(this.options.formFragment)===!1)return!1;if(this.options.runScript){const g=this.options.targetFragment?.getTarget()??null;try{const b=this.options.runScript.call(g,this.domEvent);b===!1&&this.domEvent&&this.domEvent.preventDefault(),b!=null&&typeof b.then=="function"&&await b}catch(b){p.error("Haori",`Run script execution error: ${b}`)}}if(!await this.confirm())return!1;this.options.resetBeforeFragments&&this.options.resetBeforeFragments.length>0&&(await Promise.all(this.options.resetBeforeFragments.map(g=>H.reset(g))),this.captureHistorySnapshots());const r=this.prepareFetchRequest();this.requestUserEditSequence=N.currentUserEditSequence();const i=r.payload;let n=r.url,s=r.options,a=!1,o=!1;if(this.options.beforeCallback){const g=this.options.beforeCallback(n||null,s||null);if(g!=null){if(g===!1||typeof g=="object"&&g.stop)return!1;typeof g=="object"&&(a="fetchUrl"in g,o="fetchOptions"in g,n=a?g.fetchUrl:n,s=o?g.fetchOptions:s)}}const u=Object.keys(i).length>0;if(n){const g=(s?.method||"GET").toUpperCase(),R=!a&&o&&r.transportMode==="query-get"&&yt(s)&&!Re(g)?r.baseUrl??n:n,S=vt(R,s);n=S.url;const k={...S.options},w=S.normalized?S.requestedMethod:r.requestedMethod,A=S.effectiveMethod,y=r.transportMode==="query-get"||S.normalized,D=S.queryString??r.queryString;if(y&&p.info("Haori demo fetch normalization",{runtime:l.runtime,requestedMethod:w,effectiveMethod:A,transportMode:"query-get",url:n,payload:u?i:void 0,queryString:D}),this.options.targetFragment&&n){const I=performance.now(),$={runtime:l.runtime,requestedMethod:w,effectiveMethod:A,transportMode:y?"query-get":"http",...y?{queryString:D}:{}};return M.fetchStart(this.options.targetFragment.getTarget(),n,k,u?i:void 0,$),await this.injectFetchState("loading"),fetch(n,k).then(O=>this.handleFetchResult(O,n||void 0,I)).catch(async O=>{throw n&&M.fetchError(this.options.targetFragment.getTarget(),n,O),await this.injectFetchState("error",null,O instanceof Error?O.message:String(O)),O})}return fetch(n,k).then(I=>this.handleFetchResult(I,n||void 0))}if((!this.options.bindFragments||this.options.bindFragments.length===0)&&this.options.formFragment&&u){const g=this.options.formFragment,b=g.getTarget(),R=new Set;e&&e.appliedDisabledAttribute&&this.options.targetFragment&&R.add(this.options.targetFragment);const S=g.getBindingData();Object.assign(S,De(i)),await P.setBindingData(b,S,R)}this.suppressEmptyReplaceBind=!u&&!this.options.formFragment&&(this.eventType==="change"||this.eventType==="input");const f=u?De(i):{},h=new Response(JSON.stringify(f),{headers:{"Content-Type":"application/json"}});return this.handleFetchResult(h)}finally{this.releaseExecutionLock(e)}}acquireExecutionLock(){if(this.eventType!=="click"||!this.options.targetFragment)return null;const t=this.options.targetFragment.getTarget();if(m.RUNNING_CLICK_TARGETS.has(t)||t.matches(":disabled")||t.hasAttribute("disabled")||t.hasAttribute(we))return!1;const r=t.hasAttribute(`${l.prefix}click-no-disabled`);return m.RUNNING_CLICK_TARGETS.add(t),t.setAttribute(we,""),r||t.setAttribute("disabled",""),{target:t,appliedDisabledAttribute:!r}}releaseExecutionLock(e){e&&(m.RUNNING_CLICK_TARGETS.delete(e.target),e.target.removeAttribute(we),e.appliedDisabledAttribute&&e.target.removeAttribute("disabled"))}async handleFetchResult(e,t,r){const i=ce();if(!e.ok)return Qe(e.status)||(this.options.targetFragment&&t&&M.fetchError(this.options.targetFragment.getTarget(),t,new Error(`${e.status} ${e.statusText}`),e.status,r),await this.handleFetchError(e),await this.injectFetchState("error",e.status,e.statusText||null)),!1;if(this.options.targetFragment&&t&&r&&M.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 n=[];n.push(this.bindResult(e)),n.push(this.adjust()),n.push(this.addRow()),n.push(this.removeRow()),n.push(this.movePrevRow()),n.push(this.moveNextRow()),await Promise.all(n),await this.injectFetchState("success",e.status,null),this.options.resetFragments&&this.options.resetFragments.length>0&&await Promise.all(this.options.resetFragments.map(a=>H.reset(a))),await this.copy();const s=[];if(this.options.refetchFragments&&this.options.refetchFragments.length>0&&this.options.refetchFragments.forEach(a=>{s.push(new m(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}))}if(this.options.openFragments&&this.options.openFragments.length>0&&this.options.openFragments.forEach(a=>{const o=a.getTarget();o instanceof HTMLElement?s.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?s.push(i.closeDialog(o)):p.error("Haori","Element is not an HTML element: ",o)}),await Promise.all(s),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){let a=this.options.redirectUrl;const o=this.options.redirectReturnParam;if(o){const f=new URLSearchParams(window.location.search).get(o);if(f!==null){const h=f.trim();Ze.isSafeLocalPath(h)?a=h:p.warn("Haori",`戻り先パスが安全なローカルパスではないため、既定の遷移先へフォールバックします: ${f}`)}}window.location.href=a}return!0}pushHistory(){const e=this.options.historyUrl!==void 0&&this.options.historyUrl!==null,t=this.resolveHistoryDataValues(),r=this.resolveHistoryFormValues(),i=t!=null,n=r!=null;if(!(!e&&!i&&!n))try{const s=e?this.options.historyUrl:window.location.pathname,a=new URL(s,window.location.href);if(a.origin!==window.location.origin){const u="history.pushState: cross-origin URL is not allowed: "+a.toString();p.error("Haori",u);return}const o=u=>{for(const[f,h]of Object.entries(u))h!=null&&(Array.isArray(h)?h.forEach(g=>a.searchParams.append(f,String(g))):typeof h=="object"?a.searchParams.set(f,JSON.stringify(h)):a.searchParams.set(f,String(h)))};i&&o(t),n&&o(r),history.pushState({[pt]:!0},"",a.toString())}catch(s){p.error("Haori",`history.pushState failed: ${s}`)}}async handleFetchError(e){let t=null;this.options.formFragment?t=this.options.formFragment:this.options.targetFragment&&(t=H.getFormFragment(this.options.targetFragment)||this.options.targetFragment);const r=t?t.getTarget():document.body;await ce().clearMessages(r);const i=async a=>{const o=t?t.getTarget():document.body;await ce().addErrorMessage(o,a)},n=()=>{if(!this.options.scrollOnError)return;const a=t?t.getTarget():document.body;(a.getAttribute("data-message-level")==="error"?a:a.parentElement?.getAttribute("data-message-level")==="error"?a.parentElement:a.querySelector('[data-message-level="error"]'))?.scrollIntoView({behavior:"smooth",block:"nearest"})};if((e.headers.get("Content-Type")||"").includes("application/json"))try{const a=await e.json(),o=[];if(Array.isArray(a)){const u=new Map,f=[];for(const h of a)if(h&&typeof h=="object"&&!Array.isArray(h)){const g=h.key,b=h.message,R=typeof g=="string"&&g.length>0?g:null,S=typeof b=="string"?b:b!=null?String(b):"";if(S.length===0)continue;if(R!==null){const k=u.get(R)??[];k.push(S),u.set(R,k)}else f.push(S)}else typeof h=="string"&&h.length>0&&f.push(h);for(const[h,g]of u)o.push({key:h,message:g.join(`
|
|
20
|
+
`)});for(const h of f)o.push({message:h})}else if(a&&typeof a=="object"){if(typeof a.message=="string"&&o.push({message:a.message}),Array.isArray(a.messages))for(const u of a.messages)typeof u=="string"&&o.push({message:u});if(a.errors&&typeof a.errors=="object")for(const[u,f]of Object.entries(a.errors))Array.isArray(f)?o.push({key:u,message:f.join(`
|
|
21
|
+
`)}):typeof f=="string"?o.push({key:u,message:f}):f!=null&&o.push({key:u,message:String(f)});if(o.length===0)for(const[u,f]of Object.entries(a))u==="message"||u==="messages"||u==="errors"||(Array.isArray(f)?o.push({key:u,message:f.join(`
|
|
22
|
+
`)}):typeof f=="string"&&o.push({key:u,message:f}))}if(o.length===0)return await i(`${e.status} ${e.statusText}`),n(),!1;for(const u of o)u.key&&t?await H.addErrorMessage(t,u.key,u.message):await i(u.message);return n(),!1}catch{}try{const a=await e.text();a&&a.trim().length>0?await i(a.trim()):await i(`${e.status} ${e.statusText}`)}catch{await i(`${e.status} ${e.statusText}`)}return n(),!1}validate(e){if(this.options.valid!==!0)return!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):ce().confirm(e)}bindResult(e){if(!this.options.bindFragments||this.options.bindFragments.length===0)return Promise.resolve();const t=e.headers.get("Content-Type")?.includes("application/json");return e.text().then(r=>{if(r==="")return;let i=t?JSON.parse(r):r;if(this.options.bindTransform)try{i=Y.evaluate(this.options.bindTransform,{response:i})}catch(s){p.error("Haori",`Invalid bind-transform: ${s}`)}if(this.options.bindParams){const s={};this.options.bindParams.forEach(a=>{i&&typeof i=="object"&&a in i&&(s[a]=i[a])}),i=s}if(this.suppressEmptyReplaceBind&&!this.options.bindArg&&!this.options.bindMerge&&i!==null&&typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0){p.warn("Haori",`Skipped binding because the input has no value to collect; the bind target would be replaced with an empty object. Add a name attribute to the input, or specify ${l.prefix}${this.eventType}-form.`);return}const n=[];if(this.options.bindArg)this.options.bindFragments.forEach(s=>{const a={...s.getRawBindingData()??{}},o=this.options.bindArg;if(i&&typeof i=="object"&&!Array.isArray(i)){const u=a[o],f=u&&typeof u=="object"&&!Array.isArray(u)?u:{};a[o]=this.mergeAppendBindingData(s,i,f)}else a[o]=i;n.push(P.setBindingData(s.getTarget(),this.restoreUserEditsAfterRequest(s,a),new Set,this.reentrantBind&&s.isExecutingBindingWork()))});else if(typeof i=="string"){if(this.options.defaultSelfBind){p.warn("Haori","string data is not bound because no bind target was specified.");return}return p.error("Haori","string data cannot be bound without a bindArg."),Promise.reject(new Error("string data cannot be bound without a bindArg."))}else this.options.bindFragments.forEach(s=>{const a=this.mergeAppendBindingData(s,i),o=this.options.bindMerge?{...s.getRawBindingData()??{},...a}:a;n.push(P.setBindingData(s.getTarget(),this.restoreUserEditsAfterRequest(s,o),new Set,this.reentrantBind&&s.isExecutingBindingWork()))});return Promise.all(n).then(()=>{const s=this.options.bindArg??null;this.options.bindFragments.forEach(a=>{M.bindComplete(a.getTarget(),s)})})})}restoreUserEditsAfterRequest(e,t){const r=this.requestUserEditSequence;if(r===null||!(e.getTarget()instanceof HTMLFormElement))return t;const i=H.getValuesEditedAfter(e,r);if(Object.keys(i).length===0)return t;const n=e.getAttribute(`${l.prefix}form-arg`);if(n){const s=String(n),a=t[s],o=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{...t,[s]:pe(o,i)}}return pe(t,i)}mergeAppendBindingData(e,t,r=e.getBindingData()){if(!this.options.bindAppendParams||this.options.bindAppendParams.length===0)return t;const i={...t},n=r;for(const s of this.options.bindAppendParams){const a=i[s],o=n[s];Array.isArray(o)&&Array.isArray(a)&&(i[s]=o.concat(a))}return i}copy(){if(!this.options.copyFragments||this.options.copyFragments.length===0)return Promise.resolve();const e=this.resolveCopySourceData(),t=this.pickCopyData(e),r=this.options.copyFragments.map(i=>{const n={...i.getBindingData(),...t};return P.setBindingData(i.getTarget(),n)});return Promise.all(r).then(()=>{})}resolveCopySourceData(){return this.options.copySourceFragment?this.options.copySourceFragment.getTarget().tagName==="FORM"?de(this.options.copySourceFragment):{...this.options.copySourceFragment.getBindingData()}:this.options.formFragment?de(this.options.formFragment):this.options.targetFragment?{...this.options.targetFragment.getBindingData()}:{}}buildPayload(){return this.buildPayloadResolution().payload}buildPayloadResolution(){const e={};let t=!1;const r=this.options.formFragment??this.options.selfValueFragment;if(r&&Object.assign(e,H.getValues(r)),this.options.data&&typeof this.options.data=="object"&&Object.assign(e,this.options.data),this.options.targetFragment&&this.options.dataAttrName){const i=m.resolveDataAttributeDetailed(this.options.targetFragment,this.options.dataAttrName);t=t||i.hasUnresolvedReference,i.value&&Object.assign(e,i.value)}return{payload:e,hasUnresolvedReference:t}}resolveFetchSignature(){const e=this.prepareFetchRequest();return{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,baseUrl:null,options:null,payload:t,hasUnresolvedReference:r,requestedMethod:"GET",effectiveMethod:"GET",transportMode:"http",signature:null};let i=this.options.fetchUrl;const n={...this.options.fetchOptions||{}},s=new Headers(n.headers||void 0),a=(n.method||"GET").toUpperCase(),o=l.runtime==="demo"&&!Re(a),u=o?"GET":a;if(n.method=u,Object.keys(t).length>0&&ae(t)){const h=s.get("Content-Type")||"";u!=="GET"&&u!=="HEAD"&&u!=="OPTIONS"&&/multipart\/form-data/i.test(h)?At(t)&&p.warn("Haori",`A File value nested under ${l.prefix}form-object / ${l.prefix}form-list cannot be sent. Place file inputs at the top level of the collected form values.`):p.warn("Haori",`A File value cannot be sent without ${l.prefix}fetch-content-type="multipart/form-data" and a body method such as POST.`)}if(u==="GET"||u==="HEAD"||u==="OPTIONS")Object.keys(t).length>0&&(i=_e(i,t));else if(Object.keys(t).length>0){const h=s.get("Content-Type")||"";if(/multipart\/form-data/i.test(h)){s.delete("Content-Type");const g=new FormData;for(const[b,R]of Object.entries(t))R==null?g.append(b,""):R instanceof Blob?g.append(b,R):Array.isArray(R)?R.forEach(S=>{S instanceof Blob?g.append(b,S):g.append(b,re(S))}):g.append(b,re(R));n.body=g}else if(/application\/x-www-form-urlencoded/i.test(h)){const g=new URLSearchParams;for(const[b,R]of Object.entries(t))R!==void 0&&(Array.isArray(R)?R.forEach(S=>g.append(b,re(S))):g.append(b,re(R)));n.body=g}else s.set("Content-Type","application/json"),n.body=JSON.stringify(t)}n.headers=s;let f;return o&&(f=new URL(i,window.location.href).search||void 0,s.delete("Content-Type")),{url:i,baseUrl:this.options.fetchUrl,options:n,payload:t,hasUnresolvedReference:!1,requestedMethod:a,effectiveMethod:u,queryString:f,transportMode:o?"query-get":"http",signature:St(i,n)}}captureHistorySnapshots(){this.options.targetFragment&&this.options.historyDataAttrName?this.historyDataSnapshot=m.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.historyDataSnapshot=void 0,this.historyFormSnapshot=this.options.historyFormFragment?de(this.options.historyFormFragment):void 0}resolveHistoryDataValues(){return this.historyDataSnapshot!==void 0?this.historyDataSnapshot:this.options.targetFragment&&this.options.historyDataAttrName?m.resolveDataAttribute(this.options.targetFragment,this.options.historyDataAttrName):this.options.historyData}resolveHistoryFormValues(){if(this.historyFormSnapshot!==void 0)return this.historyFormSnapshot;if(this.options.historyFormFragment)return de(this.options.historyFormFragment)}pickCopyData(e){if(!this.options.copyParams||this.options.copyParams.length===0)return e;const t=new Set,r=new Set;this.options.copyParams.forEach(s=>{const a=s.trim();if(a){if(a.startsWith("!")){const o=a.slice(1).trim();o&&r.add(o);return}t.add(a)}});const i={};return(t.size>0?Array.from(t):Object.keys(e)).forEach(s=>{s in e&&(r.has(s)||(i[s]=e[s]))}),i}adjust(){if(!this.options.adjustFragments||this.options.adjustFragments.length===0)return Promise.resolve();const e=this.options.adjustValue??0,t=[];for(const r of this.options.adjustFragments){let i=r.getValue();(i==null||i==="")&&(i="0");let n=Number(i);isNaN(n)&&(n=0),n+=e,t.push(r.setValue(String(n)))}return Promise.all(t).then(()=>{})}getRowFragment(){if(!this.options.targetFragment)return 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)}resolveRowContainer(e){const t=this.options.targetFragment;if(!t)return p.error("Haori","Target fragment is not specified for row operation."),null;const r=m.attrName(this.eventType,e),i=t.getRawAttribute(r);if(i!==null&&i.trim()!==""){const s=document.querySelector(i);if(s===null)return p.error("Haori",`Row container not found: ${i} (${r})`),null;const a=T.get(s);return a instanceof N?a.hasAttribute(`${l.prefix}each`)?a:(p.error("Haori",`Row container must have ${l.prefix}each: ${i} (${r})`),null):(p.error("Haori",`Row container is not initialized: ${i} (${r})`),null)}const n=this.getRowFragment();return n?n.getParent():null}static resolveEachArray(e){const t=e.getRawAttribute(`${l.prefix}each`);if(t===null)return p.error("Haori",`Row container has no ${l.prefix}each expression.`),null;const r=t.trim().split(".");if(!(r.length>0&&r.every(o=>/^[A-Za-z_$][\w$]*$/.test(o))))return p.error("Haori",`Row operations require a plain identifier path for ${l.prefix}each (got: ${t}).`),null;let n=e,s=null;for(;n;){const o=n.getRawBindingData();if(o&&r[0]in o){s=o;break}n=n.getParent()}if(!n||!s)return p.error("Haori",`Binding data owner not found for ${l.prefix}each="${t}".`),null;let a=s;for(const o of r){if(a===null||typeof a!="object"||Array.isArray(a)){a=void 0;break}a=a[o]}return Array.isArray(a)?{owner:n,ownerData:s,array:a,path:r}:(p.error("Haori",`${l.prefix}each="${t}" does not resolve to an array.`),null)}static withPathValue(e,t,r){const i={...e};let n=i;for(let s=0;s<t.length-1;s+=1){const a=t[s],u={...n[a]};n[a]=u,n=u}return n[t[t.length-1]]=r,i}static getRowFragments(e){return e.getChildElementFragments().filter(t=>!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`))}addRow(){return this.options.rowAdd!==!0?Promise.resolve():this.spliceRows("row-add",(e,t)=>(e.splice(t+1,0,{}),!0))}removeRow(){if(this.options.rowRemove!==!0)return Promise.resolve();const e=this.options.targetFragment?.hasAttribute(m.attrName(this.eventType,"row-remove-empty"));return this.spliceRows("row-remove",(t,r)=>r<0||r>=t.length||!e&&t.length<=1?!1:(t.splice(r,1),!0))}movePrevRow(){return this.options.rowMovePrev!==!0?Promise.resolve():this.spliceRows("row-prev",(e,t)=>{if(t<=0||t>=e.length)return!1;const[r]=e.splice(t,1);return e.splice(t-1,0,r),!0})}moveNextRow(){return this.options.rowMoveNext!==!0?Promise.resolve():this.spliceRows("row-next",(e,t)=>{if(t<0||t>=e.length-1)return!1;const[r]=e.splice(t,1);return e.splice(t+1,0,r),!0})}spliceRows(e,t){const r=this.resolveRowContainer(e);if(!r)return Promise.reject(new Error("Row container not found."));const i=m.resolveEachArray(r);if(!i)return Promise.reject(new Error("Row array not resolved."));const n=this.options.targetFragment,s=n?n.closestByAttribute(`${l.prefix}row`):null,a=m.getRowFragments(r),o=s?a.indexOf(s):a.length-1,u=i.array.slice();return t(u,o)?P.setBindingData(i.owner.getTarget(),m.withPathValue(i.ownerData,i.path,u)):Promise.resolve()}async injectFetchState(e,t=null,r=null){const i=this.options.fetchStateFragments;if(!i||i.length===0)return;const n={status:e,loading:e==="loading",success:e==="success",error:e==="error",statusCode:t,message:r};await Promise.all(i.map(s=>{const a=s.getTarget(),o={...s.getRawBindingData()??{},_fetch:n};return P.setBindingData(a,o,new Set,!1,!1)}))}};m.DATA_PLACEHOLDER_REGEX=/\{\{\{([\s\S]+?)\}\}\}|\{\{([\s\S]+?)\}\}/g,m.SINGLE_PLACEHOLDER_REGEX=/^(\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\})$/,m.RUNNING_CLICK_TARGETS=new WeakSet;let G=m;class wt{static async load(e,t){let r;try{r=await fetch(e,t)}catch(n){throw p.error("[Haori]","Failed to fetch import source:",e,n),new Error(`Failed to fetch: ${e}`)}if(!r.ok){Qe(r.status);const n=`${r.status} ${r.statusText}`;throw p.error("[Haori]","Import HTTP error:",e,n),new Error(`Failed to load ${e}: ${n}`)}let i;try{i=await r.text()}catch(n){throw p.error("[Haori]","Failed to read response text:",e,n),new Error(`Failed to read response from: ${e}`)}try{const s=new DOMParser().parseFromString(i,"text/html");return s&&s.body?s.body.innerHTML:(p.warn("[Haori]","No body found in imported document:",e),i)}catch(n){return p.error("[Haori]","Failed to parse imported HTML:",e,n),i}}}const c=class c{static isDeferredAttributeName(e){return c.DEFERRED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static isEvaluateAllExcludedAttributeName(e){return c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES.some(t=>e===`${l.prefix}${t}`)}static shouldReevaluateAttribute(e,t){return t!==null&&!c.isEvaluateAllExcludedAttributeName(e)&&c.ATTRIBUTE_PLACEHOLDER_REGEX.test(t)}static getAliasedAttributeName(e){const t=`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}`;return!e.startsWith(t)||e.length<=t.length?null:e.slice(t.length)}static isAliasedAttributeReflection(e,t){const r=T.get(e);return r instanceof N?r.hasAttribute(`${l.prefix}${c.ATTRIBUTE_ALIAS_SUFFIX}${t}`):!1}static reevaluateInterpolatedAttributes(e){let t=Promise.resolve();for(const r of e.getAttributeNames()){const i=e.getRawAttribute(r);c.shouldReevaluateAttribute(r,i)&&(t=t.then(()=>c.setAttribute(e.getTarget(),r,i)))}return t.then(()=>{})}static reevaluateChildren(e){const t=[];return e.getChildren().forEach(r=>{r instanceof N?t.push(c.evaluateAll(r)):r instanceof z&&t.push(c.evaluateText(r))}),Promise.all(t).then(()=>{})}static getReactiveFetchState(e){const t=c.REACTIVE_FETCH_STATES.get(e);if(t)return t;const r={lastSignature:null,running:!1,rerunRequested:!1};return c.REACTIVE_FETCH_STATES.set(e,r),r}static getReactiveImportState(e){const t=c.REACTIVE_IMPORT_STATES.get(e);if(t)return t;const r={lastUrl:null,running:!1,rerunRequested:!1};return c.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(c.executeManagedFetch(e)),e.hasAttribute(`${l.prefix}import`)&&r.push(c.executeManagedImport(e)),e.getChildren().forEach(i=>{i instanceof N&&r.push(c.reevaluateReactiveSpecialAttributes(i,t))}),Promise.all(r).then(()=>{})}static executeManagedFetch(e){const t=e.getTarget(),r=c.getReactiveFetchState(t),i=G.resolveAutoFetchSignature(e);if(r.running)return(i.hasUnresolvedReference||i.signature!==r.lastSignature)&&(r.rerunRequested=!0),Promise.resolve();if(i.hasUnresolvedReference||i.signature===null)return r.lastSignature=null,Promise.resolve();if(r.lastSignature===i.signature)return Promise.resolve();r.lastSignature=i.signature,r.running=!0;const n=new G(e,null);return n.markReentrantBind(),n.runWithResult().then(()=>{}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedFetch(e)})}static executeManagedImport(e){const t=e.getTarget(),r=c.getReactiveImportState(t),i=e.getAttributeEvaluation(`${l.prefix}import`),n=i&&!i.hasUnresolvedReference&&typeof i.value=="string"&&i.value!==""?i.value:null;if(r.running)return n!==r.lastUrl&&(r.rerunRequested=!0),Promise.resolve();if(n===null)return r.lastUrl=null,Promise.resolve();if(r.lastUrl===n)return Promise.resolve();r.lastUrl=n,r.running=!0;const s=performance.now();return t.setAttribute(`${l.prefix}importing`,""),M.importStart(t,n),wt.load(n).then(a=>{const o=new TextEncoder().encode(a).length;return B.enqueue(()=>{t.innerHTML=a}).then(()=>{if(t.removeAttribute(`${l.prefix}importing`),M.importEnd(t,n,o,s),!document.body.hasAttribute("data-haori-ready")){const u=[];return t.childNodes.forEach(f=>{const h=T.get(f);h instanceof N?u.push(c.scan(h.getTarget())):h instanceof z&&u.push(c.evaluateText(h))}),Promise.all(u).then(()=>{})}})}).catch(a=>{t.removeAttribute(`${l.prefix}importing`),M.importError(t,n,a),p.error("[Haori]","Failed to import HTML:",n,a)}).finally(()=>{if(r.running=!1,r.rerunRequested)return r.rerunRequested=!1,c.executeManagedImport(e)})}static scan(e){const t=T.get(e);return t?c.initializeElementFragment(t,!1).then(()=>H.restoreInitialValues(e)):Promise.resolve()}static initializeFreshEachRow(e){return c.initializeElementFragment(e,!0).then(()=>{c.needsScheduledEvaluateAll(e)&&c.scheduleEvaluateAll(e)})}static initializeElementFragment(e,t){return c.syncMountedState(e),t&&e.isFreshInitializationSkippable()?Promise.resolve():c.initializeElementAttributes(e).then(()=>{if(c.shouldSkipChildInitialization(e,t)){c.refreshDerivedSubtreeSignature(e);return}const r=[];return e.getChildren().forEach(i=>{i instanceof N?r.push(c.initializeElementFragment(i,t)):i instanceof z&&r.push(c.evaluateText(i))}),Promise.all(r).then(()=>{c.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 c.PRIORITY_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>c.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}for(const i of e.getAttributeNames()){if(r.has(i)||c.isDeferredAttributeName(i))continue;const n=e.getRawAttribute(i);n!==null&&(t=t.then(()=>c.setAttribute(e.getTarget(),i,n)))}for(const i of c.DEFERRED_ATTRIBUTE_SUFFIXES){const n=l.prefix+i;e.hasAttribute(n)&&(t=t.then(()=>c.setAttribute(e.getTarget(),n,e.getRawAttribute(n))),r.add(n))}return t.then(()=>H.prepareFormName(e))}static shouldSkipChildInitialization(e,t){const r=e.getAttribute(`${l.prefix}if`);return e.hasAttribute(`${l.prefix}if`)&&c.isHiddenIfCondition(r)?!0:t&&e.hasAttribute(`${l.prefix}each`)}static setAttribute(e,t,r,i=!1){const n=T.get(e),s=c.getAliasedAttributeName(t);if(s!==null)return r===null?n.removeAliasedAttribute(t,s):n.setAliasedAttribute(t,s,r,i);const a=[];let o=null,u=null;switch(t){case`${l.prefix}bind`:{if(r===null)n.clearBindingDataCache(),n.setBindingData({});else{if(i&&n instanceof N&&n.consumeSelfWrittenBind(r))break;n.setBindingData(c.parseDataBind(r))}break}case`${l.prefix}derive`:u=c.createDeriveInputSignature(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),o=c.evaluateDerive(n,r,n.getRawAttribute(`${l.prefix}derive-name`)),a.push(o.then(()=>{}));break;case`${l.prefix}derive-name`:u=c.createDeriveInputSignature(n,n.getRawAttribute(`${l.prefix}derive`),r),o=c.evaluateDerive(n,n.getRawAttribute(`${l.prefix}derive`),r),a.push(o.then(()=>{}));break;case`${l.prefix}if`:a.push(c.evaluateIf(n));break;case`${l.prefix}each`:a.push(c.evaluateEach(n));break;case`${l.prefix}fetch`:a.push(c.executeManagedFetch(n));break;case`${l.prefix}import`:typeof r=="string"&&a.push(c.executeManagedImport(n));break;case`${l.prefix}url-param`:{const f=n.getAttribute(`${l.prefix}url-arg`),h=Ze.readParams();if(f===null)a.push(c.setBindingData(e,h,new Set,!0));else{const g=n.getRawBindingData()||{};g[String(f)]=h,a.push(c.setBindingData(e,g,new Set,!0))}break}}return r===null?a.push(n.removeAttribute(t)):a.push(n.setAttribute(t,r,i)),Promise.all(a).then(()=>{if(o!==null)return n.setDeriveInputSignature(u),o.then(f=>{if(f)return c.reevaluateChildren(n)})}).then(()=>{})}static setBindingData(e,t,r=new Set,i=!1,n=!0){const s=T.get(e),a=s.getRawBindingData();s.setBindingData(t),n&&M.bindChange(e,a,t,"manual");const o=()=>{s.markBindingWorkStart();const u=s.getRawBindingData()??t;let f=n?s.setAttribute(`${l.prefix}bind`,JSON.stringify(u)):Promise.resolve();return e.tagName==="FORM"&&(f=f.then(()=>{const h=s.getRawBindingData()??t;return H.syncValues(s,H.resolveSyncValues(s,h))})),f=f.then(()=>c.evaluateAll(s,r)),f=f.then(()=>c.reevaluateReactiveSpecialAttributes(s,r)),f.then(()=>s.markBindingWorkEnd(),h=>{throw s.markBindingWorkEnd(),h})};return i?o():s.enqueueBindingWork(o)}static getBindingData(e,t={}){const r=T.get(e);return r instanceof N?t.resolved?r.getBindingData():r.getRawBindingData():null}static dumpScope(e){const t=T.get(e);if(!t)return{resolved:{},sources:{}};const r=t.getBindingData(),i={},n=u=>{const f=u.getTarget(),h=c.resolveElementId(f);return h!==""?`#${h}`:f.tagName.toLowerCase()},s=(u,f,h,g)=>{if(u)for(const b of Object.keys(u))b in i||(i[b]={value:u[b],source:n(f),kind:h,depth:g})};let a=t,o=0;for(;a;)a!==t&&s(a.getRawDerivedBindingData(),a,"derive",o),s(a.getRawBindingData(),a,"bind",o),a=a.getParent(),o+=1;return W.isEnabled()&&p.info("[Haori]","scope dump for",e,{resolved:r,sources:i}),{resolved:r,sources:i}}static parseDataBind(e){if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return p.error("[Haori]","Invalid JSON in data-bind:",t),{}}else{const t=new URLSearchParams(e),r={};for(const[i,n]of t.entries())r[i]!==void 0?Array.isArray(r[i])?r[i].push(n):r[i]=[r[i],n]:r[i]=n;return r}}static addNode(e,t){const r=T.get(e);if(r.isSkipMutationNodes())return;const i=T.get(t.nextSibling),n=T.get(t);n&&(r.insertBefore(n,i),n instanceof N?c.scan(n.getTarget()):n instanceof z&&c.evaluateText(n))}static removeNode(e){const t=T.get(e);if(t){const r=t.getParent();if(r&&r.isSkipMutationNodes())return;t.remove()}}static changeText(e,t){const r=T.get(e);r&&r.setContent(t)}static changeValue(e,t){const r=T.get(e);if(r.getValue()===t)return Promise.resolve();const i=[];i.push(r.setValue(t));const n=c.getFormFragment(r);if(n){const s=H.getValues(n),a=n.getAttribute(`${l.prefix}form-arg`);let o;a?(o=n.getRawBindingData(),o||(o={}),o[String(a)]=s):o=s,i.push(c.setBindingData(n.getTarget(),o))}return Promise.all(i).then(()=>{})}static getFormFragment(e){if(e.getTarget()instanceof HTMLFormElement)return e;const t=e.getParent();return t?c.getFormFragment(t):null}static evaluateAll(e,t=new Set){if(t.has(e))return Promise.resolve();let r=c.reevaluateInterpolatedAttributes(e);const i=e.hasAttribute(`${l.prefix}derive`),n=e.hasAttribute(`${l.prefix}if`),s=e.hasAttribute(`${l.prefix}each`),a=e.getRawAttribute(`${l.prefix}derive`),o=e.getRawAttribute(`${l.prefix}derive-name`);let u=!1,f=!1,h=null;if(!i&&e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),!i&&e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),i){const g=c.createDeriveInputSignature(e,a,o);g===null?(e.getDeriveInputSignature()!==null&&e.setDeriveInputSignature(null),r=r.then(()=>c.evaluateDerive(e,a,o).then(()=>{}))):e.getDeriveInputSignature()!==g&&(r=r.then(()=>c.evaluateDerive(e,a,o).then(()=>{e.setDeriveInputSignature(g)})))}return n&&(r=r.then(()=>c.evaluateIf(e))),s?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>c.evaluateEach(e))):n?(e.getDeriveSubtreeSignature()!==null&&e.setDeriveSubtreeSignature(null),r.then(()=>{})):(i&&(r=r.then(()=>{if(!c.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}h=c.createDescendantBindingSignature(e,"evaluateAll"),f=!0,u=e.getDeriveSubtreeSignature()!==null&&e.getDeriveSubtreeSignature()===h,c.logDerivedSubtreeProfileSnapshot(e,u?"skip-hit":"skip-miss")})),r.then(()=>{if(u)return;const g=[];return e.getChildren().forEach(b=>{if(b instanceof N){if(c.canSkipUnchangedNestedEach(b))return;g.push(c.evaluateAll(b,t))}else b instanceof z&&g.push(c.evaluateText(b))}),Promise.all(g).then(()=>{})}).then(()=>{f&&h!==null&&e.setDeriveSubtreeSignature(h)}))}static evaluateDerive(e,t=e.getRawAttribute(`${l.prefix}derive`),r=e.getRawAttribute(`${l.prefix}derive-name`)){const i=e.getRawDerivedBindingData(),n=typeof r=="string"?r.trim():"";if(!t||n==="")return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const s=Y.evaluateDetailed(t,e.getBindingData());if(s.unresolvedReference)return i===null?Promise.resolve(!1):(e.setDerivedBindingData(null),Promise.resolve(!0));const a={[n]:s.value};return c.createBindingSignature(i)===c.createBindingSignature(a)?Promise.resolve(!1):(e.setDerivedBindingData(a),Promise.resolve(!0))}static evaluateText(e){return e.evaluate()}static isHiddenIfCondition(e){return!e}static logFalsyIfDiagnostics(e){const t=e.getRawAttribute(`${l.prefix}if`);if(typeof t!="string"||t.indexOf("{{")>=0)return;const{sources:r}=c.dumpScope(e.getTarget()),i=new Set,n=t.match(/[A-Za-z_$][\w$]*/g)??[];let s=0;n.forEach(o=>{const u=t.indexOf(o,s);s=u+o.length,!(u>0&&t[u-1]===".")&&i.add(o)});const a={};i.forEach(o=>{o in r&&(a[o]=r[o])}),p.info("[Haori]","data-if is falsy (hidden):",t,"— referenced scope:",a)}static evaluateIf(e){const t=[],r=e.getAttribute(`${l.prefix}if`);if(c.isHiddenIfCondition(r))W.isEnabled()&&c.logFalsyIfDiagnostics(e),t.push(e.hide().then(()=>{M.hide(e.getTarget())}));else{const i=e.isVisible(),n=[];e.getChildren().forEach(s=>{s instanceof N?n.push(s.isMounted()?c.evaluateAll(s):c.scan(s.getTarget())):s instanceof z&&n.push(c.evaluateText(s))}),t.push(e.show().then(()=>{M.show(e.getTarget()),i||c.triggerLoadOnShow(e)})),t.push(Promise.all(n).then(()=>{}))}return Promise.all(t).then(()=>{})}static triggerLoadOnShow(e){const t=`${l.prefix}load-`;e.getTarget().getAttributeNames().some(i=>i.startsWith(t))&&new G(e,"load").run().catch(i=>{p.error("[Haori]","data-load procedure error (on show):",i)})}static getEachUpdateState(e){let t=c.EACH_UPDATE_STATES.get(e);return t||(t={running:!1,rerunRequested:!1,settled:null},c.EACH_UPDATE_STATES.set(e,t)),t}static evaluateEach(e){if(!e.isVisible()||!e.isMounted())return Promise.resolve();const t=c.getEachUpdateState(e);return t.running?(t.rerunRequested=!0,t.settled??Promise.resolve()):c.runEachUpdateLoop(e,t)}static runEachUpdateLoop(e,t){t.running=!0,e.getTarget().removeAttribute(`${l.prefix}each-done`);const r=(async()=>{try{do t.rerunRequested=!1,await c.performEachUpdate(e);while(t.rerunRequested);const i=e.getTarget();i.setAttribute(`${l.prefix}each-done`,""),c.runEachRenderedScript(i)}finally{t.running=!1,t.settled=null}c.runEachRenderedChange(e)})();return t.settled=r,r}static runEachRenderedScript(e){const t=`${l.prefix}each-rendered-run`;if(!e.hasAttribute(t))return;const r=String(e.getAttribute(t)??"");let i=null;try{i=new Function(`"use strict"; return (
|
|
22
23
|
${r}
|
|
23
24
|
);`)}catch{try{i=new Function(`"use strict";
|
|
24
25
|
${r}
|
|
25
|
-
`)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${u.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(d.EACH_RENDERED_CHANGE_WARNED.has(r)||(d.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),d.countEachRenderedRows(e)!==0){if(!n){if(d.EACH_RENDERED_CHANGE_FIRED.has(r))return;d.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${u.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=d.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${u.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof M){if(a.hasAttribute(`${u.prefix}each-before`)||a.hasAttribute(`${u.prefix}each-after`))return;r=a.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(l=>!l.hasAttribute(`${u.prefix}each-before`)&&!l.hasAttribute(`${u.prefix}each-after`)).forEach(l=>{if(!s){const c=S.get(l);c instanceof M&&(r=c.clone(),d.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const h=S.get(l);h instanceof M&&e.getChildren().includes(h)&&(e.removeChild(h),h.setMounted(!1)),l.parentNode&&l.parentNode.removeChild(l)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?Promise.resolve():this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${u.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(`${u.prefix}each`)||e.getEachInputSignature()===null)return!1;const t=e.getParent();if(t?.closestByAttribute(`${u.prefix}derive`)||t?.closestByAttribute(`${u.prefix}derive-name`)||t?.closestByAttribute(`${u.prefix}if`)||t?.closestByAttribute(`${u.prefix}fetch`)||t?.closestByAttribute(`${u.prefix}import`)||d.hasNonEachDynamicElementState(e))return!1;const r=d.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${u.prefix}each-key`),n=d.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${u.prefix}derive`)||e.hasAttribute(`${u.prefix}if`)||e.hasAttribute(`${u.prefix}each`)||e.hasAttribute(`${u.prefix}fetch`)||e.hasAttribute(`${u.prefix}import`)?!1:!d.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof M?t.hasAttribute(`${u.prefix}derive`)||t.hasAttribute(`${u.prefix}derive-name`)||t.hasAttribute(`${u.prefix}fetch`)||t.hasAttribute(`${u.prefix}import`)?!0:d.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return d.recordDerivedSubtreeSignatureComputation(e,t),d.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:d.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!d.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),d.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(d.createDescendantBindingSignature(e,"refresh")),d.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!U.isEnabled()||!e.hasAttribute(`${u.prefix}derive`))return null;const t=d.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:d.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return d.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 n=i.tagName.toLowerCase();if(i.id.trim()!==""){n+=`#${i.id.trim()}`,t.unshift(n);break}const s=r.getRawAttribute(`${u.prefix}derive-name`);typeof s=="string"&&s.trim()!==""&&(n+=`[${u.prefix}derive-name="${s.trim()}"]`);const a=r.getParent();if(a){const o=a.getChildren().filter(l=>l instanceof M).findIndex(l=>l===r);n+=`:nth-child(${o+1})`}t.unshift(n),r=a}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=d.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=d.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([`${u.prefix}each`,`${u.prefix}each-key`,`${u.prefix}each-arg`,`${u.prefix}each-index`]);return e.getAttributeNames().some(i=>{if(t.has(i))return!1;if(i.startsWith(`${u.prefix}attr-`)||i.startsWith(u.prefix))return!0;const n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof j&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>d.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof M?!d.markFreshInitializationSkippable(n):n instanceof j?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${u.prefix}attr-`)||t.startsWith(u.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(`${u.prefix}each-index`);i&&(i=String(i));const n=e.getAttribute(`${u.prefix}each-key`),s=e.getAttribute(`${u.prefix}each-arg`),a=new Map,o=[];t.forEach((b,v)=>{const R=d.createListKey(b,n?String(n):null,v);o.push(R),a.set(R,{item:b,itemIndex:v})});const l=new Set(o),h=[];let c=e.getChildren().filter(b=>b instanceof M).filter(b=>!b.hasAttribute(`${u.prefix}each-before`)&&!b.hasAttribute(`${u.prefix}each-after`));const m=c.map(b=>b.getListKey());c=c.filter(b=>l.has(String(b.getListKey()))?!0:(h.push(b.remove()),!1));const y=c.map(b=>b.getListKey()),T=new Map;c.forEach(b=>{const v=b.getListKey();v!==null&&!T.has(v)&&T.set(v,b)});const I=e.getChildElementFragments().slice(),H=I.filter(b=>b.hasAttribute(`${u.prefix}each-before`)).length;let E=Promise.resolve();return o.forEach((b,v)=>{const{item:R,itemIndex:C}=a.get(b);let F;const L=T.get(b);if(L)F=L,E=E.then(()=>d.updateRowFragment(F,R,i,C,s?String(s):null,b).then(B=>{if(B)return d.evaluateAll(F)}));else{F=r.clone();const B=H+v;E=E.then(()=>d.updateRowFragment(F,R,i,C,s?String(s):null,b).then(()=>{const z=I[B]??null;return e.insertBefore(F,z).then(()=>{I.splice(B,0,F)}).then(()=>d.initializeFreshEachRow(F))}))}}),Promise.all(h).then(()=>E).then(()=>{const b=o.filter(B=>B!==null),v=y.filter(B=>B!==null),R=new Set(v),C=b.filter(B=>!R.has(B)),L=m.filter(B=>B!==null).filter(B=>!l.has(B));N.eachUpdate(e.getTarget(),C,L,b)})}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a=t;if(typeof t=="object"&&t!==null)a={...t},r&&(a[r]=i),n&&(a={[n]:a});else if(n)a={[n]:t},r&&(a[r]=i);else return p.error("[Haori]",`Primitive value requires '${u.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);const o=a,l=d.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===l?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(l),e.setBindingData(o),e.setAttribute(`${u.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&d.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${u.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>d.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${d.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{d.evaluateAll(e)},100)}};d.ATTRIBUTE_ALIAS_SUFFIX="attr-",d.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],d.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],d.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],d.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,d.REACTIVE_FETCH_STATES=new WeakMap,d.REACTIVE_IMPORT_STATES=new WeakMap,d.DERIVE_SUBTREE_PROFILES=new WeakMap,d.EACH_UPDATE_STATES=new WeakMap,d.EACH_RENDERED_CHANGE_FIRED=new WeakSet,d.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let x=d;const ee=class ee{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[ee.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=S.get(e);t&&new K(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate))}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${u.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(ee.BUILTIN_EVENT_NAMES.has(e)){p.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=S.get(i);n instanceof M&&new K(n,"on",t).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${u.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${u.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=S.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof M&&(i.syncValue(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=S.get(a);o instanceof M&&o.syncValue()}}const n=()=>{new K(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${u.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${u.prefix}click-`,r=`${u.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};ee.HISTORY_STATE_KEY="__haoriHistoryState__",ee.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Ee=ee;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=S.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),n=D.resolveRootMargin(r),s=D.resolveThreshold(r),a=r.hasAttribute(`${u.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&D.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),D.registrations.delete(e));const o=new IntersectionObserver(l=>{const h=D.registrations.get(e);h&&l.forEach(c=>{!c.isIntersecting||h.running||D.isDisabled(h.fragment)||(h.running=!0,new K(h.fragment,"intersect").runWithResult().then(m=>{m&&h.once&&(h.observer.disconnect(),D.registrations.delete(e))}).catch(m=>{p.error("[Haori]","Intersect procedure execution error:",m)}).finally(()=>{const m=D.registrations.get(e);m&&(m.running=!1)}))})},{root:i,rootMargin:n,threshold:s});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(`${u.prefix}intersect-`))return!1;const r=t.slice(`${u.prefix}intersect-`.length);return!D.CONFIG_KEYS.has(r)})}static resolveRoot(e){const t=`${u.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=`${u.prefix}intersect-root-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?"0px":String(r)}static resolveThreshold(e){const t=`${u.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=`${u.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 _=D;function dt(f){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f()):Promise.resolve().then(f)}const w=class w{static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(w.isHtmlElement(e)&&w.syncElement(e),e.querySelectorAll("*").forEach(t=>{w.syncElement(t)}))}static syncElement(e){const t=w.registrations.get(e),r=S.get(e);if(!(r instanceof M)||!w.shouldObserve(r)){t&&(t.observer.disconnect(),w.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=w.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),w.registrations.delete(e)),p.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=w.resolveRoot(r),s=w.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,w.refreshRows(t);return}t&&(t.observer.disconnect(),w.registrations.delete(e));const a=new IntersectionObserver(l=>{const h=w.registrations.get(e);if(!h)return;let c=!1;l.forEach(m=>{const y=m.target;h.observedRows.has(y)&&(m.isIntersecting?h.visibleRows.has(y)||(h.visibleRows.add(y),c=!0):h.visibleRows.delete(y)&&(c=!0))}),c&&w.scheduleCompute(h)},{root:n,rootMargin:s,threshold:w.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};w.registrations.set(e,o),w.refreshRows(o)}static cleanupTree(e){if(w.isHtmlElement(e)){const t=w.registrations.get(e);t&&(t.observer.disconnect(),w.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=w.registrations.get(t);r&&(r.observer.disconnect(),w.registrations.delete(t))})}static disconnectAll(){w.registrations.forEach(e=>{e.observer.disconnect()}),w.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${u.prefix}each`)&&e.hasAttribute(`${u.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${u.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${u.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return w.isHtmlElement(i)?i:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${u.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?w.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof M&&!t.hasAttribute(`${u.prefix}each-before`)&&!t.hasAttribute(`${u.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=w.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));w.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,dt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();w.registrations.get(t)===e&&w.computeAndPublish(e)}))}static computeAndPublish(e){const t=w.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const l of i)l<a&&(a=l),l>o&&(o=l);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,w.publish(e,n))}static publish(e,t){const r=w.resolveBindOwner(e.fragment);if(!r){p.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);x.setBindingData(i,n,a,!1,!1).catch(o=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${u.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};w.THRESHOLD=0,w.DEFAULT_ROOT_MARGIN="0px",w.registrations=new Map;let X=w;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=new Ee;O._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([x.scan(document.head),x.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await k.wait(),document.body.setAttribute("data-haori-ready",""),O.observe(document.head),O.observe(document.body),_.syncTree(document.body),X.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return O._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${u.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(O.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&x.isAliasedAttributeReflection(n,i.attributeName))break;x.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),_.syncElement(n),X.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{_.cleanupTree(n),X.cleanupTree(n),x.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(x.addNode(n.parentElement,n),_.syncTree(n),X.syncTree(n))}),i.target instanceof Element&&X.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?x.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(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),O._mutationObservers.push(t)}};O._initialized=!1,O._mutationObservers=[],O._dispatcher=null;let ue=O;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ue.init):ue.init();const ft=()=>W.waitForRenders(),gt="0.26.2";exports.Core=x;exports.Env=u;exports.Form=A;exports.Fragment=S;exports.Haori=W;exports.Log=p;exports.Queue=k;exports.default=W;exports.version=gt;exports.waitForRenders=ft;
|
|
26
|
+
`)}catch(n){p.error("[Haori]",`Invalid each-rendered-run script: ${n}`)}}if(i)try{i.call(e)}catch(n){p.error("[Haori]",`each-rendered-run execution error: ${n}`)}}static runEachRenderedChange(e){const t=`${l.prefix}each-rendered-change`,r=e.getTarget();if(!r.hasAttribute(t))return;const i=String(r.getAttribute(t)??"").trim().toLowerCase();let n=!1;if(i==="always"?n=!0:i!==""&&i!=="once"&&(c.EACH_RENDERED_CHANGE_WARNED.has(r)||(c.EACH_RENDERED_CHANGE_WARNED.add(r),p.warn("[Haori]",`Invalid ${t} value: "${i}". Use "once" (default) or "always".`))),c.countEachRenderedRows(e)!==0){if(!n){if(c.EACH_RENDERED_CHANGE_FIRED.has(r))return;c.EACH_RENDERED_CHANGE_FIRED.add(r)}try{r.dispatchEvent(new Event("change",{bubbles:!0}))}catch(s){p.error("[Haori]",`each-rendered-change dispatch error: ${s}`)}}}static countEachRenderedRows(e){let t=0;for(const r of e.getChildElementFragments())r.getTarget().hasAttribute(`${l.prefix}row`)&&(t+=1);return t}static performEachUpdate(e){const t=c.resolveEachItems(e);if(t===null)return Promise.reject(new Error("Invalid each attribute."));let r=e.getTemplate();const i=e.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:t});if(r===null){let s=!1;if(e.getChildren().forEach(a=>{if(!s&&a instanceof N){if(a.hasAttribute(`${l.prefix}each-before`)||a.hasAttribute(`${l.prefix}each-after`))return;r=a.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0,e.removeChild(a);const o=a.getTarget();o.parentNode&&o.parentNode.removeChild(o),a.setMounted(!1)}}),!s){const a=e.getTarget();Array.from(a.children).filter(u=>!u.hasAttribute(`${l.prefix}each-before`)&&!u.hasAttribute(`${l.prefix}each-after`)).forEach(u=>{if(!s){const h=T.get(u);h instanceof N&&(r=h.clone(),c.markFreshInitializationSkippable(r),e.setTemplate(r),s=!0)}const f=T.get(u);f instanceof N&&e.getChildren().includes(f)&&(e.removeChild(f),f.setMounted(!1)),u.parentNode&&u.parentNode.removeChild(u)})}return this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}return e.getEachInputSignature()===n?c.reevaluateEachRows(e):this.updateDiff(e,t).then(()=>{e.setEachInputSignature(n)})}static reevaluateEachRows(e){if(c.isRowLocalEachTemplate(e))return Promise.resolve();const t=e.getChildElementFragments().filter(r=>!r.hasAttribute(`${l.prefix}each-before`)&&!r.hasAttribute(`${l.prefix}each-after`));return t.length===0?Promise.resolve():Promise.all(t.map(r=>c.evaluateAll(r))).then(()=>{})}static resolveEachItems(e){const t=e.getAttributeEvaluation(`${l.prefix}each`),r=t?.value;return t?.hasUnresolvedReference||r===!1||r===null||r===void 0?[]:Array.isArray(r)?r:(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`)||c.hasNonEachDynamicElementState(e)||!c.isRowLocalEachTemplate(e))return!1;const r=c.resolveEachItems(e);if(r===null)return!1;const i=e.getAttribute(`${l.prefix}each-key`),n=c.createBindingSignature({key:i?String(i):null,items:r});return e.getEachInputSignature()===n}static isRowLocalEachTemplate(e){const t=e.getRowLocalTemplate();if(t!==null)return t;const r=e.getTemplate(),i=e.getAttribute(`${l.prefix}each-arg`);if(r===null||!i)return e.setRowLocalTemplate(!1),!1;const n=new Set([String(i)]),s=e.getAttribute(`${l.prefix}each-index`);s&&n.add(String(s));const a=c.isRowLocalSubtree(r,n);return e.setRowLocalTemplate(a),a}static isRowLocalSubtree(e,t){for(const i of e.getAttributeNames()){const n=e.getRawAttribute(i),s=typeof n=="string"?n:"";if(s.includes("{{")){if(!c.areExpressionsRowLocal(c.extractInterpolations(s),t))return!1;continue}if(!i.startsWith(l.prefix))continue;const a=i.slice(l.prefix.length);if(c.ROW_LOCAL_EXPRESSION_ATTRIBUTES.has(a)){if(!c.areExpressionsRowLocal([s],t))return!1;continue}if(!c.ROW_LOCAL_STATIC_ATTRIBUTES.has(a))return!1}let r=t;if(e.hasAttribute(`${l.prefix}each`)){const i=e.getRawAttribute(`${l.prefix}each-arg`);if(typeof i!="string"||i==="")return!1;const n=new Set(t);n.add(i);const s=e.getRawAttribute(`${l.prefix}each-index`);typeof s=="string"&&s!==""&&n.add(s),r=n}for(const i of e.getChildren())if(i instanceof N){if(!c.isRowLocalSubtree(i,r))return!1}else if(i instanceof z){const n=i.getRawText();if(n.includes("{{")&&!c.areExpressionsRowLocal(c.extractInterpolations(n),t))return!1}return!0}static areExpressionsRowLocal(e,t){for(const r of e){const i=r.trim();if(i==="")continue;const n=Y.getFreeIdentifiers(i);if(n.length===0||n.some(s=>!t.has(s)))return!1}return!0}static extractInterpolations(e){const t=[],r=/\{\{([\s\S]*?)\}\}/g;let i=r.exec(e);for(;i!==null;)t.push(i[1]),i=r.exec(e);return t}static canSkipStableDerivedSubtree(e){return!e.hasAttribute(`${l.prefix}derive`)||e.hasAttribute(`${l.prefix}if`)||e.hasAttribute(`${l.prefix}each`)||e.hasAttribute(`${l.prefix}fetch`)||e.hasAttribute(`${l.prefix}import`)?!1:!c.hasDisallowedDerivedSubtreeDescendant(e)}static hasDisallowedDerivedSubtreeDescendant(e){return e.getChildren().some(t=>t instanceof N?t.hasAttribute(`${l.prefix}derive`)||t.hasAttribute(`${l.prefix}derive-name`)||t.hasAttribute(`${l.prefix}fetch`)||t.hasAttribute(`${l.prefix}import`)?!0:c.hasDisallowedDerivedSubtreeDescendant(t):!1)}static createDescendantBindingSignature(e,t){return c.recordDerivedSubtreeSignatureComputation(e,t),c.createBindingSignature(e.getDescendantBindingData())}static createDeriveInputSignature(e,t,r){const i=typeof r=="string"?r.trim():"";return!t||i===""?null:c.createBindingSignature({expression:t,name:i,scope:e.getBindingData()})}static refreshDerivedSubtreeSignature(e){if(!c.canSkipStableDerivedSubtree(e)){e.setDeriveSubtreeSignature(null),c.logDerivedSubtreeProfileSnapshot(e,"skip-ineligible");return}e.setDeriveSubtreeSignature(c.createDescendantBindingSignature(e,"refresh")),c.logDerivedSubtreeProfileSnapshot(e,"refresh")}static getOrCreateDerivedSubtreeProfile(e){if(!W.isEnabled()||!e.hasAttribute(`${l.prefix}derive`))return null;const t=c.DERIVE_SUBTREE_PROFILES.get(e);if(t)return t;const r={hostId:c.createDerivedSubtreeHostId(e),signatureComputeTotal:0,signatureComputeFromEvaluateAll:0,signatureComputeFromRefresh:0,skipHitCount:0,skipMissCount:0,skipIneligibleCount:0};return c.DERIVE_SUBTREE_PROFILES.set(e,r),r}static resolveElementId(e){return e.getAttribute("id")??""}static createDerivedSubtreeHostId(e){const t=[];let r=e;for(;r;){const i=r.getTarget();if(!(i instanceof HTMLElement))break;let n=i.tagName.toLowerCase();const s=c.resolveElementId(i).trim();if(s!==""){n+=`#${s}`,t.unshift(n);break}const a=r.getRawAttribute(`${l.prefix}derive-name`);typeof a=="string"&&a.trim()!==""&&(n+=`[${l.prefix}derive-name="${a.trim()}"]`);const o=r.getParent();if(o){const u=o.getChildren().filter(f=>f instanceof N).findIndex(f=>f===r);n+=`:nth-child(${u+1})`}t.unshift(n),r=o}return t.join(" > ")}static recordDerivedSubtreeSignatureComputation(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);if(r!==null){if(r.signatureComputeTotal+=1,t==="refresh"){r.signatureComputeFromRefresh+=1;return}r.signatureComputeFromEvaluateAll+=1}}static logDerivedSubtreeProfileSnapshot(e,t){const r=c.getOrCreateDerivedSubtreeProfile(e);r!==null&&(t==="skip-hit"?r.skipHitCount+=1:t==="skip-miss"?r.skipMissCount+=1:t==="skip-ineligible"&&(r.skipIneligibleCount+=1),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 n=e.getRawAttribute(i);return typeof n=="string"&&n.includes("{{")})?!0:e.getChildren().some(i=>i instanceof z&&i.hasDynamicContent())}static markFreshInitializationSkippable(e){const t=e.getAttributeNames().some(n=>c.isFreshInitializationDynamicAttribute(e,n)),r=e.getChildren().some(n=>n instanceof N?!c.markFreshInitializationSkippable(n):n instanceof z?n.hasDynamicContent():!1),i=!t&&!r;return e.setFreshInitializationSkippable(i),i}static isFreshInitializationDynamicAttribute(e,t){if(t.startsWith(`${l.prefix}attr-`)||t.startsWith(l.prefix))return!0;const r=e.getRawAttribute(t);return typeof r=="string"&&r.includes("{{")}static updateDiff(e,t){const r=e.getTemplate();if(r===null)return 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 n=e.getAttribute(`${l.prefix}each-key`),s=e.getAttribute(`${l.prefix}each-arg`),a=new Map,o=[];t.forEach((y,D)=>{const I=c.createListKey(y,n?String(n):null,D);o.push(I),a.set(I,{item:y,itemIndex:D})});const u=new Set(o),f=[];let h=e.getChildren().filter(y=>y instanceof N).filter(y=>!y.hasAttribute(`${l.prefix}each-before`)&&!y.hasAttribute(`${l.prefix}each-after`));const g=h.map(y=>y.getListKey()),b=new Set;h=h.filter(y=>u.has(String(y.getListKey()))?!0:(b.add(y),f.push(y.remove()),!1));const R=h.map(y=>y.getListKey()),S=new Map;h.forEach(y=>{const D=y.getListKey();D!==null&&!S.has(D)&&S.set(D,y)});const k=e.getChildElementFragments().filter(y=>!b.has(y)),w=k.filter(y=>y.hasAttribute(`${l.prefix}each-before`)).length;let A=Promise.resolve();return o.forEach((y,D)=>{const{item:I,itemIndex:$}=a.get(y);let O;const K=S.get(y);if(K){O=K;const U=w+D;A=A.then(()=>c.updateRowFragment(O,I,i,$,s?String(s):null,y).then(Z=>c.repositionEachRow(e,O,k,U).then(()=>{if(Z)return c.evaluateAll(O).then(()=>c.applyRowFormValues(e,O,I))})))}else{O=r.clone();const U=w+D;A=A.then(()=>c.updateRowFragment(O,I,i,$,s?String(s):null,y).then(()=>{const Z=k[U]??null;return e.insertBefore(O,Z).then(()=>{k.splice(U,0,O)}).then(()=>c.initializeFreshEachRow(O)).then(()=>c.applyRowFormValues(e,O,I))}))}}),Promise.all(f).then(()=>A).then(()=>{const y=o.filter(U=>U!==null),D=R.filter(U=>U!==null),I=new Set(D),$=y.filter(U=>!I.has(U)),K=g.filter(U=>U!==null).filter(U=>!u.has(U));M.eachUpdate(e.getTarget(),$,K,y)})}static repositionEachRow(e,t,r,i){const n=r.indexOf(t);if(n===-1||n===i)return Promise.resolve();r.splice(n,1);const s=r[i]??null;return r.splice(i,0,t),e.insertBefore(t,s)}static applyRowFormValues(e,t,r){return!e.hasAttribute(`${l.prefix}form-list`)||typeof r!="object"||r===null||Array.isArray(r)?Promise.resolve():H.syncRowValues(t,r)}static createListKey(e,t,r){let i;if(typeof e=="object"&&e!==null)if(t){const n=e[t];n==null?i=`__index_${r}`:typeof n=="object"?i=JSON.stringify(n):i=String(n)}else i=`__index_${r}`;else i=String(e);return i}static updateRowFragment(e,t,r,i,n,s){let a;if(typeof t=="object"&&t!==null)a=n?{[n]:{...t}}:{...t};else if(n)a={[n]:t};else return p.error("[Haori]",`Primitive value requires '${l.prefix}each-arg' attribute: ${t}`),Promise.resolve(!1);r&&(a[r]=i);const o=a,u=c.createBindingSignature({listKey:s,bindingData:o});return e.getListKey()===s&&e.getRenderSignature()===u?Promise.resolve(!1):(e.setListKey(s),e.setRenderSignature(u),e.setBindingData(o),e.setAttribute(`${l.prefix}row`,s).then(()=>!0))}static needsScheduledEvaluateAll(e){const t=[e];for(;t.length>0;){const r=t.pop();if(r.getChildElementFragments().forEach(i=>{t.push(i)}),r!==e&&!r.isMounted()&&c.hasMountSensitiveAttribute(r))return!0}return!1}static hasMountSensitiveAttribute(e){return["fetch","import"].some(t=>e.hasAttribute(`${l.prefix}${t}`))}static createBindingSignature(e,t=new WeakMap,r={value:0}){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="function")return`[Function:${e.name||"anonymous"}]`;if(typeof e=="symbol")return e.toString();if(e instanceof Date)return`[Date:${e.toISOString()}]`;if(typeof File<"u"&&e instanceof File)return`[File:${e.name}:${e.size}:${e.lastModified}:${e.type}]`;if(typeof Blob<"u"&&e instanceof Blob)return`[Blob:${e.size}:${e.type}]`;if(Array.isArray(e)){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`array-${r.value}`;return r.value+=1,t.set(e,i),`[${e.map(n=>c.createBindingSignature(n,t,r)).join(",")}]`}if(typeof e=="object"){if(t.has(e))return`[Circular:${t.get(e)}]`;const i=`object-${r.value}`;r.value+=1,t.set(e,i);const n=e;return`{${Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${c.createBindingSignature(n[s],t,r)}`).join(",")}}`}return String(e)}static scheduleEvaluateAll(e){setTimeout(()=>{c.evaluateAll(e)},100)}};c.ATTRIBUTE_ALIAS_SUFFIX="attr-",c.PRIORITY_ATTRIBUTE_SUFFIXES=["bind","url-param","derive-name","derive","if","each"],c.DEFERRED_ATTRIBUTE_SUFFIXES=["fetch"],c.EVALUATE_ALL_EXCLUDED_ATTRIBUTE_SUFFIXES=["bind","derive","derive-name","if","each","fetch","import","url-param"],c.ATTRIBUTE_PLACEHOLDER_REGEX=/\{\{\{[\s\S]+?\}\}\}|\{\{[\s\S]+?\}\}/,c.ROW_LOCAL_EXPRESSION_ATTRIBUTES=new Set(["each","if","derive"]),c.ROW_LOCAL_STATIC_ATTRIBUTES=new Set(["each-arg","each-key","each-index","each-before","each-after","derive-name","row","form","form-arg","form-list","form-object","form-detach"]),c.REACTIVE_FETCH_STATES=new WeakMap,c.REACTIVE_IMPORT_STATES=new WeakMap,c.DERIVE_SUBTREE_PROFILES=new WeakMap,c.EACH_UPDATE_STATES=new WeakMap,c.EACH_RENDERED_CHANGE_FIRED=new WeakSet,c.EACH_RENDERED_CHANGE_WARNED=new WeakSet;let P=c;const se=class se{constructor(e=document){this.customEventHandlers=new Map,this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures=[],this.onClick=t=>this.delegate(t,"click"),this.onChange=t=>this.delegate(t,"change"),this.onInput=t=>this.delegate(t,"input"),this.onLoadCapture=t=>this.delegate(t,"load"),this.onWindowLoad=()=>{if(this.deferred){this.deferredProcedures.push(()=>this.runWindowLoadProcedure());return}this.runWindowLoadProcedure()},this.onPopstate=t=>{const r=t.state;!r||r[se.HISTORY_STATE_KEY]!==!0||location.reload()},this.root=e}runWindowLoadProcedure(){const e=document.documentElement,t=T.get(e);t&&new G(t,"load").run()}start(){this.deferred=!1,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations()}startDeferred(){this.deferred=!0,this.addBuiltinListeners(),this.subscribeDeclaredCustomEvents()}release(){if(!this.deferred)return;this.deferred=!1,this.subscribeDeclaredCustomEvents(),this.observeCustomEventDeclarations();const e=this.deferredProcedures.splice(0);for(const t of e)try{t()}catch(r){p.error("[Haori]","Deferred event handling error:",r)}}addBuiltinListeners(){this.builtinListenersAdded||(this.builtinListenersAdded=!0,this.root.addEventListener("click",this.onClick),this.root.addEventListener("change",this.onChange),this.root.addEventListener("input",this.onInput),this.root.addEventListener("load",this.onLoadCapture,!0),window.addEventListener("load",this.onWindowLoad,{once:!0}),window.addEventListener("popstate",this.onPopstate))}stop(){this.root.removeEventListener("click",this.onClick),this.root.removeEventListener("change",this.onChange),this.root.removeEventListener("input",this.onInput),this.root.removeEventListener("load",this.onLoadCapture,!0),window.removeEventListener("load",this.onWindowLoad),window.removeEventListener("popstate",this.onPopstate),this.builtinListenersAdded=!1,this.deferred=!1,this.deferredProcedures.length=0;for(const[e,t]of this.customEventHandlers)window.removeEventListener(e,t,!0);this.customEventHandlers.clear(),this.customEventObserver?.disconnect(),this.customEventObserver=void 0}get onAttributeName(){return`${l.prefix}on`}subscribeDeclaredCustomEvents(){this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(t=>this.subscribeCustomEvent(t.getAttribute(this.onAttributeName)))}subscribeCustomEvent(e){if(e===null||e==="")return;if(se.BUILTIN_EVENT_NAMES.has(e)){p.warn("[Haori]",`data-on="${e}" は組み込みイベントです。data-${e}-* を使用してください(data-on はカスタムイベント専用)。`);return}if(this.customEventHandlers.has(e))return;const t=r=>this.runCustomEventProcedures(e,r);this.customEventHandlers.set(e,t),window.addEventListener(e,t,!0)}runCustomEventProcedures(e,t){if(this.deferred){this.deferredProcedures.push(()=>this.runCustomEventProcedures(e,t));return}this.root.querySelectorAll(`[${this.onAttributeName}]`).forEach(i=>{if(i.getAttribute(this.onAttributeName)!==e)return;const n=T.get(i);n instanceof N&&new G(n,"on",t).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})})}observeCustomEventDeclarations(){if(typeof MutationObserver>"u")return;const e=this.root instanceof Document?this.root:this.root.ownerDocument??document,t=this.root instanceof Document?e.body:this.root;t&&(this.customEventObserver=new MutationObserver(r=>{for(const i of r)i.addedNodes.forEach(n=>{n instanceof HTMLElement&&(n.hasAttribute(this.onAttributeName)&&this.subscribeCustomEvent(n.getAttribute(this.onAttributeName)),n.querySelectorAll(`[${this.onAttributeName}]`).forEach(s=>this.subscribeCustomEvent(s.getAttribute(this.onAttributeName))))})}),this.customEventObserver.observe(t,{childList:!0,subtree:!0}))}delegate(e,t){const r=this.getElementFromTarget(e.target,t);if(r){if(t==="input"){const i=`${l.prefix}input-`;if(!r.getAttributeNames().some(s=>s.startsWith(i)))return}if(r.hasAttribute(`${l.prefix}${t}-prevent`)&&e.preventDefault(),this.deferred){this.deferredProcedures.push(()=>{r.isConnected&&this.runProcedureFor(r,t,e)});return}this.runProcedureFor(r,t,e)}}runProcedureFor(e,t,r){const i=T.get(e);if(!i)return;if((t==="change"||t==="input")&&i instanceof N&&(i.syncValue(),i.markUserEdit(),e instanceof HTMLInputElement&&e.type==="radio"&&e.name)){const s=document.getElementsByName(e.name);for(const a of Array.from(s)){if(a===e||!(a instanceof HTMLInputElement)||a.type!=="radio"||a.form!==e.form)continue;const o=T.get(a);o instanceof N&&(o.syncValue(),o.markUserEdit())}}const n=()=>{new G(i,t,r).run().catch(s=>{p.error("[Haori]","Procedure execution error:",s)})};if(t==="click"&&e.hasAttribute(`${l.prefix}click-defer`)){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>n()):setTimeout(n,0);return}n()}getElementFromTarget(e,t){if(!e)return null;if(e instanceof HTMLElement)return t==="click"?this.findClickableElement(e):e;if(e instanceof Node){const r=e.parentElement;return r?t==="click"?this.findClickableElement(r):r:null}return null}findClickableElement(e){const t=`${l.prefix}click-`,r=`${l.prefix}click-passive`;let i=e;for(;i;){if(i.getAttributeNames().some(s=>s.startsWith(t)&&s!==r))return i;if(i.hasAttribute(r))return null;i=i.parentElement}return null}};se.HISTORY_STATE_KEY="__haoriHistoryState__",se.BUILTIN_EVENT_NAMES=new Set(["click","change","input","load"]);let Fe=se;const C=class C{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)&&(C.isHtmlElement(e)&&C.syncElement(e),e.querySelectorAll("*").forEach(t=>{C.syncElement(t)}))}static syncElement(e){const t=C.registrations.get(e),r=T.get(e);if(!r||!C.shouldObserve(r)){t&&(t.observer.disconnect(),C.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=C.resolveRoot(r),n=C.resolveRootMargin(r),s=C.resolveThreshold(r),a=r.hasAttribute(`${l.prefix}intersect-once`);if(t&&t.observer.root===i&&t.observer.rootMargin===n&&C.sameThreshold(t.observer.thresholds,s)&&t.once===a){t.fragment=r;return}t&&(t.observer.disconnect(),C.registrations.delete(e));const o=new IntersectionObserver(u=>{const f=C.registrations.get(e);f&&u.forEach(h=>{!h.isIntersecting||f.running||C.isDisabled(f.fragment)||(f.running=!0,new G(f.fragment,"intersect").runWithResult().then(g=>{g&&f.once&&(f.observer.disconnect(),C.registrations.delete(e))}).catch(g=>{p.error("[Haori]","Intersect procedure execution error:",g)}).finally(()=>{const g=C.registrations.get(e);g&&(g.running=!1)}))})},{root:i,rootMargin:n,threshold:s});o.observe(e),C.registrations.set(e,{fragment:r,observer:o,once:a,running:!1})}static cleanupTree(e){if(C.isHtmlElement(e)){const t=C.registrations.get(e);t&&(t.observer.disconnect(),C.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=C.registrations.get(t);r&&(r.observer.disconnect(),C.registrations.delete(t))})}static disconnectAll(){C.registrations.forEach(e=>{e.observer.disconnect()}),C.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!C.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 C.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}};C.CONFIG_KEYS=new Set(["root","root-margin","threshold","disabled","once"]),C.registrations=new Map;let ie=C;const v=class v{static syncTree(e){(e instanceof Element||e instanceof DocumentFragment)&&(v.isHtmlElement(e)&&v.syncElement(e),e.querySelectorAll("*").forEach(t=>{v.syncElement(t)}))}static syncElement(e){const t=v.registrations.get(e);if(!t&&!v.hasPollAttribute(e))return;const r=T.get(e);if(!(r instanceof N)||!v.shouldObserve(r)){t&&v.teardown(e,t);return}const i=v.buildConfigKey(r);if(t){if(t.configKey===i){t.fragment=r;return}v.teardown(e,t)}v.startPolling(e,r,i)}static cleanupTree(e){if(v.isHtmlElement(e)){const t=v.registrations.get(e);t&&v.teardown(e,t)}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=v.registrations.get(t);r&&v.teardown(t,r)})}static disconnectAll(){v.registrations.forEach(e=>{v.clearTimers(e)}),v.registrations.clear(),v.visibilityListener&&typeof document<"u"&&document.removeEventListener("visibilitychange",v.visibilityListener),v.visibilityListener=null}static isHtmlElement(e){if(!(e instanceof Element))return!1;const t=e.ownerDocument?.defaultView?.HTMLElement;return typeof t<"u"&&e instanceof t}static hasPollAttribute(e){const t=`${l.prefix}poll-`,r=e.attributes;for(let i=0;i<r.length;i+=1)if(r[i].name.startsWith(t))return!0;return!1}static shouldObserve(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().some(r=>r.startsWith(t)?!v.CONFIG_KEYS.has(r.slice(t.length)):!1)}static buildConfigKey(e){const t=`${l.prefix}poll-`;return e.getAttributeNames().filter(r=>r.startsWith(t)).sort().map(r=>`${r}=${e.getRawAttribute(r)??""}`).join(`
|
|
27
|
+
`)}static startPolling(e,t,r){const i={fragment:t,configKey:r,intervalMs:v.resolveInterval(t),timeoutMs:v.resolveTimeout(t),errorLimit:v.resolveErrorLimit(t),startedAt:performance.now(),intervalTimerId:null,timeoutTimerId:null,fetching:!1,paused:!1,stopped:!1,timedOut:!1,stopReason:null,count:0,consecutiveErrors:0};v.registrations.set(e,i),v.ensureVisibilityListener(),i.timeoutMs!==null&&(i.timeoutTimerId=setTimeout(()=>{v.handleTimeout(e)},i.timeoutMs)),v.injectState(i),v.tick(e)}static async tick(e){const t=v.registrations.get(e);if(!t||t.stopped||t.fetching)return;if(t.intervalTimerId=null,!e.isConnected){await v.stop(e,t,"detached");return}const r=v.isHidden(e)||v.isDisabled(t.fragment);if(r!==t.paused&&(t.paused=r,await v.injectState(t)),r){v.schedule(e,t);return}if(v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}t.fetching=!0,t.count+=1;let i=!1;try{i=await new G(t.fragment,"poll").runWithResult()}catch(n){p.error("[Haori]","Poll procedure execution error:",n)}finally{t.fetching=!1}if(!(v.registrations.get(e)!==t||t.stopped)){if(i)t.consecutiveErrors=0;else if(t.consecutiveErrors+=1,t.errorLimit!==null&&t.consecutiveErrors>=t.errorLimit){await v.stop(e,t,"error");return}if(await v.restoreStateIfCleared(t),i&&v.isUntilSatisfied(t.fragment)){await v.stop(e,t,"until");return}v.schedule(e,t)}}static schedule(e,t){t.stopped||t.intervalTimerId!==null||(t.intervalTimerId=setTimeout(()=>{v.tick(e)},t.intervalMs))}static async handleTimeout(e){const t=v.registrations.get(e);!t||t.stopped||(t.timeoutTimerId=null,t.timedOut=!0,e.isConnected&&M.pollTimeout(e,t.count,v.elapsed(t)),await v.stop(e,t,"timeout"))}static async stop(e,t,r){if(!t.stopped){if(t.stopped=!0,t.stopReason=r,t.paused=!1,v.clearTimers(t),r==="detached"){v.registrations.delete(e);return}await v.injectState(t),e.isConnected&&M.pollStop(e,r,t.count,v.elapsed(t))}}static teardown(e,t){v.clearTimers(t),v.registrations.delete(e)}static clearTimers(e){e.intervalTimerId!==null&&(clearTimeout(e.intervalTimerId),e.intervalTimerId=null),e.timeoutTimerId!==null&&(clearTimeout(e.timeoutTimerId),e.timeoutTimerId=null)}static elapsed(e){return Math.round(performance.now()-e.startedAt)}static ensureVisibilityListener(){if(v.visibilityListener||typeof document>"u")return;const e=()=>{document.visibilityState==="visible"&&Array.from(v.registrations.entries()).forEach(([t,r])=>{r.stopped||r.fetching||(r.intervalTimerId!==null&&(clearTimeout(r.intervalTimerId),r.intervalTimerId=null),v.tick(t))})};v.visibilityListener=e,document.addEventListener("visibilitychange",e)}static injectState(e){const t=v.resolveStateFragments(e);if(t.length===0)return Promise.resolve();const r={running:!e.stopped,paused:e.paused,stopped:e.stopped,timedOut:e.timedOut,stopReason:e.stopReason,count:e.count,elapsedMs:v.elapsed(e)};return Promise.all(t.map(i=>{const n=i.getTarget(),s={...i.getRawBindingData()??{},_poll:r};return P.setBindingData(n,s,new Set,!1,!1)})).then(()=>{})}static async restoreStateIfCleared(e){v.resolveStateFragments(e).some(i=>(i.getRawBindingData()??{})._poll===void 0)&&await v.injectState(e)}static resolveStateFragments(e){const t=`${l.prefix}poll-state`,r=e.fragment;if(!r.hasAttribute(t))return[];const i=r.getAttribute(t);if(typeof i!="string"||i.trim()==="")return r.getTarget().isConnected?[r]:[];const n=document.querySelectorAll(i);if(n.length===0)return p.error("[Haori]",`Poll state element not found: ${i}`),[];const s=[];return n.forEach(a=>{if(!a.isConnected)return;const o=T.get(a);o instanceof N&&s.push(o)}),s}static resolveInterval(e){const t=`${l.prefix}poll-interval`;if(!e.hasAttribute(t))return v.DEFAULT_INTERVAL_MS;const r=v.toNumber(e.getAttribute(t));return r===null?(p.warn("[Haori]",`${t} は数値で指定してください。既定値 ${v.DEFAULT_INTERVAL_MS}ms を使用します。`),v.DEFAULT_INTERVAL_MS):r<v.MIN_INTERVAL_MS?(p.warn("[Haori]",`${t} の下限は ${v.MIN_INTERVAL_MS}ms です。${r}ms は下限へ切り上げます。`),v.MIN_INTERVAL_MS):r}static resolveTimeout(e){const t=`${l.prefix}poll-timeout`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<=0?(p.warn("[Haori]",`${t} は正の数値で指定してください。無制限として扱います。`),null):r}static resolveErrorLimit(e){const t=`${l.prefix}poll-error-limit`;if(!e.hasAttribute(t))return null;const r=v.toNumber(e.getAttribute(t));return r===null||r<1?(p.warn("[Haori]",`${t} は 1 以上の数値で指定してください。無制限として扱います。`),null):Math.floor(r)}static toNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;const t=Number(e.trim());return Number.isFinite(t)?t:null}static isHidden(e){return e.closest(`[${l.prefix}if-false]`)!==null}static isDisabled(e){const t=`${l.prefix}poll-disabled`;return e.hasAttribute(t)?v.isTruthy(e.getAttribute(t)):!1}static isUntilSatisfied(e){const t=`${l.prefix}poll-until`;if(!e.hasAttribute(t))return!1;const r=e.getAttributeEvaluation(t);return r?r.hasUnresolvedReference?(p.warn("[Haori]",`${t} に未解決の参照が含まれています(停止条件は成立扱いにしません):`,e.getRawAttribute(t),e.getTarget()),!1):v.isTruthy(r.value):!1}static isTruthy(e){if(e==null||e===!1)return!1;if(typeof e=="boolean")return e;if(typeof e=="string"){const t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}};v.CONFIG_KEYS=new Set(["interval","timeout","until","error-limit","disabled","state"]),v.DEFAULT_INTERVAL_MS=5e3,v.MIN_INTERVAL_MS=100,v.registrations=new Map,v.visibilityListener=null;let ne=v;function Tt(d){typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>d()):Promise.resolve().then(d)}const F=class F{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)&&(F.isHtmlElement(e)&&F.syncElement(e),e.querySelectorAll("*").forEach(t=>{F.syncElement(t)}))}static syncElement(e){const t=F.registrations.get(e),r=T.get(e);if(!(r instanceof N)||!F.shouldObserve(r)){t&&(t.observer.disconnect(),F.registrations.delete(e));return}if(typeof IntersectionObserver>"u")return;const i=F.resolveVarName(r);if(i===""){t&&(t.observer.disconnect(),F.registrations.delete(e)),p.warn("[Haori]",'data-each-visible requires a variable name (e.g. data-each-visible="visibleRange").');return}const n=F.resolveRoot(r),s=F.resolveRootMargin(r);if(t&&t.observer.root===n&&t.observer.rootMargin===s&&t.varName===i){t.fragment=r,F.refreshRows(t);return}t&&(t.observer.disconnect(),F.registrations.delete(e));const a=new IntersectionObserver(u=>{const f=F.registrations.get(e);if(!f)return;let h=!1;u.forEach(g=>{const b=g.target;f.observedRows.has(b)&&(g.isIntersecting?f.visibleRows.has(b)||(f.visibleRows.add(b),h=!0):f.visibleRows.delete(b)&&(h=!0))}),h&&F.scheduleCompute(f)},{root:n,rootMargin:s,threshold:F.THRESHOLD}),o={fragment:r,observer:a,varName:i,root:n,rootMargin:s,observedRows:new Set,visibleRows:new Set,scheduled:!1,lastSnapshot:null};F.registrations.set(e,o),F.refreshRows(o)}static cleanupTree(e){if(F.isHtmlElement(e)){const t=F.registrations.get(e);t&&(t.observer.disconnect(),F.registrations.delete(e))}(e instanceof Element||e instanceof DocumentFragment)&&e.querySelectorAll("*").forEach(t=>{const r=F.registrations.get(t);r&&(r.observer.disconnect(),F.registrations.delete(t))})}static disconnectAll(){F.registrations.forEach(e=>{e.observer.disconnect()}),F.registrations.clear()}static shouldObserve(e){return e.hasAttribute(`${l.prefix}each`)&&e.hasAttribute(`${l.prefix}each-visible`)}static resolveVarName(e){const t=e.getRawAttribute(`${l.prefix}each-visible`);return typeof t=="string"?t.trim():""}static resolveRoot(e){const t=`${l.prefix}each-visible-root`;if(!e.hasAttribute(t))return null;const r=e.getAttribute(t);if(typeof r!="string"||r.trim()==="")return null;const i=document.querySelector(r);return F.isHtmlElement(i)?i:(p.error("[Haori]",`Visible range root element not found: ${r}`),null)}static resolveRootMargin(e){const t=`${l.prefix}each-visible-margin`,r=e.getAttribute(t);return r===null||r===!1||r===""?F.DEFAULT_ROOT_MARGIN:String(r)}static realRowElements(e){return e.getChildren().filter(t=>t instanceof N&&!t.hasAttribute(`${l.prefix}each-before`)&&!t.hasAttribute(`${l.prefix}each-after`)).map(t=>t.getTarget())}static refreshRows(e){const t=F.realRowElements(e.fragment),r=new Set(t);for(const i of[...e.observedRows])r.has(i)||(e.observer.unobserve(i),e.observedRows.delete(i),e.visibleRows.delete(i));for(const i of t)e.observedRows.has(i)||(e.observer.observe(i),e.observedRows.add(i));F.scheduleCompute(e)}static scheduleCompute(e){e.scheduled||(e.scheduled=!0,Tt(()=>{e.scheduled=!1;const t=e.fragment.getTarget();F.registrations.get(t)===e&&F.computeAndPublish(e)}))}static computeAndPublish(e){const t=F.realRowElements(e.fragment),r=new Map;t.forEach((a,o)=>r.set(a,o));const i=[];for(const a of e.visibleRows){const o=r.get(a);o!==void 0&&i.push(o)}let n;if(i.length===0)n={first:-1,last:-1,firstLabel:0,lastLabel:0,count:0,total:t.length,empty:!0};else{let a=i[0],o=i[0];for(const u of i)u<a&&(a=u),u>o&&(o=u);n={first:a,last:o,firstLabel:a+1,lastLabel:o+1,count:i.length,total:t.length,empty:!1}}const s=JSON.stringify(n);s!==e.lastSnapshot&&(e.lastSnapshot=s,F.publish(e,n))}static publish(e,t){const r=F.resolveBindOwner(e.fragment);if(!r){p.warn("[Haori]","data-each-visible found no ancestor data-bind scope to publish into.");return}const i=r.getTarget(),n={...r.getRawBindingData()??{}};n[e.varName]={...t};const s=e.fragment.getTarget(),a=i===s?new Set:new Set([e.fragment]);P.setBindingData(i,n,a,!1,!1).catch(o=>{p.error("[Haori]","Failed to publish visible range:",o)})}static resolveBindOwner(e){const t=`${l.prefix}bind`;let r=e.getParent();for(;r;){if(r.hasAttribute(t))return r;r=r.getParent()}return e.hasAttribute(t)?e:null}};F.THRESHOLD=0,F.DEFAULT_ROOT_MARGIN="0px",F.registrations=new Map;let _=F;const q=class q{static disconnectMutationObservers(){q._mutationObservers.forEach(e=>{e.disconnect()}),q._mutationObservers.length=0}static async init(){if(q._initialized)return;q._initialized=!0,q.disconnectMutationObservers();const e=new Fe;q._dispatcher=e,e.startDeferred();try{const t=await Promise.allSettled([P.scan(document.head),P.scan(document.body)]),[r,i]=t;r.status!=="fulfilled"&&p.error("[Haori]","Failed to build head fragment:",r.reason),i.status!=="fulfilled"&&p.error("[Haori]","Failed to build body fragment:",i.reason),await B.wait(),document.body.setAttribute("data-haori-ready",""),q.observe(document.head),q.observe(document.body),ie.syncTree(document.body),ne.syncTree(document.body),_.syncTree(document.body)}finally{e.release()}}static getDispatcher(){return q._dispatcher}static isExternallyManaged(e){return(e instanceof Element?e:e?.parentElement??null)?.closest(`[${l.prefix}external]`)!=null}static observe(e){const t=new MutationObserver(async r=>{for(const i of r)try{if(q.isExternallyManaged(i.target))continue;switch(i.type){case"attributes":{const n=i.target;if(i.attributeName&&n.hasAttribute("data-haori-click-lock")&&(i.attributeName==="disabled"||i.attributeName==="data-haori-click-lock")||i.attributeName&&P.isAliasedAttributeReflection(n,i.attributeName))break;P.setAttribute(n,i.attributeName,n.getAttribute(i.attributeName),!0),ie.syncElement(n),ne.syncElement(n),_.syncElement(n);break}case"childList":{Array.from(i.removedNodes).forEach(n=>{ie.cleanupTree(n),ne.cleanupTree(n),_.cleanupTree(n),P.removeNode(n)}),Array.from(i.addedNodes).forEach(n=>{n.parentElement instanceof Element&&(P.addNode(n.parentElement,n),ie.syncTree(n),ne.syncTree(n),_.syncTree(n))}),i.target instanceof Element&&_.syncElement(i.target);break}case"characterData":{i.target instanceof Text||i.target instanceof Comment?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(n){p.error("[Haori]","Error processing mutation:",n)}});t.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),q._mutationObservers.push(t)}};q._initialized=!1,q._mutationObservers=[],q._dispatcher=null;let ge=q;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ge.init):ge.init();const Rt=()=>X.waitForRenders(),Dt="0.28.0";exports.Core=P;exports.Env=l;exports.Form=H;exports.Fragment=T;exports.Haori=X;exports.Log=p;exports.Queue=B;exports.default=X;exports.version=Dt;exports.waitForRenders=Rt;
|
|
26
28
|
//# sourceMappingURL=haori.cjs.js.map
|