var gk=Object.defineProperty;var mk=(Yt,ra,aa)=>ra in Yt?gk(Yt,ra,{enumerable:!0,configurable:!0,writable:!0,value:aa}):Yt[ra]=aa;var $=(Yt,ra,aa)=>mk(Yt,typeof ra!="symbol"?ra+"":ra,aa);(function(Yt){"use strict";function ra(s,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}function aa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bd={exports:{}},Ke={};/** * @license React * react.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var gg;function Lw(){if(gg)return Ke;gg=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),C=Symbol.iterator;function S(z){return z===null||typeof z!="object"?null:(z=C&&z[C]||z["@@iterator"],typeof z=="function"?z:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,w={};function R(z,T,pe){this.props=z,this.context=T,this.refs=w,this.updater=pe||v}R.prototype.isReactComponent={},R.prototype.setState=function(z,T){if(typeof z!="object"&&typeof z!="function"&&z!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,z,T,"setState")},R.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function L(){}L.prototype=R.prototype;function O(z,T,pe){this.props=z,this.context=T,this.refs=w,this.updater=pe||v}var j=O.prototype=new L;j.constructor=O,x(j,R.prototype),j.isPureReactComponent=!0;var F=Array.isArray;function G(){}var P={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function he(z,T,pe){var fe=pe.ref;return{$$typeof:s,type:z,key:T,ref:fe!==void 0?fe:null,props:pe}}function Ee(z,T){return he(z.type,T,z.props)}function ke(z){return typeof z=="object"&&z!==null&&z.$$typeof===s}function ze(z){var T={"=":"=0",":":"=2"};return"$"+z.replace(/[=:]/g,function(pe){return T[pe]})}var Be=/\/+/g;function je(z,T){return typeof z=="object"&&z!==null&&z.key!=null?ze(""+z.key):T.toString(36)}function bt(z){switch(z.status){case"fulfilled":return z.value;case"rejected":throw z.reason;default:switch(typeof z.status=="string"?z.then(G,G):(z.status="pending",z.then(function(T){z.status==="pending"&&(z.status="fulfilled",z.value=T)},function(T){z.status==="pending"&&(z.status="rejected",z.reason=T)})),z.status){case"fulfilled":return z.value;case"rejected":throw z.reason}}throw z}function X(z,T,pe,fe,me){var ae=typeof z;(ae==="undefined"||ae==="boolean")&&(z=null);var Re=!1;if(z===null)Re=!0;else switch(ae){case"bigint":case"string":case"number":Re=!0;break;case"object":switch(z.$$typeof){case s:case e:Re=!0;break;case m:return Re=z._init,X(Re(z._payload),T,pe,fe,me)}}if(Re)return me=me(z),Re=fe===""?"."+je(z,0):fe,F(me)?(pe="",Re!=null&&(pe=Re.replace(Be,"$&/")+"/"),X(me,T,pe,"",function(Ge){return Ge})):me!=null&&(ke(me)&&(me=Ee(me,pe+(me.key==null||z&&z.key===me.key?"":(""+me.key).replace(Be,"$&/")+"/")+Re)),T.push(me)),1;Re=0;var Pe=fe===""?".":fe+":";if(F(z))for(var Me=0;Me>>1,ge=X[Z];if(0>>1;Zi(pe,Ce))fei(me,pe)?(X[Z]=me,X[fe]=Ce,Z=fe):(X[Z]=pe,X[T]=Ce,Z=T);else if(fei(me,Ce))X[Z]=me,X[fe]=Ce,Z=fe;else break e}}return de}function i(X,de){var Ce=X.sortIndex-de.sortIndex;return Ce!==0?Ce:X.id-de.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;s.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();s.unstable_now=function(){return c.now()-d}}var f=[],p=[],m=1,y=null,C=3,S=!1,v=!1,x=!1,w=!1,R=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function j(X){for(var de=n(p);de!==null;){if(de.callback===null)r(p);else if(de.startTime<=X)r(p),de.sortIndex=de.expirationTime,e(f,de);else break;de=n(p)}}function F(X){if(x=!1,j(X),!v)if(n(f)!==null)v=!0,G||(G=!0,ze());else{var de=n(p);de!==null&&bt(F,de.startTime-X)}}var G=!1,P=-1,K=5,he=-1;function Ee(){return w?!0:!(s.unstable_now()-heX&&Ee());){var Z=y.callback;if(typeof Z=="function"){y.callback=null,C=y.priorityLevel;var ge=Z(y.expirationTime<=X);if(X=s.unstable_now(),typeof ge=="function"){y.callback=ge,j(X),de=!0;break t}y===n(f)&&r(f),j(X)}else r(f);y=n(f)}if(y!==null)de=!0;else{var z=n(p);z!==null&&bt(F,z.startTime-X),de=!1}}break e}finally{y=null,C=Ce,S=!1}de=void 0}}finally{de?ze():G=!1}}}var ze;if(typeof O=="function")ze=function(){O(ke)};else if(typeof MessageChannel<"u"){var Be=new MessageChannel,je=Be.port2;Be.port1.onmessage=ke,ze=function(){je.postMessage(null)}}else ze=function(){R(ke,0)};function bt(X,de){P=R(function(){X(s.unstable_now())},de)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(X){X.callback=null},s.unstable_forceFrameRate=function(X){0>X||125Z?(X.sortIndex=Ce,e(p,X),n(f)===null&&X===n(p)&&(x?(L(P),P=-1):x=!0,bt(F,Ce-Z))):(X.sortIndex=ge,e(f,X),v||S||(v=!0,G||(G=!0,ze()))),X},s.unstable_shouldYield=Ee,s.unstable_wrapCallback=function(X){var de=C;return function(){var Ce=C;C=de;try{return X.apply(this,arguments)}finally{C=Ce}}}})(Cd)),Cd}var bg;function Mw(){return bg||(bg=1,wd.exports=$w()),wd.exports}var Ed={exports:{}},wn={};/** * @license React * react-dom.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var vg;function Nw(){if(vg)return wn;vg=1;var s=vd();function e(f){var p="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Ed.exports=Nw(),Ed.exports}/** * @license React * react-dom-client.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Cg;function Iw(){if(Cg)return uo;Cg=1;var s=Mw(),e=vd(),n=wg();function r(t){var a="https://react.dev/errors/"+t;if(1ge||(t.current=Z[ge],Z[ge]=null,ge--)}function pe(t,a){ge++,Z[ge]=t.current,t.current=a}var fe=z(null),me=z(null),ae=z(null),Re=z(null);function Pe(t,a){switch(pe(ae,a),pe(me,t),pe(fe,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?ZS(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=ZS(a),t=ew(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(fe),pe(fe,t)}function Me(){T(fe),T(me),T(ae)}function Ge(t){t.memoizedState!==null&&pe(Re,t);var a=fe.current,o=ew(a,t.type);a!==o&&(pe(me,t),pe(fe,o))}function kt(t){me.current===t&&(T(fe),T(me)),Re.current===t&&(T(Re),Ql._currentValue=Ce)}var vt,hn;function Dt(t){if(vt===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);vt=a&&a[1]||"",hn=-1)":-1h||H[u]!==Y[h]){var ne=` `+H[u].replace(" at new "," at ");return t.displayName&&ne.includes("")&&(ne=ne.replace("",t.displayName)),ne}while(1<=u&&0<=h);break}}}finally{Xt=!1,Error.prepareStackTrace=o}return(o=t?t.displayName||t.name:"")?Dt(o):""}function Ut(t,a){switch(t.tag){case 26:case 27:case 5:return Dt(t.type);case 16:return Dt("Lazy");case 13:return t.child!==a&&a!==null?Dt("Suspense Fallback"):Dt("Suspense");case 19:return Dt("SuspenseList");case 0:case 15:return un(t.type,!1);case 11:return un(t.type.render,!1);case 1:return un(t.type,!0);case 31:return Dt("Activity");default:return""}}function $r(t){try{var a="",o=null;do a+=Ut(t,o),o=t,t=t.return;while(t);return a}catch(u){return` Error generating stack: `+u.message+` `+u.stack}}var En=Object.prototype.hasOwnProperty,dn=s.unstable_scheduleCallback,pn=s.unstable_cancelCallback,fr=s.unstable_shouldYield,er=s.unstable_requestPaint,Pt=s.unstable_now,St=s.unstable_getCurrentPriorityLevel,da=s.unstable_ImmediatePriority,In=s.unstable_UserBlockingPriority,kn=s.unstable_NormalPriority,Rn=s.unstable_LowPriority,jn=s.unstable_IdlePriority,gn=s.log,fa=s.unstable_setDisableYieldValue,zn=null,Vt=null;function _n(t){if(typeof gn=="function"&&fa(t),Vt&&typeof Vt.setStrictMode=="function")try{Vt.setStrictMode(zn,t)}catch{}}var an=Math.clz32?Math.clz32:ce,q=Math.log,oe=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(q(t)/oe|0)|0}var J=256,ve=262144,ue=4194304;function we(t){var a=t&42;if(a!==0)return a;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function _e(t,a,o){var u=t.pendingLanes;if(u===0)return 0;var h=0,g=t.suspendedLanes,E=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?h=we(u):(E&=k,E!==0?h=we(E):o||(o=k&~t,o!==0&&(h=we(o))))):(k=u&~g,k!==0?h=we(k):E!==0?h=we(E):o||(o=u&~t,o!==0&&(h=we(o)))),h===0?0:a!==0&&a!==h&&(a&g)===0&&(g=h&-h,o=a&-a,g>=o||g===32&&(o&4194048)!==0)?a:h}function qe(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function xe(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function De(){var t=ue;return ue<<=1,(ue&62914560)===0&&(ue=4194304),t}function Ae(t){for(var a=[],o=0;31>o;o++)a.push(t);return a}function tt(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Ne(t,a,o,u,h,g){var E=t.pendingLanes;t.pendingLanes=o,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=o,t.entangledLanes&=o,t.errorRecoveryDisabledLanes&=o,t.shellSuspendCounter=0;var k=t.entanglements,H=t.expirationTimes,Y=t.hiddenUpdates;for(o=E&~o;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Ni=/[\n"\\]/g;function Bn(t){return t.replace(Ni,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function ma(t,a,o,u,h,g,E,k){t.name="",E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?t.type=E:t.removeAttribute("type"),a!=null?E==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+Pn(a)):t.value!==""+Pn(a)&&(t.value=""+Pn(a)):E!=="submit"&&E!=="reset"||t.removeAttribute("value"),a!=null?rl(t,E,Pn(a)):o!=null?rl(t,E,Pn(o)):u!=null&&t.removeAttribute("value"),h==null&&g!=null&&(t.defaultChecked=!!g),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+Pn(k):t.removeAttribute("name")}function nu(t,a,o,u,h,g,E,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(t.type=g),a!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||a!=null)){tl(t);return}o=o!=null?""+Pn(o):"",a=a!=null?""+Pn(a):o,k||a===t.value||(t.value=a),t.defaultValue=a}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"&&(t.name=E),tl(t)}function rl(t,a,o){a==="number"&&ga(t.ownerDocument)===t||t.defaultValue===""+o||(t.defaultValue=""+o)}function Va(t,a,o,u){if(t=t.options,a){a={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ol=!1;if(Ir)try{var ji={};Object.defineProperty(ji,"passive",{get:function(){ol=!0}}),window.addEventListener("test",ji,ji),window.removeEventListener("test",ji,ji)}catch{ol=!1}var jr=null,ll=null,Ls=null;function Fe(){if(Ls)return Ls;var t,a=ll,o=a.length,u,h="value"in jr?jr.value:jr.textContent,g=h.length;for(t=0;t=ct),du=" ",pl=!1;function fu(t,a){switch(t){case"keyup":return Ve.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function gl(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ja=!1;function hu(t,a){switch(t){case"compositionend":return gl(a);case"keypress":return a.which!==32?null:(pl=!0,du);case"textInput":return t=a.data,t===du&&pl?null:t;default:return null}}function Ch(t,a){if(Ja)return t==="compositionend"||!it&&fu(t,a)?(t=Fe(),Ls=ll=jr=null,Ja=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-t};t=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=yb(o)}}function vb(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?vb(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Sb(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=ga(t.document);a instanceof t.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)t=a.contentWindow;else break;a=ga(t.document)}return a}function _h(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var Wx=Ir&&"documentMode"in document&&11>=document.documentMode,Is=null,Ah=null,El=null,xh=!1;function wb(t,a,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;xh||Is==null||Is!==ga(u)||(u=Is,"selectionStart"in u&&_h(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),El&&Cl(El,u)||(El=u,u=rd(Ah,"onSelect"),0>=E,h-=E,Zr=1<<32-an(a)+h|o<Qe?(ot=Le,Le=null):ot=Le.sibling;var pt=Q(V,Le,W[Qe],se);if(pt===null){Le===null&&(Le=ot);break}t&&Le&&pt.alternate===null&&a(V,Le),B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt,Le=ot}if(Qe===W.length)return o(V,Le),ut&&Sa(V,Qe),Ie;if(Le===null){for(;QeQe?(ot=Le,Le=null):ot=Le.sibling;var Si=Q(V,Le,pt.value,se);if(Si===null){Le===null&&(Le=ot);break}t&&Le&&Si.alternate===null&&a(V,Le),B=g(Si,B,Qe),ht===null?Ie=Si:ht.sibling=Si,ht=Si,Le=ot}if(pt.done)return o(V,Le),ut&&Sa(V,Qe),Ie;if(Le===null){for(;!pt.done;Qe++,pt=W.next())pt=le(V,pt.value,se),pt!==null&&(B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt);return ut&&Sa(V,Qe),Ie}for(Le=u(Le);!pt.done;Qe++,pt=W.next())pt=te(Le,V,Qe,pt.value,se),pt!==null&&(t&&pt.alternate!==null&&Le.delete(pt.key===null?Qe:pt.key),B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt);return t&&Le.forEach(function(pk){return a(V,pk)}),ut&&Sa(V,Qe),Ie}function xt(V,B,W,se){if(typeof W=="object"&&W!==null&&W.type===x&&W.key===null&&(W=W.props.children),typeof W=="object"&&W!==null){switch(W.$$typeof){case S:e:{for(var Ie=W.key;B!==null;){if(B.key===Ie){if(Ie=W.type,Ie===x){if(B.tag===7){o(V,B.sibling),se=h(B,W.props.children),se.return=V,V=se;break e}}else if(B.elementType===Ie||typeof Ie=="object"&&Ie!==null&&Ie.$$typeof===K&&Yi(Ie)===B.type){o(V,B.sibling),se=h(B,W.props),Rl(se,W),se.return=V,V=se;break e}o(V,B);break}else a(V,B);B=B.sibling}W.type===x?(se=Gi(W.props.children,V.mode,se,W.key),se.return=V,V=se):(se=Su(W.type,W.key,W.props,null,V.mode,se),Rl(se,W),se.return=V,V=se)}return E(V);case v:e:{for(Ie=W.key;B!==null;){if(B.key===Ie)if(B.tag===4&&B.stateNode.containerInfo===W.containerInfo&&B.stateNode.implementation===W.implementation){o(V,B.sibling),se=h(B,W.children||[]),se.return=V,V=se;break e}else{o(V,B);break}else a(V,B);B=B.sibling}se=$h(W,V.mode,se),se.return=V,V=se}return E(V);case K:return W=Yi(W),xt(V,B,W,se)}if(bt(W))return Te(V,B,W,se);if(ze(W)){if(Ie=ze(W),typeof Ie!="function")throw Error(r(150));return W=Ie.call(W),Ue(V,B,W,se)}if(typeof W.then=="function")return xt(V,B,Tu(W),se);if(W.$$typeof===O)return xt(V,B,Eu(V,W),se);ku(V,W)}return typeof W=="string"&&W!==""||typeof W=="number"||typeof W=="bigint"?(W=""+W,B!==null&&B.tag===6?(o(V,B.sibling),se=h(B,W),se.return=V,V=se):(o(V,B),se=Lh(W,V.mode,se),se.return=V,V=se),E(V)):o(V,B)}return function(V,B,W,se){try{kl=0;var Ie=xt(V,B,W,se);return Ks=null,Ie}catch(Le){if(Le===Vs||Le===Au)throw Le;var ht=nr(29,Le,null,V.mode);return ht.lanes=se,ht.return=V,ht}finally{}}}var Ji=Gb(!0),Fb=Gb(!1),ri=!1;function Fh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Vh(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ai(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ii(t,a,o){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(mt&2)!==0){var h=u.pending;return h===null?a.next=a:(a.next=h.next,h.next=a),u.pending=a,a=vu(t),kb(t,null,o),a}return bu(t,u,a,o),vu(t)}function Dl(t,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Se(t,o)}}function Kh(t,a){var o=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var h=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var E={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?h=g=E:g=g.next=E,o=o.next}while(o!==null);g===null?h=g=a:g=g.next=a}else h=g=a;o={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},t.updateQueue=o;return}t=o.lastBaseUpdate,t===null?o.firstBaseUpdate=a:t.next=a,o.lastBaseUpdate=a}var Wh=!1;function Ol(){if(Wh){var t=Fs;if(t!==null)throw t}}function Ll(t,a,o,u){Wh=!1;var h=t.updateQueue;ri=!1;var g=h.firstBaseUpdate,E=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var H=k,Y=H.next;H.next=null,E===null?g=Y:E.next=Y,E=H;var ne=t.alternate;ne!==null&&(ne=ne.updateQueue,k=ne.lastBaseUpdate,k!==E&&(k===null?ne.firstBaseUpdate=Y:k.next=Y,ne.lastBaseUpdate=H))}if(g!==null){var le=h.baseState;E=0,ne=Y=H=null,k=g;do{var Q=k.lane&-536870913,te=Q!==k.lane;if(te?(st&Q)===Q:(u&Q)===Q){Q!==0&&Q===Gs&&(Wh=!0),ne!==null&&(ne=ne.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Te=t,Ue=k;Q=a;var xt=o;switch(Ue.tag){case 1:if(Te=Ue.payload,typeof Te=="function"){le=Te.call(xt,le,Q);break e}le=Te;break e;case 3:Te.flags=Te.flags&-65537|128;case 0:if(Te=Ue.payload,Q=typeof Te=="function"?Te.call(xt,le,Q):Te,Q==null)break e;le=y({},le,Q);break e;case 2:ri=!0}}Q=k.callback,Q!==null&&(t.flags|=64,te&&(t.flags|=8192),te=h.callbacks,te===null?h.callbacks=[Q]:te.push(Q))}else te={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ne===null?(Y=ne=te,H=le):ne=ne.next=te,E|=Q;if(k=k.next,k===null){if(k=h.shared.pending,k===null)break;te=k,k=te.next,te.next=null,h.lastBaseUpdate=te,h.shared.pending=null}}while(!0);ne===null&&(H=le),h.baseState=H,h.firstBaseUpdate=Y,h.lastBaseUpdate=ne,g===null&&(h.shared.lanes=0),ui|=E,t.lanes=E,t.memoizedState=le}}function Vb(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function Kb(t,a){var o=t.callbacks;if(o!==null)for(t.callbacks=null,t=0;tg?g:8;var E=X.T,k={};X.T=k,hp(t,!1,a,o);try{var H=h(),Y=X.S;if(Y!==null&&Y(k,H),H!==null&&typeof H=="object"&&typeof H.then=="function"){var ne=rT(H,u);Nl(t,a,ne,or(t))}else Nl(t,a,u,or(t))}catch(le){Nl(t,a,{then:function(){},status:"rejected",reason:le},or())}finally{de.p=g,E!==null&&k.types!==null&&(E.types=k.types),X.T=E}}function cT(){}function dp(t,a,o,u){if(t.tag!==5)throw Error(r(476));var h=Av(t).queue;_v(t,h,a,Ce,o===null?cT:function(){return xv(t),o(u)})}function Av(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:Ce,baseState:Ce,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_a,lastRenderedState:Ce},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_a,lastRenderedState:o},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function xv(t){var a=Av(t);a.next===null&&(a=t.alternate.memoizedState),Nl(t,a.next.queue,{},or())}function fp(){return bn(Ql)}function Tv(){return Wt().memoizedState}function kv(){return Wt().memoizedState}function uT(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var o=or();t=ai(o);var u=ii(a,t,o);u!==null&&(Kn(u,a,o),Dl(u,a,o)),a={cache:Ph()},t.payload=a;return}a=a.return}}function dT(t,a,o){var u=or();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},zu(t)?Dv(a,o):(o=Dh(t,a,o,u),o!==null&&(Kn(o,t,u),Ov(o,a,u)))}function Rv(t,a,o){var u=or();Nl(t,a,o,u)}function Nl(t,a,o,u){var h={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(zu(t))Dv(a,h);else{var g=t.alternate;if(t.lanes===0&&(g===null||g.lanes===0)&&(g=a.lastRenderedReducer,g!==null))try{var E=a.lastRenderedState,k=g(E,o);if(h.hasEagerState=!0,h.eagerState=k,tr(k,E))return bu(t,a,h,0),Rt===null&&yu(),!1}catch{}finally{}if(o=Dh(t,a,h,u),o!==null)return Kn(o,t,u),Ov(o,a,u),!0}return!1}function hp(t,a,o,u){if(u={lane:2,revertLane:Fp(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},zu(t)){if(a)throw Error(r(479))}else a=Dh(t,o,u,2),a!==null&&Kn(a,t,2)}function zu(t){var a=t.alternate;return t===Xe||a!==null&&a===Xe}function Dv(t,a){Ys=Ou=!0;var o=t.pending;o===null?a.next=a:(a.next=o.next,o.next=a),t.pending=a}function Ov(t,a,o){if((o&4194048)!==0){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Se(t,o)}}var Il={readContext:bn,use:Mu,useCallback:qt,useContext:qt,useEffect:qt,useImperativeHandle:qt,useLayoutEffect:qt,useInsertionEffect:qt,useMemo:qt,useReducer:qt,useRef:qt,useState:qt,useDebugValue:qt,useDeferredValue:qt,useTransition:qt,useSyncExternalStore:qt,useId:qt,useHostTransitionStatus:qt,useFormState:qt,useActionState:qt,useOptimistic:qt,useMemoCache:qt,useCacheRefresh:qt};Il.useEffectEvent=qt;var Lv={readContext:bn,use:Mu,useCallback:function(t,a){return Dn().memoizedState=[t,a===void 0?null:a],t},useContext:bn,useEffect:gv,useImperativeHandle:function(t,a,o){o=o!=null?o.concat([t]):null,Iu(4194308,4,vv.bind(null,a,t),o)},useLayoutEffect:function(t,a){return Iu(4194308,4,t,a)},useInsertionEffect:function(t,a){Iu(4,2,t,a)},useMemo:function(t,a){var o=Dn();a=a===void 0?null:a;var u=t();if(Qi){_n(!0);try{t()}finally{_n(!1)}}return o.memoizedState=[u,a],u},useReducer:function(t,a,o){var u=Dn();if(o!==void 0){var h=o(a);if(Qi){_n(!0);try{o(a)}finally{_n(!1)}}}else h=a;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=dT.bind(null,Xe,t),[u.memoizedState,t]},useRef:function(t){var a=Dn();return t={current:t},a.memoizedState=t},useState:function(t){t=sp(t);var a=t.queue,o=Rv.bind(null,Xe,a);return a.dispatch=o,[t.memoizedState,o]},useDebugValue:cp,useDeferredValue:function(t,a){var o=Dn();return up(o,t,a)},useTransition:function(){var t=sp(!1);return t=_v.bind(null,Xe,t.queue,!0,!1),Dn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,o){var u=Xe,h=Dn();if(ut){if(o===void 0)throw Error(r(407));o=o()}else{if(o=a(),Rt===null)throw Error(r(349));(st&127)!==0||Zb(u,a,o)}h.memoizedState=o;var g={value:o,getSnapshot:a};return h.queue=g,gv(tv.bind(null,u,g,t),[t]),u.flags|=2048,Js(9,{destroy:void 0},ev.bind(null,u,g,o,a),null),o},useId:function(){var t=Dn(),a=Rt.identifierPrefix;if(ut){var o=ea,u=Zr;o=(u&~(1<<32-an(u)-1)).toString(32)+o,a="_"+a+"R_"+o,o=Lu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?E.createElement("select",{is:u.is}):E.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?E.createElement(h,{is:u.is}):E.createElement(h)}}g[jt]=a,g[mn]=u;e:for(E=a.child;E!==null;){if(E.tag===5||E.tag===6)g.appendChild(E.stateNode);else if(E.tag!==4&&E.tag!==27&&E.child!==null){E.child.return=E,E=E.child;continue}if(E===a)break e;for(;E.sibling===null;){if(E.return===null||E.return===a)break e;E=E.return}E.sibling.return=E.return,E=E.sibling}a.stateNode=g;e:switch(Sn(g,h,u),h){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&xa(a)}}return $t(a),Tp(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,o),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==u&&xa(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(t=ae.current,Bs(a)){if(t=a.stateNode,o=a.memoizedProps,u=null,h=yn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[jt]=a,t=!!(t.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||JS(t.nodeValue,o)),t||ti(a,!0)}else t=ad(t).createTextNode(u),t[jt]=a,a.stateNode=t}return $t(a),null;case 31:if(o=a.memoizedState,t===null||t.memoizedState!==null){if(u=Bs(a),o!==null){if(t===null){if(!u)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[jt]=a}else Fi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),t=!1}else o=jh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),t=!0;if(!t)return a.flags&256?(ar(a),a):(ar(a),null);if((a.flags&128)!==0)throw Error(r(558))}return $t(a),null;case 13:if(u=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Bs(a),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(r(318));if(h=a.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));h[jt]=a}else Fi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),h=!1}else h=jh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return a.flags&256?(ar(a),a):(ar(a),null)}return ar(a),(a.flags&128)!==0?(a.lanes=o,a):(o=u!==null,t=t!==null&&t.memoizedState!==null,o&&(u=a.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==h&&(u.flags|=2048)),o!==t&&o&&(a.child.flags|=8192),qu(a,a.updateQueue),$t(a),null);case 4:return Me(),t===null&&Yp(a.stateNode.containerInfo),$t(a),null;case 10:return Ca(a.type),$t(a),null;case 19:if(T(Kt),u=a.memoizedState,u===null)return $t(a),null;if(h=(a.flags&128)!==0,g=u.rendering,g===null)if(h)zl(u,!1);else{if(Gt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(g=Du(t),g!==null){for(a.flags|=128,zl(u,!1),t=g.updateQueue,a.updateQueue=t,qu(a,t),a.subtreeFlags=0,t=o,o=a.child;o!==null;)Rb(o,t),o=o.sibling;return pe(Kt,Kt.current&1|2),ut&&Sa(a,u.treeForkCount),a.child}t=t.sibling}u.tail!==null&&Pt()>Wu&&(a.flags|=128,h=!0,zl(u,!1),a.lanes=4194304)}else{if(!h)if(t=Du(g),t!==null){if(a.flags|=128,h=!0,t=t.updateQueue,a.updateQueue=t,qu(a,t),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!ut)return $t(a),null}else 2*Pt()-u.renderingStartTime>Wu&&o!==536870912&&(a.flags|=128,h=!0,zl(u,!1),a.lanes=4194304);u.isBackwards?(g.sibling=a.child,a.child=g):(t=u.last,t!==null?t.sibling=g:a.child=g,u.last=g)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Pt(),t.sibling=null,o=Kt.current,pe(Kt,h?o&1|2:o&1),ut&&Sa(a,u.treeForkCount),t):($t(a),null);case 22:case 23:return ar(a),Xh(),u=a.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(o&536870912)!==0&&(a.flags&128)===0&&($t(a),a.subtreeFlags&6&&(a.flags|=8192)):$t(a),o=a.updateQueue,o!==null&&qu(a,o.retryQueue),o=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==o&&(a.flags|=2048),t!==null&&T(Wi),null;case 24:return o=null,t!==null&&(o=t.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),Ca(Qt),$t(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function mT(t,a){switch(Nh(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return Ca(Qt),Me(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return kt(a),null;case 31:if(a.memoizedState!==null){if(ar(a),a.alternate===null)throw Error(r(340));Fi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(ar(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Fi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return T(Kt),null;case 4:return Me(),null;case 10:return Ca(a.type),null;case 22:case 23:return ar(a),Xh(),t!==null&&T(Wi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return Ca(Qt),null;case 25:return null;default:return null}}function nS(t,a){switch(Nh(a),a.tag){case 3:Ca(Qt),Me();break;case 26:case 27:case 5:kt(a);break;case 4:Me();break;case 31:a.memoizedState!==null&&ar(a);break;case 13:ar(a);break;case 19:T(Kt);break;case 10:Ca(a.type);break;case 22:case 23:ar(a),Xh(),t!==null&&T(Wi);break;case 24:Ca(Qt)}}function Hl(t,a){try{var o=a.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var h=u.next;o=h;do{if((o.tag&t)===t){u=void 0;var g=o.create,E=o.inst;u=g(),E.destroy=u}o=o.next}while(o!==h)}}catch(k){Ct(a,a.return,k)}}function li(t,a,o){try{var u=a.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var g=h.next;u=g;do{if((u.tag&t)===t){var E=u.inst,k=E.destroy;if(k!==void 0){E.destroy=void 0,h=a;var H=o,Y=k;try{Y()}catch(ne){Ct(h,H,ne)}}}u=u.next}while(u!==g)}}catch(ne){Ct(a,a.return,ne)}}function rS(t){var a=t.updateQueue;if(a!==null){var o=t.stateNode;try{Kb(a,o)}catch(u){Ct(t,t.return,u)}}}function aS(t,a,o){o.props=Zi(t.type,t.memoizedProps),o.state=t.memoizedState;try{o.componentWillUnmount()}catch(u){Ct(t,a,u)}}function Ul(t,a){try{var o=t.ref;if(o!==null){switch(t.tag){case 26:case 27:case 5:var u=t.stateNode;break;case 30:u=t.stateNode;break;default:u=t.stateNode}typeof o=="function"?t.refCleanup=o(u):o.current=u}}catch(h){Ct(t,a,h)}}function ta(t,a){var o=t.ref,u=t.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(h){Ct(t,a,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(h){Ct(t,a,h)}else o.current=null}function iS(t){var a=t.type,o=t.memoizedProps,u=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(h){Ct(t,t.return,h)}}function kp(t,a,o){try{var u=t.stateNode;zT(u,t.type,o,a),u[mn]=a}catch(h){Ct(t,t.return,h)}}function sS(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&gi(t.type)||t.tag===4}function Rp(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||sS(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&gi(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Dp(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(t,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(t),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=hr));else if(u!==4&&(u===27&&gi(t.type)&&(o=t.stateNode,a=null),t=t.child,t!==null))for(Dp(t,a,o),t=t.sibling;t!==null;)Dp(t,a,o),t=t.sibling}function Gu(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?o.insertBefore(t,a):o.appendChild(t);else if(u!==4&&(u===27&&gi(t.type)&&(o=t.stateNode),t=t.child,t!==null))for(Gu(t,a,o),t=t.sibling;t!==null;)Gu(t,a,o),t=t.sibling}function oS(t){var a=t.stateNode,o=t.memoizedProps;try{for(var u=t.type,h=a.attributes;h.length;)a.removeAttributeNode(h[0]);Sn(a,u,o),a[jt]=t,a[mn]=o}catch(g){Ct(t,t.return,g)}}var Ta=!1,tn=!1,Op=!1,lS=typeof WeakSet=="function"?WeakSet:Set,fn=null;function yT(t,a){if(t=t.containerInfo,Qp=dd,t=Sb(t),_h(t)){if("selectionStart"in t)var o={start:t.selectionStart,end:t.selectionEnd};else e:{o=(o=t.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var h=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var E=0,k=-1,H=-1,Y=0,ne=0,le=t,Q=null;t:for(;;){for(var te;le!==o||h!==0&&le.nodeType!==3||(k=E+h),le!==g||u!==0&&le.nodeType!==3||(H=E+u),le.nodeType===3&&(E+=le.nodeValue.length),(te=le.firstChild)!==null;)Q=le,le=te;for(;;){if(le===t)break t;if(Q===o&&++Y===h&&(k=E),Q===g&&++ne===u&&(H=E),(te=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=te}o=k===-1||H===-1?null:{start:k,end:H}}else o=null}o=o||{start:0,end:0}}else o=null;for(Zp={focusedElem:t,selectionRange:o},dd=!1,fn=a;fn!==null;)if(a=fn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,fn=t;else for(;fn!==null;){switch(a=fn,g=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(o=0;o title"))),Sn(g,u,o),g[jt]=t,Jt(g),u=g;break e;case"link":var E=pw("link","href",h).get(u+(o.href||""));if(E){for(var k=0;kxt&&(E=xt,xt=Ue,Ue=E);var V=bb(k,Ue),B=bb(k,xt);if(V&&B&&(te.rangeCount!==1||te.anchorNode!==V.node||te.anchorOffset!==V.offset||te.focusNode!==B.node||te.focusOffset!==B.offset)){var W=le.createRange();W.setStart(V.node,V.offset),te.removeAllRanges(),Ue>xt?(te.addRange(W),te.extend(B.node,B.offset)):(W.setEnd(B.node,B.offset),te.addRange(W))}}}}for(le=[],te=k;te=te.parentNode;)te.nodeType===1&&le.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;ko?32:o,X.T=null,o=zp,zp=null;var g=fi,E=La;if(on=0,no=fi=null,La=0,(mt&6)!==0)throw Error(r(331));var k=mt;if(mt|=4,vS(g.current),mS(g,g.current,E,o),mt=k,Vl(0,!1),Vt&&typeof Vt.onPostCommitFiberRoot=="function")try{Vt.onPostCommitFiberRoot(zn,g)}catch{}return!0}finally{de.p=h,X.T=u,jS(t,a)}}function HS(t,a,o){a=gr(o,a),a=yp(t.stateNode,a,2),t=ii(t,a,2),t!==null&&(tt(t,2),na(t))}function Ct(t,a,o){if(t.tag===3)HS(t,t,o);else for(;a!==null;){if(a.tag===3){HS(a,t,o);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(di===null||!di.has(u))){t=gr(o,t),o=Uv(2),u=ii(a,o,2),u!==null&&(Pv(o,u,a,t),tt(u,2),na(u));break}}a=a.return}}function Bp(t,a,o){var u=t.pingCache;if(u===null){u=t.pingCache=new ST;var h=new Set;u.set(a,h)}else h=u.get(a),h===void 0&&(h=new Set,u.set(a,h));h.has(o)||(Mp=!0,h.add(o),t=AT.bind(null,t,a,o),a.then(t,t))}function AT(t,a,o){var u=t.pingCache;u!==null&&u.delete(a),t.pingedLanes|=t.suspendedLanes&o,t.warmLanes&=~o,Rt===t&&(st&o)===o&&(Gt===4||Gt===3&&(st&62914560)===st&&300>Pt()-Ku?(mt&2)===0&&ro(t,0):Np|=o,to===st&&(to=0)),na(t)}function US(t,a){a===0&&(a=De()),t=qi(t,a),t!==null&&(tt(t,a),na(t))}function xT(t){var a=t.memoizedState,o=0;a!==null&&(o=a.retryLane),US(t,o)}function TT(t,a){var o=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(o=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),US(t,o)}function kT(t,a){return dn(t,a)}var ed=null,io=null,qp=!1,td=!1,Gp=!1,pi=0;function na(t){t!==io&&t.next===null&&(io===null?ed=io=t:io=io.next=t),td=!0,qp||(qp=!0,DT())}function Vl(t,a){if(!Gp&&td){Gp=!0;do for(var o=!1,u=ed;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var g=0;else{var E=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-an(42|t)+1)-1,g&=h&~(E&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,GS(u,g))}else g=st,g=_e(u,u===Rt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||qe(u,g)||(o=!0,GS(u,g));u=u.next}while(o);Gp=!1}}function RT(){PS()}function PS(){td=qp=!1;var t=0;pi!==0&&UT()&&(t=pi);for(var a=Pt(),o=null,u=ed;u!==null;){var h=u.next,g=BS(u,a);g===0?(u.next=null,o===null?ed=h:o.next=h,h===null&&(io=o)):(o=u,(t!==0||(g&3)!==0)&&(td=!0)),u=h}on!==0&&on!==5||Vl(t),pi!==0&&(pi=0)}function BS(t,a){for(var o=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,g=t.pendingLanes&-62914561;0k)break;var ne=H.transferSize,le=H.initiatorType;ne&&QS(le)&&(H=H.responseEnd,E+=ne*(H"u"?null:document;function uw(t,a,o){var u=so;if(u&&typeof a=="string"&&a){var h=Bn(a);h='link[rel="'+t+'"][href="'+h+'"]',typeof o=="string"&&(h+='[crossorigin="'+o+'"]'),cw.has(h)||(cw.add(h),t={rel:t,crossOrigin:o,href:a},u.querySelector(h)===null&&(a=u.createElement("link"),Sn(a,"link",t),Jt(a),u.head.appendChild(a)))}}function YT(t){$a.D(t),uw("dns-prefetch",t,null)}function XT(t,a){$a.C(t,a),uw("preconnect",t,a)}function JT(t,a,o){$a.L(t,a,o);var u=so;if(u&&t&&a){var h='link[rel="preload"][as="'+Bn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(h+='[imagesrcset="'+Bn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(h+='[imagesizes="'+Bn(o.imageSizes)+'"]')):h+='[href="'+Bn(t)+'"]';var g=h;switch(a){case"style":g=oo(t);break;case"script":g=lo(t)}wr.has(g)||(t=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:t,as:a},o),wr.set(g,t),u.querySelector(h)!==null||a==="style"&&u.querySelector(Xl(g))||a==="script"&&u.querySelector(Jl(g))||(a=u.createElement("link"),Sn(a,"link",t),Jt(a),u.head.appendChild(a)))}}function QT(t,a){$a.m(t,a);var o=so;if(o&&t){var u=a&&typeof a.as=="string"?a.as:"script",h='link[rel="modulepreload"][as="'+Bn(u)+'"][href="'+Bn(t)+'"]',g=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=lo(t)}if(!wr.has(g)&&(t=y({rel:"modulepreload",href:t},a),wr.set(g,t),o.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Jl(g)))return}u=o.createElement("link"),Sn(u,"link",t),Jt(u),o.head.appendChild(u)}}}function ZT(t,a,o){$a.S(t,a,o);var u=so;if(u&&t){var h=Yr(u).hoistableStyles,g=oo(t);a=a||"default";var E=h.get(g);if(!E){var k={loading:0,preload:null};if(E=u.querySelector(Xl(g)))k.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},o),(o=wr.get(g))&&sg(t,o);var H=E=u.createElement("link");Jt(H),Sn(H,"link",t),H._p=new Promise(function(Y,ne){H.onload=Y,H.onerror=ne}),H.addEventListener("load",function(){k.loading|=1}),H.addEventListener("error",function(){k.loading|=2}),k.loading|=4,sd(E,a,u)}E={type:"stylesheet",instance:E,count:1,state:k},h.set(g,E)}}}function ek(t,a){$a.X(t,a);var o=so;if(o&&t){var u=Yr(o).hoistableScripts,h=lo(t),g=u.get(h);g||(g=o.querySelector(Jl(h)),g||(t=y({src:t,async:!0},a),(a=wr.get(h))&&og(t,a),g=o.createElement("script"),Jt(g),Sn(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(h,g))}}function tk(t,a){$a.M(t,a);var o=so;if(o&&t){var u=Yr(o).hoistableScripts,h=lo(t),g=u.get(h);g||(g=o.querySelector(Jl(h)),g||(t=y({src:t,async:!0,type:"module"},a),(a=wr.get(h))&&og(t,a),g=o.createElement("script"),Jt(g),Sn(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(h,g))}}function dw(t,a,o,u){var h=(h=ae.current)?id(h):null;if(!h)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=oo(o.href),o=Yr(h).hoistableStyles,u=o.get(a),u||(u={type:"style",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){t=oo(o.href);var g=Yr(h).hoistableStyles,E=g.get(t);if(E||(h=h.ownerDocument||h,E={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(t,E),(g=h.querySelector(Xl(t)))&&!g._p&&(E.instance=g,E.state.loading=5),wr.has(t)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},wr.set(t,o),g||nk(h,t,o,E.state))),a&&u===null)throw Error(r(528,""));return E}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=lo(o),o=Yr(h).hoistableScripts,u=o.get(a),u||(u={type:"script",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function oo(t){return'href="'+Bn(t)+'"'}function Xl(t){return'link[rel="stylesheet"]['+t+"]"}function fw(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function nk(t,a,o,u){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=t.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),Sn(a,"link",o),Jt(a),t.head.appendChild(a))}function lo(t){return'[src="'+Bn(t)+'"]'}function Jl(t){return"script[async]"+t}function hw(t,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var u=t.querySelector('style[data-href~="'+Bn(o.href)+'"]');if(u)return a.instance=u,Jt(u),u;var h=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Jt(u),Sn(u,"style",h),sd(u,o.precedence,t),a.instance=u;case"stylesheet":h=oo(o.href);var g=t.querySelector(Xl(h));if(g)return a.state.loading|=4,a.instance=g,Jt(g),g;u=fw(o),(h=wr.get(h))&&sg(u,h),g=(t.ownerDocument||t).createElement("link"),Jt(g);var E=g;return E._p=new Promise(function(k,H){E.onload=k,E.onerror=H}),Sn(g,"link",u),a.state.loading|=4,sd(g,o.precedence,t),a.instance=g;case"script":return g=lo(o.src),(h=t.querySelector(Jl(g)))?(a.instance=h,Jt(h),h):(u=o,(h=wr.get(g))&&(u=y({},o),og(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Jt(h),Sn(h,"link",u),t.head.appendChild(h),a.instance=h);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,sd(u,o.precedence,t));return a.instance}function sd(t,a,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,g=h,E=0;E title"):null)}function rk(t,a,o){if(o===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return t=a.disabled,typeof a.precedence=="string"&&t==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function mw(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function ak(t,a,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var h=oo(u.href),g=a.querySelector(Xl(h));if(g){a=g._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=ld.bind(t),a.then(t,t)),o.state.loading|=4,o.instance=g,Jt(g);return}g=a.ownerDocument||a,u=fw(u),(h=wr.get(h))&&sg(u,h),g=g.createElement("link"),Jt(g);var E=g;E._p=new Promise(function(k,H){E.onload=k,E.onerror=H}),Sn(g,"link",u),o.instance=g}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(t.count++,o=ld.bind(t),a.addEventListener("load",o),a.addEventListener("error",o))}}var lg=0;function ik(t,a){return t.stylesheets&&t.count===0&&ud(t,t.stylesheets),0lg?50:800)+a);return t.unsuspend=o,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function ld(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ud(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var cd=null;function ud(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,cd=new Map,a.forEach(sk,t),cd=null,ld.call(t))}function sk(t,a){if(!(a.state.loading&4)){var o=cd.get(t);if(o)var u=o.get(null);else{o=new Map,cd.set(t,o);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Sd.exports=Iw(),Sd.exports}var _d=jw();const Ad=aa(_d),fo=[],zw=50;let xd=!1;function _g(){try{return window.G7Core?.devTools}catch{return}}function ns(s,e,n){const r=_g();if(xd&&r?.isEnabled?.()){r.trackLog?.(s,e,n);return}xd||(s==="error"||s==="warn")&&fo.length{n.isDebugEnabled()&&console.log(e,...r),ns("log",s,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),ns("warn",s,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),ns("error",s,r)}}}ho.getInstance();const Ag="extension",rs="extensionless",xg="file";function Hw(){const s=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===rs)return rs;const n=s?.assetUrlMode;return n===rs||n===Ag?n:s?.settings?.general?.asset_url_mode===rs?rs:Ag}function kd(){return Hw()===rs}function Uw(s,e,n){return Rd("templates",s,e,n)}function Pw(s,e){const n=e.replace(/^\/+/,"").replace(/\/+$/,""),r=encodeURIComponent(s),i=po(`templates/${s}/assets/${n}`);return i!==null?i:`/api/templates/assets/${r}/${n}`}function Bw(s,e,n){return Rd("modules",s,e,n)}function qw(s,e,n){return Rd("plugins",s,e,n)}function Rd(s,e,n,r){const i=n.replace(/^\/+/,""),l=encodeURIComponent(e);if(!kd())return`/api/${s}/assets/${l}/${i}${Vw(r)}`;let c=`${xg}=${encodeURIComponent(i)}`;return r!=null&&r!==""&&(c+=`&v=${r}`),`/api/${s}/assets/${l}?${c}`}function Pr(s,e,n,r){const i=s.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=kd()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Tg(){const s=globalThis?.G7Config?.staticBase;return typeof s=="string"&&s!==""?s.replace(/\/+$/,""):null}function Gw(){const s=Tg();if(!s)return null;const e=s.match(/\/(\d+)$/);return e?Number(e[1]):null}function po(s,e){const n=Tg();if(!n)return null;const r=s.replace(/^\/+/,"");return e!==void 0&&e>0&&e!==Gw()?`${n.replace(/\/\d+$/,"")}/${e}/${r}`:`${n}/${r}`}function Dd(s){if(!s)return null;const e=globalThis?.location?.origin,r=(e&&s.startsWith(e)?s.slice(e.length):s).match(/^\/build\/ext\/(\d+)\/(.+)$/);if(!r)return null;const i=r[1],l=r[2].split("?")[0],c=l.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);if(c){const[,p,m,y]=c;return`/api/${p}/assets/${m}/${y}?v=${i}`}const d=l.match(/^bundles\/(modules|plugins)\.(js|css)$/);if(d)return`/api/${d[1]}/bundle.${d[2]}?v=${i}`;const f=l.match(/^templates\/([^/]+)\/(routes\.json|components\.json|lang\/([a-zA-Z-]+)\.json)$/);if(f){const[,p,m]=f,y=m.replace(/\.json$/,"");return`/api/templates/${p}/${y}.json?v=${i}`}return null}function xn(s){if(!s||!kd())return s;const e=globalThis?.location?.origin,n=e&&s.startsWith(e)?s.slice(e.length):s;if(!n.startsWith("/api/"))return s;const[r,i]=Fw(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return kg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,p,m]=c,y=`${xg}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${p}?${y}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?kg(d[1],i):s}function Fw(s){const e=s.indexOf("?");return e===-1?[s,""]:[s.slice(0,e),s.slice(e+1)]}function kg(s,e){return e?`${s}?${e}`:s}function Vw(s){return s==null||s===""?"":`?v=${s}`}const ia=dt("networkResilience"),Od=2,Ld=300,$d=2e3,Kw=15e3;function Md(s){return s?.name==="AbortError"}function Rg(s){if(Md(s))return!1;if(s instanceof TypeError)return!0;const e=s?.code;return e==="ERR_NETWORK"||e==="ECONNABORTED"}let nc=!1,Dg=!1;function rc(){return nc}function Ww(){typeof window>"u"||Dg||(Dg=!0,window.addEventListener("pagehide",()=>{nc=!0}),window.addEventListener("pageshow",s=>{s.persisted&&(nc=!1)}),window.addEventListener("beforeunload",()=>{nc=!0}))}function Nd(s,e,n){const r=Math.min(e*Math.pow(2,s),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function Id(s){return new Promise(e=>setTimeout(e,s))}async function ac(s,e={}){const{retries:n=Od,baseDelayMs:r=Ld,maxDelayMs:i=$d,timeoutMs:l=Kw,label:c=s,init:d}=e,f=n+1;let p;for(let m=0;m0?new AbortController:null;try{const v={...d};if(S){const w=d?.signal;w&&(w.aborted?S.abort():w.addEventListener("abort",()=>S.abort(),{once:!0})),v.signal=S.signal,C=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(s,v)}catch(v){if(p=v,Md(v)&&!y||!(y||Rg(v)))throw v;if(rc())throw ia.warn(`Document unloading, aborting retries: ${c}`),v;if(m===f-1)throw ia.warn(`All ${f} attempts failed: ${c}`,v),v;const R=Nd(m,r,i);ia.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${R}ms: ${c}`),await Id(R)}finally{C!==void 0&&clearTimeout(C)}}throw p}async function Cr(s,e={},n={}){const{retries:r=Od,baseDelayMs:i=Ld,maxDelayMs:l=$d,label:c=s}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=s,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>n(),i.onerror=()=>r(new Error(`Failed to load script: ${s}`)),document.head.appendChild(i)})}async function sa(s,e={},n={}){const{retries:r=Od,baseDelayMs:i=Ld,maxDelayMs:l=$d,label:c=s}=n,d=r+1;for(let f=0;f{s.onload=()=>e(),s.onerror=()=>n(new Error(`Failed to load stylesheet: ${s.href}`))})}async function ic(s,e,n={}){if(!s)return ac(e,n);try{const r=await fetch(s,n.init);if(r.ok){const i=await r.text();try{return JSON.parse(i),new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return console.warn(`[fetchStaticFirst] Static fast path returned malformed JSON — falling back to API: ${s}`),ac(e,n)}}console.warn(`[fetchStaticFirst] Static fast path miss (${r.status}) — falling back to API: ${s}`)}catch(r){console.warn(`[fetchStaticFirst] Static fast path fetch failed — falling back to API: ${s}`,r)}return ac(e,n)}const Br=dt("ComponentRegistry");class ln extends Error{constructor(e,n,r){super(e),this.code=n,this.details=r,this.name="ComponentRegistryError"}}const Zn=class Zn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"cacheVersion",0);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Zn.instance||(Zn.instance=new Zn),Zn.instance}static createIsolatedInstance(){return new Zn}static resetInstance(){Zn.instance=null}async loadComponents(e,n,r=0){if(this.loadingState==="loading")throw new ln("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Br.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.cacheVersion=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Br.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(i){throw this.loadingState="error",this.error=i instanceof Error?i:new Error(String(i)),new ln(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new ln("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}:v${this.cacheVersion||0}`;if(Zn.manifestCache.has(e)){this.manifest=Zn.manifestCache.get(e),Br.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Pr(`/api/templates/${this.templateId}/components`,"json",this.cacheVersion>0?this.cacheVersion:null),r=await ic(this.cacheVersion>0?po(`templates/${this.templateId}/components.json`,this.cacheVersion):null,n,{label:"components.json"});if(!r.ok)throw new ln(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Zn.manifestCache.set(e,i),Br.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof ln?e:new ln("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new ln("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new ln("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new ln("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new ln(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new ln(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new ln(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Br.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new ln("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new ln(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(n),Br.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof ln?e:new ln("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new ln("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new ln("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Br.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,r){this.registry[e]&&Br.warn(`Component '${e}' already registered, overwriting`);const i=We.memo(n);this.registry[e]={component:i,metadata:r},Br.log(`[ComponentRegistry] Registered component: ${e} (${r.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Br.log("Registry cleared")}};$(Zn,"instance",null),$(Zn,"manifestCache",new Map);let Er=Zn;const as=dt("PipeRegistry");function Og(s,e){const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0"),d=String(s.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(s.getMonth()+1)).replace("DD",i).replace("D",String(s.getDate())).replace("HH",l).replace("H",String(s.getHours())).replace("mm",c).replace("m",String(s.getMinutes())).replace("ss",d).replace("s",String(s.getSeconds()))}function Qw(s,e="ko"){const r=new Date().getTime()-s.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),p=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:c<24?`${c}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:p<12?`${p}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:p<12?`${p} month${p===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function jd(s){if(s==null)return null;if(s instanceof Date)return s;if(typeof s=="number")return new Date(s);if(typeof s=="string"){const e=new Date(s);return isNaN(e.getTime())?null:e}return null}const go={date:{fn:(s,e="YYYY-MM-DD")=>{const n=jd(s);return n?Og(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(s,e="YYYY-MM-DD HH:mm")=>{const n=jd(s);return n?Og(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(s,e="ko")=>{const n=jd(s);return n?Qw(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(s,e)=>{const n=Number(s);if(isNaN(n))return String(s??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(s,e=100,n="...")=>typeof s!="string"?String(s??""):s.length<=e?s:s.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:s=>typeof s!="string"?String(s??""):s.toUpperCase(),description:"대문자 변환"},lowercase:{fn:s=>typeof s!="string"?String(s??""):s.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:s=>typeof s!="string"?String(s??""):s.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(s,e="")=>s==null||s===""?e:s,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(s,e)=>s??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:s=>{if(Array.isArray(s))return s[0]},description:"배열의 첫 번째 요소"},last:{fn:s=>{if(Array.isArray(s))return s[s.length-1]},description:"배열의 마지막 요소"},join:{fn:(s,e=", ")=>Array.isArray(s)?s.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:s=>Array.isArray(s)||typeof s=="string"?s.length:0,description:"배열/문자열 길이"},filterBy:{fn:(s,e,n)=>Array.isArray(s)?Array.isArray(e)?s.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):s:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:s=>s==null||typeof s!="object"?[]:Object.keys(s),description:"객체의 키 배열"},values:{fn:s=>s==null||typeof s!="object"?[]:Object.values(s),description:"객체의 값 배열"},json:{fn:(s,e)=>{try{return JSON.stringify(s,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(s,e)=>s==null?"":typeof s=="string"?s:typeof s!="object"?String(s):s[e||"ko"]||s.ko||s.en||Object.values(s)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},is=new Map,Li=class Li{static getInstance(){return Li.instance||(Li.instance=new Li),Li.instance}register(e,n,r){if(go[e]){as.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}is.set(e,{fn:n,description:r}),as.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(go[e])return as.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=is.delete(e);return n&&as.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=go[e];return n?n.fn:is.get(e)?.fn}has(e){return!!go[e]||is.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return as.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return as.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(go))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of is.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){is.clear()}};$(Li,"instance",null);let sc=Li;sc.getInstance();function Zw(s){const e=s.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let c="",d=null,f=0;for(let p=0;p0?i[p-1]:"")==="\\"){c+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){c+=m;continue}if(m==="("||m==="["||m==="{"){f++,c+=m;continue}if(m===")"||m==="]"||m==="}"){f--,c+=m;continue}if(m===","&&f===0){l.push(Lg(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(Lg(c.trim())),{name:r,args:l}}function Lg(s){if(s==="null")return null;if(s==="undefined")return;if(s==="true")return!0;if(s==="false")return!1;const e=Number(s);return!isNaN(e)&&s!==""?e:s}function e0(s){const e=[];let n="",r=null,i=0;for(let l=0;l0?s[l-1]:"",f=l0?s[r-1]:"",c=r",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/api",i=!1){const l=`${e}:${n}`;if(!i){const c=this.getFromCache(l);if(c)return this.translations.set(l,c),c}try{const c=[];i&&c.push(`_=${Date.now()}`);const d=Pr(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=!i&&this.cacheVersion>0?po(`templates/${e}/lang/${n}.json`,this.cacheVersion):null,p=f!==null?await ic(f,d,{label:`lang/${n}.json`}):await fetch(d);if(!p.ok)throw new Hd(`Failed to load translations: ${p.statusText}`,void 0,n);const y=await p.json();return this.saveToCache(l,y),this.translations.set(l,y),y}catch(c){throw new Hd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,r)),i===d)break;c++}return i.replace(Nn.TRANSLATION_PATTERN,(d,f,p)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(p);return this.translate(f,n,m,r)+y})}translate(e,n,r,i){const l=this.getTranslation(e,n),c=r&&this.cleanParamsStr(r);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${i}`,c=this.translations.get(l);if(c){const d=this.getNestedValue(c,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const p=this.getNestedValue(f,e);if(p!==null)return p}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=r.split(".");let f=c;for(let p=0;p(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(Nn.PARAM_PATTERN);for(const f of d){const[,p,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(C,S)=>l[parseInt(S,10)]);r[p.trim()]=this.resolveParamValue(y.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(On(r)&&n)try{const l=uc.evaluatePipeExpression(r,n);return String(l??"")}catch(l){return zd.error("Pipe expression evaluation failed:",r,l),""}if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const l=uc.evaluateExpression(r,n);return String(l??"")}catch(l){return zd.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);return String(l??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$(Nn,"instance",null),$(Nn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(Nn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(Nn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let wi=Nn;const $g=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:wi,TranslationError:Hd},Symbol.toStringTag,{value:"Module"})),Ud=new Map([["true",!0],["false",!1],["null",null],["undefined",void 0]]);function Ma(s){if(typeof s!="string"||!s.startsWith("{{")||!s.endsWith("}}")||s.length<4)return null;const e=s.slice(2,-2);let n=null,r=0;for(let i=0;i0){r--;continue}return null}}return r===0?e.trim():null}function n0(s){const e=[];if(typeof s!="string")return e;for(let n=0;n0){i--;continue}if(s[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:s.slice(n+2,l)}),n=l+1)}return e}function mo(s){return/[?:|&!+\-*/<>=()[\]{}]/.test(s)}function Mg(s){const e=typeof s=="string"?s.trim():"";return e===""?"empty":Ud.has(e)?"literal":On(e)?"pipe":mo(e)?"expression":"path"}function Pd(s,e,n,r){const i=typeof s=="string"?s.trim():"",l=Mg(i),c=r?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){r?.onEmpty?.(s);return}if(l==="literal")return Ud.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,r?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,r?.trackingInfo):n.resolve(i,e,c,r?.trackingInfo)}catch(d){if(r?.onError)return r.onError(d,i);throw d}}const lr="raw:";function Ng(s){return s.startsWith(lr)?s.slice(lr.length):s}const yo="﷐",Ci="﷑",Na="﷒";function bo(s){return yo+s+Ci}function oc(s){return s.length>=2&&s.charCodeAt(0)===64976&&s.charCodeAt(s.length-1)===64977}function lc(s){return s.includes(yo)}function Bd(s){return s.slice(1,-1)}function ss(s){if(typeof s=="string")return bo(s);if(Array.isArray(s))return s.map(ss);if(s&&typeof s=="object"){const e={};for(const[n,r]of Object.entries(s))e[n]=ss(r);return e}return s}function Ia(s){if(typeof s=="string")return oc(s)?Bd(s):lc(s)||s.includes(Ci)?s.split(yo).join("").split(Ci).join(""):s;if(Array.isArray(s)){let e=!1;const n=s.map(r=>{const i=Ia(r);return i!==r&&(e=!0),i});return e?n:s}if(s&&typeof s=="object"){if(s.$$typeof!==void 0)return s;let e=!1;const n={};for(const[r,i]of Object.entries(s)){const l=Ia(i);l!==i&&(e=!0),n[r]=l}return e?n:s}return s}const vo=new Set(["constructor","__proto__","prototype","__lookupGetter__","__lookupSetter__","__defineGetter__","__defineSetter__"]),r0=new Set(["Function","eval","globalThis","window","self","document","require","module","process","Reflect","Proxy","WebAssembly","import","constructor"]);function Ig(s,e){if(s!==null&&(typeof s=="object"||typeof s=="function")&&jg.has(s))throw new Error(`Object.${e} on a built-in global object is not allowed`);return s}const a0=Object.freeze({keys:Object.keys,values:Object.values,entries:Object.entries,assign:(s,...e)=>{const n=Ig(s,"assign");for(const r of e)if(r!=null)for(const i of Object.keys(r)){if(vo.has(i))throw new Error(`Access to "${i}" is forbidden`);Xd(n,i,r[i])}return n},freeze:s=>Object.freeze(Ig(s,"freeze")),fromEntries:Object.fromEntries,create:Object.create,isFrozen:Object.isFrozen}),qd={Math,JSON,Date,Array,Object:a0,Number,String,Boolean,Set,Map,WeakSet,WeakMap,parseInt,parseFloat,isNaN,isFinite},Gd={Date,Set,Map,WeakSet,WeakMap,Array,Number,String,Boolean,Object},jg=new Set([...Object.values(qd),...Object.values(Gd)].filter(s=>s!==null&&(typeof s=="object"||typeof s=="function"))),cc=new Set(["function"]),_r=Symbol("short-circuit");class Fd{constructor(e){this.value=e}}class Vd{}class Kd{}function i0(s){return/[A-Za-z_$]/.test(s)}function s0(s){return/[A-Za-z0-9_$]/.test(s)}function Ei(s){return s>="0"&&s<="9"}function o0(s,e,n){let r=e+1;for(;r0;){const p=s[n];if(p==="{")f++,n++;else if(p==="}"){if(f--,f===0)break;n++}else p==='"'||p==="'"?n=o0(s,n,p):p==="`"?n=zg(s,n).end:n++}if(f!==0)throw new Error("Unterminated ${...} in template literal");i.push(s.slice(d,n)),n++;continue}l+=c,n++}throw new Error(`Unterminated template literal at position ${e}`)}function l0(s){const e=[];let n=0;const r=s.length,i=l=>n+l=r)throw new Error(`Unterminated string literal at position ${p}`);n++,e.push({type:"str",value:y,pos:p});continue}if(i0(l)){const p=n;for(n++;n"?(e.push({type:"punct",value:"=>",pos:c}),n+=2):i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"===",pos:c}),n+=3):(e.push({type:"punct",value:"==",pos:c}),n+=2):(e.push({type:"punct",value:"=",pos:c}),n+=1);continue}case"!":{i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"!==",pos:c}),n+=3):(e.push({type:"punct",value:"!=",pos:c}),n+=2):(e.push({type:"punct",value:"!",pos:c}),n+=1);continue}case"<":{if(i(1)==="=")e.push({type:"punct",value:"<=",pos:c}),n+=2;else{if(i(1)==="<")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:"<",pos:c}),n+=1}continue}case">":{if(i(1)==="=")e.push({type:"punct",value:">=",pos:c}),n+=2;else{if(i(1)===">")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:">",pos:c}),n+=1}continue}case"&":{if(i(1)==="&")e.push({type:"punct",value:"&&",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"|":{if(i(1)==="|")e.push({type:"punct",value:"||",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"?":{i(1)==="."&&!Ei(i(2))?(e.push({type:"punct",value:"?.",pos:c}),n+=2):i(1)==="?"?(e.push({type:"punct",value:"??",pos:c}),n+=2):(e.push({type:"punct",value:"?",pos:c}),n+=1);continue}case"+":{if(i(1)==="+")throw new Error("Increment operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"+",pos:c}),n+=1;continue}case"-":{if(i(1)==="-")throw new Error("Decrement operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"-",pos:c}),n+=1;continue}case"*":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");if(i(1)==="*")throw new Error("Exponentiation operator is not supported");e.push({type:"punct",value:"*",pos:c}),n+=1;continue}case"/":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"/",pos:c}),n+=1;continue}case"%":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"%",pos:c}),n+=1;continue}case"~":case"^":throw new Error("Bitwise operators are not allowed");case".":case":":case"(":case")":case"[":case"]":case"{":case"}":case",":e.push({type:"punct",value:l,pos:c}),n+=1;continue;case";":e.push({type:"punct",value:";",pos:c}),n+=1;continue;default:throw new Error(`Unexpected character "${l}" at position ${c}`)}}return e}const c0={"??":1,"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},u0=new Set(["??","||","&&"]);class d0{constructor(e){$(this,"tokens");$(this,"pos",0);this.tokens=e}atEnd(){return this.pos>=this.tokens.length}peek(e=0){const n=this.pos+e;return n"}"`);this.pos++}parseExpression(){const e=this.tryParseArrow();return e||this.parseTernary()}tryParseArrow(){const e=this.pos,n=this.peek();if(!n)return null;if(n.type==="ident"&&this.isPunct("=>",1)&&!cc.has(String(n.value))){this.pos+=1,this.pos+=1;const{body:r,isBlock:i}=this.parseArrowBody();return{type:"Arrow",params:[{name:String(n.value),default:null}],body:r,isBlock:i}}if(n.type==="punct"&&n.value==="("){this.pos+=1;const r=this.tryParseParamList();if(r&&this.isPunct(")")&&(this.pos+=1,this.isPunct("=>"))){this.pos+=1;const{body:i,isBlock:l}=this.parseArrowBody();return{type:"Arrow",params:r,body:i,isBlock:l}}return this.pos=e,null}return this.pos=e,null}tryParseParamList(){const e=[];if(this.isPunct(")"))return e;for(;;){const n=this.peek();let r=null,i;if(n&&n.type==="punct"&&n.value==="["){const c=this.tryParseArrayPattern();if(!c)return null;i=c}else if(n&&n.type==="ident"&&!cc.has(String(n.value)))r=String(n.value),this.pos+=1;else return null;let l=null;if(this.isPunct("=")&&(this.pos+=1,l=this.parseExpression()),e.push(i?{name:r,elements:i,default:l}:{name:r,default:l}),this.isPunct(",")){this.pos+=1;continue}break}return e}tryParseArrayPattern(){const e=this.pos;this.pos+=1;const n=[];for(;;){if(this.isPunct("]"))return this.pos+=1,n;if(this.isPunct(",")){n.push(null),this.pos+=1;continue}const r=this.peek();if(!r||r.type!=="ident"||cc.has(String(r.value)))return this.pos=e,null;if(n.push(String(r.value)),this.pos+=1,this.isPunct(",")){this.pos+=1;continue}return this.isPunct("]")?(this.pos+=1,n):(this.pos=e,null)}}parseArrowBody(){return this.isPunct("{")?{body:this.parseBlock(),isBlock:!0}:{body:this.parseExpression(),isBlock:!1}}parseBlock(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.atEnd())throw new Error("Unterminated block");e.push(this.parseStatement())}return this.expectPunct("}"),{type:"Block",body:e}}parseStatement(){const e=this.peek();if(!e)throw new Error("Unexpected end of statement");if(e.type==="punct"&&e.value==="{")return this.parseBlock();if(e.type==="punct"&&e.value===";")return this.pos+=1,{type:"Empty"};if(e.type==="ident")switch(String(e.value)){case"const":case"let":return this.parseVarDecl();case"if":return this.parseIf();case"for":return this.parseForOf();case"return":return this.parseReturn();case"try":return this.parseTry();case"break":return this.pos+=1,this.consumeSemicolon(),{type:"Break"};case"continue":return this.pos+=1,this.consumeSemicolon(),{type:"Continue"}}const n=this.parseExpression();return this.consumeSemicolon(),{type:"ExprStmt",expression:n}}consumeSemicolon(){this.isPunct(";")&&(this.pos+=1)}parseVarDecl(){this.pos+=1;const e=[];for(;;){const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected variable name in declaration");const r=String(n.value);this.pos+=1,this.expectPunct("=");const i=this.parseExpression();if(e.push({name:r,init:i}),this.isPunct(",")){this.pos+=1;continue}break}return this.consumeSemicolon(),{type:"VarDecl",declarations:e}}parseIf(){this.pos+=1,this.expectPunct("(");const e=this.parseExpression();this.expectPunct(")");const n=this.parseStatement();let r=null;const i=this.peek();return i&&i.type==="ident"&&i.value==="else"&&(this.pos+=1,r=this.parseStatement()),{type:"If",test:e,consequent:n,alternate:r}}parseForOf(){this.pos+=1,this.expectPunct("(");const e=this.peek();if(!e||e.type!=="ident"||e.value!=="const"&&e.value!=="let")throw new Error('Only "for (const x of …)" / "for (let x of …)" loops are supported');this.pos+=1;const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected loop variable name");const r=String(n.value);this.pos+=1;const i=this.peek();if(!i||i.type!=="ident"||i.value!=="of")throw new Error("Only for-of loops are supported (for-in / C-style for are not allowed)");this.pos+=1;const l=this.parseExpression();this.expectPunct(")");const c=this.parseStatement();return{type:"ForOf",name:r,iterable:l,body:c}}parseReturn(){if(this.pos+=1,this.isPunct(";")||this.isPunct("}")||this.atEnd())return this.consumeSemicolon(),{type:"Return",argument:null};const e=this.parseExpression();return this.consumeSemicolon(),{type:"Return",argument:e}}parseTry(){this.pos+=1;const e=this.parseBlock();let n=null,r=null,i=null;const l=this.peek();if(l&&l.type==="ident"&&l.value==="catch"){if(this.pos+=1,this.isPunct("(")){this.pos+=1;const d=this.peek();d&&d.type==="ident"&&(n=String(d.value),this.pos+=1),this.expectPunct(")")}r=this.parseBlock()}const c=this.peek();if(c&&c.type==="ident"&&c.value==="finally"&&(this.pos+=1,i=this.parseBlock()),!r&&!i)throw new Error("Missing catch or finally after try");return{type:"Try",block:e,handlerParam:n,handler:r,finalizer:i}}parseFunctionExpression(){this.pos+=1;let e=null;const n=this.peek();n&&n.type==="ident"&&n.value!==void 0&&!this.isPunct("(")&&(e=String(n.value),this.pos+=1),this.expectPunct("(");const r=this.tryParseParamList();if(!r)throw new Error("Invalid function parameter list");this.expectPunct(")");const i=this.parseBlock();return{type:"Function",name:e,params:r,body:i}}parseTernary(){const e=this.parseBinary(0);if(this.isPunct("?")){this.pos+=1;const n=this.parseExpression();this.expectPunct(":");const r=this.parseExpression();return{type:"Conditional",test:e,consequent:n,alternate:r}}return e}parseBinary(e){let n=this.parseUnary();for(;;){const r=this.peek();if(!r||r.type!=="punct")break;const i=String(r.value),l=c0[i];if(l===void 0||lHg(l));return{type:"Template",quasis:n,expressions:i}}if(e.type==="ident"&&e.value==="new")return this.parseNew();if(e.type==="ident"&&e.value==="function")return this.parseFunctionExpression();if(e.type==="ident"){const n=String(e.value);if(cc.has(n))throw new Error(`Keyword "${n}" is not allowed`);switch(this.pos+=1,n){case"true":return{type:"Literal",value:!0};case"false":return{type:"Literal",value:!1};case"null":return{type:"Literal",value:null};case"undefined":return{type:"Literal",value:void 0};default:return{type:"Identifier",name:n}}}if(e.type==="punct"){if(e.value==="("){this.pos+=1;const n=this.parseExpression();return this.expectPunct(")"),n}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral()}throw new Error(`Unexpected token "${e.value}"`)}parseArrayLiteral(){this.expectPunct("[");const e=[];for(;!this.isPunct("]");){if(this.isPunct(",")){this.pos+=1,e.push({type:"Literal",value:void 0});continue}if(this.isPunct("...")?(this.pos+=1,e.push({type:"Spread",argument:this.parseExpression()})):e.push(this.parseExpression()),this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("]"),{type:"Array",elements:e}}parseObjectLiteral(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.isPunct("..."))this.pos+=1,e.push({kind:"spread",value:this.parseExpression()});else{let n,r=!1;const i=this.peek();if(!i)throw new Error("Unexpected end of expression in object literal");if(i.type==="punct"&&i.value==="[")this.pos+=1,n=this.parseExpression(),this.expectPunct("]"),r=!0;else if(i.type==="str")this.pos+=1,n={type:"Literal",value:i.value};else if(i.type==="num")this.pos+=1,n={type:"Literal",value:String(i.value)};else if(i.type==="ident")this.pos+=1,n={type:"Literal",value:String(i.value)};else throw new Error(`Unexpected token "${i.value}" in object literal`);if(this.isPunct(":")){this.pos+=1;const l=this.parseExpression();e.push({kind:"init",key:n,computed:r,value:l})}else{if(r||n.type!=="Literal"||typeof n.value!="string")throw new Error("Invalid shorthand property in object literal");if(i.type!=="ident")throw new Error("Invalid shorthand property in object literal");e.push({kind:"init",key:n,computed:!1,value:{type:"Identifier",name:n.value}})}}if(this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("}"),{type:"Object",properties:e}}}function Hg(s){const e=l0(s),n=new d0(e),r=n.parseExpression();if(!n.atEnd()){const i=n.peek();throw i&&i.type==="punct"&&i.value===","?new Error("The comma/sequence operator is not allowed"):new Error(`Unexpected token "${i?i.value:""}" after expression`)}return r}function f0(s,e){let n=e;for(;n;){if(Object.prototype.hasOwnProperty.call(n.vars,s))return n.vars[s];n=n.parent}if(Object.prototype.hasOwnProperty.call(qd,s))return qd[s];if(r0.has(s))throw new Error(`Reference to forbidden global "${s}" is not allowed`)}function Wd(s){const e=typeof s=="symbol"?s:String(s);if(typeof e=="string"&&vo.has(e))throw new Error(`Access to "${e}" is forbidden`);return e}function Yd(s,e){return s.type==="Member"?Ug(s,e):s.type==="Call"?Pg(s,e):Ze(s,e)}function Ug(s,e){const n=Yd(s.object,e);if(n===_r||s.optional&&n==null)return _r;let r;s.computed?r=Ze(s.property,e):r=s.property.value;const i=Wd(r);if(n!=null)return n[i]}function Pg(s,e){let n,r;if(s.callee.type==="Member"){const l=s.callee,c=Yd(l.object,e);if(c===_r||l.optional&&c==null)return _r;let d;l.computed?d=Ze(l.property,e):d=l.property.value;const f=Wd(d);c==null?n=void 0:(n=c[f],r=c)}else if(n=Yd(s.callee,e),n===_r)return _r;if(s.optional&&n==null)return _r;if(typeof n!="function")throw new Error("Attempted to call a non-function value");const i=Bg(s.args,e);return n.apply(r,i)}function Bg(s,e){const n=[];for(const r of s)if(r.type==="Spread"){const i=Ze(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(Ze(r,e));return n}function qg(s,e,n){for(let r=0;r":return n>r;case"<=":return n<=r;case">=":return n>=r;default:throw new Error(`Unknown binary operator "${s.operator}"`)}}case"Logical":{const n=Ze(s.left,e);switch(s.operator){case"&&":return n&&Ze(s.right,e);case"||":return n||Ze(s.right,e);case"??":return n??Ze(s.right,e);default:throw new Error(`Unknown logical operator "${s.operator}"`)}}case"Conditional":return Ze(s.test,e)?Ze(s.consequent,e):Ze(s.alternate,e);case"Array":{const n=[];for(const r of s.elements)if(r.type==="Spread"){const i=Ze(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(Ze(r,e));return n}case"Object":{const n={};for(const r of s.properties)if(r.kind==="spread"){const i=Ze(r.value,e);if(i!=null&&typeof i=="object")for(const l of Object.keys(i))Xd(n,l,i[l])}else{let i;r.computed?i=Ze(r.key,e):i=r.key.value;const l=Ze(r.value,e);Xd(n,String(i),l)}return n}case"Arrow":{const n=e,r=s.params,i=s.body,l=s.isBlock;return function(...d){const f={vars:{},parent:n};return qg(r,d,f),l?Gg(i,f):Ze(i,f)}}case"Function":{const n=e,r=s.params,i=s.body,l=s.name,c=function(...f){const p={vars:{},parent:n};return l&&(p.vars[l]=c),qg(r,f,p),Gg(i,p)};return c}case"Delete":{const n=s.argument,r=Ze(n.object,e);let i;n.computed?i=Ze(n.property,e):i=n.property.value;const l=Wd(i);if(r==null||typeof r!="object"&&typeof r!="function")return!0;if(jg.has(r))throw new Error("delete on a built-in global object is not allowed");return delete r[l]}case"Block":{const n={vars:{},parent:e};for(const r of s.body)Ze(r,n);return}case"VarDecl":{for(const n of s.declarations)e.vars[n.name]=Ze(n.init,e);return}case"If":{Ze(s.test,e)?Ze(s.consequent,e):s.alternate&&Ze(s.alternate,e);return}case"ForOf":{const n=Ze(s.iterable,e);if(n!=null)for(const r of n){const i={vars:{},parent:e};i.vars[s.name]=r;try{Ze(s.body,i)}catch(l){if(l instanceof Kd)continue;if(l instanceof Vd)break;throw l}}return}case"Return":throw new Fd(s.argument?Ze(s.argument,e):void 0);case"ExprStmt":Ze(s.expression,e);return;case"Break":throw new Vd;case"Continue":throw new Kd;case"Empty":return;case"Try":{try{try{Ze(s.block,e)}catch(n){if(n instanceof Fd||n instanceof Vd||n instanceof Kd)throw n;if(s.handler){const r={vars:{},parent:e};s.handlerParam&&(r.vars[s.handlerParam]=n),Ze(s.handler,r)}else throw n}}finally{s.finalizer&&Ze(s.finalizer,e)}return}case"New":{const n=Gd[s.ctor];if(typeof n!="function")throw new Error("new on non-whitelisted constructor");const r=Bg(s.args,e);return new n(...r)}case"Template":{let n=s.quasis[0]??"";for(let r=0;r0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(C,S)=>{const v=S.trim();let x=!1,w=v;if(v.startsWith(lr)&&(x=!0,w=v.slice(lr.length)),On(w))try{const P=this.evaluatePipeExpression(w,d,l,{...i,method:"resolveBindings",displayExpression:`{{${v}}}`}),K=this.formatValue(P);return x?bo(K):K}catch(P){return ja.error("Pipe expression evaluation failed:",w,P),C}if(mo(w)){const P=c?.isEnabled()?performance.now():0;try{let K,he=!1;if(l.skipCache)K=this.evaluateExpression(w,d);else{const ke=`expr:${w}`,ze=this.getFromRenderCycleCache(ke);ze!==void 0?(K=ze,he=!0):(K=this.evaluateExpression(w,d),this.saveToRenderCycleCache(ke,K))}if(c?.isEnabled()){const ke=performance.now()-P;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:he,duration:ke,method:"resolveBindings",skipCache:l.skipCache})}const Ee=this.formatValue(K);return x?bo(Ee):Ee}catch(K){return ja.error("Expression evaluation failed:",w,K),C}}if(l.skipCache){const P=c?.isEnabled()?performance.now():0,K=this.resolvePath(w,d,l);if(c?.isEnabled()){const Ee=performance.now()-P;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:Ee,method:"resolveBindings",skipCache:!0})}const he=this.formatValue(K);return x?bo(he):he}const L=w.startsWith("_global")||w.startsWith("_local")||w.startsWith("_isolated")||w.startsWith("$parent"),O=c?.isEnabled()?performance.now():0;let j,F=!1;if(L){const P=this.getFromRenderCycleCache(w);P!==void 0?(j=P,F=!0):(j=this.resolvePath(w,d,l),this.saveToRenderCycleCache(w,j))}else{const P=this.getFromCache(w);P!==void 0?(j=P,F=!0):(j=this.resolvePath(w,d,l),this.saveToCache(w,j))}if(c?.isEnabled()){const P=performance.now()-O;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(j),resultType:this.getResultType(j),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:F,duration:P,method:"resolveBindings",skipCache:l.skipCache})}const G=this.formatValue(j);return x?bo(G):G},p=n0(e);if(p.length===0)return e;let m="",y=0;for(const C of p)m+=e.slice(y,C.start),m+=f(e.slice(C.start,C.end),C.expr),y=C.end;return m+e.slice(y)}evaluatePipeExpression(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[p,m]=e0(e);let y,C=!1;const S=mo(p),v=p.startsWith("_global")||p.startsWith("_local")||p.startsWith("_isolated")||p.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(p,f):y=this.resolvePath(p,f,l);else if(S){const w=this.getFromRenderCycleCache(`expr:${p}`);w!==void 0?(y=w,C=!0):(y=this.evaluateExpression(p,f),this.saveToRenderCycleCache(`expr:${p}`,y))}else if(v){const w=this.getFromRenderCycleCache(p);w!==void 0?(y=w,C=!0):(y=this.resolvePath(p,f,l),this.saveToRenderCycleCache(p,y))}else{const w=this.getFromCache(p);w!==void 0?(y=w,C=!0):(y=this.resolvePath(p,f,l),this.saveToCache(p,y))}const x=t0(y,m);if(c?.isEnabled()){const w=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:C,duration:w,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return x}resolve(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,n,l);return c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),y}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let p=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return p=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return p=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:p,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){ja.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new Qd(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fua.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}resolveObject(e,n,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,r)}catch(p){ja.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,p),i[d]=void 0}}return i}resolveObjectEntry(e,n,r,i,l){if(typeof r=="string"){const c=Ma(r);if(c!==null){const d=c.trim();let f=!1,p=d;d.startsWith(lr)&&(f=!0,p=d.slice(lr.length));let m;switch(Mg(p)){case"empty":ja.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=Ud.get(p);break;case"pipe":m=this.evaluatePipeExpression(p,i,l);break;case"expression":m=this.evaluateExpression(p,i,l);break;default:m=this.resolve(p,i,l)}e[n]=f&&m!=null?ss(m):m}else e[n]=this.resolveBindings(r,i,l)}else Array.isArray(r)?e[n]=r.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):r&&typeof r=="object"?e[n]=this.resolveObject(r,i,l):e[n]=r}clearCache(){this.cache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>ua.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>ua.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=So(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let c=this.preprocessOptionalChaining(e);c=this.preprocessTranslationTokens(c);const d=this.extractVariablesFromExpression(c),f={...n};for(const w of d)w in f||(f[w]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let p=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!p||!m)){const w=window.__templateApp?.getConfig?.();p??(p=w?.templateId),m??(m=w?.locale)}const y=m||"ko";f.$localized=(w,R)=>{if(w==null&&!R)return"";if(typeof w=="string")return w;if(w&&typeof w=="object"&&w[y])return w[y];if(R&&typeof R=="string"){const L=f.$t?f.$t(R):R;if(L&&L!==R)return L}return w&&typeof w=="object"?w.ko||w.en||Object.values(w)[0]||"":w==null?"":String(w)};const C=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>C?.uuid?C.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,w=>{const R=Math.random()*16|0;return(w==="x"?R:R&3|8).toString(16)});const S={templateId:p||"",locale:y};f.$t=w=>{if(!w||typeof w!="string")return"";try{return wi.getInstance().translate(w,S)}catch(R){return ja.warn("$t() translation failed for key:",w,R),w}},f.$get=(w,R,L=void 0)=>{if(w==null)return L;const O=Array.isArray(R)?R:[R];if(O.length===0)return w;let j=w;for(const F of O){if(j==null||F==null)return L;j=j[F]}return j??L};const v=!1,x=Jd(c,f);if(i?.isEnabled()){const w=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:v,duration:w,method:"evaluateExpression",skipCache:r?.skipCache})}return x}catch(c){throw new Error(`Failed to evaluate expression "${e}": ${c instanceof Error?c.message:String(c)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const n=Object.keys(e);return n.length>20?`{Object(${n.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(n,r,i,l)=>`$t('${l}')`),e.replace(/(['"]\s*)?(\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*)(?!\s*['"])/g,(n,r,i)=>r?n:`"${i}"`)}preprocessOptionalChaining(e){const n=[];let r=e.replace(/(['"])(?:(?!\1|\\).|\\.)*\1/g,l=>(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),r}extractVariablesFromExpression(e){const n=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),r=/(^|[^.\w$])([a-zA-Z_$][a-zA-Z0-9_$]*)/g,i=new Set;let l;for(;(l=r.exec(e))!==null;){const c=l[2];n.has(c)||i.add(c)}return Array.from(i)}isSwitchExpression(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}resolveSwitch(e,n,r){const i={...r,skipCache:!0};let l;try{l=this.resolveBindings(e.$switch,n,i)?.toString()?.trim()??""}catch(d){ja.warn("resolveSwitch: $switch 키 평가 실패:",e.$switch,d),l=""}let c;if(l&&e.$cases&&l in e.$cases)c=e.$cases[l];else if("$default"in e)c=e.$default;else return;return typeof c=="string"?c.includes("{{")?this.resolveBindings(c,n,i):c:c!==null&&typeof c=="object"?this.resolveObject(c,n,i):c}};$(ua,"PATH_SEGMENT_PATTERN",/([^.[\]]+)|\[(\d+)\]/g),$(ua,"CACHE_EXPIRY",3e4);let Tn=ua;const uc=new Tn,dc={mobile:{min:0,max:767},tablet:{min:768,max:1023},desktop:{min:1024,max:1/0},portable:{min:0,max:1023}},fc=new Map;function h0(s,e){let n=null;return((...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{s(...r)},e)})}class p0{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=h0(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(fc.has(e))return fc.get(e)??null;let n=null;if(dc[e])n={...dc[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(n={min:c,max:d})}}return fc.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!dc[i]})}return r.length===0?null:(r.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const c=i.range.max-i.range.min,d=l.range.max-l.range.min;return c-d}),r[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),fc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const _i=new p0,wo=dt("ConditionEvaluator");function g0(s,e,n,r){return Pd(Ng(s),e,n,{skipCache:!0,onEmpty:()=>{wo.warn(`${r}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function Fg(s,e,n){if(!s)return!0;try{const r=Ma(s);let i;if(r!==null?i=g0(r,e,n,"evaluateStringCondition"):i=n.resolveBindings(s,e,{skipCache:!0}),typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(r){return wo.warn(`evaluateStringCondition: 조건 평가 실패: ${s}`,r),!1}}function hc(s,e,n){if(typeof s=="string")return Fg(s,e,n);if("and"in s){if(!Array.isArray(s.and)||s.and.length===0)return wo.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of s.and)if(!hc(r,e,n))return!1;return!0}if("or"in s){if(!Array.isArray(s.or)||s.or.length===0)return wo.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of s.or)if(hc(r,e,n))return!0;return!1}return wo.warn("evaluateConditionExpression: 알 수 없는 조건 형식",s),!1}function Vg(s,e,n){if(!Array.isArray(s)||s.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r{cr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${r||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(s,e,{skipCache:!0}),typeof l=="string"){const c=l.toLowerCase().trim();if(c==="false"||c==="0"||c===""||c==="null"||c==="undefined")return!1}return!!l}catch(i){return cr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function os(s,e,n,r){if(s.if!==void 0)return Xg(s.if,e,n,r);if(s.condition!==void 0)return Xg(s.condition,e,n,r);if(s.conditions===void 0)return!0;const i=s.conditions;try{return m0(i)?hc(i,e,n):y0(i)?Vg(i,e,n).matched:(cr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return cr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function Jg(s){if(!s.responsive)return s;const e=_i.getWidth(),n=_i.getMatchingKey(s.responsive,e);if(!n)return s;const r=s.responsive[n];return{...s,props:{...s.props,...r.props},children:r.children??s.children,text:r.text??s.text,if:r.if??s.if,iteration:r.iteration??s.iteration}}function Co(s,e,n,r,i){if(!s||s.length===0)return[];const l=i?.bindingEngine??new Tn,c=i?.translationEngine??wi.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=v0(e,i?.componentContext),p=(S,v)=>{if(typeof S=="string")return oc(S)||lc(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,v);if(Array.isArray(S))return S.map(x=>p(x,v));if(S&&typeof S=="object"){const x={};for(const[w,R]of Object.entries(S))x[w]=p(R,v);return x}return S},m=(S,v)=>{if(typeof S=="string"){if(oc(S))return Bd(S);if(lc(S)){const w=[],R=S.replace(new RegExp(`${yo}([^${Ci}]*)${Ci}`,"g"),(O,j)=>(w.push(j),`${Na}${w.length-1}${Na}`));let L=R;return/\$t:[a-zA-Z0-9._-]+/.test(R)&&(L=c.resolveTranslations(R,d,v)),L.replace(new RegExp(`${Na}(\\d+)${Na}`,"g"),(O,j)=>w[parseInt(j)])}if(S.startsWith("$t:defer:")){const w="$t:"+S.slice(9);return c.resolveTranslations(w,d,v)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,v);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const w=S.trim();if(!(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,v)}const x=Yg(S);if(x!==null){let w=!1,R=x;x.startsWith(lr)&&(w=!0,R=x.slice(lr.length));let L=!1,O=Pd(R,v,l,{skipCache:!0,onError:j=>{cr.warn("renderItemChildren: 표현식 평가 실패:",j),L=!0},onEmpty:()=>{cr.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return L?void 0:(w||(O=p(O,v)),w&&O!=null?ss(O):O)}if(S.includes("{{")){const w=l.resolveBindings(S,v,{skipCache:!0});return typeof w=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(w)?c.resolveTranslations(w,d,v):w}return S}if(Array.isArray(S))return S.map(x=>m(x,v));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,v,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const x={};for(const[w,R]of Object.entries(S))x[w]=m(R,v);return x}return S},y=(S,v)=>{if(!S)return{};const x={};for(const[w,R]of Object.entries(S))x[w]=m(R,v);return x},C=(S,v,x)=>{const w=Jg(S),R=w.iteration;if(!R)return[];const L=Zd(R.source,x,l);if(!Array.isArray(L))return cr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${R.source}`),[];const O=Kg();if(O?.isEnabled()){const F=`${v}-iteration`;O.trackIteration(F,R.source,R.item_var,R.index_var,L.length)}const j=n[w.name];return j?L.flatMap((F,G)=>{const P={...x,[R.item_var]:F,[`${R.item_var}_index`]:G,...R.index_var?{[R.index_var]:G}:{}},K=os({if:w.if,condition:w.condition,conditions:w.conditions},P,l,w.id);if(w.if&&O?.isEnabled()){const bt=`${v}-iter-${G}-if`;O.trackIfCondition(bt,w.if,K,w.name)}if(!K)return[];const he=w.id?String(Ia(m(w.id,P))):void 0,Ee=`${v}-iter-${G}`,ke=i?.getRemountKey?i.getRemountKey(he,Ee):Ee,ze=y(w.props,P),Be=ef(ze,w.actions,P,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let je=null;return w.text!==void 0?je=m(w.text,P):w.children&&w.children.length>0&&(je=Co(w.children,P,n,ke,i)),O?.isEnabled()&&O.trackRender(w.name),[We.createElement(j,{key:ke,...Ia(Be)},Ia(je))]}):(cr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${w.name}`),[])};return s.flatMap((S,v)=>{const x=Jg(S),w=x.id?String(Ia(m(x.id,f))):void 0,R=r?`${r}-${w||v}`:w||`child-${v}`,L=i?.getRemountKey?i.getRemountKey(w,R):R;if(x.iteration)return C(x,L,f);const O=os({if:x.if,condition:x.condition,conditions:x.conditions},f,l,x.id),j=Kg();if(x.if&&j?.isEnabled()){const he=`${L}-if`;j.trackIfCondition(he,x.if,O,x.name)}if(!O)return[];const F=n[x.name];if(!F)return cr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[];const G=y(x.props,f),P=ef(G,x.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let K=null;return x.text!==void 0?K=m(x.text,f):x.children&&x.children.length>0&&(K=Co(x.children,f,n,L,i)),j?.isEnabled()&&j.trackRender(x.name),[We.createElement(F,{key:L,...Ia(P)},Ia(K))]})}function ls(s,e,n,r){let i,l;return n instanceof Tn?(i=n,l=r):(i=Wg,l=n),i.resolveBindings(s,e,l)}function S0(s,e,n,r){const i=n??Wg,l={skipCache:!0,...r};let c;try{c=i.resolveBindings(s.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(p){cr.warn("resolveClassMap: key 평가 실패:",s.key,p),c=""}let d="";c&&s.variants&&c in s.variants?d=s.variants[c]:s.default&&(d=s.default);const f=[];return s.base?.trim()&&f.push(s.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function Qg(s,e){return function(){return s.apply(e,arguments)}}const{toString:w0}=Object.prototype,{getPrototypeOf:tf}=Object,{iterator:pc,toStringTag:Zg}=Symbol,gc=(s=>e=>{const n=w0.call(e);return s[n]||(s[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Ar=s=>(s=s.toLowerCase(),e=>gc(e)===s),mc=s=>e=>typeof e===s,{isArray:cs}=Array,us=mc("undefined");function Eo(s){return s!==null&&!us(s)&&s.constructor!==null&&!us(s.constructor)&&Ln(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const em=Ar("ArrayBuffer");function C0(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&em(s.buffer),e}const E0=mc("string"),Ln=mc("function"),tm=mc("number"),_o=s=>s!==null&&typeof s=="object",_0=s=>s===!0||s===!1,yc=s=>{if(gc(s)!=="object")return!1;const e=tf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Zg in s)&&!(pc in s)},A0=s=>{if(!_o(s)||Eo(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},x0=Ar("Date"),T0=Ar("File"),k0=Ar("Blob"),R0=Ar("FileList"),D0=s=>_o(s)&&Ln(s.pipe),O0=s=>{let e;return s&&(typeof FormData=="function"&&s instanceof FormData||Ln(s.append)&&((e=gc(s))==="formdata"||e==="object"&&Ln(s.toString)&&s.toString()==="[object FormData]"))},L0=Ar("URLSearchParams"),[$0,M0,N0,I0]=["ReadableStream","Request","Response","Headers"].map(Ar),j0=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ao(s,e,{allOwnKeys:n=!1}={}){if(s===null||typeof s>"u")return;let r,i;if(typeof s!="object"&&(s=[s]),cs(s))for(r=0,i=s.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const Ai=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rm=s=>!us(s)&&s!==Ai;function nf(){const{caseless:s,skipUndefined:e}=rm(this)&&this||{},n={},r=(i,l)=>{const c=s&&nm(n,l)||l;yc(n[c])&&yc(i)?n[c]=nf(n[c],i):yc(i)?n[c]=nf({},i):cs(i)?n[c]=i.slice():(!e||!us(i))&&(n[c]=i)};for(let i=0,l=arguments.length;i(Ao(e,(i,l)=>{n&&Ln(i)?s[l]=Qg(i,n):s[l]=i},{allOwnKeys:r}),s),H0=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),U0=(s,e,n,r)=>{s.prototype=Object.create(e.prototype,r),s.prototype.constructor=s,Object.defineProperty(s,"super",{value:e.prototype}),n&&Object.assign(s.prototype,n)},P0=(s,e,n,r)=>{let i,l,c;const d={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),l=i.length;l-- >0;)c=i[l],(!r||r(c,s,e))&&!d[c]&&(e[c]=s[c],d[c]=!0);s=n!==!1&&tf(s)}while(s&&(!n||n(s,e))&&s!==Object.prototype);return e},B0=(s,e,n)=>{s=String(s),(n===void 0||n>s.length)&&(n=s.length),n-=e.length;const r=s.indexOf(e,n);return r!==-1&&r===n},q0=s=>{if(!s)return null;if(cs(s))return s;let e=s.length;if(!tm(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=s[e];return n},G0=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&tf(Uint8Array)),F0=(s,e)=>{const r=(s&&s[pc]).call(s);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(s,l[0],l[1])}},V0=(s,e)=>{let n;const r=[];for(;(n=s.exec(e))!==null;)r.push(n);return r},K0=Ar("HTMLFormElement"),W0=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),am=(({hasOwnProperty:s})=>(e,n)=>s.call(e,n))(Object.prototype),Y0=Ar("RegExp"),im=(s,e)=>{const n=Object.getOwnPropertyDescriptors(s),r={};Ao(n,(i,l)=>{let c;(c=e(i,l,s))!==!1&&(r[l]=c||i)}),Object.defineProperties(s,r)},X0=s=>{im(s,(e,n)=>{if(Ln(s)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=s[n];if(Ln(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},J0=(s,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return cs(s)?r(s):r(String(s).split(e)),n},Q0=()=>{},Z0=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function eC(s){return!!(s&&Ln(s.append)&&s[Zg]==="FormData"&&s[pc])}const tC=s=>{const e=new Array(10),n=(r,i)=>{if(_o(r)){if(e.indexOf(r)>=0)return;if(Eo(r))return r;if(!("toJSON"in r)){e[i]=r;const l=cs(r)?[]:{};return Ao(r,(c,d)=>{const f=n(c,i+1);!us(f)&&(l[d]=f)}),e[i]=void 0,l}}return r};return n(s,0)},nC=Ar("AsyncFunction"),rC=s=>s&&(_o(s)||Ln(s))&&Ln(s.then)&&Ln(s.catch),sm=((s,e)=>s?setImmediate:e?((n,r)=>(Ai.addEventListener("message",({source:i,data:l})=>{i===Ai&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Ai.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ln(Ai.postMessage)),aC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ai):typeof process<"u"&&process.nextTick||sm,ee={isArray:cs,isArrayBuffer:em,isBuffer:Eo,isFormData:O0,isArrayBufferView:C0,isString:E0,isNumber:tm,isBoolean:_0,isObject:_o,isPlainObject:yc,isEmptyObject:A0,isReadableStream:$0,isRequest:M0,isResponse:N0,isHeaders:I0,isUndefined:us,isDate:x0,isFile:T0,isBlob:k0,isRegExp:Y0,isFunction:Ln,isStream:D0,isURLSearchParams:L0,isTypedArray:G0,isFileList:R0,forEach:Ao,merge:nf,extend:z0,trim:j0,stripBOM:H0,inherits:U0,toFlatObject:P0,kindOf:gc,kindOfTest:Ar,endsWith:B0,toArray:q0,forEachEntry:F0,matchAll:V0,isHTMLForm:K0,hasOwnProperty:am,hasOwnProp:am,reduceDescriptors:im,freezeMethods:X0,toObjectSet:J0,toCamelCase:W0,noop:Q0,toFiniteNumber:Z0,findKey:nm,global:Ai,isContextDefined:rm,isSpecCompliantForm:eC,toJSONObject:tC,isAsyncFn:nC,isThenable:rC,setImmediate:sm,asap:aC,isIterable:s=>s!=null&&Ln(s[pc])};function Ye(s,e,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=s,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}ee.inherits(Ye,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ee.toJSONObject(this.config),code:this.code,status:this.status}}});const om=Ye.prototype,lm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(s=>{lm[s]={value:s}}),Object.defineProperties(Ye,lm),Object.defineProperty(om,"isAxiosError",{value:!0}),Ye.from=(s,e,n,r,i,l)=>{const c=Object.create(om);ee.toFlatObject(s,c,function(m){return m!==Error.prototype},p=>p!=="isAxiosError");const d=s&&s.message?s.message:"Error",f=e==null&&s?s.code:e;return Ye.call(c,d,f,n,r,i),s&&c.cause==null&&Object.defineProperty(c,"cause",{value:s,configurable:!0}),c.name=s&&s.name||"Error",l&&Object.assign(c,l),c};const iC=null;function rf(s){return ee.isPlainObject(s)||ee.isArray(s)}function cm(s){return ee.endsWith(s,"[]")?s.slice(0,-2):s}function um(s,e,n){return s?s.concat(e).map(function(i,l){return i=cm(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function sC(s){return ee.isArray(s)&&!s.some(rf)}const oC=ee.toFlatObject(ee,{},null,function(e){return/^is[A-Z]/.test(e)});function bc(s,e,n){if(!ee.isObject(s))throw new TypeError("target must be an object");e=e||new FormData,n=ee.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,w){return!ee.isUndefined(w[x])});const r=n.metaTokens,i=n.visitor||m,l=n.dots,c=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&ee.isSpecCompliantForm(e);if(!ee.isFunction(i))throw new TypeError("visitor must be a function");function p(v){if(v===null)return"";if(ee.isDate(v))return v.toISOString();if(ee.isBoolean(v))return v.toString();if(!f&&ee.isBlob(v))throw new Ye("Blob is not supported. Use a Buffer instead.");return ee.isArrayBuffer(v)||ee.isTypedArray(v)?f&&typeof Blob=="function"?new Blob([v]):Buffer.from(v):v}function m(v,x,w){let R=v;if(v&&!w&&typeof v=="object"){if(ee.endsWith(x,"{}"))x=r?x:x.slice(0,-2),v=JSON.stringify(v);else if(ee.isArray(v)&&sC(v)||(ee.isFileList(v)||ee.endsWith(x,"[]"))&&(R=ee.toArray(v)))return x=cm(x),R.forEach(function(O,j){!(ee.isUndefined(O)||O===null)&&e.append(c===!0?um([x],j,l):c===null?x:x+"[]",p(O))}),!1}return rf(v)?!0:(e.append(um(w,x,l),p(v)),!1)}const y=[],C=Object.assign(oC,{defaultVisitor:m,convertValue:p,isVisitable:rf});function S(v,x){if(!ee.isUndefined(v)){if(y.indexOf(v)!==-1)throw Error("Circular reference detected in "+x.join("."));y.push(v),ee.forEach(v,function(R,L){(!(ee.isUndefined(R)||R===null)&&i.call(e,R,ee.isString(L)?L.trim():L,x,C))===!0&&S(R,x?x.concat(L):[L])}),y.pop()}}if(!ee.isObject(s))throw new TypeError("data must be an object");return S(s),e}function dm(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(s).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function af(s,e){this._pairs=[],s&&bc(s,this,e)}const fm=af.prototype;fm.append=function(e,n){this._pairs.push([e,n])},fm.toString=function(e){const n=e?function(r){return e.call(this,r,dm)}:dm;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function lC(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function hm(s,e,n){if(!e)return s;const r=n&&n.encode||lC;ee.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let l;if(i?l=i(e,n):l=ee.isURLSearchParams(e)?e.toString():new af(e,n).toString(r),l){const c=s.indexOf("#");c!==-1&&(s=s.slice(0,c)),s+=(s.indexOf("?")===-1?"?":"&")+l}return s}class pm{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ee.forEach(this.handlers,function(r){r!==null&&e(r)})}}const gm={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},cC={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:af,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},sf=typeof window<"u"&&typeof document<"u",of=typeof navigator=="object"&&navigator||void 0,uC=sf&&(!of||["ReactNative","NativeScript","NS"].indexOf(of.product)<0),dC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",fC=sf&&window.location.href||"http://localhost",Cn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:sf,hasStandardBrowserEnv:uC,hasStandardBrowserWebWorkerEnv:dC,navigator:of,origin:fC},Symbol.toStringTag,{value:"Module"})),...cC};function hC(s,e){return bc(s,new Cn.classes.URLSearchParams,{visitor:function(n,r,i,l){return Cn.isNode&&ee.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}function pC(s){return ee.matchAll(/\w+|\[(\w*)]/g,s).map(e=>e[0]==="[]"?"":e[1]||e[0])}function gC(s){const e={},n=Object.keys(s);let r;const i=n.length;let l;for(r=0;r=n.length;return c=!c&&ee.isArray(i)?i.length:c,f?(ee.hasOwnProp(i,c)?i[c]=[i[c],r]:i[c]=r,!d):((!i[c]||!ee.isObject(i[c]))&&(i[c]=[]),e(n,r,i[c],l)&&ee.isArray(i[c])&&(i[c]=gC(i[c])),!d)}if(ee.isFormData(s)&&ee.isFunction(s.entries)){const n={};return ee.forEachEntry(s,(r,i)=>{e(pC(r),i,n,0)}),n}return null}function mC(s,e,n){if(ee.isString(s))try{return(e||JSON.parse)(s),ee.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(s)}const xo={transitional:gm,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=ee.isObject(e);if(l&&ee.isHTMLForm(e)&&(e=new FormData(e)),ee.isFormData(e))return i?JSON.stringify(mm(e)):e;if(ee.isArrayBuffer(e)||ee.isBuffer(e)||ee.isStream(e)||ee.isFile(e)||ee.isBlob(e)||ee.isReadableStream(e))return e;if(ee.isArrayBufferView(e))return e.buffer;if(ee.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){if(r.indexOf("application/x-www-form-urlencoded")>-1)return hC(e,this.formSerializer).toString();if((d=ee.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return bc(d?{"files[]":e}:e,f&&new f,this.formSerializer)}}return l||i?(n.setContentType("application/json",!1),mC(e)):e}],transformResponse:[function(e){const n=this.transitional||xo.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(ee.isResponse(e)||ee.isReadableStream(e))return e;if(e&&ee.isString(e)&&(r&&!this.responseType||i)){const c=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(d){if(c)throw d.name==="SyntaxError"?Ye.from(d,Ye.ERR_BAD_RESPONSE,this,null,this.response):d}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Cn.classes.FormData,Blob:Cn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ee.forEach(["delete","get","head","post","put","patch"],s=>{xo.headers[s]={}});const yC=ee.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),bC=s=>{const e={};let n,r,i;return s&&s.split(` `).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),r=c.substring(i+1).trim(),!(!n||e[n]&&yC[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},ym=Symbol("internals");function To(s){return s&&String(s).trim().toLowerCase()}function vc(s){return s===!1||s==null?s:ee.isArray(s)?s.map(vc):String(s)}function vC(s){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(s);)e[r[1]]=r[2];return e}const SC=s=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function lf(s,e,n,r,i){if(ee.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!ee.isString(e)){if(ee.isString(r))return e.indexOf(r)!==-1;if(ee.isRegExp(r))return r.test(e)}}function wC(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function CC(s,e){const n=ee.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(s,r+n,{value:function(i,l,c){return this[r].call(this,e,i,l,c)},configurable:!0})})}let $n=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,p){const m=To(f);if(!m)throw new Error("header name must be a non-empty string");const y=ee.findKey(i,m);(!y||i[y]===void 0||p===!0||p===void 0&&i[y]!==!1)&&(i[y||f]=vc(d))}const c=(d,f)=>ee.forEach(d,(p,m)=>l(p,m,f));if(ee.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(ee.isString(e)&&(e=e.trim())&&!SC(e))c(bC(e),n);else if(ee.isObject(e)&&ee.isIterable(e)){let d={},f,p;for(const m of e){if(!ee.isArray(m))throw TypeError("Object iterator must return a key-value pair");d[p=m[0]]=(f=d[p])?ee.isArray(f)?[...f,m[1]]:[f,m[1]]:m[1]}c(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=To(e),e){const r=ee.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return vC(i);if(ee.isFunction(n))return n.call(this,i,r);if(ee.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=To(e),e){const r=ee.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||lf(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(c){if(c=To(c),c){const d=ee.findKey(r,c);d&&(!n||lf(r,r[d],d,n))&&(delete r[d],i=!0)}}return ee.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||lf(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return ee.forEach(this,(i,l)=>{const c=ee.findKey(r,l);if(c){n[c]=vc(i),delete n[l];return}const d=e?wC(l):String(l).trim();d!==l&&delete n[l],n[d]=vc(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return ee.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&ee.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[ym]=this[ym]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=To(c);r[d]||(CC(i,c),r[d]=!0)}return ee.isArray(e)?e.forEach(l):l(e),this}};$n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ee.reduceDescriptors($n.prototype,({value:s},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(r){this[n]=r}}}),ee.freezeMethods($n);function cf(s,e){const n=this||xo,r=e||n,i=$n.from(r.headers);let l=r.data;return ee.forEach(s,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function bm(s){return!!(s&&s.__CANCEL__)}function ds(s,e,n){Ye.call(this,s??"canceled",Ye.ERR_CANCELED,e,n),this.name="CanceledError"}ee.inherits(ds,Ye,{__CANCEL__:!0});function vm(s,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?s(n):e(new Ye("Request failed with status code "+n.status,[Ye.ERR_BAD_REQUEST,Ye.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function EC(s){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(s);return e&&e[1]||""}function _C(s,e){s=s||10;const n=new Array(s),r=new Array(s);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const p=Date.now(),m=r[l];c||(c=p),n[i]=f,r[i]=p;let y=l,C=0;for(;y!==i;)C+=n[y++],y=y%s;if(i=(i+1)%s,i===l&&(l=(l+1)%s),p-c{n=m,i=null,l&&(clearTimeout(l),l=null),s(...p)};return[(...p)=>{const m=Date.now(),y=m-n;y>=r?c(p,m):(i=p,l||(l=setTimeout(()=>{l=null,c(i)},r-y)))},()=>i&&c(i)]}const Sc=(s,e,n=3)=>{let r=0;const i=_C(50,250);return AC(l=>{const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=c-r,p=i(f),m=c<=d;r=c;const y={loaded:c,total:d,progress:d?c/d:void 0,bytes:f,rate:p||void 0,estimated:p&&d&&m?(d-c)/p:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};s(y)},n)},Sm=(s,e)=>{const n=s!=null;return[r=>e[0]({lengthComputable:n,total:s,loaded:r}),e[1]]},wm=s=>(...e)=>ee.asap(()=>s(...e)),xC=Cn.hasStandardBrowserEnv?((s,e)=>n=>(n=new URL(n,Cn.origin),s.protocol===n.protocol&&s.host===n.host&&(e||s.port===n.port)))(new URL(Cn.origin),Cn.navigator&&/(msie|trident)/i.test(Cn.navigator.userAgent)):()=>!0,TC=Cn.hasStandardBrowserEnv?{write(s,e,n,r,i,l){const c=[s+"="+encodeURIComponent(e)];ee.isNumber(n)&&c.push("expires="+new Date(n).toGMTString()),ee.isString(r)&&c.push("path="+r),ee.isString(i)&&c.push("domain="+i),l===!0&&c.push("secure"),document.cookie=c.join("; ")},read(s){const e=document.cookie.match(new RegExp("(^|;\\s*)("+s+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(s){this.write(s,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function kC(s){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(s)}function RC(s,e){return e?s.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):s}function Cm(s,e,n){let r=!kC(e);return s&&(r||n==!1)?RC(s,e):e}const Em=s=>s instanceof $n?{...s}:s;function xi(s,e){e=e||{};const n={};function r(p,m,y,C){return ee.isPlainObject(p)&&ee.isPlainObject(m)?ee.merge.call({caseless:C},p,m):ee.isPlainObject(m)?ee.merge({},m):ee.isArray(m)?m.slice():m}function i(p,m,y,C){if(ee.isUndefined(m)){if(!ee.isUndefined(p))return r(void 0,p,y,C)}else return r(p,m,y,C)}function l(p,m){if(!ee.isUndefined(m))return r(void 0,m)}function c(p,m){if(ee.isUndefined(m)){if(!ee.isUndefined(p))return r(void 0,p)}else return r(void 0,m)}function d(p,m,y){if(y in e)return r(p,m);if(y in s)return r(void 0,p)}const f={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,responseEncoding:c,validateStatus:d,headers:(p,m,y)=>i(Em(p),Em(m),y,!0)};return ee.forEach(Object.keys({...s,...e}),function(m){const y=f[m]||i,C=y(s[m],e[m],m);ee.isUndefined(C)&&y!==d||(n[m]=C)}),n}const _m=s=>{const e=xi({},s);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:l,headers:c,auth:d}=e;if(e.headers=c=$n.from(c),e.url=hm(Cm(e.baseURL,e.url,e.allowAbsoluteUrls),s.params,s.paramsSerializer),d&&c.set("Authorization","Basic "+btoa((d.username||"")+":"+(d.password?unescape(encodeURIComponent(d.password)):""))),ee.isFormData(n)){if(Cn.hasStandardBrowserEnv||Cn.hasStandardBrowserWebWorkerEnv)c.setContentType(void 0);else if(ee.isFunction(n.getHeaders)){const f=n.getHeaders(),p=["content-type","content-length"];Object.entries(f).forEach(([m,y])=>{p.includes(m.toLowerCase())&&c.set(m,y)})}}if(Cn.hasStandardBrowserEnv&&(r&&ee.isFunction(r)&&(r=r(e)),r||r!==!1&&xC(e.url))){const f=i&&l&&TC.read(l);f&&c.set(i,f)}return e},DC=typeof XMLHttpRequest<"u"&&function(s){return new Promise(function(n,r){const i=_m(s);let l=i.data;const c=$n.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:p}=i,m,y,C,S,v;function x(){S&&S(),v&&v(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function R(){if(!w)return;const O=$n.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),F={data:!d||d==="text"||d==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:O,config:s,request:w};vm(function(P){n(P),x()},function(P){r(P),x()},F),w=null}"onloadend"in w?w.onloadend=R:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(R)},w.onabort=function(){w&&(r(new Ye("Request aborted",Ye.ECONNABORTED,s,w)),w=null)},w.onerror=function(j){const F=j&&j.message?j.message:"Network Error",G=new Ye(F,Ye.ERR_NETWORK,s,w);G.event=j||null,r(G),w=null},w.ontimeout=function(){let j=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const F=i.transitional||gm;i.timeoutErrorMessage&&(j=i.timeoutErrorMessage),r(new Ye(j,F.clarifyTimeoutError?Ye.ETIMEDOUT:Ye.ECONNABORTED,s,w)),w=null},l===void 0&&c.setContentType(null),"setRequestHeader"in w&&ee.forEach(c.toJSON(),function(j,F){w.setRequestHeader(F,j)}),ee.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),d&&d!=="json"&&(w.responseType=i.responseType),p&&([C,v]=Sc(p,!0),w.addEventListener("progress",C)),f&&w.upload&&([y,S]=Sc(f),w.upload.addEventListener("progress",y),w.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=O=>{w&&(r(!O||O.type?new ds(null,s,w):O),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const L=EC(i.url);if(L&&Cn.protocols.indexOf(L)===-1){r(new Ye("Unsupported protocol "+L+":",Ye.ERR_BAD_REQUEST,s));return}w.send(l||null)})},OC=(s,e)=>{const{length:n}=s=s?s.filter(Boolean):[];if(e||n){let r=new AbortController,i;const l=function(p){if(!i){i=!0,d();const m=p instanceof Error?p:this.reason;r.abort(m instanceof Ye?m:new ds(m instanceof Error?m.message:m))}};let c=e&&setTimeout(()=>{c=null,l(new Ye(`timeout ${e} of ms exceeded`,Ye.ETIMEDOUT))},e);const d=()=>{s&&(c&&clearTimeout(c),c=null,s.forEach(p=>{p.unsubscribe?p.unsubscribe(l):p.removeEventListener("abort",l)}),s=null)};s.forEach(p=>p.addEventListener("abort",l));const{signal:f}=r;return f.unsubscribe=()=>ee.asap(d),f}},LC=function*(s,e){let n=s.byteLength;if(n{const i=$C(s,e);let l=0,c,d=f=>{c||(c=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:p,value:m}=await i.next();if(p){d(),f.close();return}let y=m.byteLength;if(n){let C=l+=y;n(C)}f.enqueue(new Uint8Array(m))}catch(p){throw d(p),p}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},xm=64*1024,{isFunction:wc}=ee,NC=(({Request:s,Response:e})=>({Request:s,Response:e}))(ee.global),{ReadableStream:Tm,TextEncoder:km}=ee.global,Rm=(s,...e)=>{try{return!!s(...e)}catch{return!1}},IC=s=>{s=ee.merge.call({skipUndefined:!0},NC,s);const{fetch:e,Request:n,Response:r}=s,i=e?wc(e):typeof fetch=="function",l=wc(n),c=wc(r);if(!i)return!1;const d=i&&wc(Tm),f=i&&(typeof km=="function"?(v=>x=>v.encode(x))(new km):async v=>new Uint8Array(await new n(v).arrayBuffer())),p=l&&d&&Rm(()=>{let v=!1;const x=new n(Cn.origin,{body:new Tm,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!x}),m=c&&d&&Rm(()=>ee.isReadableStream(new r("").body)),y={stream:m&&(v=>v.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!y[v]&&(y[v]=(x,w)=>{let R=x&&x[v];if(R)return R.call(x);throw new Ye(`Response type '${v}' is not supported`,Ye.ERR_NOT_SUPPORT,w)})});const C=async v=>{if(v==null)return 0;if(ee.isBlob(v))return v.size;if(ee.isSpecCompliantForm(v))return(await new n(Cn.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(ee.isArrayBufferView(v)||ee.isArrayBuffer(v))return v.byteLength;if(ee.isURLSearchParams(v)&&(v=v+""),ee.isString(v))return(await f(v)).byteLength},S=async(v,x)=>{const w=ee.toFiniteNumber(v.getContentLength());return w??C(x)};return async v=>{let{url:x,method:w,data:R,signal:L,cancelToken:O,timeout:j,onDownloadProgress:F,onUploadProgress:G,responseType:P,headers:K,withCredentials:he="same-origin",fetchOptions:Ee}=_m(v),ke=e||fetch;P=P?(P+"").toLowerCase():"text";let ze=OC([L,O&&O.toAbortSignal()],j),Be=null;const je=ze&&ze.unsubscribe&&(()=>{ze.unsubscribe()});let bt;try{if(G&&p&&w!=="get"&&w!=="head"&&(bt=await S(K,R))!==0){let z=new n(x,{method:"POST",body:R,duplex:"half"}),T;if(ee.isFormData(R)&&(T=z.headers.get("content-type"))&&K.setContentType(T),z.body){const[pe,fe]=Sm(bt,Sc(wm(G)));R=Am(z.body,xm,pe,fe)}}ee.isString(he)||(he=he?"include":"omit");const X=l&&"credentials"in n.prototype,de={...Ee,signal:ze,method:w.toUpperCase(),headers:K.normalize().toJSON(),body:R,duplex:"half",credentials:X?he:void 0};Be=l&&new n(x,de);let Ce=await(l?ke(Be,Ee):ke(x,de));const Z=m&&(P==="stream"||P==="response");if(m&&(F||Z&&je)){const z={};["status","statusText","headers"].forEach(me=>{z[me]=Ce[me]});const T=ee.toFiniteNumber(Ce.headers.get("content-length")),[pe,fe]=F&&Sm(T,Sc(wm(F),!0))||[];Ce=new r(Am(Ce.body,xm,pe,()=>{fe&&fe(),je&&je()}),z)}P=P||"text";let ge=await y[ee.findKey(y,P)||"text"](Ce,v);return!Z&&je&&je(),await new Promise((z,T)=>{vm(z,T,{data:ge,headers:$n.from(Ce.headers),status:Ce.status,statusText:Ce.statusText,config:v,request:Be})})}catch(X){throw je&&je(),X&&X.name==="TypeError"&&/Load failed|fetch/i.test(X.message)?Object.assign(new Ye("Network Error",Ye.ERR_NETWORK,v,Be),{cause:X.cause||X}):Ye.from(X,X&&X.code,v,Be)}}},jC=new Map,Dm=s=>{let e=s?s.env:{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let c=l.length,d=c,f,p,m=jC;for(;d--;)f=l[d],p=m.get(f),p===void 0&&m.set(f,p=d?new Map:IC(e)),m=p;return p};Dm();const uf={http:iC,xhr:DC,fetch:{get:Dm}};ee.forEach(uf,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{value:e})}catch{}Object.defineProperty(s,"adapterName",{value:e})}});const Om=s=>`- ${s}`,zC=s=>ee.isFunction(s)||s===null||s===!1,Lm={getAdapter:(s,e)=>{s=ee.isArray(s)?s:[s];const{length:n}=s;let r,i;const l={};for(let c=0;c`adapter ${f} `+(p===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : `+c.map(Om).join(` `):" "+Om(c[0]):"as no adapter specified";throw new Ye("There is no suitable adapter to dispatch the request "+d,"ERR_NOT_SUPPORT")}return i},adapters:uf};function df(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new ds(null,s)}function $m(s){return df(s),s.headers=$n.from(s.headers),s.data=cf.call(s,s.transformRequest),["post","put","patch"].indexOf(s.method)!==-1&&s.headers.setContentType("application/x-www-form-urlencoded",!1),Lm.getAdapter(s.adapter||xo.adapter,s)(s).then(function(r){return df(s),r.data=cf.call(s,s.transformResponse,r),r.headers=$n.from(r.headers),r},function(r){return bm(r)||(df(s),r&&r.response&&(r.response.data=cf.call(s,s.transformResponse,r.response),r.response.headers=$n.from(r.response.headers))),Promise.reject(r)})}const Mm="1.12.2",Cc={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{Cc[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});const Nm={};Cc.transitional=function(e,n,r){function i(l,c){return"[Axios v"+Mm+"] Transitional option '"+l+"'"+c+(r?". "+r:"")}return(l,c,d)=>{if(e===!1)throw new Ye(i(c," has been removed"+(n?" in "+n:"")),Ye.ERR_DEPRECATED);return n&&!Nm[c]&&(Nm[c]=!0,console.warn(i(c," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,c,d):!0}},Cc.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function HC(s,e,n){if(typeof s!="object")throw new Ye("options must be an object",Ye.ERR_BAD_OPTION_VALUE);const r=Object.keys(s);let i=r.length;for(;i-- >0;){const l=r[i],c=e[l];if(c){const d=s[l],f=d===void 0||c(d,l,s);if(f!==!0)throw new Ye("option "+l+" must be "+f,Ye.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ye("Unknown option "+l,Ye.ERR_BAD_OPTION)}}const Ec={assertOptions:HC,validators:Cc},qr=Ec.validators;let Ti=class{constructor(e){this.defaults=e||{},this.interceptors={request:new pm,response:new pm}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?l&&!String(r.stack).endsWith(l.replace(/^.+\n.+\n/,""))&&(r.stack+=` `+l):r.stack=l}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=xi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&Ec.assertOptions(r,{silentJSONParsing:qr.transitional(qr.boolean),forcedJSONParsing:qr.transitional(qr.boolean),clarifyTimeoutError:qr.transitional(qr.boolean)},!1),i!=null&&(ee.isFunction(i)?n.paramsSerializer={serialize:i}:Ec.assertOptions(i,{encode:qr.function,serialize:qr.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ec.assertOptions(n,{baseUrl:qr.spelling("baseURL"),withXsrfToken:qr.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let c=l&&ee.merge(l.common,l[n.method]);l&&ee.forEach(["delete","get","head","post","put","patch","common"],v=>{delete l[v]}),n.headers=$n.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(f=f&&x.synchronous,d.unshift(x.fulfilled,x.rejected))});const p=[];this.interceptors.response.forEach(function(x){p.push(x.fulfilled,x.rejected)});let m,y=0,C;if(!f){const v=[$m.bind(this),void 0];for(v.unshift(...d),v.push(...p),C=v.length,m=Promise.resolve(n);y{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{r.subscribe(d),l=d}).then(i);return c.cancel=function(){r.unsubscribe(l)},c},e(function(l,c,d){r.reason||(r.reason=new ds(l,c,d),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Dw(function(i){e=i}),cancel:e}}};function PC(s){return function(n){return s.apply(null,n)}}function BC(s){return ee.isObject(s)&&s.isAxiosError===!0}const ff={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ff).forEach(([s,e])=>{ff[e]=s});function Im(s){const e=new Ti(s),n=Qg(Ti.prototype.request,e);return ee.extend(n,Ti.prototype,e,{allOwnKeys:!0}),ee.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return Im(xi(s,i))},n}const Ft=Im(xo);Ft.Axios=Ti,Ft.CanceledError=ds,Ft.CancelToken=UC,Ft.isCancel=bm,Ft.VERSION=Mm,Ft.toFormData=bc,Ft.AxiosError=Ye,Ft.Cancel=Ft.CanceledError,Ft.all=function(e){return Promise.all(e)},Ft.spread=PC,Ft.isAxiosError=BC,Ft.mergeConfig=xi,Ft.AxiosHeaders=$n,Ft.formToJSON=s=>mm(ee.isHTMLForm(s)?new FormData(s):s),Ft.getAdapter=Lm.getAdapter,Ft.HttpStatusCode=ff,Ft.default=Ft;const{Axios:Ek,AxiosError:_k,CanceledError:Ak,isCancel:xk,CancelToken:Tk,VERSION:kk,all:Rk,Cancel:Dk,isAxiosError:Ok,spread:Lk,toFormData:$k,AxiosHeaders:Mk,HttpStatusCode:Nk,formToJSON:Ik,getAdapter:jk,mergeConfig:zk}=Ft,hf="g7.identity.redirectStash",_c=dt("IdentityGuardInterceptor");class yt{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){_c.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,r){this.domainNoticeShown=!1;const i=this.launcher??GC,c=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const p=qC(f.url,d.token);return fetch(p,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return _c.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(hf,JSON.stringify(r))}catch(i){_c.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(yt,"launcher",null),$(yt,"deferredResolver",null),$(yt,"domainNoticeShown",!1);function qC(s,e){if(!e)return s;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(s,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(s)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=s.includes("?")?"&":"?";return`${s}${n}verification_token=${encodeURIComponent(e)}`}}const GC=async s=>{if(typeof window>"u")return{status:"cancelled"};if(s.render_hint==="external_redirect"||s.redirect_url)return yt.redirectExternally(s);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,r={return_url:n,payload:s,stashed_at:Date.now()};try{window.sessionStorage?.setItem(hf,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){_c.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},jm=dt("ApiClient");function pf(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class FC{constructor(e={}){$(this,"client");$(this,"config");$(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Ft.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)r.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.join("&")}}}),this.setupInterceptors()}setToken(e){if(typeof e!="string"||e===""){jm.warn("Ignoring invalid auth token — token must be a non-empty string.");return}typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const n=this.getToken();if(n&&e.headers&&!this.isCrossOriginRequest(e.url)&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=pf();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=r.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,r=n._devToolsRequestId;if(r){const i=pf();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(c=>r.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await Yn.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(yt.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[C,S]of Object.entries(d))typeof S=="string"&&(c[C]=S);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),c["Content-Type"]=c["Content-Type"]??"application/json");const p=n?.identity_target,m=await yt.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},p);if(!m)return Promise.reject(e);let y=null;try{y=await m.json()}catch{y=null}return m.ok?{...e.response,status:m.status,data:y}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:y}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const r=pf();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}isCrossOriginRequest(e){if(!e||typeof window>"u"||!window.location||!/^(https?:)?\/\//i.test(e))return!1;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const r=e.params,i=[];for(const[l,c]of Object.entries(r))if(c!=null)if(Array.isArray(c)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of c)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(c))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(n)}catch(r){jm.error("Error in onError handler:",r)}}}let gf=null;function Wn(){return gf||(gf=new FC),gf}const ko=dt("AuthManager");function ki(s,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(s,e,n,r)}catch{}}const zm={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh",twoFactorEndpoint:"/auth/admin/login/two-factor",twoFactorResendEndpoint:"/auth/admin/login/two-factor/resend"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh",twoFactorEndpoint:"/auth/login/two-factor",twoFactorResendEndpoint:"/auth/login/two-factor/resend"}},Or=class Or{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",zm.admin),this.config.set("user",zm.user)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Wn();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return ko.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return ko.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.loginEndpoint,n,c);if(d.success&&d.data){if(d.data.two_factor_required===!0)return ki("login",!0,void 0,{type:e,two_factor:!0}),{status:"two_factor_required",challenge:{challengeId:String(d.data.challenge_id??""),providerId:String(d.data.provider_id??""),expiresAt:d.data.expires_at??null}};if(d.data.token&&d.data.user)return{status:"authenticated",user:this.establishSession(e,d.data.token,d.data.user)}}throw new Error("Login failed")}catch(c){throw this.clearState(),this.enhanceAuthError(c,e,"Login failed")}}async completeTwoFactor(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.twoFactorEndpoint,{challenge_id:n.challengeId,code:n.code},c);if(d.success&&d.data?.token&&d.data?.user)return this.establishSession(e,d.data.token,d.data.user);throw new Error("Login failed")}catch(c){throw this.clearState(),this.enhanceAuthError(c,e,"Login failed")}}async resendTwoFactor(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.twoFactorResendEndpoint,{challenge_id:n.challengeId},c);if(d.success&&d.data?.challenge_id)return{challengeId:String(d.data.challenge_id),providerId:String(d.data.provider_id??""),expiresAt:d.data.expires_at??null};throw new Error("Resend failed")}catch(c){throw this.enhanceAuthError(c,e,"Resend failed")}}establishSession(e,n,r){Wn().setToken(n);const l=r.language,c=localStorage.getItem(Or.LOCALE_STORAGE_KEY),d=l&&l!==c;if(l)try{localStorage.setItem(Or.LOCALE_STORAGE_KEY,l)}catch(f){ko.warn("Failed to save user language to localStorage:",f)}return this.state={isAuthenticated:!0,user:r,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ki("login",!0,void 0,{userId:r.uuid,email:r.email,type:e}),d&&window.__templateApp&&window.__templateApp.changeLocale(l),r}enhanceAuthError(e,n,r){const i=e?.response?.data?.message,l=new Error(i||e?.message||r);return l.response=e?.response,l.status=e?.response?.status,l.code=e?.code,ki("login",!1,l.message,{type:n,status:e?.response?.status}),l}async logout(){const e=Wn(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){ko.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ki("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const n=this.config.get(e);if(!n)return!1;const r=Wn();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ki("token-refresh",!0,void 0,{type:e}),!0):(ki("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return ko.error("Token refresh failed:",i),ki("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return r&&(c+=`&reason=${encodeURIComponent(r)}`),c}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const c=decodeURIComponent(l);if(c.startsWith("/"))return c}catch{}return r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Or.instance=null}};$(Or,"instance"),$(Or,"LOCALE_STORAGE_KEY","g7_locale");let Yn=Or;const Hm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},oa={findHandler(s,e){if(s){if(s[e])return s[e];if(s[String(e)])return s[String(e)];if(s.default)return s.default}},normalizeOnError(s){return s?Array.isArray(s)?s:[s]:[]},injectErrorCode(s,e,n){if(s.handler!=="showErrorPage"||s.params?.errorCode!==void 0)return s;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?s:{...s,params:{...s.params,errorCode:i}}}},xr=dt("ErrorHandlingResolver"),Ba=class Ba{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Ba.instance||(Ba.instance=new Ba),Ba.instance}static resetInstance(){Ba.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,xr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,xr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;xr.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=oa.findHandler(r,e);if(l){const c=this.getMatchedKey(r,e);return{handler:oa.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=oa.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=oa.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:oa.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=oa.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:oa.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=oa.findHandler(Hm,e),l){const c=this.getMatchedKey(Hm,e);return{handler:oa.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){xr.error("Action executor is not set");return}xr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw xr.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(xr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return xr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return xr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,xr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,xr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Ba,"instance",null);let mf=Ba;function Tr(){return mf.getInstance()}function Ro(s,e){const n={...s};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=Ro(n[r],e[r])):n[r]=e[r];return n}var yf={exports:{}},Do={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Um;function VC(){if(Um)return Do;Um=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,l){var c=null;if(l!==void 0&&(c=""+l),i.key!==void 0&&(c=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:s,type:r,key:c,ref:i!==void 0?i:null,props:l}}return Do.Fragment=e,Do.jsx=n,Do.jsxs=n,Do}var Pm;function KC(){return Pm||(Pm=1,yf.exports=VC()),yf.exports}var ft=KC();const WC=ra({__proto__:null,default:aa(ft)},[ft]),bf=dt("ParentContextProvider"),Bm=M.createContext(null);let Ac=null;function vf(){Ac?(bf.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ac()):bf.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const qm=({children:s})=>{const[e,n]=M.useState(0),r=M.useRef(!0),i=M.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);M.useEffect(()=>(r.current=!0,Ac=()=>{r.current&&(n(c=>c+1),bf.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Ac=null}),[]);const l={version:e,getParentDataContext:i};return ft.jsx(Bm.Provider,{value:l,children:s})};function YC(){return M.useContext(Bm)}function Gm(s){return s.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function Fm(s,e){try{const n=typeof window<"u"&&window.location?.protocol||"https:",r=e||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",i=s.startsWith("//")?`${n}${s}`:s,l=new URL(i,r);return l.protocol!=="http:"&&l.protocol!=="https:"?null:l.hostname.toLowerCase()}catch{return null}}function fs(){const s=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(s)?s.map(e=>String(e).toLowerCase()):[]}function Oo(s,e){if(typeof s!="string")return!1;const n=s.trim();if(n==="")return!1;const r=Gm(n),i=r.startsWith("//"),l=/^[a-z][a-z0-9+.-]*:/i.test(r);if(!i&&!l&&r.startsWith("/"))return!0;const c=Fm(r),d=e??fs();return c!==null&&d.map(f=>String(f).toLowerCase()).includes(c)}const N=dt("ActionDispatcher");function XC(s,e,n,r){return n||(Rg(s)||Md(s)?"$t:core.errors.network_request_failed":r||`Failed to execute action: ${e}`)}const Vm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),JC=new Set(["redirect"]);function Xn(){try{return window.G7Core?.devTools}catch{return}}class Tt extends Error{constructor(n,r,i){super(n);$(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const Km={click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"},rn=class rn{constructor(e={},n,r){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"localMirrorDepth",0);$(this,"intervals",new Map);this.bindingEngine=new Tn,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Xn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),N.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,N.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Vm}static getPreviewSuppressedLayoutFeatures(){return JC}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return N.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const r=Xn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,p={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(p.key=c),d!==void 0&&(p.event=d),p}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=ls(c,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;Tr().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){N.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...r.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},p=r.data?._local||r.state||{},m={...f,...p},y=r.isolatedContext?.state;N.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...y?{isolatedStateOverride:y}:{}})}else N.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,r)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){N.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){N.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){N.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else N.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,r)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){N.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){N.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(N.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):N.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,r)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:p=2e3,delay:m=0,retryCount:y=0,retryInterval:C=50,scrollContainer:S}=n.params||{};if(!i){N.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){N.warn("scrollIntoView: window/document is not available");return}let v=null;if(f){if(v=await new Promise(x=>{const w=document.querySelector(i);if(w){x(w);return}const R=setTimeout(()=>{L.disconnect(),x(null)},p),L=new MutationObserver(()=>{const O=document.querySelector(i);O&&(clearTimeout(R),L.disconnect(),x(O))});L.observe(document.body,{childList:!0,subtree:!0})}),!v){N.warn(`scrollIntoView: element not found for selector "${i}" after ${p}ms timeout`);return}}else{m>0&&await new Promise(w=>setTimeout(w,m)),v=document.querySelector(i);let x=0;for(;!v&&xsetTimeout(w,C)),v=document.querySelector(i),x++;if(!v){N.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){N.warn(`scrollIntoView: container not found for selector "${S}"`);return}const w=v.getBoundingClientRect(),R=x.getBoundingClientRect(),L=w.top-R.top+x.scrollTop,O=L+w.height;let j;switch(c){case"start":j=L;break;case"center":j=L-x.clientHeight/2+w.height/2;break;case"end":j=O-x.clientHeight;break;case"nearest":default:const F=w.topR.bottom;if(F)j=L;else if(G)j=O-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,j),behavior:l});return}v.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{if(typeof window>"u"){N.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw N.error("reloadExtensions: reloadExtensionState failed",d),d}else N.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},r)}catch(d){N.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){N.error("reloadExtensions: reloadPluginHandlers failed",d)}N.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{if(typeof window>"u"){N.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),N.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw N.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),N.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,r)=>{if(typeof window>"u"){N.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,r)=>{const{componentId:i}=n.params||{};if(!i){N.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){N.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),N.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,r)=>{if(typeof window>"u"){N.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),N.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw N.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,r)=>{if(typeof window>"u"){N.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){N.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){N.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){N.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){N.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,N.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js){const p=c.assets.js,m=`module-${f}`;this.assertAllowedExtensionAssetUrl(p,`module script (${f})`,n),document.getElementById(m)?N.warn(`reloadModuleHandlers: Script ${m} already loaded`):(await Cr(p,{id:m},{label:`module-script:${f}`}),N.log(`reloadModuleHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const p=c.assets.css,m=`module-css-${f}`;this.assertAllowedExtensionAssetUrl(p,`module stylesheet (${f})`,n),document.getElementById(m)||(await sa(p,{id:m},{label:`module-css:${f}`}),N.log(`reloadModuleHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],N.log(`reloadModuleHandlers: Removed assets for ${f}`));const p=`module-${f}`,m=document.getElementById(p);m&&(m.remove(),N.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,C=document.getElementById(y);C&&(C.remove(),N.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(p){throw N.error(`reloadModuleHandlers: Failed to ${l} module assets`,p),p}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{if(typeof window>"u"){N.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){N.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){N.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){N.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){N.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,N.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js){const p=c.assets.js,m=`plugin-${f}`;this.assertAllowedExtensionAssetUrl(p,`plugin script (${f})`,n),document.getElementById(m)?N.warn(`reloadPluginHandlers: Script ${m} already loaded`):(await Cr(p,{id:m},{label:`plugin-script:${f}`}),N.log(`reloadPluginHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const p=c.assets.css,m=`plugin-css-${f}`;this.assertAllowedExtensionAssetUrl(p,`plugin stylesheet (${f})`,n),document.getElementById(m)||(await sa(p,{id:m},{label:`plugin-css:${f}`}),N.log(`reloadPluginHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],N.log(`reloadPluginHandlers: Removed assets for ${f}`));const p=`plugin-${f}`,m=document.getElementById(p);m&&(m.remove(),N.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,C=document.getElementById(y);C&&(C.remove(),N.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(p){throw N.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,p),p}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{if(e){N.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,N.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,N.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,N.warn("showErrorPage: ErrorPageHandler not available");return}const c=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),N.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const p=(m,y=6e4)=>new Promise((C,S)=>{const v=document.getElementById(m);if(v){C(v);return}N.log(`showErrorPage: Waiting for container #${m}...`);let x;const w=new MutationObserver((R,L)=>{const O=document.getElementById(m);O&&(N.log(`showErrorPage: Container #${m} found`),L.disconnect(),clearTimeout(x),C(O))});w.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{w.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await p(f);const m=Tr(),y=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||N.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(y)}}catch(m){throw N.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,r)=>{const i=n.params?.event,l=n.params?.data;if(!i){N.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){N.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){N.warn("emitEvent: G7Core.componentEvent is not available");return}try{N.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:r.data,state:r.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?N.warn(`emitEvent: No listeners found for "${i}"`):N.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const p=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...p,_eventResult:m}});const y=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:p;window.__g7SequenceLocalSync={...y,_eventResult:m}}}catch(d){if(N.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=c?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,r)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){N.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){N.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){N.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(C=>C.id===i?{...C,[l]:c,_modified:!0}:C),y=new Set(f._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(y)}}),N.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw N.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,r)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){N.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){N.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){N.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const p=f.state.get()||{},y=(p.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const v=S.options.map(x=>x.id===l?{...x,[c]:d,_modified:!0}:x);return{...S,options:v,_modified:!0}}return S}),C=new Set(p._local?.modifiedProductIds||[]);C.add(i),this.globalStateUpdater({products:{...p.products,data:{...p.products?.data,data:y}},_local:{...p._local,modifiedProductIds:Array.from(C)}}),N.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(p){throw N.error("updateOptionField: Error updating option field",p),p}}),this.registerHandler("setLocale",async(n,r)=>{const i=n.target;if(!i||typeof i!="string"){N.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),N.log("setLocale: Locale changed to",i)}catch(c){N.error("setLocale: Failed to change locale:",c),window.location.reload()}else{N.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{N.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Xn();if(!e?.isEnabled())return;const n=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){N.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=r?.state?{...r.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(N.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??r?.state??{},y=Date.now()-l;for(const C of Object.keys(c)){const S=c[C],v=m[C];S!==v&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${C}`,capturedValue:S,capturedAt:l,currentValue:v,actionId:d,stackTrace:new Error().stack}),N.warn(`[Stale Closure] _local.${C} changed after handler creation:`,`captured="${S}" → current="${v}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let p={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const C=f.target;new FormData(C).forEach((v,x)=>{p[x]=v})}const m={...this.defaultContext,data:{...n,form:p,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let C=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&C.startsWith("$t:")&&(C=this.translationEngine.resolveTranslations(C,this.translationContext,m.data)),!confirm(C))return}const y=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(p){if(N.error("Action execution failed:",p),e.onError){const m=p instanceof Tt&&p.originalError?p.originalError:p,y={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},C=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of C)await this.executeAction(S,y)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${r}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const r=Xn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),p=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(N.log("[executeAction] if condition result:",e.handler,p),!p)return i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return N.error("[executeAction] if condition error:",e.handler,f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(c=this.sanitizeForDevTools(f));const p=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,p);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&Vm.has(e.handler))return N.warn(`Preview mode: "${e.handler}" suppressed`,p||f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const y=f.path||p;m=await this.handleNavigate(y,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const v=f.path||p;m=await this.handleOpenWindow(v,f);break}case"replaceUrl":{const v=f.path||p||window.location.pathname;m=await this.handleReplaceUrl(v,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const v=window.G7Core,x={};if(v?.state?.get){const w=v.state.get();x._global=w}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const C=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(p,f,n,C,S);break;case"login":m=await this.handleLogin(p,f,n);break;case"loginTwoFactor":m=await this.handleLoginTwoFactor(p,f,n);break;case"loginTwoFactorResend":m=await this.handleLoginTwoFactorResend(p,f,n);break;case"logout":m=await this.handleLogout(p,n);break;case"setState":N.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(p,f,n);break;case"openModal":m=await this.handleOpenModal(p,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(p,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:p,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:C,merge:S}=e.resultTo,v=this.resolveValue(C,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const w=this.buildNestedUpdate(v,m),R=x!=="deep"?{...w,__mergeMode:x}:w;this.writeLocalState(n,R),N.log(`[resultTo] Saved to _local.${v} (merge=${x}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const L=(window.G7Core?.state?.get()||{})._local||{},O=this.buildNestedUpdate(v,m);let j;x==="replace"?j=O:x==="shallow"?j={...L,...O}:j=this.deepMergeWithState(O,L),this.globalStateUpdater({_local:j}),N.log(`[resultTo] Saved to _local.${v} via globalStateUpdater (merge=${x}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const w=this.buildNestedUpdate(v,m);this.globalStateUpdater(w),N.log(`[resultTo] Saved to _global.${v}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const w=this.buildNestedUpdate(v,m);n.isolatedContext.mergeState(w,x),N.log(`[resultTo] Saved to _isolated.${v} (merge=${x}):`,m)}else N.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,v={};S?.state?.get&&(v._global=S.state.get()),n.state&&(v._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,v,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},C=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];C.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:C},y):C.length===1&&await this.executeAction(C[0],y)}return i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const p=f instanceof Tt?f:new Tt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=p.originalError?.response||{},y=m.data||{},C=p.originalError?.status||m.status||500;let S=XC(p.originalError??f,e.handler,y.message,p.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const v={status:C,message:S,errors:y.errors||m.errors,data:y,statusText:p.originalError?.statusText,error_code:y.error_code??m.error_code};if(p.unknownHandler)throw N.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),p;const w=Tr().resolve(C,{errorHandling:e.errorHandling,onError:e.onError});if(w.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const L=window.G7Core,O={};L?.state?.get&&(O._global=L.state.get()),n.state&&(O._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,O,"callback-state-capture",i)}const R={...n,data:{...n.data,error:v}};try{const L={type:"click",handler:w.handler.handler,target:w.handler.target,params:w.handler.params,actions:w.handler.actions};return await this.executeAction(L,R),{success:!1,error:p}}catch(L){return N.error("Error executing error handler:",L),{success:!1,error:p}}}throw i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:p.name,message:p.message,stack:p.stack}}),p}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:p,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const c=new URLSearchParams;for(const[f,p]of Object.entries(n.query))if(p!=null&&p!=="")if(Array.isArray(p)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of p)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(p));const d=c.toString();d&&(i=`${e}?${d}`)}if(N.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await c.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),N.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}N.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){N.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new Tt("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const c=e.split("?")[0];return l.match(c)?null:this.resolveNavigateFallback(r,e,n)}resolveNavigateFallback(e,n,r){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(N.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const C=y;return"container"in C||"to"in C||"block"in C||"offset"in C},d=(y,C,S=0)=>{y===window?window.scrollTo({top:C,left:S,behavior:l}):y.scrollTo({top:C,left:S,behavior:l})},f=(y,C,S,v)=>{if(C===window){y.scrollIntoView({behavior:l,block:S}),v&&window.scrollBy({top:-v,left:0,behavior:l});return}const x=C,w=y.getBoundingClientRect(),R=x.getBoundingClientRect(),L=x.scrollTop+(w.top-R.top);let O;S==="center"?O=L-(x.clientHeight-y.clientHeight)/2:S==="end"?O=L-(x.clientHeight-y.clientHeight):O=L,O-=v,x.scrollTo({top:Math.max(0,O),left:0,behavior:l})},p=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const v=window.getComputedStyle(S),x=v.overflowY,w=v.overflowX;(x==="auto"||x==="scroll"||w==="auto"||w==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,C=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let v=window;if(typeof y.container=="string"&&y.container.length>0){const w=document.querySelector(y.container);if(!w){N.warn(`applyScrollOption: container not found: ${y.container}`);return}v=w}const x=y.to??"top";if(x==="top"){v===window?p():d(v,0);return}if(typeof x=="number"){d(v,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:w=0,y:R=0}=x;d(v,R-S,w);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const w=document.querySelector(x);w?f(w,v,C,S):N.warn(`applyScrollOption: target element not found: ${x}`);return}N.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){p();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:C=0}=i;window.scrollTo({top:C,left:y,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:l,block:"start"});return}}catch(y){N.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let r=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(r=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";N.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){N.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){N.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const p of d)p!=null&&p!==""&&i.append(f,String(p))}else i.set(c,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}N.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")r.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;r.delete(c),r.delete(f);for(const p of d)p!=null&&p!==""&&r.append(f,String(p))}else r.set(c,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Tt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await yt.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){N.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){N.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;case"cancelled":default:r={status:"cancelled"};break}return yt.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:c="GET",body:d,headers:f,contentType:p}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const K=Wn().getToken();K&&(y={Authorization:`Bearer ${K}`})}let C=e;const S=n.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const P=this.buildQueryString(S);if(P){const K=e.includes("?")?"&":"?";C=`${e}${K}${P}`}}const v=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},w={_global:v,_local:x},R=this.getMatchingGlobalHeaders(e,w),L={};if(typeof window<"u"){const P=localStorage.getItem("g7_locale");P&&(L["Accept-Language"]=P)}const O=p==="multipart/form-data",j={method:c,headers:{...O?{}:{"Content-Type":"application/json"},Accept:"application/json",...L,...m&&{"X-XSRF-TOKEN":m},...y,...R,...f},credentials:"include"};if(d&&c!=="GET")if(O){const P=new FormData;for(const[K,he]of Object.entries(d))he instanceof File||he instanceof Blob?P.append(K,he):he!=null&&P.append(K,typeof he=="object"?JSON.stringify(he):String(he));j.body=P}else j.body=JSON.stringify(d);const F=Xn();let G=null;F?.isEnabled()&&(G=F.trackRequest(C,c));try{let P=await fetch(C,j),K;try{K=await P.json()}catch{K=null}if(yt.isIdentityRequired(P.status,K)){const he=await yt.handle(K,{body:j.body,headers:j.headers,credentials:j.credentials},l);if(he){P=he;try{K=await P.json()}catch{K=null}}}if(G&&F?.isEnabled()&&(F.completeRequest(G,P.status,K),G=null),!P.ok){const he=K||{},Ee=new Error(he.message||`API call failed: ${P.statusText}`);throw Ee.response=he,Ee.status=P.status,Ee.statusText=P.statusText,new Tt(he.message||`API call failed: ${P.statusText}`,void 0,Ee)}return K}catch(P){throw G&&F?.isEnabled()&&F.failRequest(G,P instanceof Error?P.message:String(P)),P}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new Tt("Login requires email and password in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=Yn.getInstance();try{const f=await d.login(l,{email:i.email,password:i.password},this.buildAuthRequestOptions(c,r));return f.status==="two_factor_required"?{user:null,two_factor_required:!0,challenge_id:f.challenge.challengeId,provider_id:f.challenge.providerId,expires_at:f.challenge.expiresAt}:{user:f.user,two_factor_required:!1}}catch(f){throw this.toLoginActionError(f,"Login failed")}}async handleLoginTwoFactor(e,n,r){const{body:i}=n;if(!i||!i.challenge_id||!i.code)throw new Tt("loginTwoFactor requires challenge_id and code in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login/two-factor":"/api/auth/login/two-factor";try{return{user:await Yn.getInstance().completeTwoFactor(l,{challengeId:String(i.challenge_id),code:String(i.code)},this.buildAuthRequestOptions(c,r))}}catch(d){throw this.toLoginActionError(d,"Login failed")}}async handleLoginTwoFactorResend(e,n,r){const{body:i}=n;if(!i||!i.challenge_id)throw new Tt("loginTwoFactorResend requires challenge_id in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login/two-factor/resend":"/api/auth/login/two-factor/resend";try{const d=await Yn.getInstance().resendTwoFactor(l,{challengeId:String(i.challenge_id)},this.buildAuthRequestOptions(c,r));return{two_factor_required:!0,challenge_id:d.challengeId,provider_id:d.providerId,expires_at:d.expiresAt}}catch(d){throw this.toLoginActionError(d,"Resend failed")}}resolveAuthType(e){return e==="user"?"user":"admin"}buildAuthRequestOptions(e,n){const r=window.G7Core?.state?.getGlobal?.()||n.state?._global||{},i=window.G7Core?.state?.getLocal?.()||n.state?._local||{},l={_global:r,_local:i},c=this.getMatchingGlobalHeaders(e,l);return Object.keys(c).length>0?{headers:c}:void 0}toLoginActionError(e,n){const r=e?.message||n,i=new Error(r);return i.response=e?.response?.data||{},i.status=e?.status||e?.response?.status||500,i.code=e?.code,new Tt(r,void 0,i)}async handleLogout(e,n){await Yn.getInstance().logout()}async handleSetState(e,n){N.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:c,...d}=e,f=Xn(),p=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:p?.state?.get()||{},y=r==="global"?"_global":r.startsWith("_local.")?r:"_local",C=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,C,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,v=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=v!=="deep"?{...d,__mergeMode:v,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){N.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const w=p?.state?.get()||{},{__setStateId:R,__mergeMode:L,...O}=x,j=v==="deep"?this.deepMergeWithState(O,w):O,F={...j,...S?{__setStateId:S}:{},...v!=="deep"?{__mergeMode:v}:{}};return N.log("setState global:",F),this.globalStateUpdater(F,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",...v!=="deep"?{__mergeMode:v}:{},...j}}else if(r==="isolated"){const w=n.isolatedContext;if(w){const{__mergeMode:R,__setStateId:L,...O}=x;return w.mergeState(O,v),N.log("[handleSetState] isolated state updated:",O,"mergeMode:",v),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...O}}else if(N.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const L=window.__g7PendingLocalState||n.state||{},O=v==="deep"?this.deepMergeWithState(x,L):x;return this.writeLocalState(n,O),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}else throw S&&f&&f.completeStateChange(S),new Tt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const R=window.__g7LayoutContextStack||[];if(R.length>0){const L=i==="parent"?R[R.length-1]:R[0];if(L?.setState){const{__mergeMode:O,__setStateId:j,...F}=x,G=v==="deep"?this.deepMergeWithState(F,L.state||{}):F;return N.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,G),L.setState(G),S&&f&&setTimeout(()=>f.completeStateChange(S),0),G}}N.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const w=n.setState&&!n._isDispatchFallbackContext;if(N.log("[handleSetState] isRealComponentContext:",w,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),w){N.log("[handleSetState] Using COMPONENT setState path"),N.log("[handleSetState] resolvedPayload:",x),N.log("[handleSetState] context.state:",n.state),N.log("[handleSetState] mergeMode:",v);const L=window.__g7PendingLocalState||n.state||{},O=v==="deep"?this.deepMergeWithState(x,{}):x;N.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",O),n.setState(O);const j=v==="deep"?this.deepMergeWithState(x,L):v==="shallow"?{...n.state||{},...x}:x,{__mergeMode:F,__setStateId:G,...P}=j;window.__g7PendingLocalState=P,N.log("[handleSetState] __g7PendingLocalState updated:",P);const K=(window.__g7LayoutContextStack||[]).length;let he;if(this.globalStateUpdater){const je=K===0?window.__templateApp?.getGlobalState?.()?._local:void 0;if(v!=="replace"&&!!je&&typeof je=="object"&&!Array.isArray(je)){const de=v==="deep"?this.deepMergeWithState(x,je):{...je,...x},{__mergeMode:Ce,__setStateId:Z,...ge}=de;he=ge}else v!=="replace"&&N.log("[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백",{modalDepth:K,hasTemplateApp:!!window.__templateApp});const X=he?Ro(he,P):P;this.globalStateUpdater({_local:X},{render:!1}),N.log("[handleSetState] _global._local synced (render:false):",X)}const{__mergeMode:Ee,__setStateId:ke,...ze}=x;if(v==="replace")window.__g7ForcedLocalFields=ze;else{const je=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(ze,je)}return N.log("[handleSetState] __g7ForcedLocalFields updated:",ze),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...he?Ro(he,P):j,...v!=="deep"?{__mergeMode:v}:{}}}else if(this.globalStateUpdater){N.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const L=window.__g7PendingLocalState||m._local||{};N.log("[handleSetState] currentLocal (with pending):",L);const O=v==="deep"?this.deepMergeWithState(x,L):x;return N.log("[handleSetState] finalLocal (merged):",O),this.globalStateUpdater({_local:O},{render:c}),window.__g7PendingLocalState=O,N.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...O}}else throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const w=r.slice(7),{__mergeMode:R,__setStateId:L,...O}=x,j=O.value!==void 0?O.value:Object.values(O)[0];if(n.setState){const G=window.__g7PendingLocalState||n.state||{},P=this.createNestedUpdate(w,j,G),K={...G,...P};if(n.setState(P),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const he=window.__templateApp?.getGlobalState?.()?._local,Ee=he&&typeof he=="object"?{...he,...P}:K;this.globalStateUpdater({_local:Ee},{render:!1}),N.log("[handleSetState] _global._local synced for dot notation (render:false):",Ee)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),K}else throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context");const R=window.__g7PendingLocalState||n.state||{},L=v==="deep"?this.deepMergeWithState(x,R):x;return this.writeLocalState(n,L,void 0,{scope:i}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),L}}async handleParentScopeSetState(e,n,r,i){const l=Xn(),c=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),p=f?"$parent.":"$root.",m=e.slice(p.length);let y,C;if(m==="_local"||m==="_global")y=m,C=void 0;else if(m.startsWith("_local."))y="_local",C=m.slice(7);else if(m.startsWith("_global."))y="_global",C=m.slice(8);else{N.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){N.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const v=f?S[S.length-1]:S[0];if(!v){N.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=y==="_global"?v.state?._global:v.state?._local,w=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:R,__setStateId:L,...O}=n;if(y==="_global"){if(!this.globalStateUpdater){N.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),w&&l&&l.completeStateChange(w);return}const j=c?.state?.get()||{};if(C){const F=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(C,F,j),P={...j,...G};N.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,P),this.globalStateUpdater(P)}else{const F=d==="deep"?this.deepMergeWithState(O,j):O;N.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,F),this.globalStateUpdater(d!=="deep"?{...F,__mergeMode:d}:F)}return w&&l&&setTimeout(()=>l.completeStateChange(w),0),{__target:e,...O}}else{if(!v.setState){N.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),w&&l&&l.completeStateChange(w);return}const j=v.state||{};if(C){const F=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(C,F,j),P={...j,...G};return N.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,G),v.setState(G),v.state=P,v.dataContext&&(v.dataContext._local=P),vf(),w&&l&&setTimeout(()=>l.completeStateChange(w),0),P}else{const F=d!=="deep"?{...O,__mergeMode:d}:O,G=d==="replace"?O:d==="shallow"?{...j,...O}:this.deepMergeWithState(O,j);return N.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,G),v.setState(F),v.state=G,v.dataContext&&(v.dataContext._local=G),vf(),w&&l&&setTimeout(()=>l.completeStateChange(w),0),G}}}deepMergeWithState(e,n){const r=["errors"];let i=e;if("..."in e){const c=e["..."];if(c&&typeof c=="object"&&!Array.isArray(c)){const{"...":d,...f}=e;i={...c,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[c,d]of Object.entries(i)){if(r.includes(c)){l[c]=d;continue}if(c.includes(".")&&c!=="..."){const f=this.createNestedUpdate(c,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[c]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[c]!==null&&typeof n[c]=="object"&&!Array.isArray(n[c])?l[c]=this.deepMergeWithState(d,n[c]):l[c]=d}return l}deepMergeInto(e,n,r){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:C,dataContext:{_local:y||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,N.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else N.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const p=Xn();if(p?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;p.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){N.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],r=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,c=window.__g7LayoutContextStack||[];if(c.length>0){const d=c[c.length-1];d&&(d.dataContext=void 0),c.pop(),window.__g7LayoutContextStack=c,N.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(r){const d=Xn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:c}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&yt.consumeDomainNoticeShown()){N.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const p={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],p];this.globalStateUpdater({toasts:S})}else N.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){N.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,N.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],N.log("switch handler: using $args[0] as case key:",l)),l==null){if(r.default)return N.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);N.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=r[c];if(!d&&r.default&&(N.log(`switch handler: no case found for key "${c}", using default case`),d=r.default),!d){N.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:r}=e;if(!r||!Array.isArray(r)){N.warn("conditions handler requires conditions array");return}const i=n.data||{},l=Vg(r,i,this.bindingEngine);if(!l.matched){N.log("conditions handler: no matching branch found");return}const c=r[l.branchIndex];if(N.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){N.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(c.then)?await this.handleSequence({...e,actions:c.then},n):await this.executeAction(c.then,n)}handleStartInterval(e,n){const r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return N.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(r);c&&(clearInterval(c),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(p=>{N.error(`[startInterval:${r}] tick action failed`,p)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return N.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return N.warn("sequence handler requires non-empty actions array"),[];const i=Xn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},p=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,C=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(p).length>0?{...p}:void 0});for(let S=0;S0){const O={},j={...n.data,_local:f,_computed:O,$computed:O,_isolated:p};for(const[F,G]of Object.entries(L))if(typeof G=="string"){const P=G.trim();if(P.startsWith("{{")&&P.endsWith("}}"))try{const K=P.slice(2,-2).trim();O[F]=On(K)?this.bindingEngine.evaluatePipeExpression(K,j,{skipCache:!0}):this.bindingEngine.evaluateExpression(K,j,{skipCache:!0})}catch{O[F]=m[F]}}m=O,N.log("[handleSequence] _computed recalculated after setState:",m)}}if(v.handler!=="setState"){const L=window.__g7SequenceLocalSync;if(L&&L!==f){f=L,window.__g7SequenceLocalSync=void 0,N.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",v.handler);const O=n.data?._computedDefinitions;if(O&&Object.keys(O).length>0){const j={},F={...n.data,_local:f,_computed:j,$computed:j,_isolated:p};for(const[G,P]of Object.entries(O))if(typeof P=="string"){const K=P.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const he=K.slice(2,-2).trim();j[G]=On(he)?this.bindingEngine.evaluatePipeExpression(he,F,{skipCache:!0}):this.bindingEngine.evaluateExpression(he,F,{skipCache:!0})}catch{j[G]=m[G]}}m=j,N.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,C(),Date.now()-x,R.data)}catch(R){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,C(),Date.now()-x,void 0,R),i.endSequenceExecution?.(l,R)),N.error(`sequence handler: action[${S}] failed:`,R),R}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return N.warn("parallel handler requires non-empty actions array"),[];N.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,p)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw N.error(`parallel handler: action[${p}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&N.warn(`parallel handler: ${d}/${r.length} actions failed`),c}assertAllowedExtensionAssetUrl(e,n,r){if(!Oo(e,fs()))throw N.error(`Blocked untrusted ${n} asset url: ${e}`),new Tt(`Blocked untrusted ${n} url (same-origin path or declared trusted host required): ${e}`,r)}async handleLoadScript(e,n,r){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new Tt('loadScript handler requires "src" parameter',n);if(!Oo(i,fs()))throw N.warn(`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${i}`),new Tt(`Blocked untrusted script src (same-origin path or declared trusted host required): ${i}`,n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;if(rn.loadedScripts.has(f))return N.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0;const p=rn.loadingScripts.get(f);if(p)return N.log(`loadScript: joining in-flight load: ${f}`),await p,n.onLoad&&await this.executeAction(n.onLoad,r),!0;if(document.getElementById(f))return N.log(`loadScript: script element already exists: ${f}`),rn.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0;N.log(`loadScript: loading script: ${i}`);const y=document.createElement("script");if(y.id=f,y.src=i,y.async=c,y.defer=d,y.hasAttribute("data-gdpr-blocked-src"))return N.warn(`loadScript: script blocked by consent manager (not loaded): ${i}`),!1;const C=new Promise((S,v)=>{y.onload=()=>{N.log(`loadScript: script loaded successfully: ${f}`),rn.loadedScripts.add(f),rn.loadingScripts.delete(f),S()},y.onerror=x=>{N.error(`loadScript: failed to load script: ${i}`,x),rn.loadingScripts.delete(f),v(new Tt(`Failed to load script: ${i}`,n))},document.head.appendChild(y)});if(C.catch(()=>{}),rn.loadingScripts.set(f,C),await C,n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){N.error("loadScript: onLoad action failed:",S)}return!0}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,p=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new Tt('callExternal handler requires "constructor" parameter',n);const C=this.getNestedProperty(window,i);if(!C||typeof C!="function")throw new Tt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);this.assertCallableExternalConstructor(C,i,n),N.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,w]of Object.entries(l))w===!0&&(S[x]=R=>{if(N.log(`callExternal: callback triggered for ${x}`,R),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,R),m&&r.setState){const L=F=>{const G={};for(const[P,K]of Object.entries(F)){if(rn.isPrototypePathSegment(P)){N.warn(`callExternal: skipped prototype-polluting mapping key: ${P}`);continue}typeof K=="string"?G[P]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[P]=L(K))}return G},O=L(m);N.log("callExternal: callbackSetState mapping result",O);const j=this.deepMergeWithState(O,r.state||{});N.log("callExternal: merged with existing state",j),this.writeLocalState(r,j)}else f&&r.setState&&this.writeLocalState(r,{[`${f.replace(/:/g,"_")}_result`]:R});if(y){const L={...r,data:{...r.data,$event:R}},O=Array.isArray(y)?y:[y];for(const j of O)try{this.executeAction(j,L)}catch(F){N.error("callExternal: callbackAction failed:",F)}}});const v=new C(S);if(c&&typeof v[c]=="function"){if(N.log(`callExternal: calling method ${c}`),c==="embed"&&p){const x=document.querySelector(p);if(x)return v[c](x,...d);throw new Tt(`Embed target element not found: ${p}`,n)}return v[c](...d)}return v}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,p=e.callbackAction;if(!i)throw new Tt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new Tt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);this.assertCallableExternalConstructor(m,i,n),N.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:C}=this.createEmbedLayer(f),S={...l};for(const[x,w]of Object.entries(l))w===!0&&(S[x]=R=>{if(N.log(`callExternalEmbed: callback triggered for ${x}`,R),C(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,R),c&&r.setState){const L=F=>{const G={};for(const[P,K]of Object.entries(F)){if(rn.isPrototypePathSegment(P)){N.warn(`callExternal: skipped prototype-polluting mapping key: ${P}`);continue}typeof K=="string"?G[P]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[P]=L(K))}return G},O=L(c);N.log("callExternalEmbed: callbackSetState mapping result",O);const j=this.deepMergeWithState(O,r.state||{});N.log("callExternalEmbed: merged with existing state",j),this.writeLocalState(r,j)}if(p){const L={...r,data:{...r.data,$event:R}},O=Array.isArray(p)?p:[p];for(const j of O)try{this.executeAction(j,L)}catch(F){N.error("callExternalEmbed: callbackAction failed:",F)}}});const v=new m(S);if(typeof v.embed=="function")v.embed(y),N.log("callExternalEmbed: embedded in layer");else throw C(),new Tt(`Constructor ${i} does not have embed method`,n);return v}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 9999; display: flex; align-items: center; justify-content: center; `;const r=document.createElement("div");r.id="g7-embed-layer",r.style.cssText=` position: relative; background: white; border-radius: 8px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); max-width: 90vw; max-height: 90vh; overflow: hidden; `,e&&(r.className=e);const i=document.createElement("button");i.type="button",i.innerHTML="×",i.style.cssText=` position: absolute; top: 8px; right: 8px; width: 32px; height: 32px; border: none; background: rgba(0, 0, 0, 0.1); border-radius: 50%; font-size: 20px; cursor: pointer; z-index: 10; display: flex; align-items: center; justify-content: center; color: #666; transition: background-color 0.2s; `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),n.onclick=d=>{d.target===n&&l()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}static isPrototypePathSegment(e){return rn.PROTOTYPE_PATH_SEGMENTS.includes(e)}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>{if(!rn.isPrototypePathSegment(i))return r&&r[i]!==void 0?r[i]:void 0},e)}assertCallableExternalConstructor(e,n,r){if(typeof window>"u")return;if([window.Function,window.eval,window.setTimeout,window.setInterval].some(l=>l!==void 0&&l===e))throw N.error(`callExternal: blocked arbitrary code execution seam: ${n}`),new Tt(`Blocked constructor (arbitrary code execution): ${n}`,r)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return N.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),N.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return N.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:c}=e;if(!r)return N.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(r);if(d===null)return N.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&this.writeLocalState(n,{[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return N.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&this.writeLocalState(n,{[l]:f}),f}catch(d){return N.error("loadFromLocalStorage: failed to load",{key:r,error:d}),c}}writeLocalState(e,n,r,i){const l=r||e.setState;if(!l)return;if(typeof n=="function"){N.warn("[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다."),l(n);return}if(i?.scope==="parent"||i?.scope==="root"){l(n);return}if(this.localMirrorDepth>0||l?.__g7CanonicalWriter){l(n);return}const c=n&&typeof n=="object"?n:{},d=c.__mergeMode;if(d==="replace"){l(n);return}const{__mergeMode:f,__setStateId:p,...m}=c;if("errors"in m||!rn.isMirrorSafePayload(m)){l(n);return}const y=window;if((y.__g7LayoutContextStack||[]).length>0){l(n);return}const C=y.G7Core?.state?.setLocal;if(!y.__templateApp||typeof C!="function"){l(n);return}const S=this.deepMergeWithState(m,{});this.localMirrorDepth++;try{C(S,{render:!1,merge:d??"deep"}),y.__g7ActionContext?.setState!==l&&l(n),d&&(y.__g7ForcedLocalFields={...y.__g7ForcedLocalFields||{},...S})}finally{this.localMirrorDepth--}}static isMirrorSafePayload(e,n=0){if(e===null||typeof e!="object"||n>=8)return!0;if(Array.isArray(e))return e.every(i=>rn.isMirrorSafePayload(i,n+1));const r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null?!1:Object.values(e).every(i=>rn.isMirrorSafePayload(i,n+1))}makeLocalSetStateProxy(e){const n=e.setState;if(!n)return;if(n.__g7CanonicalWriter)return n;const r=i=>{this.writeLocalState(e,i,n)};return r.__g7CanonicalWriter=!0,r}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){N.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const c=new Tt(`Unknown action handler: ${e.handler}`,e);throw c.unknownHandler=!0,c}const i=this.makeLocalSetStateProxy(n),l=i&&i!==n.setState?{...n,setState:i}:n;return await r(e,l)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&N.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,n):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,n)),c&&typeof c=="object"&&!Array.isArray(c)&&(r={...r,...c})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=Ma(e);if(r===null){let c=n;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...n,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(c={...c,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,c,{skipCache:!0})}let i=r;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=n;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...n,_global:d})}if(i.includes("_computed")||i.includes("$computed")){const d=window.__g7ActionContext?.computedRef?.current;d&&Object.keys(d).length>0&&(l={...l,_computed:d,$computed:d})}i.includes("_global.modules")&&(N.log("[evaluateExpression] expression:",i),N.log("[evaluateExpression] dataContext._global:",l._global),N.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=On(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&N.log("[evaluateExpression] result:",c),typeof c=="string"&&c.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(c,this.translationContext,n):c}catch(c){return N.error("Expression evaluation failed:",e,c),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(N.error("dispatchAction failed:",i),e.onError){const l=i instanceof Tt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...r,data:{...r.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,c)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,r){this.customHandlers.set(e,n);const i=Xn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Xn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,r,i,l){const c={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,r,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,p=this.extractEventData(n),m=p._changedKeys;if(m&&Array.isArray(m)&&p?.target?.value&&typeof p.target.value=="object"&&!Array.isArray(p.target.value)){const v=this.debounceAccumulatedValues.get(f);if(v){const x={...v};for(const w of m)x[w]=p.target.value[w];p.target.value=x}this.debounceAccumulatedValues.set(f,p.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const C=Xn();C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,p,r,i,c),C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const v=()=>{this.executeDebouncedAction(e,p,r,i,c),C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),v()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,v)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const y=this.resolveActionRef(m),C=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(C)||l.set(C,[]),l.get(C).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),p=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!p&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...C)=>{for(const S of y){const v=C[0],x=v&&typeof v=="object"&&"preventDefault"in v;if(x&&(m==="onDragOver"||m==="onDrop")&&v.preventDefault(),x&&S.key&&"key"in v){if(this.isImeComposing(v)){N.log("Key filter skipped (IME composing):",S.key);continue}if(v.key!==S.key){N.log("Key filter not matched:",S.key,"actual:",v.key);continue}N.log("Key filter matched:",S.key)}if(S.debounce){const w=`${c}-${S.handler}-${m}`,R=v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null;let L;if(x)L=v;else if(R){const j={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};v._changedKeys&&(j._changedKeys=v._changedKeys),L=j}else L=new Event("custom");const O=S.event?{...n,$args:C}:n;this.handleDebouncedAction(S,L,O,r,w,C)}else if(this.flushPendingDebounceTimers(),S.event){const w={...n,$args:C},R=this.resolveEventForHandler(v,x);this.createHandler(S,w,r)(R)}else if(x)this.createHandler(S,n,r)(v);else if(v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null){const R={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(R)}}}}return i}getEventHandlerName(e){return Km[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return Km[e]??e}resolveEventForHandler(e,n){if(n)return e;if(!(e&&typeof e=="object"&&!("preventDefault"in e)&&"target"in e&&e.target!==null))return new Event("custom");const i={type:"custom",target:e.target,preventDefault:()=>{},stopPropagation:()=>{}};return e._changedKeys&&(i._changedKeys=e._changedKeys),i}sanitizeForDevTools(e,n=5){const r=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(r.has(l))return"[Circular Array]";r.add(l);const d=l.slice(0,10).map(f=>i(f,c+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),p=f.slice(0,20);for(const m of p)try{d[m]=i(l[m],c+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(rn,"loadedScripts",new Set),$(rn,"loadingScripts",new Map),$(rn,"PROTOTYPE_PATH_SEGMENTS",["__proto__","prototype","constructor"]);let Lo=rn,xc=null;function Wm(s){return xc||(xc=new Lo(s)),xc}function QC(s){xc=s}const Ym=dt("TransitionManager");class ZC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Ym.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){Ym.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Gr=new ZC,Tc=dt("TransitionContext"),Xm=M.createContext({isTransitioning:!1}),Sf=({children:s})=>{const[e,n]=M.useState(()=>{const i=Gr.getIsPending();return Tc.log("Initial state:",i),i});M.useEffect(()=>{Tc.log("Subscribing to TransitionManager");const i=Gr.subscribe(l=>{Tc.log("Received isPending update:",l),n(l)});return()=>{Tc.log("Unsubscribing from TransitionManager"),i()}},[]);const r=M.useMemo(()=>({isTransitioning:e}),[e]);return ft.jsx(Xm.Provider,{value:r,children:s})},Jm=()=>M.useContext(Xm),kc="__g7LocalInitTracking";function wf(){const s=globalThis;return s[kc]||(s[kc]={hash:"",timestamp:void 0,consumed:void 0}),s[kc]}function eE(){const s=globalThis;s[kc]={hash:"",timestamp:void 0,consumed:void 0}}function tE(s){wf().consumed=s}function nE(s){return wf().consumed===s}function rE(s){return s.globalTrackedKey!==s.trackingKey?"apply":s.instanceHandledKey===s.trackingKey?"skip":"prune"}function aE(s,e){return typeof s=="number"&&typeof e=="number"?Math.max(s,e):e??s}function iE(s,e){if(e===void 0)return s;if(!(s!==null&&typeof s=="object"&&e!==null&&typeof e=="object"&&!nE(s)))return e;const{_forceLocalInit:r,...i}=s,{_forceLocalInit:l,...c}=e,d={...i,...c},f=aE(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function sE(s){return s<768?"mobile":s<1024?"tablet":"desktop"}function Qm(s){const e=sE(s);return{width:s,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Cf=M.createContext(Qm(1024)),Rc=({children:s,overrideWidth:e})=>{const[n,r]=M.useState(()=>_i.getWidth());M.useEffect(()=>{const c=_i.subscribe(d=>{r(d)});return()=>{c()}},[]);const i=e??n,l=M.useMemo(()=>Qm(i),[i]);return ft.jsx(Cf.Provider,{value:l,children:s})},Ef=()=>M.useContext(Cf);window.G7Core?.createLogger?.("Core:State");function oE(s,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},c=s!==void 0;M.useRef(c);const[d,f]=M.useState(s!==void 0?s:e),p=d,m=M.useRef(s),y=M.useRef(!1);M.useEffect(()=>{if(y.current){m.current=s;return}i&&c&&s!==m.current&&(l?!l(d,s):d!==s)&&f(s),m.current=s},[s,c,i,l,d]);const C=M.useCallback(S=>{const v=typeof S=="function"?S(p):S;(l?l(p,v):p===v)||(y.current=!0,f(v),n?.(v),requestAnimationFrame(()=>{y.current=!1}))},[p,c,n,l]);return[p,C]}function lE(s,e){return s===e?!0:s.length!==e.length?!1:s.every((n,r)=>n===e[r])}function Zm(s,e){if(s===e)return!0;const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>s[i]===e[i])}const ey=M.createContext({}),cE=({children:s,value:e})=>ft.jsx(ey.Provider,{value:e,children:s}),uE=()=>M.useContext(ey),dE=(s,e)=>{if(!s)return;const n=e.split(".");let r=s;for(const i of n){if(r==null)return;r=r[i]}return r},ty=(s,e,n)=>{const r=e.split(".");if(r.length===1)return{...s,[r[0]]:n};const i={...s};let l=i;for(let c=0;c{hs.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{hs.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},ny=M.createContext(fE);let hE=0;function pE(){return`isolated-${++hE}-${Date.now().toString(36)}`}function ry(s,e){if(e==null)return s;if(typeof e!="object"||Array.isArray(e))return e;const n={...s};for(const r of Object.keys(e)){const i=e[r],l=s?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=ry(l,i):n[r]=i}return n}function gE(s,e){return e?e.split(".").reduce((n,r)=>n?.[r],s):s}function mE(s,e,n){const r=e.split("."),i={...s};let l=i;for(let c=0;c{const i=M.useRef(e||pE()).current,[l,c]=M.useState(s),d=M.useRef(l);d.current=l;const f=M.useCallback(S=>gE(d.current,S),[]),p=M.useCallback((S,v)=>{c(x=>{const w=mE(x,S,v);return hs.log(`[${i}] setState: ${S} =`,v),w})},[i]),m=M.useCallback((S,v="deep")=>{c(x=>{let w;return v==="replace"?w=S:v==="shallow"?w={...x,...S}:w=ry(x,S),hs.log(`[${i}] mergeState (${v}):`,S),w})},[i]),y=M.useMemo(()=>({state:l,setState:p,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,p,f,m,i]),C=M.useMemo(()=>({state:d.current,setState:p,getState:f,mergeState:m}),[p,f,m]);return M.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=v),v[i]=C,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),hs.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete v[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),hs.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,C]),M.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates;v?.[i]&&(v[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),ft.jsx(ny.Provider,{value:y,children:n})},bE=()=>{const s=M.useContext(ny);return s.scopeId?s:null};var za=wg();function vE(){for(var s=arguments.length,e=new Array(s),n=0;nr=>{e.forEach(i=>i(r))},e)}const Dc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ps(s){const e=Object.prototype.toString.call(s);return e==="[object Window]"||e==="[object global]"}function _f(s){return"nodeType"in s}function Mn(s){var e,n;return s?ps(s)?s:_f(s)&&(e=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Af(s){const{Document:e}=Mn(s);return s instanceof e}function $o(s){return ps(s)?!1:s instanceof Mn(s).HTMLElement}function ay(s){return s instanceof Mn(s).SVGElement}function gs(s){return s?ps(s)?s.document:_f(s)?Af(s)?s:$o(s)||ay(s)?s.ownerDocument:document:document:document}const Fr=Dc?M.useLayoutEffect:M.useEffect;function xf(s){const e=M.useRef(s);return Fr(()=>{e.current=s}),M.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{s.current=setInterval(r,i)},[]),n=M.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[e,n]}function Mo(s,e){e===void 0&&(e=[s]);const n=M.useRef(s);return Fr(()=>{n.current!==s&&(n.current=s)},e),n}function No(s,e){const n=M.useRef();return M.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...e])}function Oc(s){const e=xf(s),n=M.useRef(null),r=M.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Tf(s){const e=M.useRef();return M.useEffect(()=>{e.current=s},[s]),e.current}let kf={};function Io(s,e){return M.useMemo(()=>{if(e)return e;const n=kf[s]==null?0:kf[s]+1;return kf[s]=n,s+"-"+n},[s,e])}function iy(s){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,p]of d){const m=l[f];m!=null&&(l[f]=m+s*p)}return l},{...e})}}const ms=iy(1),jo=iy(-1);function wE(s){return"clientX"in s&&"clientY"in s}function Rf(s){if(!s)return!1;const{KeyboardEvent:e}=Mn(s.target);return e&&s instanceof e}function CE(s){if(!s)return!1;const{TouchEvent:e}=Mn(s.target);return e&&s instanceof e}function Df(s){if(CE(s)){if(s.touches&&s.touches.length){const{clientX:e,clientY:n}=s.touches[0];return{x:e,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:e,clientY:n}=s.changedTouches[0];return{x:e,y:n}}}return wE(s)?{x:s.clientX,y:s.clientY}:null}const zo=Object.freeze({Translate:{toString(s){if(!s)return;const{x:e,y:n}=s;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:e,scaleY:n}=s;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[zo.Translate.toString(s),zo.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:e,duration:n,easing:r}=s;return e+" "+n+"ms "+r}}}),sy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function EE(s){return s.matches(sy)?s:s.querySelector(sy)}const _E={display:"none"};function AE(s){let{id:e,value:n}=s;return We.createElement("div",{id:e,style:_E},n)}function xE(s){let{id:e,announcement:n,ariaLiveType:r="assertive"}=s;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return We.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function TE(){const[s,e]=M.useState("");return{announce:M.useCallback(r=>{r!=null&&e(r)},[]),announcement:s}}const oy=M.createContext(null);function kE(s){const e=M.useContext(oy);M.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(s)},[s,e])}function RE(){const[s]=M.useState(()=>new Set),e=M.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[M.useCallback(r=>{let{type:i,event:l}=r;s.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[s]),e]}const DE={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. `},OE={onDragStart(s){let{active:e}=s;return"Picked up draggable item "+e.id+"."},onDragOver(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(s){let{active:e}=s;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function LE(s){let{announcements:e=OE,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=DE}=s;const{announce:l,announcement:c}=TE(),d=Io("DndLiveRegion"),[f,p]=M.useState(!1);if(M.useEffect(()=>{p(!0)},[]),kE(M.useMemo(()=>({onDragStart(y){let{active:C}=y;l(e.onDragStart({active:C}))},onDragMove(y){let{active:C,over:S}=y;e.onDragMove&&l(e.onDragMove({active:C,over:S}))},onDragOver(y){let{active:C,over:S}=y;l(e.onDragOver({active:C,over:S}))},onDragEnd(y){let{active:C,over:S}=y;l(e.onDragEnd({active:C,over:S}))},onDragCancel(y){let{active:C,over:S}=y;l(e.onDragCancel({active:C,over:S}))}}),[l,e])),!f)return null;const m=We.createElement(We.Fragment,null,We.createElement(AE,{id:r,value:i.draggable}),We.createElement(xE,{id:d,announcement:c}));return n?za.createPortal(m,n):m}var nn;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(nn||(nn={}));function Lc(){}function ly(s,e){return M.useMemo(()=>({sensor:s,options:e??{}}),[s,e])}function $E(){for(var s=arguments.length,e=new Array(s),n=0;n[...e].filter(r=>r!=null),[...e])}const kr=Object.freeze({x:0,y:0});function cy(s,e){return Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2))}function uy(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return n-r}function ME(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return r-n}function dy(s){let{left:e,top:n,height:r,width:i}=s;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function fy(s,e){if(!s||s.length===0)return null;const[n]=s;return n[e]}function hy(s,e,n){return e===void 0&&(e=s.left),n===void 0&&(n=s.top),{x:e+s.width*.5,y:n+s.height*.5}}const NE=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=hy(e,e.left,e.top),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const p=cy(hy(f),i);l.push({id:d,data:{droppableContainer:c,value:p}})}}return l.sort(uy)},IE=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=dy(e),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const p=dy(f),m=i.reduce((C,S,v)=>C+cy(p[v],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(uy)};function jE(s,e){const n=Math.max(e.top,s.top),r=Math.max(e.left,s.left),i=Math.min(e.left+e.width,s.left+s.width),l=Math.min(e.top+e.height,s.top+s.height),c=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=[];for(const l of r){const{id:c}=l,d=n.get(c);if(d){const f=jE(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(ME)};function HE(s,e,n){return{...s,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function py(s,e){return s&&e?{x:s.left-e.left,y:s.top-e.top}:kr}function UE(s){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...c,top:c.top+s*d.y,bottom:c.bottom+s*d.y,left:c.left+s*d.x,right:c.right+s*d.x}),{...n})}}const PE=UE(1);function BE(s){if(s.startsWith("matrix3d(")){const e=s.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(s.startsWith("matrix(")){const e=s.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function qE(s,e,n){const r=BE(e);if(!r)return s;const{scaleX:i,scaleY:l,x:c,y:d}=r,f=s.left-c-(1-i)*parseFloat(n),p=s.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?s.width/i:s.width,y=l?s.height/l:s.height;return{width:m,height:y,top:p,right:f+m,bottom:p+y,left:f}}const GE={ignoreTransform:!1};function ys(s,e){e===void 0&&(e=GE);let n=s.getBoundingClientRect();if(e.ignoreTransform){const{transform:p,transformOrigin:m}=Mn(s).getComputedStyle(s);p&&(n=qE(n,p,m))}const{top:r,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:c,bottom:d,right:f}}function gy(s){return ys(s,{ignoreTransform:!0})}function FE(s){const e=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function VE(s,e){return e===void 0&&(e=Mn(s).getComputedStyle(s)),e.position==="fixed"}function KE(s,e){e===void 0&&(e=Mn(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function $c(s,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Af(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!$o(i)||ay(i)||n.includes(i))return n;const l=Mn(s).getComputedStyle(i);return i!==s&&KE(i,l)&&n.push(i),VE(i,l)?n:r(i.parentNode)}return s?r(s):n}function my(s){const[e]=$c(s,1);return e??null}function Of(s){return!Dc||!s?null:ps(s)?s:_f(s)?Af(s)||s===gs(s).scrollingElement?window:$o(s)?s:null:null}function yy(s){return ps(s)?s.scrollX:s.scrollLeft}function by(s){return ps(s)?s.scrollY:s.scrollTop}function Lf(s){return{x:yy(s),y:by(s)}}var cn;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(cn||(cn={}));function vy(s){return!Dc||!s?!1:s===document.scrollingElement}function Sy(s){const e={x:0,y:0},n=vy(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},i=s.scrollTop<=e.y,l=s.scrollLeft<=e.x,c=s.scrollTop>=r.y,d=s.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:r,minScroll:e}}const WE={x:.2,y:.2};function YE(s,e,n,r,i){let{top:l,left:c,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=WE);const{isTop:p,isBottom:m,isLeft:y,isRight:C}=Sy(s),S={x:0,y:0},v={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!p&&l<=e.top+x.height?(S.y=cn.Backward,v.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=cn.Forward,v.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!C&&d>=e.right-x.width?(S.x=cn.Forward,v.x=r*Math.abs((e.right-x.width-d)/x.width)):!y&&c<=e.left+x.width&&(S.x=cn.Backward,v.x=r*Math.abs((e.left+x.width-c)/x.width)),{direction:S,speed:v}}function XE(s){if(s===document.scrollingElement){const{innerWidth:l,innerHeight:c}=window;return{top:0,left:0,right:l,bottom:c,width:l,height:c}}const{top:e,left:n,right:r,bottom:i}=s.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:s.clientWidth,height:s.clientHeight}}function wy(s){return s.reduce((e,n)=>ms(e,Lf(n)),kr)}function JE(s){return s.reduce((e,n)=>e+yy(n),0)}function QE(s){return s.reduce((e,n)=>e+by(n),0)}function ZE(s,e){if(e===void 0&&(e=ys),!s)return;const{top:n,left:r,bottom:i,right:l}=e(s);my(s)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const e_=[["x",["left","right"],JE],["y",["top","bottom"],QE]];class $f{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=$c(n),i=wy(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of e_)for(const f of c)Object.defineProperty(this,f,{get:()=>{const p=d(r),m=i[l]-p;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ho{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function t_(s){const{EventTarget:e}=Mn(s);return s instanceof e?s:gs(s)}function Mf(s,e){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var ur;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(ur||(ur={}));function Cy(s){s.preventDefault()}function n_(s){s.stopPropagation()}var lt;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(lt||(lt={}));const Ey={start:[lt.Space,lt.Enter],cancel:[lt.Esc],end:[lt.Space,lt.Enter,lt.Tab]},r_=(s,e)=>{let{currentCoordinates:n}=e;switch(s.code){case lt.Right:return{...n,x:n.x+25};case lt.Left:return{...n,x:n.x-25};case lt.Down:return{...n,y:n.y+25};case lt.Up:return{...n,y:n.y-25}}};class Nf{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new Ho(gs(n)),this.windowListeners=new Ho(Mn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ur.Resize,this.handleCancel),this.windowListeners.add(ur.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ur.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&ZE(r),n(kr)}handleKeyDown(e){if(Rf(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Ey,coordinateGetter:c=r_,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:p}=r.current,m=p?{x:p.left,y:p.top}:kr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:r.current,currentCoordinates:m});if(y){const C=jo(y,m),S={x:0,y:0},{scrollableAncestors:v}=r.current;for(const x of v){const w=e.code,{isTop:R,isRight:L,isLeft:O,isBottom:j,maxScroll:F,minScroll:G}=Sy(x),P=XE(x),K={x:Math.min(w===lt.Right?P.right-P.width/2:P.right,Math.max(w===lt.Right?P.left:P.left+P.width/2,y.x)),y:Math.min(w===lt.Down?P.bottom-P.height/2:P.bottom,Math.max(w===lt.Down?P.top:P.top+P.height/2,y.y))},he=w===lt.Right&&!L||w===lt.Left&&!O,Ee=w===lt.Down&&!j||w===lt.Up&&!R;if(he&&K.x!==y.x){const ke=x.scrollLeft+C.x,ze=w===lt.Right&&ke<=F.x||w===lt.Left&&ke>=G.x;if(ze&&!C.y){x.scrollTo({left:ke,behavior:d});return}ze?S.x=x.scrollLeft-ke:S.x=w===lt.Right?x.scrollLeft-F.x:x.scrollLeft-G.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(Ee&&K.y!==y.y){const ke=x.scrollTop+C.y,ze=w===lt.Down&&ke<=F.y||w===lt.Up&&ke>=G.y;if(ze&&!C.x){x.scrollTo({top:ke,behavior:d});return}ze?S.y=x.scrollTop-ke:S.y=w===lt.Down?x.scrollTop-F.y:x.scrollTop-G.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,ms(jo(y,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Nf.activators=[{eventName:"onKeyDown",handler:(s,e,n)=>{let{keyboardCodes:r=Ey,onActivation:i}=e,{active:l}=n;const{code:c}=s.nativeEvent;if(r.start.includes(c)){const d=l.activatorNode.current;return d&&s.target!==d?!1:(s.preventDefault(),i?.({event:s.nativeEvent}),!0)}return!1}}];function _y(s){return!!(s&&"distance"in s)}function Ay(s){return!!(s&&"delay"in s)}class If{constructor(e,n,r){var i;r===void 0&&(r=t_(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:l}=e,{target:c}=l;this.props=e,this.events=n,this.document=gs(c),this.documentListeners=new Ho(this.document),this.listeners=new Ho(r),this.windowListeners=new Ho(Mn(c)),this.initialCoordinates=(i=Df(l))!=null?i:kr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ur.Resize,this.handleCancel),this.windowListeners.add(ur.DragStart,Cy),this.windowListeners.add(ur.VisibilityChange,this.handleCancel),this.windowListeners.add(ur.ContextMenu,Cy),this.documentListeners.add(ur.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ay(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(_y(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ur.Click,n_,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ur.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Df(e))!=null?n:kr,p=jo(i,f);if(!r&&d){if(_y(d)){if(d.tolerance!=null&&Mf(p,d.tolerance))return this.handleCancel();if(Mf(p,d.distance))return this.handleStart()}if(Ay(d)&&Mf(p,d.tolerance))return this.handleCancel();this.handlePending(d,p);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===lt.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const a_={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class jf extends If{constructor(e){const{event:n}=e,r=gs(n.target);super(e,a_,r)}}jf.activators=[{eventName:"onPointerDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const i_={move:{name:"mousemove"},end:{name:"mouseup"}};var zf;(function(s){s[s.RightClick=2]="RightClick"})(zf||(zf={}));class s_ extends If{constructor(e){super(e,i_,gs(e.event.target))}}s_.activators=[{eventName:"onMouseDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return n.button===zf.RightClick?!1:(r?.({event:n}),!0)}}];const Hf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class o_ extends If{constructor(e){super(e,Hf)}static setup(){return window.addEventListener(Hf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Hf.move.name,e)};function e(){}}}o_.activators=[{eventName:"onTouchStart",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var Uo;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(Uo||(Uo={}));var Mc;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Mc||(Mc={}));function l_(s){let{acceleration:e,activator:n=Uo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:c=5,order:d=Mc.TreeOrder,pointerCoordinates:f,scrollableAncestors:p,scrollableAncestorRects:m,delta:y,threshold:C}=s;const S=u_({delta:y,disabled:!l}),[v,x]=SE(),w=M.useRef({x:0,y:0}),R=M.useRef({x:0,y:0}),L=M.useMemo(()=>{switch(n){case Uo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Uo.DraggableRect:return i}},[n,i,f]),O=M.useRef(null),j=M.useCallback(()=>{const G=O.current;if(!G)return;const P=w.current.x*R.current.x,K=w.current.y*R.current.y;G.scrollBy(P,K)},[]),F=M.useMemo(()=>d===Mc.TreeOrder?[...p].reverse():p,[d,p]);M.useEffect(()=>{if(!l||!p.length||!L){x();return}for(const G of F){if(r?.(G)===!1)continue;const P=p.indexOf(G),K=m[P];if(!K)continue;const{direction:he,speed:Ee}=YE(G,K,L,e,C);for(const ke of["x","y"])S[ke][he[ke]]||(Ee[ke]=0,he[ke]=0);if(Ee.x>0||Ee.y>0){x(),O.current=G,v(j,c),w.current=Ee,R.current=he;return}}w.current={x:0,y:0},R.current={x:0,y:0},x()},[e,j,r,x,l,c,JSON.stringify(L),JSON.stringify(S),v,p,F,m,JSON.stringify(C)])}const c_={x:{[cn.Backward]:!1,[cn.Forward]:!1},y:{[cn.Backward]:!1,[cn.Forward]:!1}};function u_(s){let{delta:e,disabled:n}=s;const r=Tf(e);return No(i=>{if(n||!r||!i)return c_;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[cn.Backward]:i.x[cn.Backward]||l.x===-1,[cn.Forward]:i.x[cn.Forward]||l.x===1},y:{[cn.Backward]:i.y[cn.Backward]||l.y===-1,[cn.Forward]:i.y[cn.Forward]||l.y===1}}},[n,e,r])}function d_(s,e){const n=e!=null?s.get(e):void 0,r=n?n.node.current:null;return No(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function f_(s,e){return M.useMemo(()=>s.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,r)}));return[...n,...l]},[]),[s,e])}var Po;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Po||(Po={}));var Uf;(function(s){s.Optimized="optimized"})(Uf||(Uf={}));const xy=new Map;function h_(s,e){let{dragging:n,dependencies:r,config:i}=e;const[l,c]=M.useState(null),{frequency:d,measure:f,strategy:p}=i,m=M.useRef(s),y=w(),C=Mo(y),S=M.useCallback(function(R){R===void 0&&(R=[]),!C.current&&c(L=>L===null?R:L.concat(R.filter(O=>!L.includes(O))))},[C]),v=M.useRef(null),x=No(R=>{if(y&&!n)return xy;if(!R||R===xy||m.current!==s||l!=null){const L=new Map;for(let O of s){if(!O)continue;if(l&&l.length>0&&!l.includes(O.id)&&O.rect.current){L.set(O.id,O.rect.current);continue}const j=O.node.current,F=j?new $f(f(j),j):null;O.rect.current=F,F&&L.set(O.id,F)}return L}return R},[s,l,n,y,f]);return M.useEffect(()=>{m.current=s},[s]),M.useEffect(()=>{y||S()},[n,y]),M.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),M.useEffect(()=>{y||typeof d!="number"||v.current!==null||(v.current=setTimeout(()=>{S(),v.current=null},d))},[d,y,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function w(){switch(p){case Po.Always:return!1;case Po.BeforeDragging:return n;default:return!n}}}function Ty(s,e){return No(n=>s?n||(typeof e=="function"?e(s):s):null,[e,s])}function p_(s,e){return Ty(s,e)}function g_(s){let{callback:e,disabled:n}=s;const r=xf(e),i=M.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return M.useEffect(()=>()=>i?.disconnect(),[i]),i}function Nc(s){let{callback:e,disabled:n}=s;const r=xf(e),i=M.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return M.useEffect(()=>()=>i?.disconnect(),[i]),i}function m_(s){return new $f(ys(s),s)}function ky(s,e,n){e===void 0&&(e=m_);const[r,i]=M.useState(null);function l(){i(f=>{if(!s)return null;if(s.isConnected===!1){var p;return(p=f??n)!=null?p:null}const m=e(s);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=g_({callback(f){if(s)for(const p of f){const{type:m,target:y}=p;if(m==="childList"&&y instanceof HTMLElement&&y.contains(s)){l();break}}}}),d=Nc({callback:l});return Fr(()=>{l(),s?(d?.observe(s),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[s]),r}function y_(s){const e=Ty(s);return py(s,e)}const Ry=[];function b_(s){const e=M.useRef(s),n=No(r=>s?r&&r!==Ry&&s&&e.current&&s.parentNode===e.current.parentNode?r:$c(s):Ry,[s]);return M.useEffect(()=>{e.current=s},[s]),n}function v_(s){const[e,n]=M.useState(null),r=M.useRef(s),i=M.useCallback(l=>{const c=Of(l.target);c&&n(d=>d?(d.set(c,Lf(c)),new Map(d)):null)},[]);return M.useEffect(()=>{const l=r.current;if(s!==l){c(l);const d=s.map(f=>{const p=Of(f);return p?(p.addEventListener("scroll",i,{passive:!0}),[p,Lf(p)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=s}return()=>{c(s),c(l)};function c(d){d.forEach(f=>{const p=Of(f);p?.removeEventListener("scroll",i)})}},[i,s]),M.useMemo(()=>s.length?e?Array.from(e.values()).reduce((l,c)=>ms(l,c),kr):wy(s):kr,[s,e])}function Dy(s,e){e===void 0&&(e=[]);const n=M.useRef(null);return M.useEffect(()=>{n.current=null},e),M.useEffect(()=>{const r=s!==kr;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?jo(s,n.current):kr}function S_(s){M.useEffect(()=>{if(!Dc)return;const e=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},s.map(e=>{let{sensor:n}=e;return n}))}function w_(s,e){return M.useMemo(()=>s.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=c=>{l(c,e)},n},{}),[s,e])}function Oy(s){return M.useMemo(()=>s?FE(s):null,[s])}const Ly=[];function C_(s,e){e===void 0&&(e=ys);const[n]=s,r=Oy(n?Mn(n):null),[i,l]=M.useState(Ly);function c(){l(()=>s.length?s.map(f=>vy(f)?r:new $f(e(f),f)):Ly)}const d=Nc({callback:c});return Fr(()=>{d?.disconnect(),c(),s.forEach(f=>d?.observe(f))},[s]),i}function E_(s){if(!s)return null;if(s.children.length>1)return s;const e=s.children[0];return $o(e)?e:s}function __(s){let{measure:e}=s;const[n,r]=M.useState(null),i=M.useCallback(p=>{for(const{target:m}of p)if($o(m)){r(y=>{const C=e(m);return y?{...y,width:C.width,height:C.height}:C});break}},[e]),l=Nc({callback:i}),c=M.useCallback(p=>{const m=E_(p);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Oc(c);return M.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const A_=[{sensor:jf,options:{}},{sensor:Nf,options:{}}],x_={current:{}},Ic={draggable:{measure:gy},droppable:{measure:gy,strategy:Po.WhileDragging,frequency:Uf.Optimized},dragOverlay:{measure:ys}};class Bo extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const T_={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Bo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Lc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Ic,measureDroppableContainers:Lc,windowRect:null,measuringScheduled:!1},k_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Lc,draggableNodes:new Map,over:null,measureDroppableContainers:Lc},jc=M.createContext(k_),$y=M.createContext(T_);function R_(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Bo}}}function D_(s,e){switch(e.type){case nn.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case nn.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:e.coordinates.x-s.draggable.initialCoordinates.x,y:e.coordinates.y-s.draggable.initialCoordinates.y}}};case nn.DragEnd:case nn.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case nn.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Bo(s.droppable.containers);return i.set(r,n),{...s,droppable:{...s.droppable,containers:i}}}case nn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=s.droppable.containers.get(n);if(!l||r!==l.key)return s;const c=new Bo(s.droppable.containers);return c.set(n,{...l,disabled:i}),{...s,droppable:{...s.droppable,containers:c}}}case nn.UnregisterDroppable:{const{id:n,key:r}=e,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Bo(s.droppable.containers);return l.delete(n),{...s,droppable:{...s.droppable,containers:l}}}default:return s}}function O_(s){let{disabled:e}=s;const{active:n,activatorEvent:r,draggableNodes:i}=M.useContext(jc),l=Tf(r),c=Tf(n?.id);return M.useEffect(()=>{if(!e&&!r&&l&&c!=null){if(!Rf(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:p}=d;if(!f.current&&!p.current)return;requestAnimationFrame(()=>{for(const m of[f.current,p.current]){if(!m)continue;const y=EE(m);if(y){y.focus();break}}})}},[r,e,i,c,l]),null}function L_(s,e){let{transform:n,...r}=e;return s!=null&&s.length?s.reduce((i,l)=>l({transform:i,...r}),n):n}function $_(s){return M.useMemo(()=>({draggable:{...Ic.draggable,...s?.draggable},droppable:{...Ic.droppable,...s?.droppable},dragOverlay:{...Ic.dragOverlay,...s?.dragOverlay}}),[s?.draggable,s?.droppable,s?.dragOverlay])}function M_(s){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=s;const l=M.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Fr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!r)return;const p=e?.node.current;if(!p||p.isConnected===!1)return;const m=n(p),y=py(m,r);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const C=my(p);C&&C.scrollBy({top:y.y,left:y.x})}},[e,c,d,r,n])}const My=M.createContext({...kr,scaleX:1,scaleY:1});var Ha;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Ha||(Ha={}));const N_=M.memo(function(e){var n,r,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:p,sensors:m=A_,collisionDetection:y=zE,measuring:C,modifiers:S,...v}=e;const x=M.useReducer(D_,void 0,R_),[w,R]=x,[L,O]=RE(),[j,F]=M.useState(Ha.Uninitialized),G=j===Ha.Initialized,{draggable:{active:P,nodes:K,translate:he},droppable:{containers:Ee}}=w,ke=P!=null?K.get(P):null,ze=M.useRef({initial:null,translated:null}),Be=M.useMemo(()=>{var ue;return P!=null?{id:P,data:(ue=ke?.data)!=null?ue:x_,rect:ze}:null},[P,ke]),je=M.useRef(null),[bt,X]=M.useState(null),[de,Ce]=M.useState(null),Z=Mo(v,Object.values(v)),ge=Io("DndDescribedBy",c),z=M.useMemo(()=>Ee.getEnabled(),[Ee]),T=$_(C),{droppableRects:pe,measureDroppableContainers:fe,measuringScheduled:me}=h_(z,{dragging:G,dependencies:[he.x,he.y],config:T.droppable}),ae=d_(K,P),Re=M.useMemo(()=>de?Df(de):null,[de]),Pe=ve(),Me=p_(ae,T.draggable.measure);M_({activeNode:P!=null?K.get(P):null,config:Pe.layoutShiftCompensation,initialRect:Me,measure:T.draggable.measure});const Ge=ky(ae,T.draggable.measure,Me),kt=ky(ae?ae.parentElement:null),vt=M.useRef({activatorEvent:null,active:null,activeNode:ae,collisionRect:null,collisions:null,droppableRects:pe,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),hn=Ee.getNodeFor((n=vt.current.over)==null?void 0:n.id),Dt=__({measure:T.dragOverlay.measure}),Xt=(r=Dt.nodeRef.current)!=null?r:ae,un=G?(i=Dt.rect)!=null?i:Ge:null,Ut=!!(Dt.nodeRef.current&&Dt.rect),$r=y_(Ut?null:Ge),En=Oy(Xt?Mn(Xt):null),dn=b_(G?hn??ae:null),pn=C_(dn),fr=L_(S,{transform:{x:he.x-$r.x,y:he.y-$r.y,scaleX:1,scaleY:1},activatorEvent:de,active:Be,activeNodeRect:Ge,containerNodeRect:kt,draggingNodeRect:un,over:vt.current.over,overlayNodeRect:Dt.rect,scrollableAncestors:dn,scrollableAncestorRects:pn,windowRect:En}),er=Re?ms(Re,he):null,Pt=v_(dn),St=Dy(Pt),da=Dy(Pt,[Ge]),In=ms(fr,St),kn=un?PE(un,fr):null,Rn=Be&&kn?y({active:Be,collisionRect:kn,droppableRects:pe,droppableContainers:z,pointerCoordinates:er}):null,jn=fy(Rn,"id"),[gn,fa]=M.useState(null),zn=Ut?fr:ms(fr,da),Vt=HE(zn,(l=gn?.rect)!=null?l:null,Ge),_n=M.useRef(null),an=M.useCallback((ue,we)=>{let{sensor:_e,options:qe}=we;if(je.current==null)return;const xe=K.get(je.current);if(!xe)return;const De=ue.nativeEvent,Ae=new _e({active:je.current,activeNode:xe,event:De,options:qe,context:vt,onAbort(Ne){if(!K.get(Ne))return;const{onDragAbort:Se}=Z.current,$e={id:Ne};Se?.($e),L({type:"onDragAbort",event:$e})},onPending(Ne,He,Se,$e){if(!K.get(Ne))return;const{onDragPending:Ot}=Z.current,Mt={id:Ne,constraint:He,initialCoordinates:Se,offset:$e};Ot?.(Mt),L({type:"onDragPending",event:Mt})},onStart(Ne){const He=je.current;if(He==null)return;const Se=K.get(He);if(!Se)return;const{onDragStart:$e}=Z.current,et={activatorEvent:De,active:{id:He,data:Se.data,rect:ze}};za.unstable_batchedUpdates(()=>{$e?.(et),F(Ha.Initializing),R({type:nn.DragStart,initialCoordinates:Ne,active:He}),L({type:"onDragStart",event:et}),X(_n.current),Ce(De)})},onMove(Ne){R({type:nn.DragMove,coordinates:Ne})},onEnd:tt(nn.DragEnd),onCancel:tt(nn.DragCancel)});_n.current=Ae;function tt(Ne){return async function(){const{active:Se,collisions:$e,over:et,scrollAdjustedTranslate:Ot}=vt.current;let Mt=null;if(Se&&Ot){const{cancelDrop:Hn}=Z.current;Mt={activatorEvent:De,active:Se,collisions:$e,delta:Ot,over:et},Ne===nn.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Mt))&&(Ne=nn.DragCancel)}je.current=null,za.unstable_batchedUpdates(()=>{R({type:Ne}),F(Ha.Uninitialized),fa(null),X(null),Ce(null),_n.current=null;const Hn=Ne===nn.DragEnd?"onDragEnd":"onDragCancel";if(Mt){const It=Z.current[Hn];It?.(Mt),L({type:Hn,event:Mt})}})}}},[K]),q=M.useCallback((ue,we)=>(_e,qe)=>{const xe=_e.nativeEvent,De=K.get(qe);if(je.current!==null||!De||xe.dndKit||xe.defaultPrevented)return;const Ae={active:De};ue(_e,we.options,Ae)===!0&&(xe.dndKit={capturedBy:we.sensor},je.current=qe,an(_e,we))},[K,an]),oe=f_(m,q);S_(m),Fr(()=>{Ge&&j===Ha.Initializing&&F(Ha.Initialized)},[Ge,j]),M.useEffect(()=>{const{onDragMove:ue}=Z.current,{active:we,activatorEvent:_e,collisions:qe,over:xe}=vt.current;if(!we||!_e)return;const De={active:we,activatorEvent:_e,collisions:qe,delta:{x:In.x,y:In.y},over:xe};za.unstable_batchedUpdates(()=>{ue?.(De),L({type:"onDragMove",event:De})})},[In.x,In.y]),M.useEffect(()=>{const{active:ue,activatorEvent:we,collisions:_e,droppableContainers:qe,scrollAdjustedTranslate:xe}=vt.current;if(!ue||je.current==null||!we||!xe)return;const{onDragOver:De}=Z.current,Ae=qe.get(jn),tt=Ae&&Ae.rect.current?{id:Ae.id,rect:Ae.rect.current,data:Ae.data,disabled:Ae.disabled}:null,Ne={active:ue,activatorEvent:we,collisions:_e,delta:{x:xe.x,y:xe.y},over:tt};za.unstable_batchedUpdates(()=>{fa(tt),De?.(Ne),L({type:"onDragOver",event:Ne})})},[jn]),Fr(()=>{vt.current={activatorEvent:de,active:Be,activeNode:ae,collisionRect:kn,collisions:Rn,droppableRects:pe,draggableNodes:K,draggingNode:Xt,draggingNodeRect:un,droppableContainers:Ee,over:gn,scrollableAncestors:dn,scrollAdjustedTranslate:In},ze.current={initial:un,translated:kn}},[Be,ae,Rn,kn,K,Xt,un,pe,Ee,gn,dn,In]),l_({...Pe,delta:he,draggingRect:kn,pointerCoordinates:er,scrollableAncestors:dn,scrollableAncestorRects:pn});const ce=M.useMemo(()=>({active:Be,activeNode:ae,activeNodeRect:Ge,activatorEvent:de,collisions:Rn,containerNodeRect:kt,dragOverlay:Dt,draggableNodes:K,droppableContainers:Ee,droppableRects:pe,over:gn,measureDroppableContainers:fe,scrollableAncestors:dn,scrollableAncestorRects:pn,measuringConfiguration:T,measuringScheduled:me,windowRect:En}),[Be,ae,Ge,de,Rn,kt,Dt,K,Ee,pe,gn,fe,dn,pn,T,me,En]),J=M.useMemo(()=>({activatorEvent:de,activators:oe,active:Be,activeNodeRect:Ge,ariaDescribedById:{draggable:ge},dispatch:R,draggableNodes:K,over:gn,measureDroppableContainers:fe}),[de,oe,Be,Ge,R,ge,K,gn,fe]);return We.createElement(oy.Provider,{value:O},We.createElement(jc.Provider,{value:J},We.createElement($y.Provider,{value:ce},We.createElement(My.Provider,{value:Vt},p)),We.createElement(O_,{disabled:d?.restoreFocus===!1})),We.createElement(LE,{...d,hiddenTextDescribedById:ge}));function ve(){const ue=bt?.autoScrollEnabled===!1,we=typeof f=="object"?f.enabled===!1:f===!1,_e=G&&!ue&&!we;return typeof f=="object"?{...f,enabled:_e}:{enabled:_e}}}),I_=M.createContext(null),Ny="button",j_="Draggable";function z_(s){let{id:e,data:n,disabled:r=!1,attributes:i}=s;const l=Io(j_),{activators:c,activatorEvent:d,active:f,activeNodeRect:p,ariaDescribedById:m,draggableNodes:y,over:C}=M.useContext(jc),{role:S=Ny,roleDescription:v="draggable",tabIndex:x=0}=i??{},w=f?.id===e,R=M.useContext(w?My:I_),[L,O]=Oc(),[j,F]=Oc(),G=w_(c,e),P=Mo(n);Fr(()=>(y.set(e,{id:e,key:l,node:L,activatorNode:j,data:P}),()=>{const he=y.get(e);he&&he.key===l&&y.delete(e)}),[y,e]);const K=M.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":w&&S===Ny?!0:void 0,"aria-roledescription":v,"aria-describedby":m.draggable}),[r,S,x,w,v,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:p,attributes:K,isDragging:w,listeners:r?void 0:G,node:L,over:C,setNodeRef:O,setActivatorNodeRef:F,transform:R}}function H_(){return M.useContext($y)}const U_="Droppable",P_={timeout:25};function B_(s){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=s;const l=Io(U_),{active:c,dispatch:d,over:f,measureDroppableContainers:p}=M.useContext(jc),m=M.useRef({disabled:n}),y=M.useRef(!1),C=M.useRef(null),S=M.useRef(null),{disabled:v,updateMeasurementsFor:x,timeout:w}={...P_,...i},R=Mo(x??r),L=M.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{p(Array.isArray(R.current)?R.current:[R.current]),S.current=null},w)},[w]),O=Nc({callback:L,disabled:v||!c}),j=M.useCallback((K,he)=>{O&&(he&&(O.unobserve(he),y.current=!1),K&&O.observe(K))},[O]),[F,G]=Oc(j),P=Mo(e);return M.useEffect(()=>{!O||!F.current||(O.disconnect(),y.current=!1,O.observe(F.current))},[F,O]),M.useEffect(()=>(d({type:nn.RegisterDroppable,element:{id:r,key:l,disabled:n,node:F,rect:C,data:P}}),()=>d({type:nn.UnregisterDroppable,key:l,id:r})),[r]),M.useEffect(()=>{n!==m.current.disabled&&(d({type:nn.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:c,rect:C,isOver:f?.id===r,node:F,over:f,setNodeRef:G}}function Pf(s,e,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function q_(s,e){return s.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(s.length))}function zc(s){return s!==null&&s>=0}function G_(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:c}=s;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=K_(n,c,i);if(c===i){const p=n[l];return p?{x:ii&&c<=l?{x:-d.width-f,y:0,...Hc}:c=l?{x:d.width+f,y:0,...Hc}:{x:0,y:0,...Hc}};function K_(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=s;const l=Pf(e,r,n),c=e[i],d=l[i];return!d||!c?null:{x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height}},Uc={scaleX:1,scaleY:1},W_=s=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:c}=s;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const p=l[c];return p?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...Uc}:i=c?{x:0,y:d.height+f,...Uc}:{x:0,y:0,...Uc}};function Y_(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return r?nr.map(G=>typeof G=="object"&&"id"in G?G.id:G),[r]),v=c!=null,x=c?S.indexOf(c.id):-1,w=p?S.indexOf(p.id):-1,R=M.useRef(S),L=!G_(S,R.current),O=w!==-1&&x===-1||L,j=F_(l);Fr(()=>{L&&v&&m(S)},[L,S,v,m]),M.useEffect(()=>{R.current=S},[S]);const F=M.useMemo(()=>({activeIndex:x,containerId:y,disabled:j,disableTransforms:O,items:S,overIndex:w,useDragOverlay:C,sortedRects:q_(S,f),strategy:i}),[x,y,j.draggable,j.droppable,O,S,w,f,C,i]);return We.createElement(jy.Provider,{value:F},e)}const J_=s=>{let{id:e,items:n,activeIndex:r,overIndex:i}=s;return Pf(n,r,i).indexOf(e)},Q_=s=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:p}=s;return!p||!r||d!==l&&i===c?!1:n?!0:c!==i&&e===f},Z_={duration:200,easing:"ease"},zy="transform",eA=zo.Transition.toString({property:zy,duration:0,easing:"linear"}),tA={roleDescription:"sortable"};function nA(s){let{disabled:e,index:n,node:r,rect:i}=s;const[l,c]=M.useState(null),d=M.useRef(n);return Fr(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const p=ys(r.current,{ignoreTransform:!0}),m={x:f.left-p.left,y:f.top-p.top,scaleX:f.width/p.width,scaleY:f.height/p.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),M.useEffect(()=>{l&&c(null)},[l]),l}function rA(s){let{animateLayoutChanges:e=Q_,attributes:n,disabled:r,data:i,getNewIndex:l=J_,id:c,strategy:d,resizeObserverConfig:f,transition:p=Z_}=s;const{items:m,containerId:y,activeIndex:C,disabled:S,disableTransforms:v,sortedRects:x,overIndex:w,useDragOverlay:R,strategy:L}=M.useContext(jy),O=aA(r,S),j=m.indexOf(c),F=M.useMemo(()=>({sortable:{containerId:y,index:j,items:m},...i}),[y,i,j,m]),G=M.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:P,node:K,isOver:he,setNodeRef:Ee}=B_({id:c,data:F,disabled:O.droppable,resizeObserverConfig:{updateMeasurementsFor:G,...f}}),{active:ke,activatorEvent:ze,activeNodeRect:Be,attributes:je,setNodeRef:bt,listeners:X,isDragging:de,over:Ce,setActivatorNodeRef:Z,transform:ge}=z_({id:c,data:F,attributes:{...tA,...n},disabled:O.draggable}),z=vE(Ee,bt),T=!!ke,pe=T&&!v&&zc(C)&&zc(w),fe=!R&&de,me=fe&&pe?ge:null,Re=pe?me??(d??L)({rects:x,activeNodeRect:Be,activeIndex:C,overIndex:w,index:j}):null,Pe=zc(C)&&zc(w)?l({id:c,items:m,activeIndex:C,overIndex:w}):j,Me=ke?.id,Ge=M.useRef({activeId:Me,items:m,newIndex:Pe,containerId:y}),kt=m!==Ge.current.items,vt=e({active:ke,containerId:y,isDragging:de,isSorting:T,id:c,index:j,items:m,newIndex:Ge.current.newIndex,previousItems:Ge.current.items,previousContainerId:Ge.current.containerId,transition:p,wasDragging:Ge.current.activeId!=null}),hn=nA({disabled:!vt,index:j,node:K,rect:P});return M.useEffect(()=>{T&&Ge.current.newIndex!==Pe&&(Ge.current.newIndex=Pe),y!==Ge.current.containerId&&(Ge.current.containerId=y),m!==Ge.current.items&&(Ge.current.items=m)},[T,Pe,y,m]),M.useEffect(()=>{if(Me===Ge.current.activeId)return;if(Me!=null&&Ge.current.activeId==null){Ge.current.activeId=Me;return}const Xt=setTimeout(()=>{Ge.current.activeId=Me},50);return()=>clearTimeout(Xt)},[Me]),{active:ke,activeIndex:C,attributes:je,data:F,rect:P,index:j,newIndex:Pe,items:m,isOver:he,isSorting:T,isDragging:de,listeners:X,node:K,overIndex:w,over:Ce,setNodeRef:z,setActivatorNodeRef:Z,setDroppableNodeRef:Ee,setDraggableNodeRef:bt,transform:hn??Re,transition:Dt()};function Dt(){if(hn||kt&&Ge.current.newIndex===j)return eA;if(!(fe&&!Rf(ze)||!p)&&(T||vt))return zo.Transition.toString({...p,property:zy})}}function aA(s,e){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s?.draggable)!=null?n:e.draggable,droppable:(r=s?.droppable)!=null?r:e.droppable}}function Pc(s){if(!s)return!1;const e=s.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const iA=[lt.Down,lt.Right,lt.Up,lt.Left],sA=(s,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(iA.includes(s.code)){if(s.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const C=i.get(y.id);if(C)switch(s.code){case lt.Down:r.topC.top&&f.push(y);break;case lt.Left:r.left>C.left&&f.push(y);break;case lt.Right:r.left1&&(m=p[1].id),m!=null){const y=l.get(n.id),C=l.get(m),S=C?i.get(C.id):null,v=C?.node.current;if(v&&S&&y&&C){const w=$c(v).some((G,P)=>d[P]!==G),R=Hy(y,C),L=oA(y,C),O=w||!R?{x:0,y:0}:{x:L?r.width-S.width:0,y:L?r.height-S.height:0},j={x:S.left,y:S.top};return O.x&&O.y?j:jo(j,O)}}}};function Hy(s,e){return!Pc(s)||!Pc(e)?!1:s.data.current.sortable.containerId===e.data.current.sortable.containerId}function oA(s,e){return!Pc(s)||!Pc(e)||!Hy(s,e)?!1:s.data.current.sortable.index{const d=M.useId(),f=M.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),p=$E(ly(jf,{activationConstraint:{distance:5}}),ly(Nf,{coordinateGetter:sA})),m=M.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=M.useCallback(S=>{const{active:v,over:x}=S,w=Date.now();if(!x||v.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:R,lastActiveId:L,inProgress:O}=f.current;if(L===v.id&&w-R<500&&!O)return;f.current={inProgress:!1,lastSortTime:w,lastActiveId:v.id};const j=s.findIndex(G=>String(G[e])===String(v.id)),F=s.findIndex(G=>String(G[e])===String(x.id));if(j!==-1&&F!==-1&&j!==F){const G=Pf(s,j,F);i?.(G,{oldIndex:j,newIndex:F})}},[s,e,i]),C=s.map(S=>String(S[e]));return ft.jsx(N_,{id:d,sensors:p,collisionDetection:NE,onDragStart:m,onDragEnd:y,children:ft.jsx(X_,{items:C,strategy:lA[n],children:r})},c!==void 0?`${d}-v${c}`:d)},Uy=M.createContext(null),uA=({value:s,children:e})=>ft.jsx(Uy.Provider,{value:s,children:e}),dA=()=>M.useContext(Uy),fA=({id:s,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:p}=rA({id:s}),m={transform:zo.Transform.toString(d),transition:f,opacity:p?.5:1,position:"relative"};return ft.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(s),"data-dragging":p,children:ft.jsx(uA,{value:{listeners:l,handle:e,isDragging:p},children:r})})},at=dt("DynamicRenderer");function la(){try{return window.G7Core?.devTools}catch{return}}function qf(s,e,n,r){if(typeof s=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(s))try{return e.resolveTranslations(s,n,r)}catch{return s}return s}if(Array.isArray(s))return s.map(i=>qf(i,e,n,r));if(s&&typeof s=="object"){const i={};for(const[l,c]of Object.entries(s))i[l]=qf(c,e,n,r);return i}return s}function hA(s){const e=Object.keys(s);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const dr=(s,e)=>{const n=["errors"],r={...s};for(const i of Object.keys(e)){const l=e[i],c=s[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&hA(l)){const d=Object.keys(l).map(p=>parseInt(p,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)r[i]={...l};else{const p=[...c];for(const[m,y]of Object.entries(l)){const C=parseInt(m,10);C>=0&&C=p.length&&(p[C]=y)}r[i]=p}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?r[i]=dr(c,l):r[i]=l}return r},pA=(s,e,n,r)=>{if(!e||typeof e!="object"||Array.isArray(e))return s;const i=dr(s,e);return ty(i,n,r)},Bc=(s,e)=>{let n=null;const r=()=>(n===null&&(n={...s}),n);for(const i of Object.keys(e)){if(!(i in s))continue;const l=e[i],c=s[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Bc(c,l);if(d===c)continue;Object.keys(d).length===0?delete r()[i]:r()[i]=d}else delete r()[i]}return n??s},gA=s=>{const e={},n=s.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),c=r.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,p)=>p.toUpperCase());e[d]=c}}return e};class mA extends M.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){at.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:ft.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[ft.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),ft.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&ft.jsxs("details",{className:"mt-2",children:[ft.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),ft.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Vr=M.memo(({componentDef:s,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:p,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:C=!1,onComponentSelect:S,onComponentHover:v,onDragStart:x,onDragEnd:w,componentPath:R,layoutKey:L})=>{const[O,j]=M.useState({loadingActions:{}});M.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const F=M.useRef(null);M.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,_merge:oe,...ce}=e._localInit,J=`${JSON.stringify(ce)}:${q||"no-force"}`;if(F.current!==J){F.current=J;const ve=oe||"shallow",we=window.G7Core?.state?.get?.()?._local||{},_e=window.__g7PendingLocalState||{},qe={...we,..._e};ve==="replace"?window.__g7PendingLocalState={loadingActions:qe.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=dr(qe,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...qe,...ce,hasChanges:!1};const xe=window.__g7SetLocalOverrideKeys;xe&&typeof xe=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=dr(xe,{...ce,hasChanges:!1}))}}}),M.useLayoutEffect(()=>{if(!d){const q=window.__g7SetLocalOverrideKeys;if(q){j(ve=>Bc(ve,q));const oe=q,ce=window.__g7ForcedLocalFields,J=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===oe&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===J&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const G=M.useRef(L);M.useEffect(()=>{s._fromBase&&L&&G.current!==L&&(G.current=L,j({loadingActions:{}}))},[L,s._fromBase]);const P=M.useRef(""),K=M.useRef(!1),he=M.useRef(null),Ee=M.useRef(null),ke=M.useRef({}),ze=M.useRef({}),Be=M.useRef(p),je=bE(),bt=YC(),X=bt?.getParentDataContext()??p;M.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,...oe}=e._localInit,ce=JSON.stringify(oe),J=q!==void 0,ve=wf(),ue=`${ce}:${q||"no-force"}`,we=rE({globalTrackedKey:ve.hash,instanceHandledKey:Ee.current,trackingKey:ue});if(we==="apply"){Ee.current=ue,ve.hash=ue,ve.timestamp=q,P.current=ce,J&&(K.current=!0);const{_merge:qe,...xe}=oe,De=qe||"shallow";j(Ae=>De==="replace"?{loadingActions:Ae.loadingActions||{},...xe,hasChanges:!1}:De==="deep"?dr(Ae,{...xe,hasChanges:!1}):{...Ae,...xe,hasChanges:!1}),e._globalSetState&&e._globalSetState(Ae=>{const tt=Ae?._local||{};let Ne;return De==="replace"?Ne={...xe,hasChanges:!1}:De==="deep"?Ne=dr(tt,{...xe,hasChanges:!1}):Ne={...tt,...xe,hasChanges:!1},{...Ae,_local:Ne}}),i.invalidateCacheByKeys(["_local"]),at.log("_localInit applied (data changed):",Object.keys(oe))}else if(we==="prune"){Ee.current=ue;const{_merge:qe,...xe}=oe;j(Ae=>Bc(Ae,xe)),Bc(O,xe)!==O&&(i.invalidateCacheByKeys(["_local"]),at.log("_localInit pruned (applied by another renderer):",Object.keys(xe)))}he.current=e._localInit,tE(e._localInit)}},[e._localInit,p,i]);const{isTransitioning:de}=Jm(),Ce=uE(),Z=f??Ce,{width:ge}=Ef(),z=dA(),T=M.useMemo(()=>{let q=s;if(s.type==="iterator"&&s.data){const{data:J,itemName:ve,indexName:ue,...we}=s;q={...we,iteration:{source:J,item_var:ve||"item",index_var:ue}}}if(!q.responsive)return q;const oe=_i.getMatchingKey(q.responsive,ge);if(!oe)return q;const ce=q.responsive[oe];return{...q,props:{...q.props,...ce.props},children:ce.children??q.children,text:ce.text??q.text,if:ce.if??q.if,iteration:ce.iteration??q.iteration,__responsiveChildrenKey:ce.children!==void 0?oe:void 0}},[s,ge]),pe=M.useCallback(q=>{const oe=q?.__setStateId;if(j(ce=>{const J=window.__g7PendingLocalState,ue=window.__g7SetLocalOverrideKeys||J,we=ue?dr(ce,ue):ce;if(typeof q=="function"){const Ae=q(we);return dr(we,Ae)}const{__mergeMode:_e,__setStateId:qe,...xe}=q;let De;if(_e==="replace"?De=xe:_e==="shallow"?De={...we,...xe}:De=dr(we,xe),_e!==void 0){const Ae=window.__g7ForcedLocalFields;Ae&&(window.__g7ForcedLocalFields={...Ae,...xe})}return De}),oe){const ce=la();if(ce?.isEnabled()){const J=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(J,ve,0,["_local"],[]),ce.completeStateChange?.(oe)},0)}}},[T.id,T.name]),fe=d?.state??O,me=d?.setState??pe,ae=M.useMemo(()=>{const q=e._localInit&&e._localInit!==he.current;let oe;q&&e._local?oe=e._local:oe=e._local?dr(e._local,fe):fe;const ce=window.__g7ForcedLocalFields;ce&&(oe=dr(oe,ce));const J={...e,_local:oe},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const ue=new Tn,we={...J,...je?{_isolated:je.state}:{}},_e={},qe=la(),xe=qe?.isEnabled()??!1;for(const[De,Ae]of Object.entries(ve)){const tt=xe?Date.now():0,Ne=xe?e._computed?.[De]:void 0;let He;try{if(typeof Ae=="string")if(Ae.startsWith("{{")&&Ae.endsWith("}}")){const Se=Ae.slice(2,-2).trim(),$e=On(Se)?ue.evaluatePipeExpression(Se,we,{skipCache:!0}):ue.evaluateExpression(Se,we,{skipCache:!0});_e[De]=$e}else _e[De]=Ae;else if(Ae&&typeof Ae=="object"&&"$switch"in Ae){const Se=ue.resolveSwitch(Ae,we,{skipCache:!0});_e[De]=Se}}catch(Se){at.warn(`Failed to recalculate computed value: ${De}`,Se),_e[De]=e._computed?.[De],He=Se instanceof Error?Se.message:String(Se)}if(xe&&(He||Ne!==_e[De])){const $e=Date.now()-tt;qe.trackComputedProperty?.(De,typeof Ae=="string"?Ae:JSON.stringify(Ae),[{type:"_local",path:"_local",value:J._local}],_e[De],$e,T.id,He),Ne!==_e[De]&&qe.trackComputedRecalc?.(De,"dependency-change",Ne,_e[De],$e,{type:"_local",path:"_local"},T.id)}}J._computed=_e}if(je&&(J._isolated=je.state),X&&(J.$parent=X),s.extensionPointProps){const ue=i.resolveObject(s.extensionPointProps,J,y?{skipCache:!0}:void 0);J.extensionPointProps=C&&l?qf(ue,l,n,J):ue}return s.extensionPointCallbacks&&(J.extensionPointCallbacks=s.extensionPointCallbacks),C&&(J.$templateId===void 0&&n?.templateId&&(J.$templateId=n.templateId),J.$locale===void 0&&n?.locale&&(J.$locale=n.locale)),J},[e,fe,je?.state,X,bt?.version,s.extensionPointProps,s.extensionPointCallbacks]);ke.current=ae._local,ze.current=ae._computed||{},Be.current=X,M.useEffect(()=>{const q=la();if(!q?.isEnabled())return;const oe=ae._local;oe&&q.updateLocalState(oe);const ce=ae._computed;ce&&q.updateComputedState(ce),X&&q.updateParentContext?.(X);const J=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",ue={global:Object.keys(e._global||{}),local:Object.keys(oe||{}),context:d?Object.keys(d.state||{}):[]},we={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};q.trackComponentStateSource?.(J,ve,ue,we),fe&&Object.keys(fe).length>0&&q.trackDynamicState?.(J,fe);const _e=!!(T.expandChildren||T.props?.expandChildren);q.trackContextFlow?.(J,ve,!!d,_e,!0)},[ae._local,e,T.id,T.name,d,fe,T.expandChildren,T.props?.expandChildren,X]);const Re=M.useMemo(()=>({state:{...ae._local},setState:me,stateRef:ke,computedRef:ze,isolatedContext:je,parentDataContext:ae}),[ae._local,me,O,je,ae]),Pe=M.useMemo(()=>{const q=os({if:T.if,condition:T.condition,conditions:T.conditions},ae,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=la();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,q)}return q},[T.if,T.conditions,ae,i,T.id]),Me=M.useMemo(()=>{if(!T.slot)return null;const q=T.slot;if(q.startsWith("{{")&&q.endsWith("}}")){const oe=q.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},J=On(oe)?i.evaluatePipeExpression(oe,ae,void 0,ce):i.evaluateExpression(oe,ae,ce);return at.log(`[Slot] 표현식 평가: "${oe}" => "${J}" (컴포넌트: ${T.id})`),typeof J=="string"?J:null}catch(ce){return at.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return at.log(`[Slot] 정적 슬롯 ID: "${q}" (컴포넌트: ${T.id})`),q},[T.slot,T.id,ae,i]),Ge=M.useMemo(()=>!Me||!T.id?"":`${T.id}-${Me}-${JSON.stringify(T.slotOrder??0)}`,[Me,T.id,T.slotOrder]),kt=M.useRef(null);M.useEffect(()=>{const q=window.__slotContextValue,oe=q?.isEnabled??!1;if(T.slot&&at.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${oe}, shouldRender: ${Pe}, resolvedSlotId: ${Me}`),!oe||!Pe){T.slot&&at.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${oe}, shouldRender: ${Pe}`),kt.current&&T.id&&q&&(q.unregisterFromSlot(kt.current,T.id),kt.current=null);return}if(!Me||!T.id){T.slot&&at.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Me}, id: ${T.id}`),kt.current&&T.id&&q&&(q.unregisterFromSlot(kt.current,T.id),kt.current=null);return}kt.current&&kt.current!==Me&&q.unregisterFromSlot(kt.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return q.registerToSlot(Me,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>Re,translationContext:n,registrationKey:Ge}),kt.current=Me,()=>{const J=window.__slotContextValue;Me&&T.id&&J&&J.unregisterFromSlot(Me,T.id)}},[Pe,Me,T,e,f,Re,n,Ge]);const vt=M.useCallback(q=>{if(typeof q=="string"){if(oc(q))return Bd(q);if(lc(q)){const oe=[],ce=q.replace(new RegExp(`${yo}([^${Ci}]*)${Ci}`,"g"),(ve,ue)=>(oe.push(ue),`${Na}${oe.length-1}${Na}`));let J=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(J=l.resolveTranslations(ce,n,ae)),J.replace(new RegExp(`${Na}(\\d+)${Na}`,"g"),(ve,ue)=>oe[parseInt(ue)])}if(q.startsWith("$t:defer:"))return q;if(/\$t:[a-zA-Z0-9._-]+/.test(q)){const oe=q.trim();return oe.startsWith("{")&&oe.endsWith("}")||oe.startsWith("[")&&oe.endsWith("]")?q:l.resolveTranslations(q,n,ae)}return q}if(Array.isArray(q))return q.map(oe=>vt(oe));if(q&&typeof q=="object"){const oe={};for(const[ce,J]of Object.entries(q))oe[ce]=vt(J);return oe}return q},[l,n,ae]),hn=M.useCallback(q=>mo(q),[]),Dt=M.useCallback(q=>Ma(q),[]),Xt=M.useMemo(()=>{let q={...T.props||{}};const oe=["cellChildren","expandChildren","expandContext","render"],J=r.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...oe,...J])],ue=y?{skipCache:!0}:void 0,we={...ue??{},skipBindingKeys:ve},_e=Se=>{if(ue)return ue;if(Se.startsWith("_computed")||Se.startsWith("$computed"))return{skipCache:!0}};for(const[Se,$e]of Object.entries(q))if(!ve.includes(Se))if(typeof $e=="string"){const et=Dt($e);if(et!==null){let Ot=!1,Mt=et;et.startsWith(lr)&&(Ot=!0,Mt=et.slice(lr.length));const Hn={componentId:T.id,componentName:T.name,propName:Se};let It;if(On(Mt))try{It=i.evaluatePipeExpression(Mt,ae,_e(Mt),Hn)}catch(jt){at.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,jt),It=void 0}else if(hn(Mt))try{It=i.evaluateExpression(Mt,ae,Hn)}catch(jt){at.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,jt),It=void 0}else It=i.resolve(Mt,ae,_e(Mt),Hn);q[Se]=Ot&&It!=null?ss(It):It}else{const Ot={componentId:T.id,componentName:T.name,propName:Se};q[Se]=i.resolveBindings($e,ae,ue,Ot)}}else Array.isArray($e)?q[Se]=$e.map(et=>typeof et=="string"?i.resolveBindings(et,ae,ue):typeof et=="object"&&et!==null?i.resolveObject(et,ae,we):et):$e&&typeof $e=="object"&&(q[Se]=i.resolveObject($e,ae,we));for(const[Se,$e]of Object.entries(q))q[Se]=vt($e);if(typeof q.style=="string"&&(q.style=gA(q.style)),q=ef(q,C?void 0:T.actions,ae,{componentContext:Re,actionDispatcher:c}),T.classMap){const Se=S0(T.classMap,ae,i,{skipCache:!0});if(Se){const $e=q.className||"";q.className=$e?`${$e} ${Se}`:Se}}T.style&&(q.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(q,fe),T.component_layout&&(q.__componentLayoutDefs=T.component_layout);const qe=T.expandChildren||T.props?.expandChildren,xe=T.props?.cellChildren,De=T.children&&T.children.length>0,Ae=T.component_layout,tt=T.slot,Ne=T.props?.modalId,He=T.type==="composite";return(qe||xe||De||Ae||tt||Ne||He)&&(q.__componentContext=Re),q},[T.props,T.actions,T.style,T.classMap,T.id,ae,n,i,l,Re,fe,vt,hn,Dt,y]),un=M.useRef(null),Ut=M.useMemo(()=>un.current&&Zm(un.current,Xt)?un.current:(un.current=Xt,Xt),[Xt]),$r=M.useMemo(()=>{const q=T.id;if(typeof q!="string"||!q.includes("{{"))return q;const oe=i.resolveBindings(q,ae,{skipCache:!0});return typeof oe=="string"?oe:q},[T.id,ae,i]),En=M.useMemo(()=>{const q=T.dataKey,oe=T.trackChanges,ce=T.debounce;if(q){const J=q.startsWith("_global."),ve=J?q.slice(8):q,ue=J?e._global:ae._local;return{dataKey:ve,trackChanges:oe??!1,debounce:ce,setState:J?_e=>{e._globalSetState?e._globalSetState(_e):at.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:me,state:ue??{},_isGlobal:J}}if(Z.dataKey)return Z},[T.dataKey,T.trackChanges,T.debounce,T.id,me,ae._local,e._global,e._globalSetState,Z]),dn=M.useRef(new Set);M.useEffect(()=>{dn.current.clear()},[e._global?._remountKeys]);const pn=M.useCallback((q,oe)=>{const ce=e._global?._remountKeys;return q&&ce?.[q]&&!dn.current.has(q)?(dn.current.add(q),`${q}-remount-${ce[q]}`):q||oe},[e._global?._remountKeys]),fr=M.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const q=T.text;let oe=q;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},J=Dt(q);if(J!==null){let ve=!1,ue=J;if(J.startsWith(lr)&&(ve=!0,ue=J.slice(lr.length)),On(ue))try{oe=i.evaluatePipeExpression(ue,ae,{skipCache:!0},ce)}catch(we){at.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else if(hn(ue))try{oe=i.evaluateExpression(ue,ae,ce)}catch(we){at.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else oe=i.resolve(ue,ae,{skipCache:!0},ce);ve&&oe!=null&&(oe=ss(oe))}else q.includes("{{")&&(oe=i.resolveBindings(q,ae,{skipCache:!0},ce));return oe=vt(oe),oe??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((q,oe)=>{if(typeof q=="string")return q;const ce=T.__responsiveChildrenKey,J=ce?`responsive.${ce}.children`:"children",ve=R?`${R}.${J}.${oe}`:`${oe}`,ue=q._fromBase?q.id||`child-${oe}`:pn(q.id,`child-${oe}`),we=!q._fromBase&&L?`${ue}_${L}`:ue;return ft.jsx(Vr,{componentDef:q,dataContext:ae,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:En,isInsideIteration:y,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:ve,onDragStart:x,onDragEnd:w,layoutKey:L},we)})},[T.text,T.children,T.id,e,ae,n,r,i,l,c,Re,En,Dt,hn,vt,pn,y,C,S,v,R,x,w,L]),er=M.useMemo(()=>{if(!T.iteration)return null;try{const q=Zd(T.iteration.source,ae,i);if(!Array.isArray(q))return at.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,q),null;const oe=la();return oe?.isEnabled()&&oe.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,q.length),q.map((ce,J)=>{const ve={...ae,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:J};T.iteration.index_var&&(ve[T.iteration.index_var]=J);const ue=J===0||J===q.length-1;oe?.isEnabled()&&ue&&oe.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${J}`,componentType:"iteration",parentContext:{available:Object.keys(ae),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ce,...T.iteration.index_var?{[T.iteration.index_var]:J}:{}}},depth:1});const we={...T,iteration:void 0,responsive:void 0},_e=R?`${R}.iteration.${J}`:`iteration.${J}`,qe=`${pn(T.id,"item")}-${J}`;return ft.jsx(Vr,{componentDef:we,dataContext:ve,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:En,isInsideIteration:!0,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:_e,onDragStart:x,onDragEnd:w,layoutKey:L},qe)})}catch(q){return at.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,q),null}},[T.iteration,T.children,T.id,e,ae,n,r,i,l,c,Re,En,pn,C,S,v,R,x,w,L]),[Pt,St]=M.useState(0),da=M.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:q,itemTemplate:oe}=T;try{const ce=Zd(q.source,ae,i);if(!Array.isArray(ce))return at.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const J=q.itemKey||"id",ve=q.strategy||"verticalList",ue=q.itemVar||"$item",we=q.indexVar||"$index",_e=q.handle,qe=q.wrapperElement,xe=(tt,Ne)=>{const He=T.actions?.filter(Se=>Se.event==="onSortEnd"||Se.type==="onSortEnd");if(St(Se=>Se+1),He&&He.length>0&&c){const Se={...ae,$sortedItems:tt,$sortEvent:Ne};He.forEach($e=>{try{const et=c.createHandler($e,Se,Re),Ot=new Event("sortend");et(Ot)}catch(et){at.error(`onSortEnd action failed: ${$e.handler}`,et)}})}},De=tt=>{const Ne=T.actions?.filter(He=>He.event==="onSortStart"||He.type==="onSortStart");if(Ne&&Ne.length>0&&c){const He={...ae,$activeId:tt.activeId};Ne.forEach(Se=>{try{const $e=c.createHandler(Se,He,Re),et=new Event("sortstart");$e(et)}catch($e){at.error(`onSortStart action failed: ${Se.handler}`,$e)}})}},Ae=ce.map((tt,Ne)=>{const He=String(tt[J]),Se={...ae,[ue]:tt,[we]:Ne},$e=R?`${R}.sortable.${Ne}`:`sortable.${Ne}`,et=`${pn(T.id,"sortable-item")}-v${Pt}-${He}`;return ft.jsx(fA,{id:He,handle:_e,...qe?{as:qe}:{},children:(qe&&oe.children?oe.children:[oe]).map((Ot,Mt)=>ft.jsx(Vr,{componentDef:Ot,dataContext:Se,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:$e,onDragStart:x,onDragEnd:w,layoutKey:L},`${et}-child-${Mt}`))},et)});return ft.jsx(cA,{items:ce,itemKey:J,strategy:ve,onSortEnd:xe,onSortStart:De,sortVersion:Pt,children:Ae})}catch(ce){return at.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,ae,n,r,i,l,c,Re,pn,C,S,v,R,x,w,Pt,L]),In=M.useRef(!1);M.useEffect(()=>{if(In.current)return;In.current=!0;const q=la();if(q?.isEnabled()&&q.trackMount(s.id,{name:s.name,type:s.type||"component",props:Ut}),s.lifecycle?.onMount&&s.lifecycle.onMount.length>0)for(const ce of s.lifecycle.onMount)try{const J=c.createHandler(ce,ae,Re),ve=new Event("mount");J(ve),at.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${s.id})`)}catch(J){at.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${s.id})`,J)}const oe=[];if(s.onComponentEvent&&s.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const J of s.onComponentEvent){if(!J.event){at.warn(`onComponentEvent: event name is required (Component: ${s.id})`);continue}const ve=async we=>{try{const _e={...ae,_eventData:we},xe=await c.createHandler({handler:J.handler,params:J.params,onSuccess:J.onSuccess,onError:J.onError},_e,Re)(new CustomEvent(J.event,{detail:we}));return at.log(`onComponentEvent "${J.event}" handled: ${J.handler} (Component: ${s.id})`,{eventData:we,result:xe}),xe}catch(_e){throw at.error(`onComponentEvent "${J.event}" failed: ${J.handler} (Component: ${s.id})`,_e),_e}},ue=ce.componentEvent.on(J.event,ve);oe.push(ue),at.log(`onComponentEvent: Subscribed to "${J.event}" (Component: ${s.id})`)}else at.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${s.id})`)}return()=>{const ce=la();ce?.isEnabled()&&ce.trackUnmount(s.id);for(const J of oe)try{J()}catch(ve){at.error(`onComponentEvent: Failed to unsubscribe (Component: ${s.id})`,ve)}if(oe.length>0&&at.log(`onComponentEvent: Unsubscribed ${oe.length} event(s) (Component: ${s.id})`),s.lifecycle?.onUnmount&&s.lifecycle.onUnmount.length>0)for(const J of s.lifecycle.onUnmount)try{const ve=c.createHandler(J,ae,Re),ue=new Event("unmount");ve(ue),at.log(`Lifecycle onUnmount executed: ${J.handler} (Component: ${s.id})`)}catch(ve){at.error(`Lifecycle onUnmount failed: ${J.handler} (Component: ${s.id})`,ve)}}},[]);const kn=M.useMemo(()=>{const q=Ut.dataKey,oe=Ut.trackChanges,ce=Ut.debounce;return q?{dataKey:q,trackChanges:oe??!1,debounce:ce,setState:me,state:fe}:null},[Ut.dataKey,Ut.trackChanges,Ut.debounce,me,fe]);M.useEffect(()=>{const q=T.dataKey||Ut.dataKey;if(!q)return;const oe=la();if(!oe?.isEnabled())return;const ce=[],J=ue=>{if(ue)for(const we of ue){const _e=we?.props?.name;if(_e&&ce.push({name:_e,type:we.name||we.type||"unknown"}),we?.children&&J(we.children),we?.slots)for(const qe of Object.values(we.slots))Array.isArray(qe)&&J(qe)}};if(s.children&&J(s.children),s.slots)for(const ue of Object.values(s.slots))Array.isArray(ue)&&J(ue);const ve=s.id||`form-${q}`;return oe.trackForm(ve,q,ce),()=>{oe.untrackForm(ve)}},[T,Ut.dataKey,s.id,s.children]);const Rn=M.useRef(null),jn=M.useRef(void 0);M.useEffect(()=>{const q=Ut?.name;if(!q||!Z.dataKey||!Z.setState||Ut?.autoBinding===!1)return;const oe=`${Z.dataKey}.${q}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(oe,(ce.get(oe)??0)+1),()=>{const J=ce.get(oe)??0;J<=1?ce.delete(oe):ce.set(oe,J-1)}},[Ut?.name,Ut?.autoBinding,Z.dataKey,Z.setState]);const gn=M.useMemo(()=>{const{dataKey:q,trackChanges:oe,debounce:ce,...J}=Ut,ve=J.name;if(!ve||!Z.dataKey||!Z.setState)return J;if(J.autoBinding===!1){const{autoBinding:He,...Se}=J;return Se}const ue=`${Z.dataKey}.${ve}`,we=dE(Z.state,ue),_e=we!==void 0?we:J.value,xe=r.getMetadata(s.name)?.bindingType,De=typeof _e=="boolean"&&(xe==="checked"||xe==="checkable"&&["checkbox","radio"].includes(J?.type)),Ae=Z.debounce,tt=He=>{const Se=Z.state||{},$e=ty(Se,ue,He);if(Z.trackChanges&&($e.hasChanges=!0),window.__g7PendingLocalState=pA($e,window.__g7ForcedLocalFields,ue,He),Z.setState($e),Z._isGlobal)return;const et=window.G7Core,Ot={[ue]:He};Z.trackChanges&&(Ot.hasChanges=!0),et?.state?.setLocal?.(Ot,{render:!1})},Ne=(He,Se)=>{Ae&&Ae>0?(Rn.current&&clearTimeout(Rn.current),Rn.current=setTimeout(()=>{tt(He),Rn.current=null,Se&&(Se(),window.__g7PendingLocalState=null)},Ae)):(tt(He),Se&&(Se(),window.__g7PendingLocalState=null))};if(De)return{...J,checked:_e,onChange:Se=>{const $e=Se.target.checked;tt($e),J.onChange&&J.onChange(Se)}};{const He=$e=>{const et=$e?.target?.value!==void 0?$e.target.value:$e;Ae&&Ae>0&&(jn.current=et);const Ot=$e?.target?{target:{value:et,name:$e.target.name,type:$e.target.type,checked:$e.target.checked},currentTarget:$e.currentTarget?{value:et,name:$e.currentTarget.name}:void 0}:$e;Ne(et,()=>{J.onChange&&J.onChange(Ot)})};let Se;return jn.current!==void 0?Rn.current!==null?Se=jn.current:String(_e??"")===String(jn.current)?(jn.current=void 0,Se=_e??""):Se=jn.current:Se=_e??"",{...J,value:Se,onChange:He}}},[Ut,Z,Z.state,Z.debounce]),fa=M.useMemo(()=>{const q=la();if(q?.isEnabled()&&q.trackRender(s.name),!Pe)return T.iteration?er:null;if(T.sortable&&T.itemTemplate)return da;if(T.iteration)return er;if(T.type==="extension_point"){const{layout:xe,columns:De,gap:Ae,className:tt,...Ne}=T.props||{};let He=tt||"";return xe==="grid"&&De?He=`${He} grid grid-cols-${De} gap-${Ae||4}`.trim():xe==="flex"&&(He=`${He} flex flex-col gap-${Ae||4}`.trim()),ft.jsx("div",{id:$r,className:He||void 0,...Ne,children:fr})}const oe=r.getComponent(T.name);if(!oe)return at.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,J={...gn,id:gn.id??$r,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(z?.listeners&&z.handle&&gn["data-drag-handle"]!==void 0&&(Object.assign(J,z.listeners),J.style={...J.style,cursor:z.isDragging?"grabbing":"grab"}),C){const xe=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,De=Ne=>{typeof Ne.preventDefault=="function"&&Ne.preventDefault(),S&&(Ne.stopPropagation(),S(xe,Ne))},Ae={"data-editor-id":xe,"data-editor-name":T.name,"data-editor-type":T.type,onClick:De};R&&(Ae["data-editor-path"]=R);const tt=T.__editorSlotName??T.slot;typeof tt=="string"&&(Ae["data-editor-slot"]=tt),v&&(Ae.onMouseMove=Ne=>{Ne.stopPropagation(),v(xe,Ne)},Ae.onMouseLeave=Ne=>{v(null,Ne)}),Object.assign(J,Ae),J.editorAttrs=Ae}const ve=T.type==="basic",ue=T.type==="layout",_e=ve||ue?(()=>{const xe={};for(const[De,Ae]of Object.entries(J))De.startsWith("__")||De==="editorAttrs"&&ve||(xe[De]=Ae);return xe})():J;let qe=ft.jsx(oe,{..._e,children:fr});if(En&&(qe=ft.jsx(cE,{value:En,children:qe})),T.isolatedState){const xe=typeof T.isolatedState=="object"?T.isolatedState:{},De=e?._isolatedInit,Ae=De?{...xe,...De}:xe;qe=ft.jsx(yE,{initialState:Ae,scopeId:T.isolatedScopeId,children:qe})}return qe},[Pe,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,r,gn,fr,er,da,z,kn,C,S,v,x,w,R,e._global?._remountKeys]),zn=M.useMemo(()=>{const q=T.blur_until_loaded;if(!q||e?._global?.__isPreview)return!1;if(typeof q=="string"){const J=Dt(q);if(J!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(J,ae,ve)}catch(ve){return at.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${T.id}):`,ve),!1}return!1}if(typeof q=="object"&&q!==null){if(!q.enabled)return!1;if(q.data_sources)return(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).some(we=>e[we]===void 0);if(de)return!0;const J=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ue=>!J.includes(ue)&&!ue.startsWith("_")).some(ue=>e[ue]===void 0)}if(de)return!0;const oe=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(J=>!oe.includes(J)&&!J.startsWith("_")).some(J=>e[J]===void 0)},[T.blur_until_loaded,T.id,de,e,ae,i,Dt]);if(zn){const q=T.blur_until_loaded;if(typeof q=="object"&&q?.data_sources){const ce=(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).reduce((ve,ue)=>(ve[ue]=e[ue]===void 0?"UNDEFINED":"LOADED",ve),{}),J=Object.keys(e).filter(ve=>!ve.startsWith("_"));at.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",J)}else at.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,q)}const Vt=M.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const q=Xt?.className||"";if(!q)return{wrapperClasses:"",innerClasses:""};const oe=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],ce=q.split(/\s+/).filter(Boolean),J=[],ve=[];for(const ue of ce)oe.some(_e=>_e.test(ue))?J.push(ue):ve.push(ue);return{wrapperClasses:J.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Xt?.className]),_n=window.__slotContextValue;return Me&&_n?.isEnabled?null:ft.jsx(mA,{componentId:s.id,componentName:s.name,children:T.blur_until_loaded?ft.jsx("div",{className:[Vt.wrapperClasses,zn?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:fa}):fa})});Vr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Vr);function yA(s){const e={};try{const r=new URL(s,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const c=r.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function bA(s){try{return new URL(s,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return s.split("?")[0]}}const $i=class $i{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return $i.instance||($i.instance=new $i),$i.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const n={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=r?`${r}.${c}`:c,f=e?.[c],p=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=p&&typeof p=="object"&&!Array.isArray(p);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,p,d));else{const C=f===void 0?"__undefined__":JSON.stringify(f),S=p===void 0?"__undefined__":JSON.stringify(p);C!==S&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=r?`${r}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=r?`${r}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:r}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const n={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(n),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let n=0,r=0,i=0,l=0;const c={},d={};for(const p of e)p.decision==="cache_hit"?n++:p.decision==="cache_miss"?r++:p.decision==="skip_cache"?i++:p.decision==="invalidate"&&l++,c[p.reason]=(c[p.reason]||0)+1,p.context.componentId&&(d[p.context.componentId]=(d[p.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?n[i]=`{${c.join(", ")}}`:n[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.map(i=>({...i,componentId:n})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(p=>p.type==="render"),r=this.profilingData.filter(p=>p.type==="binding"),i=this.profilingData.filter(p=>p.type==="action"),l={};for(const p of n)p.component&&(l[p.component]||(l[p.component]={count:0,durations:[]}),l[p.component].count++,p.duration&&l[p.component].durations.push(p.duration));const c=Object.entries(l).map(([p,m])=>({name:p,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,C)=>y+C,0)/m.durations.length:0})).sort((p,m)=>m.renderCount-p.renderCount).slice(0,10),d={};for(const p of r)p.expression&&(d[p.expression]=(d[p.expression]||0)+1);const f=Object.entries(d).sort(([,p],[,m])=>m-p).slice(0,10).map(([p])=>p);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=bA(e),c=yA(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(r)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const p=[];let m=!0;return f.name||(p.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(p.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:p}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const c={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=c:this.formBindingValidations.push(c),c}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const r=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:n,topIssues:r}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,p={id:f,name:e,expression:n,componentId:c,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,p)}trackComputedRecalc(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,p=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:p,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(f);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=l)}analyzeComputedDependencyChain(e,n){const r=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),r.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};r.add(m),i.push(m);const C=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(C)for(const v of C.dependencies)v.type==="computed"?S.push(f(v.path,y+1)):S.push({name:v.path,type:v.type,children:[],depth:y+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:y}},p=f(e,0);return{root:e,tree:p,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const p of this.computedRecalcLogs)e[p.trigger]++,p.valueChanged||l++,n[p.computedName]=(n[p.computedName]||0)+1,r[p.computedName]||(r[p.computedName]=[]),r[p.computedName].push(p.computationTime),i+=p.computationTime;const c=Object.entries(n).sort((p,m)=>m[1]-p[1]).slice(0,5).map(([p,m])=>({name:p,count:m})),d=Object.entries(r).map(([p,m])=>({name:p,avgTime:m.reduce((y,C)=>y+C,0)/m.length})).sort((p,m)=>m.avgTime-p.avgTime).slice(0,5);let f=0;for(const p of this.computedProperties.values())this.analyzeComputedDependencyChain(p.name,p.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:c,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,n),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,n){if(!this.config.enabled)return;const r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const r=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const r=e.initialState[n],i=e.currentState[n];if(r!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:r})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},r={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,r[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(n)}detectExpressionWarning(e){const{expression:n,result:r,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(p=>p.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(c&&c>10)return{type:"slow-evaluation",message:`표현식 평가에 ${c.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),c={};for(const f of e)c[f.resultType]=(c[f.resultType]||0)+1;const d={};for(const f of r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,p)=>f+p,0)/l.length:0,byType:c,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Expression watcher error:",r)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const n=[...this.stateHistory].reverse().find(r=>r.timestamp<=e);if(n)return{_global:n.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,n,r){if(!this.config.enabled)return;const i=r.map(c=>{if(typeof c=="string")return c;try{return JSON.stringify(c)}catch{return String(c)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(r),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)r[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:r,byPrefix:i,recentErrors:l,recentWarnings:c}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=r;n&&(Array.isArray(n)?(l=n.length,c=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,c=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,c=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):c=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"error",error:n,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let n=this.dataPathTransforms.find(r=>r.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let r=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,r+=c.warnings.length;for(const d of c.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([c,d])=>({warning:c,count:d})).sort((c,d)=>d.count-c.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:r,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,r=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:r,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const r=this.nestedContexts.find(i=>i.id===e);r&&r.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const c=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:r,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,r,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(c),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((n,r)=>n+r.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,n,r,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const c={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(r),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(c),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,r,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:r,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=n.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),r=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),c=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:r,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),c){const f=this.contextFlowNodes.get(c);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(r>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const c=Object.keys(e);return`{${c.slice(0,5).join(", ")}${c.length>5?`, ... +${c.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(c=>this.summarizeValues(c,n,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,r+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._global,priority:1});for(const[l,c]of this.dynamicStates)c&&Object.keys(c).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:c,priority:2});const i=this.computeEffectiveState(r._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const c=l.values._local||l.values;for(const[d,f]of Object.entries(c)){const p=r.values[d];if(JSON.stringify(p)!==JSON.stringify(f)){const m=[],y=[];for(const C of this.componentStateSources.values())C.stateSource.local.some(v=>v===`_local.${d}`||v===d)&&(C.stateProvider.type==="dynamicState"?m.push(C.componentName):C.stateProvider.type==="globalState"&&y.push(C.componentName));n.push({path:`_local.${d}`,globalValue:p,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,n,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),c={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],r=[],i=[],l=[],c=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const p of c)if(f.startsWith(p)){r.push(f);break}for(const p of d)if(p.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,computedStyles:i,tailwindAnalysis:l}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:n,componentName:r,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const c=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));c.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:r,property:"background-color",currentValue:c.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${c[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:r,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(c),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=r?.getUser?.();if(d&&(c="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(c="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let p="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?p="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(p="sessionStorage");const m=!!i&&(!!d||f);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const C=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:C,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:p,accessTokenPreview:y},lastActivity:Date.now(),source:c}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.version};this.layoutHistory.push(c),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const n=`exec_${++this.executionIdCounter}_${Date.now()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(c=>this.executionDetails.delete(c))}return n}endHandlerExecution(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=r,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(c)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),c.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,r,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:r,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(c)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of r.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of r.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let c=!1,d;return!l&&(r==="object"||r==="array")?(c=this.deepEqual(e,n),!c&&r==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:r,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:n,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const n of this.changeAlerts)e[n.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,n){let r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:r,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};c.actions.push(d)}captureSequenceActionAfter(e,n,r,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const p=window.__g7PendingLocalState;p&&(f.pendingState=this.safeClone(p)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(c=>c.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||r.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const p=e[f],m=n[f];JSON.stringify(p)!==JSON.stringify(m)&&l.push({path:f,oldValue:p,newValue:m})}return{added:r,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,r=e.filter(p=>p.status==="success").length,i=e.filter(p=>p.status==="error").length,l=e.reduce((p,m)=>p+m.actions.length,0),c=n>0?e.reduce((p,m)=>p+m.totalDuration,0)/n:0,d={};for(const p of e)for(const m of p.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,p],[,m])=>m-p).slice(0,5).map(([p,m])=>({handler:p,count:m}));return{totalExecutions:n,successCount:r,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(r[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[p,m]of c){const y=this.getValueByPath(r,p),C=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&C>0){const S=this.createStaleClosureWarning(i,n,p,m.value,m.capturedAt,y,d,C,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,c,d,f,p,m){const y=this.getStaleClosureSeverity(e,f),{description:C,suggestion:S,docLink:v}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:C,suggestion:S,docLink:v,actionId:p,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,n,r){const i=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({location:f,count:p})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({path:f,count:p}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};$($i,"instance");let Ua=$i;const Jn=dt("LayoutLoader");class Rr extends Error{constructor(e,n,r){super(e),this.code=n,this.details=r,this.name="LayoutLoaderError"}}class Gf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Jn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Jn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Ua.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const C=n.replace("__preview__/","");l=Pr(`/api/layouts/preview/${C}`,"json",i)}else l=Pr(`/api/layouts/${e}/${n}`,"json",i);Jn.log("Fetching layout from API:",l);const c=Wn(),d=r?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const p=await ac(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await p.json()}catch{m=null}if(!p.ok){if(p.status===401&&!r&&d){Jn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof Rr&&S.details?.status===401?new Rr(S.message,S.code,{...S.details,hadToken:!0}):S}}const C=m?.message||m?.error;throw new Rr(`Failed to fetch layout: ${p.status} ${p.statusText}`,"FETCH_FAILED",{status:p.status,statusText:p.statusText,url:l,apiMessage:C})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,Ua.getInstance().trackLayoutLoad(n,e,y,"api"),Jn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Rr?i:new Rr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Rr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Rr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Rr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Jn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new Rr("No layout data to render","NO_LAYOUT_DATA");Jn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Jn.log("Layout rendered successfully")}catch(r){Jn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Jn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Jn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=`

Component not found: ${e}

`,n}createErrorElement(e,n){const r=document.createElement("div");return r.className="component-error",r.setAttribute("data-component-type",e),r.innerHTML=`

Component Error: ${e}

${n?.message||"Unknown error"}

`,r}renderErrorState(e,n){const r=n instanceof Error?n.message:String(n),i=n instanceof Rr?n.code:"UNKNOWN_ERROR";e.innerHTML=`

레이아웃 로드 실패

${r}

오류 코드: ${i}

`,Jn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Jn.log("Layout data and cache cleared")}}const vA=dt("TranslationContext"),Ff=M.createContext(null),qc=({children:s,translationEngine:e,translationContext:n})=>{const r=M.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,p])=>`${f}=${p}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=M.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return ft.jsx(Ff.Provider,{value:i,children:s})},Py=()=>{const s=M.useContext(Ff);return s||(vA.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Pa=dt("SlotContext"),SA={registerToSlot:()=>{Pa.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Pa.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},wA=M.createContext(SA),Vf=({children:s})=>{const e=M.useRef(new Map),n=M.useRef(new Map),r=M.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(C=>{try{C()}catch(S){Pa.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=M.useCallback((m,y,C)=>{if(!m||!y){Pa.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),v=S.get(y);v&&v.registrationKey===C.registrationKey||(S.set(y,C),Pa.log(`Component registered to slot: ${y} -> ${m} (order: ${C.order})`),r(m))},[r]),l=M.useCallback((m,y)=>{const C=e.current.get(m);C&&C.has(y)&&(C.delete(y),Pa.log(`Component unregistered from slot: ${y} <- ${m}`),C.size===0&&e.current.delete(m),r(m))},[r]),c=M.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((C,S)=>C.order-S.order):[]},[]),d=M.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const C=n.current.get(m);return C.add(y),()=>{C.delete(y),C.size===0&&n.current.delete(m)}},[]),f=M.useCallback(()=>{e.current.forEach((m,y)=>{r(y)}),e.current.clear(),n.current.clear(),Pa.log("All slots cleared")},[r]),p=M.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return M.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=p,Pa.log("SlotContext exposed to window.__slotContextValue"))},[p]),ft.jsx(wA.Provider,{value:p,children:s})};class Kf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}class By{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function CA(s){try{new s}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class Wf extends Kf{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,r)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,r)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class qy extends Wf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class EA extends Wf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class _A extends qy{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class Gy extends Kf{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,this.eventFormatter=new By(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(r,i)=>{this.name===r&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(r=>r!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class Fy extends Gy{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class AA extends Fy{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class Gc extends Kf{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class Vy extends Gc{whisper(e,n){return this}}class xA extends Gc{whisper(e,n){return this}}class TA extends Vy{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Ky=class Ow{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Ow._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){var e,n;return typeof window<"u"&&(e=window.Laravel)!=null&&e.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?((n=document.querySelector('meta[name="csrf-token"]'))==null?void 0:n.getAttribute("content"))??null:null}};Ky._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Yf=Ky;class Fc extends Yf{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new Wf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new qy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new EA(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new _A(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}disconnect(){this.pusher.disconnect()}}class kA extends Yf{constructor(){super(...arguments),this.channels={}}connect(){let e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(n=>{n.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new Gy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Fy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new AA(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}disconnect(){this.socket.disconnect()}}class Wy extends Yf{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new Gc}channel(e){return new Gc}privateChannel(e){return new Vy}encryptedPrivateChannel(e){return new xA}presenceChannel(e){return new TA}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class RA{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new Fc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new Fc(this.options);else if(this.options.broadcaster==="ably")this.connector=new Fc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new kA(this.options);else if(this.options.broadcaster==="null")this.connector=new Wy(this.options);else if(typeof this.options.broadcaster=="function"&&CA(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,n,r){return this.connector.listen(e,n,r)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof Fc||e instanceof Wy}socketId(){return this.connector.socketId()}registerInterceptors(){typeof Vue<"u"&&Vue!=null&&Vue.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var Xf={exports:{}};/*! * Pusher JavaScript Library v8.4.0 * https://pusher.com/ * * Copyright 2020, Pusher * Released under the MIT licence. */var Yy;function DA(){return Yy||(Yy=1,(function(s,e){(function(r,i){s.exports=i()})(window,function(){return(function(n){var r={};function i(l){if(r[l])return r[l].exports;var c=r[l]={i:l,l:!1,exports:{}};return n[l].call(c.exports,c,c.exports,i),c.l=!0,c.exports}return i.m=n,i.c=r,i.d=function(l,c,d){i.o(l,c)||Object.defineProperty(l,c,{enumerable:!0,get:d})},i.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})},i.t=function(l,c){if(c&1&&(l=i(l)),c&8||c&4&&typeof l=="object"&&l&&l.__esModule)return l;var d=Object.create(null);if(i.r(d),Object.defineProperty(d,"default",{enumerable:!0,value:l}),c&2&&typeof l!="string")for(var f in l)i.d(d,f,function(p){return l[p]}.bind(null,f));return d},i.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return i.d(c,"a",c),c},i.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},i.p="",i(i.s=2)})([(function(n,r,i){var l=this&&this.__extends||(function(){var x=function(w,R){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,O){L.__proto__=O}||function(L,O){for(var j in O)O.hasOwnProperty(j)&&(L[j]=O[j])},x(w,R)};return function(w,R){x(w,R);function L(){this.constructor=w}w.prototype=R===null?Object.create(R):(L.prototype=R.prototype,new L)}})();Object.defineProperty(r,"__esModule",{value:!0});var c=256,d=(function(){function x(w){w===void 0&&(w="="),this._paddingCharacter=w}return x.prototype.encodedLength=function(w){return this._paddingCharacter?(w+2)/3*4|0:(w*8+5)/6|0},x.prototype.encode=function(w){for(var R="",L=0;L>>18&63),R+=this._encodeByte(O>>>12&63),R+=this._encodeByte(O>>>6&63),R+=this._encodeByte(O>>>0&63)}var j=w.length-L;if(j>0){var O=w[L]<<16|(j===2?w[L+1]<<8:0);R+=this._encodeByte(O>>>18&63),R+=this._encodeByte(O>>>12&63),j===2?R+=this._encodeByte(O>>>6&63):R+=this._paddingCharacter||"",R+=this._paddingCharacter||""}return R},x.prototype.maxDecodedLength=function(w){return this._paddingCharacter?w/4*3|0:(w*6+7)/8|0},x.prototype.decodedLength=function(w){return this.maxDecodedLength(w.length-this._getPaddingLength(w))},x.prototype.decode=function(w){if(w.length===0)return new Uint8Array(0);for(var R=this._getPaddingLength(w),L=w.length-R,O=new Uint8Array(this.maxDecodedLength(L)),j=0,F=0,G=0,P=0,K=0,he=0,Ee=0;F>>4,O[j++]=K<<4|he>>>2,O[j++]=he<<6|Ee,G|=P&c,G|=K&c,G|=he&c,G|=Ee&c;if(F>>4,G|=P&c,G|=K&c),F>>2,G|=he&c),F>>8&6,R+=51-w>>>8&-75,R+=61-w>>>8&-15,R+=62-w>>>8&3,String.fromCharCode(R)},x.prototype._decodeChar=function(w){var R=c;return R+=(42-w&w-44)>>>8&-c+w-43+62,R+=(46-w&w-48)>>>8&-c+w-47+63,R+=(47-w&w-58)>>>8&-c+w-48+52,R+=(64-w&w-91)>>>8&-c+w-65+0,R+=(96-w&w-123)>>>8&-c+w-97+26,R},x.prototype._getPaddingLength=function(w){var R=0;if(this._paddingCharacter){for(var L=w.length-1;L>=0&&w[L]===this._paddingCharacter;L--)R++;if(w.length<4||R>2)throw new Error("Base64Coder: incorrect padding")}return R},x})();r.Coder=d;var f=new d;function p(x){return f.encode(x)}r.encode=p;function m(x){return f.decode(x)}r.decode=m;var y=(function(x){l(w,x);function w(){return x!==null&&x.apply(this,arguments)||this}return w.prototype._encodeByte=function(R){var L=R;return L+=65,L+=25-R>>>8&6,L+=51-R>>>8&-75,L+=61-R>>>8&-13,L+=62-R>>>8&49,String.fromCharCode(L)},w.prototype._decodeChar=function(R){var L=c;return L+=(44-R&R-46)>>>8&-c+R-45+62,L+=(94-R&R-96)>>>8&-c+R-95+63,L+=(47-R&R-58)>>>8&-c+R-48+52,L+=(64-R&R-91)>>>8&-c+R-65+0,L+=(96-R&R-123)>>>8&-c+R-97+26,L},w})(d);r.URLSafeCoder=y;var C=new y;function S(x){return C.encode(x)}r.encodeURLSafe=S;function v(x){return C.decode(x)}r.decodeURLSafe=v,r.encodedLength=function(x){return f.encodedLength(x)},r.maxDecodedLength=function(x){return f.maxDecodedLength(x)},r.decodedLength=function(x){return f.decodedLength(x)}}),(function(n,r,i){Object.defineProperty(r,"__esModule",{value:!0});var l="utf8: invalid string",c="utf8: invalid source encoding";function d(m){for(var y=new Uint8Array(f(m)),C=0,S=0;S>6,y[C++]=128|v&63):v<55296?(y[C++]=224|v>>12,y[C++]=128|v>>6&63,y[C++]=128|v&63):(S++,v=(v&1023)<<10,v|=m.charCodeAt(S)&1023,v+=65536,y[C++]=240|v>>18,y[C++]=128|v>>12&63,y[C++]=128|v>>6&63,y[C++]=128|v&63)}return y}r.encode=d;function f(m){for(var y=0,C=0;C=m.length-1)throw new Error(l);C++,y+=4}else throw new Error(l)}return y}r.encodedLength=f;function p(m){for(var y=[],C=0;C=m.length)throw new Error(c);var x=m[++C];if((x&192)!==128)throw new Error(c);S=(S&31)<<6|x&63,v=128}else if(S<240){if(C>=m.length-1)throw new Error(c);var x=m[++C],w=m[++C];if((x&192)!==128||(w&192)!==128)throw new Error(c);S=(S&15)<<12|(x&63)<<6|w&63,v=2048}else if(S<248){if(C>=m.length-2)throw new Error(c);var x=m[++C],w=m[++C],R=m[++C];if((x&192)!==128||(w&192)!==128||(R&192)!==128)throw new Error(c);S=(S&15)<<18|(x&63)<<12|(w&63)<<6|R&63,v=65536}else throw new Error(c);if(S=55296&&S<=57343)throw new Error(c);if(S>=65536){if(S>1114111)throw new Error(c);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}r.decode=p}),(function(n,r,i){n.exports=i(3).default}),(function(n,r,i){i.r(r);class l{constructor(b,_){this.lastId=0,this.prefix=b,this.name=_}create(b){this.lastId++;var _=this.lastId,D=this.prefix+_,I=this.name+"["+_+"]",ie=!1,ye=function(){ie||(b.apply(null,arguments),ie=!0)};return this[_]=ye,{number:_,id:D,name:I,callback:ye}}remove(b){delete this[b.number]}}var c=new l("_pusher_script_","Pusher.ScriptReceivers"),d={VERSION:"8.4.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""},f=d;class p{constructor(b){this.options=b,this.receivers=b.receivers||c,this.loading={}}load(b,_,D){var I=this;if(I.loading[b]&&I.loading[b].length>0)I.loading[b].push(D);else{I.loading[b]=[D];var ie=Fe.createScriptRequest(I.getPath(b,_)),ye=I.receivers.create(function(Oe){if(I.receivers.remove(ye),I.loading[b]){var Ve=I.loading[b];delete I.loading[b];for(var it=function(Bt){Bt||ie.cleanup()},ct=0;ct>>6)+ze(128|b&63):ze(224|b>>>12&15)+ze(128|b>>>6&63)+ze(128|b&63)},bt=function(A){return A.replace(/[^\x00-\x7F]/g,je)},X=function(A){var b=[0,2,1][A.length%3],_=A.charCodeAt(0)<<16|(A.length>1?A.charCodeAt(1):0)<<8|(A.length>2?A.charCodeAt(2):0),D=[Be.charAt(_>>>18),Be.charAt(_>>>12&63),b>=2?"=":Be.charAt(_>>>6&63),b>=1?"=":Be.charAt(_&63)];return D.join("")},de=window.btoa||function(A){return A.replace(/[\s\S]{1,3}/g,X)};class Ce{constructor(b,_,D,I){this.clear=_,this.timer=b(()=>{this.timer&&(this.timer=I(this.timer))},D)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}var Z=Ce;function ge(A){window.clearTimeout(A)}function z(A){window.clearInterval(A)}class T extends Z{constructor(b,_){super(setTimeout,ge,b,function(D){return _(),null})}}class pe extends Z{constructor(b,_){super(setInterval,z,b,function(D){return _(),D})}}var fe={now(){return Date.now?Date.now():new Date().valueOf()},defer(A){return new T(0,A)},method(A,...b){var _=Array.prototype.slice.call(arguments,1);return function(D){return D[A].apply(D,_.concat(arguments))}}},me=fe;function ae(A,...b){for(var _=0;_{window.console&&window.console.log&&window.console.log(b)}}debug(...b){this.log(this.globalLog,b)}warn(...b){this.log(this.globalLogWarn,b)}error(...b){this.log(this.globalLogError,b)}globalLogWarn(b){window.console&&window.console.warn?window.console.warn(b):this.globalLog(b)}globalLogError(b){window.console&&window.console.error?window.console.error(b):this.globalLogWarn(b)}log(b,..._){var D=Re.apply(this,arguments);hl.log?hl.log(D):hl.logToConsole&&b.bind(this)(D)}}var St=new Pt,da=function(A,b,_,D,I){(_.headers!==void 0||_.headersProvider!=null)&&St.warn(`To send headers with the ${D.toString()} request, you must use AJAX, rather than JSONP.`);var ie=A.nextAuthCallbackID.toString();A.nextAuthCallbackID++;var ye=A.getDocument(),Oe=ye.createElement("script");A.auth_callbacks[ie]=function(ct){I(null,ct)};var Ve="Pusher.auth_callbacks['"+ie+"']";Oe.src=_.endpoint+"?callback="+encodeURIComponent(Ve)+"&"+b;var it=ye.getElementsByTagName("head")[0]||ye.documentElement;it.insertBefore(Oe,it.firstChild)},In=da;class kn{constructor(b){this.src=b}send(b){var _=this,D="Error loading "+_.src;_.script=document.createElement("script"),_.script.id=b.id,_.script.src=_.src,_.script.type="text/javascript",_.script.charset="UTF-8",_.script.addEventListener?(_.script.onerror=function(){b.callback(D)},_.script.onload=function(){b.callback(null)}):_.script.onreadystatechange=function(){(_.script.readyState==="loaded"||_.script.readyState==="complete")&&b.callback(null)},_.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(_.errorScript=document.createElement("script"),_.errorScript.id=b.id+"_error",_.errorScript.text=b.name+"('"+D+"');",_.script.async=_.errorScript.async=!1):_.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(_.script,I.firstChild),_.errorScript&&I.insertBefore(_.errorScript,_.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Rn{constructor(b,_){this.url=b,this.data=_}send(b){if(!this.request){var _=pn(this.data),D=this.url+"/"+b.number+"?"+_;this.request=Fe.createScriptRequest(D),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var jn=function(A,b){return function(_,D){var I="http"+(b?"s":"")+"://",ie=I+(A.host||A.options.host)+A.options.path,ye=Fe.createJSONPRequest(ie,_),Oe=Fe.ScriptReceivers.create(function(Ve,it){c.remove(Oe),ye.cleanup(),it&&it.host&&(A.host=it.host),D&&D(Ve,it)});ye.send(Oe)}},gn={name:"jsonp",getAgent:jn},fa=gn;function zn(A,b,_){var D=A+(b.useTLS?"s":""),I=b.useTLS?b.hostTLS:b.hostNonTLS;return D+"://"+I+_}function Vt(A,b){var _="/app/"+A,D="?protocol="+f.PROTOCOL+"&client=js&version="+f.VERSION+(b?"&"+b:"");return _+D}var _n={getInitial:function(A,b){var _=(b.httpPath||"")+Vt(A,"flash=false");return zn("ws",b,_)}},an={getInitial:function(A,b){var _=(b.httpPath||"/pusher")+Vt(A);return zn("http",b,_)}},q={getInitial:function(A,b){return zn("http",b,b.httpPath||"/pusher")},getPath:function(A,b){return Vt(A)}};class oe{constructor(){this._callbacks={}}get(b){return this._callbacks[ce(b)]}add(b,_,D){var I=ce(b);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:_,context:D})}remove(b,_,D){if(!b&&!_&&!D){this._callbacks={};return}var I=b?[ce(b)]:Ge(this._callbacks);_||D?this.removeCallback(I,_,D):this.removeAllCallbacks(I)}removeCallback(b,_,D){vt(b,function(I){this._callbacks[I]=Xt(this._callbacks[I]||[],function(ie){return _&&_!==ie.fn||D&&D!==ie.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(b){vt(b,function(_){delete this._callbacks[_]},this)}}function ce(A){return"_"+A}class J{constructor(b){this.callbacks=new oe,this.global_callbacks=[],this.failThrough=b}bind(b,_,D){return this.callbacks.add(b,_,D),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,_,D){return this.callbacks.remove(b,_,D),this}unbind_global(b){return b?(this.global_callbacks=Xt(this.global_callbacks||[],_=>_!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,_,D){for(var I=0;I0)for(var I=0;I{this.onError(_),this.changeState("closed")}),!1}return this.bindListeners(),St.debug("Connecting",{transport:this.name,url:b}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(b){return this.state==="open"?(me.defer(()=>{this.socket&&this.socket.send(b)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(b){this.emit("error",{type:"WebSocketError",error:b}),this.timeline.error(this.buildTimelineMessage({error:b.toString()}))}onClose(b){b?this.changeState("closed",{code:b.code,reason:b.reason,wasClean:b.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(b){this.emit("message",b)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=b=>{this.onError(b)},this.socket.onclose=b=>{this.onClose(b)},this.socket.onmessage=b=>{this.onMessage(b)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(b,_){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:_})),this.emit(b,_)}buildTimelineMessage(b){return ae({cid:this.id},b)}}class ue{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,_,D,I){return new ve(this.hooks,b,_,D,I)}}var we=new ue({urls:_n,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Fe.getWebSocketAPI()},isSupported:function(){return!!Fe.getWebSocketAPI()},getSocket:function(A){return Fe.createWebSocket(A)}}),_e={urls:an,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},qe=ae({getSocket:function(A){return Fe.HTTPFactory.createStreamingSocket(A)}},_e),xe=ae({getSocket:function(A){return Fe.HTTPFactory.createPollingSocket(A)}},_e),De={isSupported:function(){return Fe.isXHRSupported()}},Ae=new ue(ae({},qe,De)),tt=new ue(ae({},xe,De)),Ne={ws:we,xhr_streaming:Ae,xhr_polling:tt},He=Ne,Se=new ue({file:"sockjs",urls:q,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(A,b){return new window.SockJS(A,null,{js_path:y.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(A,b){A.send(JSON.stringify({path:b}))}}),$e={isSupported:function(A){var b=Fe.isXDRSupported(A.useTLS);return b}},et=new ue(ae({},qe,$e)),Ot=new ue(ae({},xe,$e));He.xdr_streaming=et,He.xdr_polling=Ot,He.sockjs=Se;var Mt=He;class Hn extends J{constructor(){super();var b=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){b.emit("online")},!1),window.addEventListener("offline",function(){b.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var It=new Hn;class jt{constructor(b,_,D){this.manager=b,this.transport=_,this.minPingDelay=D.minPingDelay,this.maxPingDelay=D.maxPingDelay,this.pingDelay=void 0}createConnection(b,_,D,I){I=ae({},I,{activityTimeout:this.pingDelay});var ie=this.transport.createConnection(b,_,D,I),ye=null,Oe=function(){ie.unbind("open",Oe),ie.bind("closed",Ve),ye=me.now()},Ve=it=>{if(ie.unbind("closed",Ve),it.code===1002||it.code===1003)this.manager.reportDeath();else if(!it.wasClean&&ye){var ct=me.now()-ye;ct<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(ct/2,this.minPingDelay))}};return ie.bind("open",Oe),ie}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const mn={decodeMessage:function(A){try{var b=JSON.parse(A.data),_=b.data;if(typeof _=="string")try{_=JSON.parse(b.data)}catch{}var D={event:b.event,channel:b.channel,data:_};return b.user_id&&(D.user_id=b.user_id),D}catch(I){throw{type:"MessageParseError",error:I,data:A.data}}},encodeMessage:function(A){return JSON.stringify(A)},processHandshake:function(A){var b=mn.decodeMessage(A);if(b.event==="pusher:connection_established"){if(!b.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:b.data.socket_id,activityTimeout:b.data.activity_timeout*1e3}}else{if(b.event==="pusher:error")return{action:this.getCloseAction(b.data),error:this.getCloseError(b.data)};throw"Invalid handshake"}},getCloseAction:function(A){return A.code<4e3?A.code>=1002&&A.code<=1004?"backoff":null:A.code===4e3?"tls_only":A.code<4100?"refused":A.code<4200?"backoff":A.code<4300?"retry":"refused"},getCloseError:function(A){return A.code!==1e3&&A.code!==1001?{type:"PusherError",data:{code:A.code,message:A.reason||A.message}}:null}};var Un=mn;class Jo extends J{constructor(b,_){super(),this.id=b,this.transport=_,this.activityTimeout=_.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,_,D){var I={event:b,data:_};return D&&(I.channel=D),St.debug("Event sent",I),this.send(Un.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:D=>{var I;try{I=Un.decodeMessage(D)}catch(ie){this.emit("error",{type:"MessageParseError",error:ie,data:D.data})}if(I!==void 0){switch(St.debug("Event recd",I),I.event){case"pusher:error":this.emit("error",{type:"PusherError",data:I.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",I)}},activity:()=>{this.emit("activity")},error:D=>{this.emit("error",D)},closed:D=>{_(),D&&D.code&&this.handleCloseEvent(D),this.transport=null,this.emit("closed")}},_=()=>{Me(b,(D,I)=>{this.transport.unbind(I,D)})};Me(b,(D,I)=>{this.transport.bind(I,D)})}handleCloseEvent(b){var _=Un.getCloseAction(b),D=Un.getCloseError(b);D&&this.emit("error",D),_&&this.emit(_,{action:_,error:D})}}class rh{constructor(b,_){this.transport=b,this.callback=_,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var _;try{_=Un.processHandshake(b)}catch(D){this.finish("error",{error:D}),this.transport.close();return}_.action==="connected"?this.finish("connected",{connection:new Jo(_.id,this.transport),activityTimeout:_.activityTimeout}):(this.finish(_.action,{error:_.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var _=Un.getCloseAction(b)||"backoff",D=Un.getCloseError(b);this.finish(_,{error:D})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(b,_){this.callback(ae({transport:this.transport,action:b},_))}}class ah{constructor(b,_){this.timeline=b,this.options=_||{}}send(b,_){this.timeline.isEmpty()||this.timeline.send(Fe.TimelineTransport.getAgent(this,b),_)}}class As extends J{constructor(b,_){super(function(D,I){St.debug("No callbacks on "+b+" for "+D)}),this.name=b,this.pusher=_,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,_){return _(null,{auth:""})}trigger(b,_){if(b.indexOf("client-")!==0)throw new w("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var D=v.buildLogSuffix("triggeringClientEvents");St.warn(`Client event triggered before channel 'subscription_succeeded' event . ${D}`)}return this.pusher.send_event(b,_,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var _=b.event,D=b.data;if(_==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(_==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(_.indexOf("pusher_internal:")!==0){var I={};this.emit(_,D,I)}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",b.data)}handleSubscriptionCountEvent(b){b.data.subscription_count&&(this.subscriptionCount=b.data.subscription_count),this.emit("pusher:subscription_count",b.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(b,_)=>{b?(this.subscriptionPending=!1,St.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof K?{status:b.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:_.auth,channel_data:_.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class ha extends As{authorize(b,_){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},_)}}class Qo{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){Me(this.members,(_,D)=>{b(this.get(D))})}setMyID(b){this.myID=b}onSubscription(b){this.members=b.presence.hash,this.count=b.presence.count,this.me=this.get(this.myID)}addMember(b){return this.get(b.user_id)===null&&this.count++,this.members[b.user_id]=b.user_info,this.get(b.user_id)}removeMember(b){var _=this.get(b.user_id);return _&&(delete this.members[b.user_id],this.count--),_}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var qa=function(A,b,_,D){function I(ie){return ie instanceof _?ie:new _(function(ye){ye(ie)})}return new(_||(_=Promise))(function(ie,ye){function Oe(ct){try{it(D.next(ct))}catch(Bt){ye(Bt)}}function Ve(ct){try{it(D.throw(ct))}catch(Bt){ye(Bt)}}function it(ct){ct.done?ie(ct.value):I(ct.value).then(Oe,Ve)}it((D=D.apply(A,b||[])).next())})};class Ga extends ha{constructor(b,_){super(b,_),this.members=new Qo}authorize(b,_){super.authorize(b,(D,I)=>qa(this,void 0,void 0,function*(){if(!D)if(I=I,I.channel_data!=null){var ie=JSON.parse(I.channel_data);this.members.setMyID(ie.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let ye=v.buildLogSuffix("authorizationEndpoint");St.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),_("Invalid auth response");return}_(D,I)}))}handleEvent(b){var _=b.event;if(_.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var D=b.data,I={};b.user_id&&(I.user_id=b.user_id),this.emit(_,D,I)}}handleInternalEvent(b){var _=b.event,D=b.data;switch(_){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(b);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(b);break;case"pusher_internal:member_added":var I=this.members.addMember(D);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var ie=this.members.removeMember(D);ie&&this.emit("pusher:member_removed",ie);break}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(b.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Mi=i(1),Yr=i(0);class Jt extends ha{constructor(b,_,D){super(b,_),this.key=null,this.nacl=D}authorize(b,_){super.authorize(b,(D,I)=>{if(D){_(D,I);return}let ie=I.shared_secret;if(!ie){_(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=Object(Yr.decode)(ie),delete I.shared_secret,_(null,I)})}trigger(b,_){throw new F("Client events are not currently supported for encrypted channels")}handleEvent(b){var _=b.event,D=b.data;if(_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(_,D)}handleEncryptedEvent(b,_){if(!this.key){St.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!_.ciphertext||!_.nonce){St.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+_);return}let D=Object(Yr.decode)(_.ciphertext);if(D.length{if(ye){St.error(`Failed to make a request to the authEndpoint: ${Oe}. Unable to fetch new key, so dropping encrypted event`);return}if(ie=this.nacl.secretbox.open(D,I,this.key),ie===null){St.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(ie))});return}this.emit(b,this.getDataToEmit(ie))}getDataToEmit(b){let _=Object(Mi.decode)(b);try{return JSON.parse(_)}catch{return _}}}class eu extends J{constructor(b,_){super(),this.state="initialized",this.connection=null,this.key=b,this.options=_,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var D=Fe.getNetwork();D.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),D.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(b){return this.connection?this.connection.send(b):!1}send_event(b,_,D){return this.connection?this.connection.send_event(b,_,D):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(_,D)=>{_?this.runner=this.strategy.connect(0,b):D.action==="error"?(this.emit("error",{type:"HandshakeError",error:D.error}),this.timeline.error({handshakeError:D.error})):(this.abortConnecting(),this.handshakeCallbacks[D.action](D))};this.runner=this.strategy.connect(0,b)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var b=this.abandonConnection();b.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(b){this.timeline.info({action:"retry",delay:b}),b>0&&this.emit("connecting_in",Math.round(b/1e3)),this.retryTimer=new T(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new T(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new T(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new T(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return ae({},b,{message:_=>{this.resetActivityCheck(),this.emit("message",_)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:_=>{this.emit("error",_)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(b){return ae({},b,{connected:_=>{this.activityTimeout=Math.min(this.options.activityTimeout,_.activityTimeout,_.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(_.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let b=_=>D=>{D.error&&this.emit("error",{type:"WebSocketError",error:D.error}),_(D)};return{tls_only:b(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:b(()=>{this.disconnect()}),backoff:b(()=>{this.retryIn(1e3)}),retry:b(()=>{this.retryIn(0)})}}setConnection(b){this.connection=b;for(var _ in this.connectionCallbacks)this.connection.bind(_,this.connectionCallbacks[_]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var _=this.connection;return this.connection=null,_}}updateState(b,_){var D=this.state;if(this.state=b,D!==b){var I=b;I==="connected"&&(I+=" with new socket ID "+_.socket_id),St.debug("State changed",D+" -> "+I),this.timeline.info({state:b,params:_}),this.emit("state_change",{previous:D,current:b}),this.emit(b,_)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class tu{constructor(){this.channels={}}add(b,_){return this.channels[b]||(this.channels[b]=pa(b,_)),this.channels[b]}all(){return kt(this.channels)}find(b){return this.channels[b]}remove(b){var _=this.channels[b];return delete this.channels[b],_}disconnect(){Me(this.channels,function(b){b.disconnect()})}}function pa(A,b){if(A.indexOf("private-encrypted-")===0){if(b.config.nacl)return Mr.createEncryptedChannel(A,b,b.config.nacl);let _="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",D=v.buildLogSuffix("encryptedChannelSupport");throw new F(`${_}. ${D}`)}else{if(A.indexOf("private-")===0)return Mr.createPrivateChannel(A,b);if(A.indexOf("presence-")===0)return Mr.createPresenceChannel(A,b);if(A.indexOf("#")===0)throw new R('Cannot create a channel with name "'+A+'".');return Mr.createChannel(A,b)}}var Fa={createChannels(){return new tu},createConnectionManager(A,b){return new eu(A,b)},createChannel(A,b){return new As(A,b)},createPrivateChannel(A,b){return new ha(A,b)},createPresenceChannel(A,b){return new Ga(A,b)},createEncryptedChannel(A,b,_){return new Jt(A,b,_)},createTimelineSender(A,b){return new ah(A,b)},createHandshake(A,b){return new rh(A,b)},createAssistantToTheTransportManager(A,b,_){return new jt(A,b,_)}},Mr=Fa;class Zo{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return Mr.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Xr{constructor(b,_){this.strategies=b,this.loop=!!_.loop,this.failFast=!!_.failFast,this.timeout=_.timeout,this.timeoutLimit=_.timeoutLimit}isSupported(){return $r(this.strategies,me.method("isSupported"))}connect(b,_){var D=this.strategies,I=0,ie=this.timeout,ye=null,Oe=(Ve,it)=>{it?_(null,it):(I=I+1,this.loop&&(I=I%D.length),I0&&(ie=new T(D.timeout,function(){ye.abort(),I(!0)})),ye=b.connect(_,function(Oe,Ve){Oe&&ie&&ie.isRunning()&&!D.failFast||(ie&&ie.ensureAborted(),I(Oe,Ve))}),{abort:function(){ie&&ie.ensureAborted(),ye.abort()},forceMinPriority:function(Oe){ye.forceMinPriority(Oe)}}}}class el{constructor(b){this.strategies=b}isSupported(){return $r(this.strategies,me.method("isSupported"))}connect(b,_){return xs(this.strategies,b,function(D,I){return function(ie,ye){if(I[D].error=ie,ie){Ts(I)&&_(!0);return}vt(I,function(Oe){Oe.forceMinPriority(ye.transport.priority)}),_(null,ye)}})}}function xs(A,b,_){var D=hn(A,function(I,ie,ye,Oe){return I.connect(b,_(ie,Oe))});return{abort:function(){vt(D,Nr)},forceMinPriority:function(I){vt(D,function(ie){ie.forceMinPriority(I)})}}}function Ts(A){return En(A,function(b){return!!b.error})}function Nr(A){!A.error&&!A.aborted&&(A.abort(),A.aborted=!0)}class Pn{constructor(b,_,D){this.strategy=b,this.transports=_,this.ttl=D.ttl||1800*1e3,this.usingTLS=D.useTLS,this.timeline=D.timeline}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.usingTLS,I=ih(D),ie=I&&I.cacheSkipCount?I.cacheSkipCount:0,ye=[this.strategy];if(I&&I.timestamp+this.ttl>=me.now()){var Oe=this.transports[I.transport];Oe&&(["ws","wss"].includes(I.transport)||ie>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),ye.push(new Xr([Oe],{timeout:I.latency*2+1e3,failFast:!0}))):ie++)}var Ve=me.now(),it=ye.pop().connect(b,function ct(Bt,Hi){Bt?(nl(D),ye.length>0?(Ve=me.now(),it=ye.pop().connect(b,ct)):_(Bt)):(tl(D,Hi.transport.name,me.now()-Ve,ie),_(null,Hi))});return{abort:function(){it.abort()},forceMinPriority:function(ct){b=ct,it&&it.forceMinPriority(ct)}}}}function ks(A){return"pusherTransport"+(A?"TLS":"NonTLS")}function ih(A){var b=Fe.getLocalStorage();if(b)try{var _=b[ks(A)];if(_)return JSON.parse(_)}catch{nl(A)}return null}function tl(A,b,_,D){var I=Fe.getLocalStorage();if(I)try{I[ks(A)]=er({timestamp:me.now(),transport:b,latency:_,cacheSkipCount:D})}catch{}}function nl(A){var b=Fe.getLocalStorage();if(b)try{delete b[ks(A)]}catch{}}class ga{constructor(b,{delay:_}){this.strategy=b,this.options={delay:_}}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.strategy,I,ie=new T(this.options.delay,function(){I=D.connect(b,_)});return{abort:function(){ie.ensureAborted(),I&&I.abort()},forceMinPriority:function(ye){b=ye,I&&I.forceMinPriority(ye)}}}}class Ni{constructor(b,_,D){this.test=b,this.trueBranch=_,this.falseBranch=D}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,_){var D=this.test()?this.trueBranch:this.falseBranch;return D.connect(b,_)}}class Bn{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.strategy.connect(b,function(I,ie){ie&&D.abort(),_(I,ie)});return D}}function ma(A){return function(){return A.isSupported()}}var nu=function(A,b,_){var D={};function I(Ui,pu,gu,vl,Sl){var wl=_(A,Ui,pu,gu,vl,Sl);return D[Ui]=wl,wl}var ie=Object.assign({},b,{hostNonTLS:A.wsHost+":"+A.wsPort,hostTLS:A.wsHost+":"+A.wssPort,httpPath:A.wsPath}),ye=Object.assign({},ie,{useTLS:!0}),Oe=Object.assign({},b,{hostNonTLS:A.httpHost+":"+A.httpPort,hostTLS:A.httpHost+":"+A.httpsPort,httpPath:A.httpPath}),Ve={loop:!0,timeout:15e3,timeoutLimit:6e4},it=new Zo({minPingDelay:1e4,maxPingDelay:A.activityTimeout}),ct=new Zo({lives:2,minPingDelay:1e4,maxPingDelay:A.activityTimeout}),Bt=I("ws","ws",3,ie,it),Hi=I("wss","ws",3,ye,it),du=I("sockjs","sockjs",1,Oe),pl=I("xhr_streaming","xhr_streaming",1,Oe,ct),fu=I("xdr_streaming","xdr_streaming",1,Oe,ct),gl=I("xhr_polling","xhr_polling",1,Oe),Ja=I("xdr_polling","xdr_polling",1,Oe),hu=new Xr([Bt],Ve),Ch=new Xr([Hi],Ve),Eh=new Xr([du],Ve),ml=new Xr([new Ni(ma(pl),pl,fu)],Ve),yl=new Xr([new Ni(ma(gl),gl,Ja)],Ve),Qa=new Xr([new Ni(ma(ml),new el([ml,new ga(yl,{delay:4e3})]),yl)],Ve),ba=new Ni(ma(Qa),Qa,Eh),bl;return b.useTLS?bl=new el([hu,new ga(ba,{delay:2e3})]):bl=new el([hu,new ga(Ch,{delay:2e3}),new ga(ba,{delay:5e3})]),new Pn(new Bn(new Ni(ma(Bt),bl,ba)),D,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})},rl=nu,Va=(function(){var A=this;A.timeline.info(A.buildTimelineMessage({transport:A.name+(A.options.useTLS?"s":"")})),A.hooks.isInitialized()?A.changeState("initialized"):A.hooks.file?(A.changeState("initializing"),y.load(A.hooks.file,{useTLS:A.options.useTLS},function(b,_){A.hooks.isInitialized()?(A.changeState("initialized"),_(!0)):(b&&A.onError(b),A.onClose(),_(!1))})):A.onClose()}),ru={getRequest:function(A){var b=new window.XDomainRequest;return b.ontimeout=function(){A.emit("error",new L),A.close()},b.onerror=function(_){A.emit("error",_),A.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&A.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&A.onChunk(200,b.responseText),A.emit("finished",200),A.close()},b},abortRequest:function(A){A.ontimeout=A.onerror=A.onprogress=A.onload=null,A.abort()}},au=ru;const Ka=256*1024;class sh extends J{constructor(b,_,D){super(),this.hooks=b,this.method=_,this.url=D}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Fe.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(b)}close(){this.unloader&&(Fe.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,_){for(;;){var D=this.advanceBuffer(_);if(D)this.emit("chunk",{status:b,data:D});else break}this.isBufferTooLong(_)&&this.emit("buffer_too_long")}advanceBuffer(b){var _=b.slice(this.position),D=_.indexOf(` `);return D!==-1?(this.position+=D+1,_.slice(0,D)):null}isBufferTooLong(b){return this.position===b.length&&b.length>Ka}}var Rs;(function(A){A[A.CONNECTING=0]="CONNECTING",A[A.OPEN=1]="OPEN",A[A.CLOSED=3]="CLOSED"})(Rs||(Rs={}));var Jr=Rs,al=1;class oh{constructor(b,_){this.hooks=b,this.session=Os(1e3)+"/"+Wa(8),this.location=lh(_),this.readyState=Jr.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,_){this.onClose(b,_,!0)}sendRaw(b){if(this.readyState===Jr.OPEN)try{return Fe.createSocketRequest("POST",hr(Ds(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,_,D){this.closeStream(),this.readyState=Jr.CLOSED,this.onclose&&this.onclose({code:b,reason:_,wasClean:D})}onChunk(b){if(b.status===200){this.readyState===Jr.OPEN&&this.onActivity();var _,D=b.data.slice(0,1);switch(D){case"o":_=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(_);break;case"a":_=JSON.parse(b.data.slice(1)||"[]");for(var I=0;I<_.length;I++)this.onEvent(_[I]);break;case"m":_=JSON.parse(b.data.slice(1)||"null"),this.onEvent(_);break;case"h":this.hooks.onHeartbeat(this);break;case"c":_=JSON.parse(b.data.slice(1)||"[]"),this.onClose(_[0],_[1],!0);break}}}onOpen(b){this.readyState===Jr.CONNECTING?(b&&b.hostname&&(this.location.base=il(this.location.base,b.hostname)),this.readyState=Jr.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(b){this.readyState===Jr.OPEN&&this.onmessage&&this.onmessage({data:b})}onActivity(){this.onactivity&&this.onactivity()}onError(b){this.onerror&&this.onerror(b)}openStream(){this.stream=Fe.createSocketRequest("POST",hr(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",b=>{this.onChunk(b)}),this.stream.bind("finished",b=>{this.hooks.onFinished(this,b)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(b){me.defer(()=>{this.onError(b),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function lh(A){var b=/([^\?]*)\/*(\??.*)/.exec(A);return{base:b[1],queryString:b[2]}}function Ds(A,b){return A.base+"/"+b+"/xhr_send"}function hr(A){var b=A.indexOf("?")===-1?"?":"&";return A+b+"t="+ +new Date+"&n="+al++}function il(A,b){var _=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(A);return _[1]+b+_[3]}function Os(A){return Fe.randomInt(A)}function Wa(A){for(var b=[],_=0;_0&&A.onChunk(_.status,_.responseText);break;case 4:_.responseText&&_.responseText.length>0&&A.onChunk(_.status,_.responseText),A.emit("finished",_.status),A.close();break}},_},abortRequest:function(A){A.onreadystatechange=null,A.abort()}},ol=Ir,ji={createStreamingSocket(A){return this.createSocket(sl,A)},createPollingSocket(A){return this.createSocket(Ii,A)},createSocket(A,b){return new Ya(A,b)},createXHR(A,b){return this.createRequest(ol,A,b)},createRequest(A,b,_){return new sh(A,b,_)}},jr=ji;jr.createXDR=function(A,b){return this.createRequest(au,A,b)};var ll=jr,Ls={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:c,DependenciesReceivers:m,getDefaultStrategy:rl,Transports:Mt,transportConnectionInitializer:Va,HTTPFactory:ll,TimelineTransport:fa,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(A){window.Pusher=A;var b=()=>{this.onDocumentBody(A.ready)};window.JSON?b():y.load("json2",{},b)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Ee,jsonp:In}},onDocumentBody(A){document.body?A():setTimeout(()=>{this.onDocumentBody(A)},0)},createJSONPRequest(A,b){return new Rn(A,b)},createScriptRequest(A){return new kn(A)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var A=this.getXHRAPI();return new A},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return It},createWebSocket(A){var b=this.getWebSocketAPI();return new b(A)},createSocketRequest(A,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(A,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(A,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var A=this.getXHRAPI();return!!A&&new A().withCredentials!==void 0},isXDRSupported(A){var b=A?"https:":"http:",_=this.getProtocol();return!!window.XDomainRequest&&_===b},addUnloadListener(A){window.addEventListener!==void 0?window.addEventListener("unload",A,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",A)},removeUnloadListener(A){window.addEventListener!==void 0?window.removeEventListener("unload",A,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",A)},randomInt(A){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*A)}},Fe=Ls,Xa;(function(A){A[A.ERROR=3]="ERROR",A[A.INFO=6]="INFO",A[A.DEBUG=7]="DEBUG"})(Xa||(Xa={}));var ya=Xa;class ou{constructor(b,_,D){this.key=b,this.session=_,this.events=[],this.options=D||{},this.sent=0,this.uniqueID=0}log(b,_){b<=this.options.level&&(this.events.push(ae({},_,{timestamp:me.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ya.ERROR,b)}info(b){this.log(ya.INFO,b)}debug(b){this.log(ya.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,_){var D=ae({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],b(D,(I,ie)=>{I||this.sent++,_&&_(I,ie)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class An{constructor(b,_,D,I){this.name=b,this.priority=_,this.transport=D,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,_){if(this.isSupported()){if(this.priority{D||(ct(),ie?ie.close():I.close())},forceMinPriority:Bt=>{D||this.priority{var _="socket_id="+encodeURIComponent(A.socketId);for(var D in b.params)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return _};var Ns=A=>{if(typeof Fe.getAuthorizers()[A.transport]>"u")throw`'${A.transport}' is not a recognized auth transport`;return(b,_)=>{const D=ul(b,A);Fe.getAuthorizers()[A.transport](Fe,D,A,x.UserAuthentication,_)}};const lu=(A,b)=>{var _="socket_id="+encodeURIComponent(A.socketId);_+="&channel_name="+encodeURIComponent(A.channelName);for(var D in b.params)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return _};var uh=A=>{if(typeof Fe.getAuthorizers()[A.transport]>"u")throw`'${A.transport}' is not a recognized auth transport`;return(b,_)=>{const D=lu(b,A);Fe.getAuthorizers()[A.transport](Fe,D,A,x.ChannelAuthorization,_)}};const dh=(A,b,_)=>{const D={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(I,ie)=>{const ye=A.channel(I.channelName);_(ye,D).authorize(I.socketId,ie)}};function dl(A,b){let _={activityTimeout:A.activityTimeout||f.activityTimeout,cluster:A.cluster,httpPath:A.httpPath||f.httpPath,httpPort:A.httpPort||f.httpPort,httpsPort:A.httpsPort||f.httpsPort,pongTimeout:A.pongTimeout||f.pongTimeout,statsHost:A.statsHost||f.stats_host,unavailableTimeout:A.unavailableTimeout||f.unavailableTimeout,wsPath:A.wsPath||f.wsPath,wsPort:A.wsPort||f.wsPort,wssPort:A.wssPort||f.wssPort,enableStats:mh(A),httpHost:fh(A),useTLS:gh(A),wsHost:hh(A),userAuthenticator:cu(A),channelAuthorizer:bh(A,b)};return"disabledTransports"in A&&(_.disabledTransports=A.disabledTransports),"enabledTransports"in A&&(_.enabledTransports=A.enabledTransports),"ignoreNullOrigin"in A&&(_.ignoreNullOrigin=A.ignoreNullOrigin),"timelineParams"in A&&(_.timelineParams=A.timelineParams),"nacl"in A&&(_.nacl=A.nacl),_}function fh(A){return A.httpHost?A.httpHost:A.cluster?`sockjs-${A.cluster}.pusher.com`:f.httpHost}function hh(A){return A.wsHost?A.wsHost:ph(A.cluster)}function ph(A){return`ws-${A}.pusher.com`}function gh(A){return Fe.getProtocol()==="https:"?!0:A.forceTLS!==!1}function mh(A){return"enableStats"in A?A.enableStats:"disableStats"in A?!A.disableStats:!1}function cu(A){const b=Object.assign(Object.assign({},f.userAuthentication),A.userAuthentication);return"customHandler"in b&&b.customHandler!=null?b.customHandler:Ns(b)}function yh(A,b){let _;return"channelAuthorization"in A?_=Object.assign(Object.assign({},f.channelAuthorization),A.channelAuthorization):(_={transport:A.authTransport||f.authTransport,endpoint:A.authEndpoint||f.authEndpoint},"auth"in A&&("params"in A.auth&&(_.params=A.auth.params),"headers"in A.auth&&(_.headers=A.auth.headers)),"authorizer"in A&&(_.customHandler=dh(b,_,A.authorizer))),_}function bh(A,b){const _=yh(A,b);return"customHandler"in _&&_.customHandler!=null?_.customHandler:uh(_)}class vh extends J{constructor(b){super(function(_,D){St.debug(`No callbacks on watchlist events for ${_}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(_=>{this.emit(_.name,_)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var _=b.event;_==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function Sh(){let A,b;return{promise:new Promise((D,I)=>{A=D,b=I}),resolve:A,reject:b}}var fl=Sh;class wh extends J{constructor(b){super(function(_,D){St.debug("No callbacks on user for "+_)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(_,D)=>{if(_){St.warn(`Error during signin: ${_}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:D.auth,user_data:D.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:_,current:D})=>{_!=="connected"&&D==="connected"&&this._signin(),_==="connected"&&D!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new vh(b),this.pusher.connection.bind("message",_=>{var D=_.event;D==="pusher:signin_success"&&this._onSigninSuccess(_.data),this.serverToUserChannel&&this.serverToUserChannel.name===_.channel&&this.serverToUserChannel.handleEvent(_)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(b){try{this.user_data=JSON.parse(b.user_data)}catch{St.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){St.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=_=>{_.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.pusher.connection.state==="connected"&&_.subscribe()};this.serverToUserChannel=new As(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((_,D)=>{_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0||this.emit(_,D)}),b(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:b,resolve:_}=fl();b.done=!1;const D=()=>{b.done=!0};b.then(D).catch(D),this.signinDonePromise=b,this._signinDoneResolve=_}}class sn{static ready(){sn.isReady=!0;for(var b=0,_=sn.instances.length;b<_;b++)sn.instances[b].connect()}static getClientFeatures(){return Ge(un({ws:Fe.Transports.ws},function(b){return b.isSupported({})}))}constructor(b,_){uu(b),cl(_),this.key=b,this.config=dl(_,this),this.channels=Mr.createChannels(),this.global_emitter=new J,this.sessionID=Fe.randomInt(1e9),this.timeline=new ou(this.key,this.sessionID,{cluster:this.config.cluster,features:sn.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:ya.INFO,version:f.VERSION}),this.config.enableStats&&(this.timelineSender=Mr.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+Fe.TimelineTransport.name}));var D=I=>Fe.getDefaultStrategy(this.config,I,zi);this.connection=Mr.createConnectionManager(this.key,{getStrategy:D,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",I=>{var ie=I.event,ye=ie.indexOf("pusher_internal:")===0;if(I.channel){var Oe=this.channel(I.channel);Oe&&Oe.handleEvent(I)}ye||this.global_emitter.emit(I.event,I.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",I=>{St.warn(I)}),sn.instances.push(this),this.timeline.info({instances:sn.instances.length}),this.user=new wh(this),sn.isReady&&this.connect()}channel(b){return this.channels.find(b)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var b=this.connection.isUsingTLS(),_=this.timelineSender;this.timelineSenderTimer=new pe(6e4,function(){_.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,_,D){return this.global_emitter.bind(b,_,D),this}unbind(b,_,D){return this.global_emitter.unbind(b,_,D),this}bind_global(b){return this.global_emitter.bind_global(b),this}unbind_global(b){return this.global_emitter.unbind_global(b),this}unbind_all(b){return this.global_emitter.unbind_all(),this}subscribeAll(){var b;for(b in this.channels.channels)this.channels.channels.hasOwnProperty(b)&&this.subscribe(b)}subscribe(b){var _=this.channels.add(b,this);return _.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.connection.state==="connected"&&_.subscribe(),_}unsubscribe(b){var _=this.channels.find(b);_&&_.subscriptionPending?_.cancelSubscription():(_=this.channels.remove(b),_&&_.subscribed&&_.unsubscribe())}send_event(b,_,D){return this.connection.send_event(b,_,D)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}sn.instances=[],sn.isReady=!1,sn.logToConsole=!1,sn.Runtime=Fe,sn.ScriptReceivers=Fe.ScriptReceivers,sn.DependenciesReceivers=Fe.DependenciesReceivers,sn.auth_callbacks=Fe.auth_callbacks;var hl=r.default=sn;function uu(A){if(A==null)throw"You must pass your app key when you instantiate Pusher."}Fe.setup(sn)})])})})(Xf)),Xf.exports}var OA=DA();const Xy=aa(OA),zt=dt("WebSocketManager");class LA{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){zt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,zt.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){zt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(r)||80,d=i==="https";zt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=Xy;const f=localStorage.getItem("auth_token"),p={wsHost:n,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};zt.log("[WebSocketManager] Pusher 옵션:",p);const m=new Xy(e,p);m.connection.bind("connecting",()=>{zt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{zt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{zt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{zt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{zt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{zt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{zt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),zt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new RA({broadcaster:"reverb",client:m}),zt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,zt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return zt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return zt.log(`[WebSocketManager] 이미 구독 중: ${c}`),c;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,r),this.subscriptions.set(c,d),zt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){zt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),zt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),zt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,zt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Vc=new LA,gt=dt("DataSourceManager"),Jy=new Tn;function Kc(s,e){const n=Ma(s);if(n!==null)try{return On(n)?Jy.evaluatePipeExpression(n,e,{skipCache:!0}):Jy.evaluateExpression(n,e)}catch(r){return gt.error("Failed to evaluate param expression:",n,r),s}return ls(s,e,{skipCache:!0})}function Qy(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function $A(){try{return window.G7Core?.devTools}catch{return}}const Zc=class Zc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new Tn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Kc(c,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}os({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(os({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return gt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){gt.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(p=>(d||p.auto_fetch!==!1)&&p.type!=="websocket");return await Promise.all(f.map(async p=>{try{const m=await this.fetchDataSource(p,n,r,i,l);c[p.id]=m,this.dataCache.set(p.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(p,m);if(y!==null){const C={status:y,message:`Error condition matched for ${p.id}`,data:m},S=Tr(),v=S.resolve(y,{errorHandling:p.errorHandling,onError:p.onError});if(v.handler)try{await S.execute(v.handler,C)}catch(x){gt.error(`Error executing errorCondition handler for ${p.id}:`,x)}p.fallback!==void 0&&(c[p.id]=p.fallback,this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${p.id} (errorCondition)`));return}if(p.onSuccess)try{const C={data:m,sourceId:p.id};await this.executeOnSuccessHandler(p.onSuccess,C)}catch(C){gt.error(`Error executing onSuccess handler for ${p.id}:`,C)}}catch(m){gt.error(`Failed to fetch data source: ${p.id}`,m);const y=m?.response?.status||m?.status||500,C=m?.response?.data,S=C?.message||m.message||"Unknown error",v={status:y,message:S,errors:C?.errors,data:C,statusText:m?.response?.statusText},x=Tr(),w=x.resolve(y,{errorHandling:p.errorHandling,onError:p.onError});if(w.handler)try{await x.execute(w.handler,v)}catch(R){gt.error(`Error executing error handler for ${p.id}:`,R)}p.fallback!==void 0&&(c[p.id]=p.fallback,this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${p.id}`)),this.options.onError&&this.options.onError(m,p)}})),c}async fetchDataSourcesWithResults(e,n={},r=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");gt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=c?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const y=await this.fetchDataSource(m,n,r,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const C=this.checkErrorCondition(m,y);if(C!==null){const S={status:C,message:`Error condition matched for ${m.id}`,data:y},v=Tr(),x=v.resolve(C,{errorHandling:m.errorHandling,onError:m.onError});let w=!1;if(x.handler)if(m.loading_strategy==="blocking")v.execute(x.handler,S).catch(R=>{gt.error(`Error executing errorCondition handler for ${m.id}:`,R)}),w=!0;else try{await v.execute(x.handler,S),w=!0}catch(R){gt.error(`Error executing errorCondition handler for ${m.id}:`,R)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${C}`),errorCode:C,errorHandled:w}}if(m.onSuccess)try{const S={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){gt.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:y}}catch(y){gt.error(`Failed to fetch data source: ${m.id}`,y);const C=y?.response?.status||y?.status||500,S=y?.response?.data,v=S?.message||y.message||"Unknown error",x={status:C,message:v,errors:S?.errors,data:S,statusText:y?.response?.statusText},w=Tr(),R=w.resolve(C,{errorHandling:m.errorHandling,onError:m.onError});let L=!1;if(R.handler)if(m.loading_strategy==="blocking")w.execute(R.handler,x).catch(O=>{gt.error(`Error executing error handler for ${m.id}:`,O)}),L=!0;else try{await w.execute(R.handler,x),L=!0}catch(O){gt.error(`Error executing error handler for ${m.id}:`,O)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(y,m),{id:m.id,state:"error",error:y,errorCode:C,errorHandled:L})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,r).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const p={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Tr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,p)}catch(C){gt.error(`Error executing errorCondition handler for ${c.id}:`,C)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const p={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,p)}catch(p){gt.error(`Error executing onSuccess handler for ${c.id}:`,p)}i&&i(c.id,d)}).catch(async d=>{gt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,p=d?.response?.data,m=p?.message||d.message||"Unknown error",y={status:f,message:m,errors:p?.errors,data:p,statusText:d?.response?.statusText},C=Tr(),S=C.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await C.execute(S.handler,y)}catch(v){gt.error(`Error executing error handler for ${c.id}:`,v)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${c.id}`),i&&i(c.id,c.fallback);return}this.options.onError&&this.options.onError(d,c)})})}async fetchDataSource(e,n,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Qy(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const c={route:n,query:Qy(r)};i&&(c._global=i),l&&(c._local=l);let d=ls(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?ls(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([v,x])=>{typeof x=="string"&&(y[v]=Kc(x,c))}),Object.keys(y).forEach(v=>{y[v]===""&&delete y[v]});const C=$A();let S=null;if(C?.isEnabled()){C.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let v=d;if(f==="GET"&&Object.keys(y).length>0){const x=new URLSearchParams;Object.entries(y).forEach(([R,L])=>{Array.isArray(L)?L.forEach(O=>x.append(R,String(O))):L!=null&&x.append(R,String(L))});const w=x.toString();v=w?`${d}?${w}`:d}S=C.trackRequest(v,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),C.trackDataSourceLoading(e.id)}try{let v;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),w=Yn.getInstance().isAuthenticated();if(x==="required"&&!w){gt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),C?.isEnabled()&&(C.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&C.failRequest(S,"Skipped: not authenticated"));const L=new Error("Auth required but not authenticated");throw L.response={status:401,statusText:"Unauthorized",data:null},L.status=401,L._authSkipped=!0,L}const R=x==="required"||x==="optional"&&w;if(R){const L=Wn(),O=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&>.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${O}`);const j=this.getMatchingGlobalHeaders(d,c),F={};e.headers&&Object.entries(e.headers).forEach(([he,Ee])=>{const ke=Kc(Ee,c);ke!=null&&ke!==""&&(F[he]=String(ke))});const G={...j,...F},P=Object.keys(G).length>0,K=m?this.toFormData(y):y;switch(f){case"GET":v=await L.get(O,{params:y,...P&&{headers:G}});break;case"POST":P?v=await L.post(O,K,{headers:G}):v=await L.post(O,K);break;case"PUT":P?v=await L.put(O,K,{headers:G}):v=await L.put(O,K);break;case"PATCH":P?v=await L.patch(O,K,{headers:G}):v=await L.patch(O,K);break;case"DELETE":v=await L.delete(O,{params:y,...P&&{headers:G}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let L=d;if(f==="GET"){const K=new URLSearchParams(y).toString();L=K?`${d}?${K}`:d}const O={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const K=localStorage.getItem("g7_locale");K&&(O["Accept-Language"]=K)}const j=this.getMatchingGlobalHeaders(d,c);Object.assign(O,j),e.headers&&Object.entries(e.headers).forEach(([K,he])=>{const Ee=Kc(he,c);Ee!=null&&Ee!==""&&(O[K]=String(Ee))});let F;f!=="GET"&&(m?(F=this.toFormData(y),delete O["Content-Type"]):F=JSON.stringify(y));const G=await fetch(L,{method:f,headers:O,body:F});let P;try{P=await G.json()}catch{P=null}if(S&&C?.isEnabled()&&(C.completeRequest(S,G.status,P),S=null),!G.ok){C?.isEnabled()&&C.trackDataSourceError(e.id,`HTTP ${G.status}: ${G.statusText}`);const K=new Error(`HTTP error! status: ${G.status}`);throw K.response={status:G.status,statusText:G.statusText,data:P},K.status=G.status,K}v=P,C?.isEnabled()&&C.trackDataSourceLoaded(e.id,v)}return R&&S&&C?.isEnabled()&&(C.completeRequest(S,200,v),C.trackDataSourceLoaded(e.id,v)),v}catch(v){if(S&&C?.isEnabled()){const x=v;x?.response?C.completeRequest(S,x.response.status,x.response.data):C.failRequest(S,v instanceof Error?v.message:String(v)),C.trackDataSourceError(e.id,v instanceof Error?v.message:String(v))}throw v}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Zc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){gt.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=ls(c.channel,r,{skipCache:!0}),f=ls(c.event,r,{skipCache:!0})}catch(y){gt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const p=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(p(d)||p(f)){gt.warn(`WebSocket source ${c.id} has invalid channel/event after expression resolution, skipping. Original channel="${c.channel}", resolved="${d}". Original event="${c.event}", resolved="${f}". Available context keys: [${Object.keys(r).join(", ")}]`);return}const m=Vc.subscribe(d,f,y=>{const C=c.target_source||c.id;this.dataCache.set(C,{data:y,timestamp:Date.now()}),n(C,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Vc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??Wm();if(!r){gt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw gt.error("Failed to execute onSuccess handler:",c),c}}};$(Zc,"DATA_CACHE_TTL",3e5);let Dr=Zc;const MA=new Dr,Ri=dt("ModalDataSourceWrapper");function NA(s,e){if(!s||!e)return s;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,p=[];d&&p.push(d);const m=f.match(/\[\d+\]/g);return m&&p.push(...m),p}return[l]}).filter(l=>l!=="");let i=s;for(const l of r){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const c=parseInt(l.slice(1,-1),10);i=i[c]}else i=i[l]}return i}const Zy=({isOpen:s,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,p]=M.useState(!1),[m,y]=M.useState(!1),C=M.useRef(!1),S=M.useRef(null);S.current||(S.current=new Dr);const v=M.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){p(!0);try{const x=r.route||{},w=new URLSearchParams(window.location.search),R=n.map(O=>{let j={...O};if(O.endpoint&&l){const F=l.resolveBindings(O.endpoint,r,{skipCache:!0});j.endpoint=F}if(O.params&&l){const F={};Object.entries(O.params).forEach(([G,P])=>{typeof P=="string"?F[G]=l.resolveBindings(P,r,{skipCache:!0}):F[G]=P}),j.params=F}return j});c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,R.map(O=>({id:O.id,endpoint:O.endpoint})));const L=await S.current.fetchDataSourcesWithResults(R,x,w);i&&L.forEach(O=>{if(O.state==="success"&&O.data!==void 0){const j=R.find(F=>F.id===O.id);if(j?.initGlobal){const F=O.data?.data??O.data,G=Array.isArray(j.initGlobal)?j.initGlobal:[j.initGlobal];for(const P of G)if(typeof P=="string")i({[P]:F}),c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${O.id}.data -> _global.${P}`);else if(typeof P=="object"&&P.key){const{key:K,path:he}=P,Ee=he?NA(F,he):F;i({[K]:Ee}),c&&Ri.log(`Modal "${e}" initGlobal: ${O.id}.data${he?"."+he:""} -> _global.${K}`)}}}else O.state==="error"&&Ri.error(`Modal "${e}" data source error:`,O.id,O.error)}),c&&Ri.log(`Modal "${e}" data sources fetched successfully`)}catch(x){Ri.error(`Modal "${e}" data source fetch error:`,x)}finally{p(!1),y(!0)}}},[n,r,i,l,e,c]);return M.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),M.useEffect(()=>{!s&&C.current&&(y(!1),c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),s&&!C.current&&n&&n.length>0&&!m&&v(),C.current=s},[s,n,m,v,e,c]),ft.jsx(ft.Fragment,{children:d})};class Wc extends Error{constructor(n,r,i={}){super(r);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(n,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class IA extends Wc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function eb(s){if(s instanceof Wc)return s;if(s instanceof Error){const e=new Wc("TEMPLATE_INIT_ERROR",s.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=s.stack,e}return new Wc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const jA=dt("ErrorDisplay");class Jf{static render(e,n){const r=document.getElementById(e);if(!r){jA.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` display: flex; align-items: center; justify-content: center; min-height: 100vh; background-color: ${l?"#111827":"#f9fafb"}; padding: 1rem; font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; `,card:` max-width: 28rem; width: 100%; background-color: ${l?"#1f2937":"#ffffff"}; border-radius: 0.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); padding: 2rem; text-align: center; `,iconContainer:` margin-bottom: 1.5rem; `,icon:` font-size: 4rem; color: #ef4444; `,title:` font-size: 1.5rem; font-weight: 700; color: ${l?"#ffffff":"#111827"}; margin-bottom: 1rem; `,message:` color: ${l?"#d1d5db":"#4b5563"}; margin-bottom: 0.5rem; line-height: 1.625; `,detailMessage:` font-size: 0.875rem; color: ${l?"#9ca3af":"#6b7280"}; margin-bottom: 1.5rem; background-color: ${l?"#374151":"#f3f4f6"}; padding: 0.5rem 0.75rem; border-radius: 0.25rem; `,spacer:` margin-bottom: 1.5rem; `,stackContainer:` margin-top: 1.5rem; padding: 1rem; background-color: ${l?"#374151":"#f3f4f6"}; border-radius: 0.375rem; text-align: left; `,stackTitle:` font-size: 0.875rem; font-weight: 600; color: ${l?"#e5e7eb":"#374151"}; margin-bottom: 0.5rem; `,stackTrace:` font-size: 0.75rem; color: ${l?"#d1d5db":"#4b5563"}; overflow-x: auto; white-space: pre-wrap; word-break: break-word; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; `,buttonContainer:` margin-top: 1.5rem; `,button:` display: inline-flex; align-items: center; padding: 0.75rem 1.5rem; background-color: #2563eb; color: #ffffff; font-weight: 500; border-radius: 0.375rem; border: none; cursor: pointer; transition: background-color 0.2s; `};r.innerHTML=`

${this.escapeHtml(n.title)}

${this.escapeHtml(n.message)}

${n.detailMessage?`

${this.escapeHtml(n.detailMessage)}

`:`
`} ${i?`

Stack Trace:

${this.escapeHtml(n.stackTrace)}
`:""} ${n.showReloadButton?`
`:""}
`}static renderFromError(e,n,r,i=!1,l,c,d){let f,p;if(n.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?p=m.details.apiMessage:m.response?.data?.message&&(p=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:p,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const bs=dt("Router");class zA{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Pr(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,bs.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw bs.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,bs.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,p)=>(r.push(p),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=n.match(l);if(!c)return null;const d={};return r.forEach((f,p)=>{d[f]=c[p+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,r=this.match(e);if(!r){bs.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){bs.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const c=this.getAuthType(r.route,e),d=Yn.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const p=d.getLoginRedirectUrl(c,e+n);bs.log(`Not authenticated, redirecting to: ${p}`),window.location.href=p;return}}const i=new URLSearchParams(n),l={};for(const c of i.keys()){if(c in l)continue;const d=i.getAll(c);d.length>1?l[c]=d:d.length===1&&(c.endsWith("[]")?l[c]=d:l[c]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const n=this.pendingNavigation;this.executeNavigation(n)}}}}const HA=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function tb(s){const e=HA.exec(s);return e?{templateIdentifier:e[1]}:null}const Ht=dt("ErrorPageHandler");class UA{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(Pr(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Ht.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Ht.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Ht.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Ht.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Ht.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Ht.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Ht.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Ht.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Ht.error(`Failed to load error layout: ${i}`),!1;this.debug&&Ht.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Ht.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),y=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),C=[...m,...y];if(C.length>0)try{c=await this.dataSourceManager.fetchDataSources(C,{},new URLSearchParams),this.debug&&Ht.log("Data sources fetched:",Object.keys(c))}catch(S){Ht.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Ht.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const p={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:p,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Ht.log(`Error page ${e} rendered successfully`),!0}catch(r){return Ht.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){for(const i of e){const l=n[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=c,Ht.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;r[d]=f?this.getValueByPath(c,f):c,Ht.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=c,Ht.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:p,path:m}=f;this.globalState[p]=m?this.getValueByPath(c,m):c,Ht.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${p}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Ht.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Ht.log("Config cache cleared")}}const Yc=dt("AssetFailureNotice"),nb="g7-asset-failure-notice",PA="g7-system-banners",Kr=new Map;let vs=!1,Xc=!1,qo=null;function Di(s,e,n){try{const r=window?.G7Core?.t;if(typeof r=="function"){const i=r(s,n);if(typeof i=="string"&&i!==s&&!i.startsWith("core.assets."))return i}}catch{}return BA(e,n)}function BA(s,e){return e?Object.entries(e).reduce((n,[r,i])=>n.split("{"+r+"}").join(String(i)),s):s}function Ss(s){!s||!s.id||(Kr.set(s.id,s),Xc=!1,Yc.warn(`Asset failure notified: ${s.id} (${s.label})`),ws())}function rb(s){Kr.delete(s)&&(Yc.log(`Asset failure cleared: ${s}`),ws())}function ab(){Kr.size!==0&&(Kr.clear(),ws())}function qA(){return Array.from(Kr.values())}function ib(s,e,n){return Di(s,e,n)}async function sb(){if(vs)return;vs=!0,Xc=!1,ws();const s=Array.from(Kr.values()).filter(n=>typeof n.retry=="function");let e=!1;for(const n of s)try{await n.retry(),Kr.delete(n.id)}catch(r){e=!0,Yc.warn(`Asset retry failed: ${n.id}`,r)}vs=!1,Xc=e,ws()}function GA(){try{return document.documentElement.classList.contains("dark")}catch{return!1}}function ws(){if(typeof document>"u"||!document.body)return;const s=document.getElementById(nb);if(Kr.size===0){s?.remove(),JA();return}const e=s??FA();VA(e),e.replaceChildren(KA()),XA()}function FA(){const s=document.createElement("div");return s.id=nb,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),document.body.appendChild(s),s}function VA(s){const n=document.getElementById(PA)?.offsetHeight??0;s.style.cssText=["position:fixed",`top:${n}px`,"left:0","right:0","z-index:9998","display:flex","justify-content:center","pointer-events:none"].join(";")}function KA(){const s=GA(),e=Array.from(Kr.values()),n=typeof window<"u"&&window.innerWidth<768,r=document.createElement("div");return r.style.cssText=["pointer-events:auto","box-sizing:border-box","width:100%","max-width:960px","margin:8px","padding:12px 16px","border-radius:8px",`border:1px solid ${s?"#78350f":"#fcd34d"}`,`background:${s?"#451a03":"#fffbeb"}`,`color:${s?"#fef3c7":"#78350f"}`,"box-shadow:0 4px 12px rgba(0,0,0,0.12)","font-size:14px","line-height:1.5","display:flex",n?"flex-direction:column":"flex-direction:row",n?"align-items:stretch":"align-items:center","gap:12px"].join(";"),r.style.background=s?"#451a03":"#fffbeb",r.style.color=s?"#fef3c7":"#78350f",r.style.borderColor=s?"#78350f":"#fcd34d",r.appendChild(WA(e,n)),r.appendChild(YA(e,n,s)),r}function WA(s,e){const n=document.createElement("div");n.style.cssText=["flex:1 1 auto","min-width:0","display:flex","gap:8px"].join(";");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⚠",r.style.cssText="flex:0 0 auto;font-size:16px;line-height:1.4",n.appendChild(r);const i=document.createElement("div");if(i.style.cssText="flex:1 1 auto;min-width:0",s.length===1){const l=s[0],c=document.createElement("div");c.setAttribute("data-asset-failure-id",l.id),c.textContent=l.message??Di("core.assets.load_failed","{label}을(를) 불러오지 못했습니다.",{label:l.label}),i.appendChild(c)}else{const l=document.createElement("div");l.style.cssText="font-weight:600",l.textContent=Di("core.assets.load_failed_multiple","{count}개 항목을 불러오지 못했습니다.",{count:s.length}),i.appendChild(l);const c=document.createElement("div");c.style.cssText="margin-top:2px;opacity:0.9;word-break:break-word",c.textContent=s.map(d=>d.label).join(", "),i.appendChild(c)}if(Xc){const l=document.createElement("div");l.style.cssText="margin-top:4px;font-weight:600",l.textContent=Di("core.assets.retry_failed","다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요."),i.appendChild(l)}return n.appendChild(i),e&&(n.style.alignItems="flex-start"),n}function YA(s,e,n){const r=document.createElement("div");if(r.style.cssText=["flex:0 0 auto","display:flex","gap:8px",e?"width:100%":"","align-items:center"].filter(Boolean).join(";"),s.some(c=>typeof c.retry=="function")){const c=document.createElement("button");c.type="button",c.dataset.action="retry",c.disabled=vs,c.textContent=vs?Di("core.assets.retrying","다시 시도 중..."):Di("core.assets.retry","다시 시도"),c.style.cssText=[e?"flex:1 1 auto":"","padding:6px 14px","border-radius:6px","font-size:14px","font-weight:600","cursor:pointer",`border:1px solid ${n?"#b45309":"#d97706"}`,`background:${n?"#b45309":"#f59e0b"}`,`color:${n?"#fffbeb":"#451a03"}`,vs?"opacity:0.6":""].filter(Boolean).join(";"),c.addEventListener("click",()=>{sb()}),r.appendChild(c)}const l=document.createElement("button");return l.type="button",l.dataset.action="close",l.setAttribute("aria-label",Di("core.assets.close","닫기")),l.textContent="✕",l.style.cssText=["padding:6px 10px","border-radius:6px","font-size:14px","cursor:pointer","border:1px solid transparent","background:transparent",`color:${n?"#fef3c7":"#78350f"}`].join(";"),l.addEventListener("click",()=>{ab()}),r.appendChild(l),r}function XA(){qo||typeof MutationObserver>"u"||(qo=new MutationObserver(()=>{Kr.size>0&&ws()}),qo.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function JA(){qo?.disconnect(),qo=null}function QA(){const s=window,e=r=>({id:String(r?.id??""),label:String(r?.label??r?.url??"asset"),retry:typeof r?.retry=="function"?r.retry:void 0}),n=Array.isArray(s.__g7ExternalAssetFailures)?s.__g7ExternalAssetFailures:[];n.forEach(r=>{r?.id&&Ss(e(r))}),s.__g7ExternalAssetSink=r=>{r?.id&&Ss(e(r))},Yc.log(`템플릿 externals 실패 대기열 ${n.length}건 반영`)}const Et=dt("ModuleAssetLoader");function ZA(s){return s==="plugin"?ib("core.assets.plugin_styles","플러그인 스타일"):ib("core.assets.module_styles","모듈 스타일")}class ex{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set);$(this,"failedCssAssets",new Set)}getFailedCssAssets(){return[...this.failedCssAssets]}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Et.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Et.log("Loading module assets:",n.map(d=>d.identifier));const r=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Et.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Et.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Et.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadCustomAssets(){const e=tx();if(e.length!==0)for(const n of e){const r=`g7-custom-${n.type}-${nx(n.id)}`;if(document.getElementById(r))continue;const i=`${n.type==="style"?"custom CSS":"custom JS"}: ${n.id}`,l=(d,f)=>n.type==="style"?sa(xn(d),{id:r},{label:i,retries:f}):Cr(xn(d),{id:r},{label:i,retries:f}),c=Dd(n.url);try{if(c!==null)try{await l(n.url,0)}catch{Et.warn(`Custom asset static miss, falling back to API: ${n.id} (${n.url} -> ${c})`),await l(c)}else await l(n.url);Et.log(`Custom asset loaded: ${n.id}`)}catch(d){Et.warn(`Failed to load custom asset: ${n.id} (${n.url})`,d),Ss({id:`custom-asset:${n.id}`,label:n.id.split(":").pop()??n.id,retry:async()=>{document.getElementById(r)?.remove(),await l(c??n.url)}})}}}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Et.log(`Bundle CSS already loaded: ${e}`);return}const i=Dd(n);try{if(i!==null)try{await sa(n,{id:r},{label:`bundle CSS: ${e}`,retries:0})}catch{Et.warn(`Bundle CSS static miss, falling back to API: ${e} (${n} -> ${i})`),await sa(xn(i),{id:r},{label:`bundle CSS: ${e}`})}else await sa(n,{id:r},{label:`bundle CSS: ${e}`});Et.log(`Bundle CSS loaded: ${e}`);const l=document.getElementById(r);l&&this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l})}catch(l){this.surfaceCssFailure(`bundle-${e}`,ZA(e),i!==null?xn(i):n,l)}}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Et.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Et.log(`Bundle JS already loading: ${e}`),i;const l=Dd(n),d=(l!==null?Cr(n,{id:r},{label:`bundle JS: ${e}`,retries:0}).catch(()=>(Et.warn(`Bundle JS static miss, falling back to API: ${e} (${n} -> ${l})`),Cr(xn(l),{id:r},{label:`bundle JS: ${e}`}))):Cr(n,{id:r},{label:`bundle JS: ${e}`})).then(()=>{Et.log(`Bundle JS loaded: ${e}`);const f=document.getElementById(r);f&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:f}),this.loadingPromises.delete(r)}).catch(f=>{throw Et.warn(`Failed to load bundle JS: ${e} (${n})`,f),this.failedJsAssets.add(e),this.loadingPromises.delete(r),f});return this.loadingPromises.set(r,d),d}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Et.log(`CSS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Et.log(`CSS already loading: ${e}`),i;const l=sa(n,{id:r},{label:`CSS: ${e}`}).then(()=>{Et.log(`CSS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"css",element:c}),this.loadingPromises.delete(r)}).catch(c=>{this.loadingPromises.delete(r),this.surfaceCssFailure(e,e,n,c)});return this.loadingPromises.set(r,l),l}surfaceCssFailure(e,n,r,i){Et.warn(`Failed to load CSS after retries: ${e} (${r})`,i),this.failedCssAssets.add(e),Ss({id:`ext-css:${e}`,label:n,retry:async()=>{document.getElementById(`module-css-${e}`)?.remove(),document.getElementById(`ext-bundle-css-${e.replace(/^bundle-/,"")}`)?.remove(),await sa(r,{},{label:`CSS retry: ${e}`}),this.failedCssAssets.delete(e)}})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Et.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Et.log(`JS already loading: ${e}`),i;const l=Cr(n,{id:r},{label:`JS: ${e}`}).then(()=>{Et.log(`JS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Et.warn(`Failed to load JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Et.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Et.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Et.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Et.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let Qf=null;function tx(){const s=window?.G7Config?.customAssets;return Array.isArray(s)?s.filter(e=>e&&typeof e.id=="string"&&typeof e.url=="string"&&(e.type==="style"||e.type==="script")):[]}function nx(s){return s.replace(/[^A-Za-z0-9_-]/g,"-")}function Zf(){return Qf||(Qf=new ex),Qf}function rx(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(s.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?xn(i.js):i.js,css:i.css?xn(i.css):i.css,priority:i.priority,external:i.external})}return e}function ax(){if(typeof window>"u")return null;const s=window.G7Config;if(!s?.bundleUrls)return null;const e=s.bundleUrls;return{moduleJs:e.moduleJs?xn(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?xn(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?xn(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?xn(e.pluginCss):e.pluginCss}}function ix(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(s.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?xn(i.js):i.js,css:i.css?xn(i.css):i.css,priority:i.priority,external:i.external})}return e}const eh=dt("SystemBannerManager");class Jc{static show(e){this.banners.set(e.id,e),this.render(),eh.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),eh.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),eh.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}$(Jc,"banners",new Map),$(Jc,"containerId","g7-system-banners");const U=dt("TemplateApp");function ob(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Lr=class Lr{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"failedLayoutScripts",new Set);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,U.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,U.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,U.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,U.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new Tn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=n.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(U.warn("Route expression resolution failed, using fallback:",c),l.path=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const c=l.redirect;l.redirect=n.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(U.warn("Route redirect expression resolution failed:",c),l.redirect=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const r=localStorage.getItem(n);r&&r!==localStorage.getItem(Lr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Lr.LOCALE_STORAGE_KEY,r),U.log(`Migrated locale from '${n}' to '${Lr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){U.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{ho.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),Ww();const e=Er.getInstance(),n=Yn.getInstance(),r=typeof window<"u"&&Number(window.G7Config?.cache_version)||0,i=r>0?r:this.loadCacheVersionFromStorage()||0,[l,c,d,f,p]=await Promise.all([Yo({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:i}),e.loadComponents(this.config.templateId,this.config.templateType,i),ic(i>0?po(`templates/${this.config.templateId}/routes.json`,i):null,Pr(`/api/templates/${this.config.templateId}/routes`,"json",i>0?i:null),{label:"routes.json"}).then(w=>{if(!w.ok)throw new Error(`Failed to load routes: ${w.statusText}`);return w.json()}).then(w=>{if(!w.success)throw new Error("Failed to load routes from API");return w.data}).catch(w=>{throw U.error("Error loading routes:",w),w}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Pr(`/api/templates/${this.config.templateId}/config`,"json")).then(w=>w.ok?w.json():null).then(w=>!w?.success||!w?.data?null:w.data).catch(w=>(U.warn("Error loading template config:",w),null))]);if(U.log("Template Engine initialized"),U.log("ComponentRegistry loaded"),U.log("Routes data loaded"),U.log("User info preloaded"),U.log("Template config loaded:",p),p?.cache_version!==void 0){const w=i>0?i:null;if(this.extensionCacheVersion=p.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),U.log("Extension cache version:",this.extensionCacheVersion),w!==null&&w!==this.extensionCacheVersion){U.log("Cache version changed, reloading routes...");const R=await ic(po(`templates/${this.config.templateId}/routes.json`,this.extensionCacheVersion),Pr(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(L=>{if(!L.ok)throw new Error(`Failed to reload routes: ${L.statusText}`);return L.json()}).then(L=>{if(!L.success)throw new Error("Failed to reload routes from API");return L.data});Array.isArray(R.routes)&&(R.routes=this.resolveRouteExpressions(R.routes),Object.assign(d,R),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>$g),O=L.getInstance();O.setCacheVersion(this.extensionCacheVersion);const j=this.config.locale||"ko",F="en";await O.loadTranslations(this.config.templateId,j,"/api",!0),j!==F&&await O.loadTranslations(this.config.templateId,F,"/api",!0),U.log("Translations reloaded with new cache version")}catch(L){U.error("Failed to reload translations:",L)}}}p?.errorHandling&&(this.templateErrorHandling=p.errorHandling,Tr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{U.log("User logged out")}),n.on("authStateChange",w=>{U.log("Auth state changed:",w)}),U.log("AuthManager event handlers registered");const m=Wn(),y=this.config.templateType==="admin"?"admin":"user",C=n.getConfig(y);m.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),m.removeToken();const w=window.location.pathname+window.location.search,R=n.getLoginRedirectUrl(y,w,"session_expired");window.location.href=R}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new Gf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Dr({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new UA({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Es,dataSourceManager:S,globalState:this.globalState}),U.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){U.log("Server error handled, skipping normal initialization");return}if(this.router=new zA(this.config.templateId),Array.isArray(d.routes)){const w=this.resolveRouteExpressions(d.routes);this.router.setRoutes(w)}else throw new Error("Invalid routes data format");U.log("Router initialized:",this.router),U.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:v}=await Promise.resolve().then(()=>Wr),x=v();if(x&&(x.setDefaultContext({navigate:w=>this.router?.navigate(w)}),x.setGlobalStateUpdater((w,R)=>this.setGlobalState(w,R)),U.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",w=>this.handleRouteChange(w)),this.router.on("routeNotFound",w=>this.handleRouteNotFound(w)),typeof window<"u"&&tb(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await Es({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),U.log("Template App initialized successfully")}catch(e){U.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=Zf(),n=ax();if(!n){await this.loadExtensionAssetsIndividually(),await e.loadCustomAssets();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),await e.loadCustomAssets(),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=Zf(),n=rx();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=ix();r.length>0&&(U.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const n=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(U.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=Tr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},p=new URLSearchParams;for(const[Z,ge]of Object.entries(f))if(Array.isArray(ge))for(const z of ge)p.append(Z,z);else p.set(Z,ge);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:y,getActionDispatcher:C}=await Promise.resolve().then(()=>Wr),S=new y;if(i){const Z=C();Z&&Z.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Jc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),U.log("Preview mode activated")}else{const Z=C();Z?.isPreviewMode()&&(Z.setPreviewMode(!1),Jc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const Z=C();Z&&Z.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(ge=>ge.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const Z=C();Z&&Z.setNamedActions(l.named_actions)}const v=S.filterByCondition(d,m);d.length!==v.length&&U.log("Data sources filtered by condition:",{before:d.map(Z=>Z.id),after:v.map(Z=>Z.id)});const x=v.filter(Z=>Z.loading_strategy==="blocking"),w=v.filter(Z=>(Z.loading_strategy||"progressive")!=="blocking"&&Z.type!=="websocket"),R=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],L=R.length>0&&v.some(Z=>R.includes(Z.id)&&Z.type!=="websocket"&&(Z.loading_strategy||"progressive")!=="background");if((x.length>0||L)&&l.transition_overlay){const Z=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;Z.enabled&&Z.style==="skeleton"&&Z.skeleton?.component&&Z.target?this.renderSkeletonOverlay(Z.target,Z.skeleton,l,Z.fallback_target):Z.enabled&&Z.style==="spinner"&&Z.target&&this.renderSpinnerOverlay(Z.target,Z.spinner,Z.fallback_target)}let O={},j={},F={},G={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=v,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=p,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,p.toString()),x.length>0&&(U.log("Fetching blocking data sources:",x.map(ge=>ge.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},p)).forEach(ge=>{if(ge.state==="success"&&ge.data!==void 0)O[ge.id]=ge.data;else if(ge.state==="error"&&ge.error){const z=ge.error,T=z.response?.data?.message;j[ge.id]={message:T||ge.error.message,status:z.response?.status||z.status}}}),this.processInitOptions(x,O,F,G),this.currentFetchedData={...O},U.log("Blocking data loaded:",Object.keys(O)),Object.keys(j).length>0&&U.log("Data source errors:",j),Object.keys(F).length>0&&U.log("Local state init (blocking):",Object.keys(F)),Object.keys(G).length>0&&U.log("Isolated state init (blocking):",Object.keys(G)));const P=w.length>0;if(P&&(Gr.setPending(!0),U.log("Transition started before rendering")),n!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:K}=await Promise.resolve().then(()=>Wr),he=K().currentDataContext||{},Ee=w.map(Z=>Z.id),ke={};if(P){Ee.forEach(ge=>{he[ge]!==void 0?ke[ge]=he[ge]:ke[ge]=void 0});const Z=Object.keys(ke).filter(ge=>ke[ge]!==void 0);Z.length>0&&U.log("Preserving previous progressive data:",Z),U.log("Progressive data sources initialized:",Ee)}const ze=l.defines||{},Be={...ke,...e.params,...O,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:Z=>this.setGlobalState(Z),_dataSourceErrors:Object.keys(j).length>0?j:void 0,_localInit:Object.keys(F).length>0?F:void 0,_isolatedInit:Object.keys(G).length>0?G:void 0,_defines:Object.keys(ze).length>0?ze:void 0};if(l.computed&&Object.keys(l.computed).length>0){const Z=this.calculateComputed(l.computed,Be);Object.keys(Z).length>0&&(Be._computed=Z,this.globalState._computed=Z,U.log("Computed values calculated:",Object.keys(Z))),Be._computedDefinitions=l.computed}const je=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==je&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:je}),this.globalState._local={},eE()),this.currentLayoutName=je;const X=l.initLocal||l.state;if(X&&Object.keys(X).length>0){this.globalState._local||(this.globalState._local={});for(const[Z,ge]of Object.entries(X))this.globalState._local[Z]===void 0&&(this.globalState._local[Z]=JSON.parse(JSON.stringify(ge)));Be._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(X))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[Z,ge]of Object.entries(l.initGlobal))this.globalState[Z]===void 0&&(this.globalState[Z]=JSON.parse(JSON.stringify(ge)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[Z,ge]of Object.entries(l.initIsolated))G[Z]===void 0&&(G[Z]=JSON.parse(JSON.stringify(ge)));U.log("initIsolated applied:",Object.keys(l.initIsolated))}Be._global={...this.globalState,layoutWarnings:l.warnings||[]};const de=l.initActions||l.init_actions;if(de&&de.length>0){await this.executeInitActions(de,Be),U.log("initActions executed before render");const Z=this.globalState;if(Z._local){if(Object.keys(F).length>0){for(const[ge,z]of Object.entries(F))Z._local[ge]!==void 0?Z._local[ge]=this.deepMerge(Z._local[ge],z):Z._local[ge]=z;U.log("localInit merged into _local after initActions:",Object.keys(F))}Be._local=Z._local,U.log("_local merged into dataContext:",Z._local)}if(Be._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const ge=this.calculateComputed(l.computed,Be);Object.keys(ge).length>0&&(Be._computed=ge,this.globalState._computed=ge,U.log("Computed values recalculated after init_actions:",Object.keys(ge)))}if(Object.keys(this.currentFetchedData).length>0){for(const[ge,z]of Object.entries(this.currentFetchedData))Be[ge]=z;U.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await Es({containerId:"app",layoutJson:l,dataContext:Be,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),w.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Gr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",w.map(z=>z.id));const{updateTemplateData:Z,getState:ge}=await Promise.resolve().then(()=>Wr);try{const z=w.map(async T=>{try{const fe=(await S.fetchDataSourcesWithResults([T],e.params||{},p,this.globalState))[0];if(!fe){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(fe.state==="success"&&fe.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=fe.data;const me={};this.processInitOptions([T],{[T.id]:fe.data},me);const ae=ge();if(ae.bindingEngine){const Pe=[T.id];T.initGlobal&&Pe.push("_global"),T.initLocal&&Pe.push("_local"),ae.bindingEngine.invalidateCacheByKeys(Pe)}const Re={[T.id]:fe.data};Object.keys(me).length>0&&(Re._localInit=me,Object.assign(F,me)),T.initGlobal&&(Re._global={...this.globalState}),Z(Re)}else if(fe.state==="error"&&fe.error){const me=fe.error,ae=me.response?.data?.message;j[T.id]={message:ae||fe.error.message,status:me.response?.status||me.status},U.log(`Progressive data source error: ${T.id}`,j[T.id]),Z({[T.id]:null,_dataSourceErrors:{...j}})}}catch(pe){U.error(`Failed to fetch data source: ${T.id}`,pe)}});if(await Promise.all(z),n!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",n);return}U.log("All progressive data sources loaded")}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Ce=v.filter(Z=>Z.type==="websocket");if(Ce.length>0){U.log("Subscribing WebSocket data sources:",Ce.map(T=>T.id));const{updateTemplateData:Z,getState:ge}=await Promise.resolve().then(()=>Wr),z={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};U.log("WebSocket binding context keys:",Object.keys(z)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(v,(T,pe)=>{U.log(`WebSocket data received for: ${T}`,pe),this.currentFetchedData[T]=pe;const fe=v.find(Pe=>Pe.id===T),me=ge();if(me.bindingEngine){const Pe=[T];fe?.initGlobal&&Pe.push("_global"),fe?.initLocal&&Pe.push("_local"),me.bindingEngine.invalidateCacheByKeys(Pe)}Z({[T]:pe});const Re=v.find(Pe=>Pe.type==="websocket"&&(Pe.target_source||Pe.id)===T)?.onReceive;Array.isArray(Re)&&Re.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Me of Re)try{const Ge=this.getActionDispatcher?.();Ge&&await Ge.dispatchAction(Me,{navigate:this.getRouter?.()?(kt,vt)=>this.getRouter().navigate(kt,vt):void 0,setState:kt=>this.setGlobalState(kt),state:this.globalState,data:{...this.globalState,$args:[pe],$event:pe},_isDispatchFallbackContext:!0})}catch(Ge){U.error(`WebSocket onReceive action failed for ${T}:`,Ge)}})()},z),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(r){U.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(r._forceLocalInit=Date.now(),U.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=n[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let p=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);p={...y,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof p=="object"?(r[c.initLocal]=this.deepMerge(m,p),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(r[c.initLocal]=p,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:p,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const S=this.evaluateDefaults(c.initLocalDefaults,n);y={...S,...y},U.log(`initLocalDefaults applied for ${p}:`,Object.keys(S))}const C=this.globalState._local?.[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(r[p]=this.deepMerge(C,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${p}`)):(r[p]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${p}`))}else if(typeof c.initLocal=="object"){const p=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:C}of m){const S=this.extractValueByPathOrExpression(f,C,c.id);if(y.includes(".")){const v=y.split(".")[0];r[v]===void 0&&this.globalState._local?.[v]!==void 0&&(r[v]=JSON.parse(JSON.stringify(this.globalState._local[v]))),this.setValueAtPath(r,y,S,p),U.log(`initLocal map (${p}): ${c.id} ${C} -> _local.${y}`)}else{const v=this.globalState._local?.[y];p==="replace"?(r[y]=S,U.log(`initLocal map (replace): ${c.id} ${C} -> _local.${y}`)):p==="shallow"?v!==void 0&&typeof v=="object"&&typeof S=="object"?(r[y]={...v,...S},U.log(`initLocal map (shallow): ${c.id} ${C} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${C} -> _local.${y}`)):v!==void 0&&typeof v=="object"&&typeof S=="object"?(r[y]=this.deepMerge(v,S),U.log(`initLocal map (deep): ${c.id} ${C} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${C} -> _local.${y}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,y]of Object.entries(c.initGlobal)){if(typeof y!="string"){U.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const C=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof C=="object"?(this.globalState[m]=this.deepMerge(S,C),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=C,U.log(`initGlobal map: ${c.id} ${y} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const y of m)if(typeof y=="string"){const C=this.globalState[y];C!==void 0&&typeof C=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(C,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,U.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:C,path:S}=y,v=S?this.extractValueByPathOrExpression(f,S,c.id):f,x=this.globalState[C];x!==void 0&&typeof x=="object"&&typeof v=="object"?(this.globalState[C]=this.deepMerge(x,v),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${C}`)):(this.globalState[C]=v,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${C}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const p=i[c.initIsolated];p!==void 0&&typeof p=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(p,f),U.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,U.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:p,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,C=i[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(i[p]=this.deepMerge(C,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${p}`)):(i[p]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${p}`))}else if(typeof c.initIsolated=="object")for(const[p,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${p}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),C=i[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(i[p]=this.deepMerge(C,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${p}`)):(i[p]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${p}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();r[i]=this.evaluateExpression(c,n)}else r[i]=l;return r}evaluateExpression(e,n){try{const r=e.split("??").map(i=>i.trim());for(const i of r){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,p]=d,m=[];f&&m.push(f);const y=p.match(/\[\d+\]/g);return y&&m.push(...y),m}return[c]}).filter(c=>c!=="");for(const c of l){if(i==null)return;if(c.startsWith("[")&&c.endsWith("]")){const d=parseInt(c.slice(1,-1),10);i=i[d]}else i=i[c]}return i}extractValueByPathOrExpression(e,n,r){const i=Ma(n);if(i!==null){const l=new Tn,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=On(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!os({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){U.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){U.log(`Script already loaded: ${i.id}`);continue}if(!this.isAllowedScriptSrc(i.src)){U.warn(`Blocked untrusted external script src (same-origin path or declared trusted host required): ${i.id} (${i.src})`);continue}r.push(this.loadLayoutScript(i))}r.length>0&&(await Promise.all(r),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}async loadLayoutScript(e){const n=e.src.startsWith("/")?xn(e.src):e.src;try{await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id),rb(`layout-script:${e.id}`),U.log(`Script loaded successfully: ${e.id}`)}catch(r){this.failedLayoutScripts.add(e.id),U.warn(`Failed to load script after retries: ${e.id} (${n})`,r),Ss({id:`layout-script:${e.id}`,label:e.id,retry:async()=>{document.getElementById(e.id)?.remove(),await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id)}})}}getFailedLayoutScripts(){return Array.from(this.failedLayoutScripts)}isAllowedScriptSrc(e){return Oo(e)}static normalizeScriptSrcForOriginCheck(e){return Gm(e)}extractScriptHost(e){return Fm(e)}getTrustedScriptHosts(){return fs()}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return!!Jd(r,n)}return!!e}catch(r){return U.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(rc()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=eb(e);Jf.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(r.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",c="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;case"opaque":default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(r.target){const d=`#${CSS.escape(r.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${c}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of c.split(";")){const p=f.indexOf(":");p!==-1&&d.style.setProperty(f.slice(0,p).trim(),f.slice(p+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const c=Er.getInstance().getComponent(n.component);if(!c){U.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){U.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=f==="fullpage"?"app":f==="fallback"?i:e,C=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${C}{position:relative;z-index:0;}${C}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const v=document.createElement("div");if(v.id="g7-skeleton-overlay",v.setAttribute("role","status"),v.setAttribute("aria-busy","true"),v.setAttribute("aria-label","Loading..."),f==="fullpage")v.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const O=d.getBoundingClientRect(),j=window.scrollX||document.documentElement.scrollLeft,F=window.scrollY||document.documentElement.scrollTop;v.style.cssText=["position:absolute",`top:${O.top+F}px`,`left:${O.left+j}px`,`width:${O.width}px`,`height:${O.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(v),this.skeletonOverlayContainer=v;const x=r.components||[];let w;if(f==="fullpage")w=x;else{const O=f==="fallback"?i:e;w=this.findComponentChildrenById(x,O)}const R=_d.createRoot(v);this.skeletonOverlayRoot=R,za.flushSync(()=>{R.render(We.createElement(c,{components:w,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const L=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${L}] with "${n.component}" (${w.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=r(l.children);if(c!==null)return c}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?r:e,d=`#${CSS.escape(c)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const p=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:p},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,y=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,n?.component){const c=Er.getInstance().getComponent(n.component);if(c){const d=_d.createRoot(i);this.skeletonOverlayRoot=d,za.flushSync(()=>{d.render(We.createElement(c,{options:{text:r}}))});return}U.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),U.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){if(e instanceof Rr&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!Wn().getToken()||e.details?.hadToken===!0,f=Yn.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=eb(e);Jf.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;U.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(U.log(`${e.code} error page rendered successfully`),!0):(U.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return U.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){U.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){U.log("404 error page rendered successfully");return}U.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){U.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){U.log("reloadExtensionState: start");let e;try{const n=await fetch(Pr(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){U.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(U.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),U.log("reloadExtensionState: routes reloaded"))}catch(n){U.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(n){U.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>$g),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(n){U.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),U.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){U.warn("reloadExtensionState: supportedLocales refresh failed",n)}U.log("reloadExtensionState: done")}getActionDispatcher(){return ca().actionDispatcher}async changeLocale(e){try{if(U.log("Changing locale to:",e),this.config.locale===e){U.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),U.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),U.log("ErrorPageHandler locale updated")),Qc(),await Yo({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),U.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Wr),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),U.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),U.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),U.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),U.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),U.log("Locale changed successfully to",e)}catch(n){throw U.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Lr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Lr.LOCALE_STORAGE_KEY,e)}catch(n){U.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){U.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(r,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});c.ok?U.log("Locale saved to DB:",e):U.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){U.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Lr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return U.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Lr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){U.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),U.log(`Module handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),U.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),U.log(`Plugin handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},U.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Wr).then(({updateTemplateData:l,getState:c})=>{const d=c();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){r=l;break}}if(!r){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Gr.setPending(!0);try{const i=new Dr;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ca(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},p=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,p,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const C={};this.processInitOptions([r],{[e]:y.data},C);const S=ca();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const v={[e]:y.data};return Object.keys(C).length>0&&(v._localInit=C),r.initGlobal&&(v._global={...this.globalState}),_s(v,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){U.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Gr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),U.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Wr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},p=this.currentFetchedData[e];if(!p)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=p;for(const v of m)if(y=y?.[v],y===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const C=y.findIndex(v=>String(v[c])===String(r));if(C===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${r}' not found`),!1;d?y[C]=this.deepMerge(y[C],i):y[C]={...y[C],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Wr).then(({updateTemplateData:v})=>{v({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let c=e;for(let p=0;p0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const p=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(p.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${p.length} auto_fetch data sources`),Gr.setPending(!0);const m=ca().currentLayoutJson,y=m?.transition_overlay,C=Array.isArray(y?.wait_for)?y.wait_for:[],S=p.some(x=>(x.loading_strategy||"progressive")==="blocking"),v=C.length>0&&p.some(x=>C.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||v)&&y&&typeof y=="object"){const x=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&x?this.renderSkeletonOverlay(x,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&x&&this.renderSpinnerOverlay(x,y.spinner,y.fallback_target)}try{const x=new Dr;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const w=ca(),R=w.currentDataContext?._global||{},L=await x.fetchDataSourcesWithResults(p,this.currentRouteParams,this.currentQueryParams,R,void 0,{ignoreAutoFetch:!1}),O={},j={},F=new Map(p.map(G=>[G.id,G]));for(const G of L){const P=F.get(G.id);if(!P){U.warn(`Refetch result id not found in autoFetchDataSources: ${G.id}`);continue}const K=G.id;G.state==="success"&&G.data!==void 0?(this.currentFetchedData[K]=G.data,O[K]=G.data,this.processInitOptions([P],{[K]:G.data},j),U.log(`Data source refetched: ${K}`)):G.state==="error"&&U.error(`Failed to refetch data source: ${K}`,G.error)}if(w.bindingEngine){const G=Object.keys(O);G.push("query"),w.bindingEngine.invalidateCacheByKeys(G)}if(Object.keys(j).length>0&&(O._localInit=j),Object.keys(O).length>0){if(O.query=ob(this.currentQueryParams),w.currentLayoutJson?.computed&&Object.keys(w.currentLayoutJson.computed).length>0){const G={...w.currentDataContext,...O,query:O.query},P=this.calculateComputed(w.currentLayoutJson.computed,G);Object.keys(P).length>0&&(O._computed=P,this.globalState._computed=P,U.log("Computed values recalculated in updateQueryParams:",Object.keys(P)))}_s(O,{sync:!0}),U.log("Template data updated with new query params")}}catch(x){U.error("Error in updateQueryParams:",x)}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new Tn;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,n,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=c;r[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return Jd(e,n)}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Wr),i=r();if(!i){U.warn("ActionDispatcher not available for init_actions");return}U.log("Executing init_actions:",e.map(d=>d.handler)),U.log("Init actions dataContext:",n),U.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},p=i.createHandler(f,c),m=new Event("init");await p(m),U.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},U.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){U.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=Zf().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),p=n.filter(y=>!e.customHandlers?.has(y)),m=p.length>0&&p.every(y=>d.some(C=>y.startsWith(`${C}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:p,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const p=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(p,l)};p()})}};$(Lr,"LOCALE_STORAGE_KEY","g7_locale"),$(Lr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Go=Lr;function th(s){const e=new Go(s);return s.websocket&&(Vc.configure(s.websocket),U.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=th,window.G7Core.dataSource={refetch:async(s,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(s,e)},get:s=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(s)}});function sx(s={}){const{checked:e,value:n,name:r,type:i="checkbox"}=s,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:r??"",type:i};return{target:d,currentTarget:d,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function ox(s={}){const{button:e=0,clientX:n=0,clientY:r=0}=s;return{button:e,clientX:n,clientY:r,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function lx(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function cx(s,e="keydown"){return{key:s,code:s.length===1?`Key${s.toUpperCase()}`:s,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:s}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const ux={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function lb(s){const e=s.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(ux))if(r.test(e))return n;return null}function cb(s){const e=s.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function dx(s,e){if(!e||e.trim()==="")return s;if(!s||s.trim()==="")return e;const n=s.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of r){const d=lb(c);if(d){const f=cb(c),p=`${d}:${f}`;i.set(p,c)}}return[...n.filter(c=>{const d=lb(c);if(!d)return!0;const f=cb(c),p=`${d}:${f}`;return!i.has(p)}),...r].join(" ")}function fx(s){return Object.entries(s).filter(([,e])=>e).map(([e])=>e).join(" ")}function hx(...s){return s.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=dt("G7CoreGlobals");function px(){window.React=We,window.ReactDOM={...Ad,createPortal:za.createPortal,unstable_batchedUpdates:s=>s()},window.ReactJSXRuntime=WC,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function gx(s){const e=new Map,n=Ua.getInstance();s.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async p=>{try{return await p(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(p){d=p instanceof Error?p:new Error(String(p))}if(n.trackEventEmit(r,i,c,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function mx(s){s.__runtime||(s.__runtime={DynamicRenderer:Vr,ComponentRegistry:Er,TranslationEngine:wi,DataSourceManager:Dr,dataSourceManager:MA,DataBindingEngine:Tn,dataBindingEngine:uc,ActionDispatcher:Lo,TranslationReactContext:Ff,TranslationProvider:qc,useTranslation:Py,ResponsiveContext:Cf,ResponsiveProvider:Rc,useResponsive:Ef,responsiveManager:_i,BREAKPOINT_PRESETS:dc,AuthManager:Yn,createLogger:dt,G7DevToolsCore:Ua},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function yx(s){if(s.layoutEditor&&s.layoutEditor.__isStub!==!0||s.layoutEditor&&s.layoutEditor.__isStub===!0)return;const e=[],n=[];s.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function bx(s){s.asset={template:(e,n,r)=>Uw(e,n,r),templateDir:(e,n)=>Pw(e,n),module:(e,n,r)=>Bw(e,n,r),plugin:(e,n,r)=>qw(e,n,r),convertToCurrentMode:e=>xn(e),loadScript:(e,n,r)=>Oo(e,fs())?Cr(e,n,r):Promise.reject(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`)),isAllowedScriptSrc:e=>Oo(e,fs()),loadStylesheet:(e,n,r)=>sa(e,n,r)},s.assets={notifyFailure:Ss,clearFailure:rb,clearAll:ab,getFailures:qA,retryAll:sb},QA(),be.log("전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨")}function vx(s,e){s.useTranslation=Py,s.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function Sx(s,e){s.createChangeEvent=sx,s.createClickEvent=ox,s.createSubmitEvent=lx,s.createKeyboardEvent=cx,s.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),s.createLogger=dt,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),s.renderItemChildren=(n,r,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},y=new Set,C=(v,x)=>{const w=m._global?._remountKeys;return v&&w?.[v]&&!y.has(v)?(y.add(v),`${v}-remount-${w[v]}`):v||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:C,...c};return Co(n,m,i,l,S)},s.evaluateCondition=(n,r)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...r||{}},f=i.bindingEngine??uc;return Fg(n,d,f)},s.getComponentMap=()=>Er.getInstance().getComponentMap(),s.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=Er.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},p={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,y=(C,S)=>{const v=p._global?._remountKeys;return C&&v?.[C]&&!m.has(C)?(m.add(C),`${C}-remount-${v[C]}`):C||S};return Co(n,p,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},s.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||Er.getInstance().getComponentMap(),p=e.getState(),m=s.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},C={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},v=p.bindingEngine??s.getDataBindingEngine?.(),x={...m,_local:C,_computed:S,row:i,item:i,$item:i};let w={};if(l&&typeof l=="object"&&v)try{for(const[j,F]of Object.entries(l))if(typeof F=="string"){const G=Ma(F);if(G!==null)try{w[j]=On(G)?v.evaluatePipeExpression(G,x,{skipCache:!0}):v.evaluateExpression(G,x,{skipCache:!0})}catch{w[j]=void 0}else w[j]=v.resolveBindings(F,x,{skipCache:!0})}else w[j]=F}catch(j){be.warn("renderExpandContent: expandContext 평가 오류:",j)}const R={row:i,item:i,$item:i,_local:C,_global:m._global||{},_computed:m._computed||{},...w},L=new Set,O=(j,F)=>{const G=R._global?._remountKeys;return j&&G?.[j]&&!L.has(j)?(L.add(j),`${j}-remount-${G[j]}`):j||F};return Co(r,R,f,d,{translationContext:p.translationContext,translationEngine:p.translationEngine??void 0,bindingEngine:p.bindingEngine??void 0,actionDispatcher:p.actionDispatcher,componentContext:c,getRemountKey:O})},s.$get=function(r,i,l=void 0){if(r==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return r;let d=r;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},be.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),be.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),be.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),be.log("전역 객체 window.G7Core.$get에 노출됨")}function wx(s){s.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),c=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),p=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=p?.state??c;m&&p&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let C=p?.data??c;m&&p?.data?._local&&(C={...p.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(v,x)=>l.navigate(v,x):void 0,setState:p?.setState??d,state:y,data:C,_isDispatchFallbackContext:!p?.setState};if(e.debounce){const v=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(v,x,()=>{const{debounce:w,debounceKey:R,...L}=e;i.dispatchAction(L,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(v){return be.error("G7Core.dispatch: 액션 실행 오류:",v),{success:!1,error:v instanceof Error?v:new Error(String(v))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Fo(s){const e={};for(const[n,r]of Object.entries(s))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Qn(s,e){if(Array.isArray(s)&&!Array.isArray(e)&&Cx(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=s.length+r.length+10)){const l=[...s];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...s};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=Qn(n[r],i):n[r]={...i}:n[r]=i;return n}function Ex(s){s.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Fo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...r.getGlobalState(),...l};else{const d=r.getGlobalState();c=Qn(d,l)}r.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const w=window.__g7AutoBindingPaths;w&&w.size>0&&ub(Fo(e)).some(L=>w.has(L))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const w=r?.getActionDispatcher?.();if(w){const R=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:L,debounceKey:O,...j}=n;w.debouncedCall(R,n.debounce,()=>{s.state.setLocal(e,j)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Fo(e);if(i==="parent"||i==="root"){const w=window.__g7LayoutContextStack||[];if(w.length>0){const R=i==="parent"?w[w.length-1]:w[0];if(R?.setState){R.setState(L=>l==="replace"?d:l==="shallow"?{...L||{},...d}:Qn(L||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,p=r?.getGlobalState?.()?._local||{},C=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=C?Ro(p,C):p,v=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={...v,...d}:x=Qn(v,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,be.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const w=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Qn(w,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const w=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Qn(w,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(w=>l==="replace"?d:l==="shallow"?{...w||{},...d}:Qn(w||{},d)),r?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Qn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Qn(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(be.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,n,r)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=r):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:r);const d=c?.merge||"deep",f=Fo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const p=window.__g7ActionContext;p?.isolatedContext?.mergeState?p.isolatedContext.mergeState(f,d):be.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return be.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||s.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){be.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){be.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=r):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",p=Fo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let C;f==="replace"?C=p:f==="shallow"?C={...y,...p}:C=Qn(y,p),window.__g7PendingLocalState=C;const S=window.__templateApp;if(S?.setGlobalState){const v=S.getGlobalState?.()?._local,w=f!=="replace"&&!!v&&typeof v=="object"&&!Array.isArray(v)?f==="shallow"?{...v,...p}:Qn(v,p):void 0;S.setGlobalState({_local:w?Ro(w,C):C})}if(l.setState(C),m?l.state._local=C:l.state=C,l.dataContext&&(l.dataContext._local=C),f==="replace")window.__g7ForcedLocalFields=p;else{const v=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Qn(v,p)}vf()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,s.state.set(r),be.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),s.state.getGlobal=s.state.get,s.state.setGlobal=s.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function _x(s){s.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,r,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return be.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return be.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,p=null;if(n){const y=n.split(".");p=y.pop();for(const C of y)if(f&&typeof f=="object"&&C in f)f=f[C];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[p]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&p?(f[p]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function Ax(s,e){s.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function xx(s){s.toast={show:(e,n)=>{s.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{s.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{s.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{s.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{s.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function Tx(s){s.modal={open:e=>{s.dispatch({handler:"openModal",target:e})},close:e=>{s.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{s.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=s.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>s.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function kx(s){s.style={mergeClasses:dx,conditionalClass:fx,joinClasses:hx},be.log("전역 객체 window.G7Core.style에 노출됨")}function Rx(s,e){const{webSocketManager:n}=e;s.websocket={manager:n,subscribe:(r,i,l,c)=>n.subscribe(r,i,l,c),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function Dx(s,e){const{transitionManager:n}=e;s.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(r(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function Ox(s){s.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function Lx(s){s.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function $x(s,e){const{transitionManager:n,responsiveManager:r}=e;s.AuthManager=Yn,s.api=Wn(),s.TransitionManager=n,s.useTransitionState=Jm,s.ResponsiveManager=r,s.useResponsive=Ef,s.useControllableState=oE,s.shallowArrayEqual=lE,s.shallowObjectEqual=Zm,s.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);be.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},be.log("전역 객체 window.G7Core.AuthManager에 노출됨"),be.log("전역 객체 window.G7Core.api에 노출됨"),be.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),be.log("전역 객체 window.G7Core.useResponsive에 노출됨"),be.log("전역 객체 window.G7Core.useControllableState에 노출됨"),be.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function Mx(s,e){s.getSlotContext=()=>window.__slotContextValue??null,s.getDynamicRenderer=()=>window.__DynamicRenderer??null,s.getComponentRegistry=()=>e.getComponentRegistry?.()??Er.getInstance(),s.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,s.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,s.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function Nx(s){s.identity={setLauncher:yt.setLauncher.bind(yt),handle:yt.handle.bind(yt),isIdentityRequired:yt.isIdentityRequired.bind(yt),hasLauncher:yt.hasLauncher.bind(yt),markDomainNoticeShown:yt.markDomainNoticeShown.bind(yt),redirectExternally:yt.redirectExternally.bind(yt),createDeferred:yt.createDeferred.bind(yt),resolveDeferred:yt.resolveDeferred.bind(yt),reset:yt.reset.bind(yt),redirectStashKey:hf},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function Ix(s){if(typeof window>"u")return;px(),window.G7Core||(window.G7Core={});const e=window.G7Core;mx(e),gx(e),yx(e),$x(e,s),bx(e),vx(e,s),Sx(e,s),wx(e),Ex(e),_x(e),Ax(e,s),xx(e),Tx(e),kx(e),Rx(e,s),Dx(e,s),Ox(e),Lx(e),Mx(e,s),Nx(e),be.log("G7Core 전역 객체 초기화 완료")}function jx(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Ua.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,c)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,c):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,c,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,c)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,c,d,f)}catch{}},trackComponentStyle:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,c)}catch{}},trackAuthEvent:(r,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,c)}catch{}},trackAuthHeader:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,c,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,c,d)}catch{}},captureSequenceActionAfter:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,c,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,c,d,f,p)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,c,d,f,p)}catch{}},trackComputedRecalc:(r,i,l,c,d,f,p)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,c,d,f,p)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};s.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Vo=null;function zx(){const s=window.G7Core;return s?.__devtools?Promise.resolve(s.__devtools):Vo||(Vo=new Promise((e,n)=>{const r=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const c=document.getElementById(i);if(c){c.addEventListener("load",l,{once:!0}),c.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Vo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Vo)}function Hx(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=Ua.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Td(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}Ux(s,e)}async function Ux(s,e){let n;try{n=await zx()}catch(p){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",p),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},Td();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;jx(),Td();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(p){be.warn("StyleTracker 활성화 실패:",p)}const c=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(p,m)=>e.watchState(p,m)},actions:{getHistory:()=>e.getActionHistory(),watch:p=>e.watchActions(p),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:p=>{const m=s.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(p,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:p=>c.analyze(p),suggestFix:p=>c.suggestFix(p),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:p=>c.getRulesByCategory(p)},server:{dumpState:p=>d.dumpState(p),sendLog:p=>d.sendLog(p),sendError:(p,m)=>d.sendError(p,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:p=>e.setLogLevel(p),setMaxHistory:p=>e.setMaxHistory(p)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=f,s.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),Px(n.DevToolsPanel)}function Px(s){if(document.getElementById("g7-devtools-root")){be.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Ad.createRoot(e).render(We.createElement(s)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Je=dt("TemplateEngine"),re={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Ko=!1;const Wo=[];async function Bx(s){try{Je.log("템플릿 메타데이터 로드 중...",s);const e=s.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Je.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Je.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Je.error("템플릿 메타데이터 로드 실패",e),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function db(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=re.templateMetadata?.locales;return{$locale:re.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:re.templateId}}async function Yo(s){try{if(Je.log("템플릿 엔진 초기화 시작",s),re.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!s.templateId)throw new IA;Ko=s.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Ko),Hx(),re.templateId=s.templateId,re.locale=s.locale||"ko",Je.log("엔진 인스턴스 생성 중..."),re.registry=Er.getInstance(),re.bindingEngine=new Tn,re.translationEngine=wi.getInstance(),s.cacheVersion!==void 0&&s.cacheVersion>0&&re.translationEngine.setCacheVersion(s.cacheVersion),re.translationContext={templateId:s.templateId,locale:re.locale},re.actionDispatcher=new Lo({},re.translationEngine,re.translationContext),QC(re.actionDispatcher),Je.log("다국어 파일 로드 중...",s.templateId,re.locale);const e="en",n=[re.translationEngine.loadTranslations(s.templateId,re.locale).then(()=>{Je.log(`다국어 파일 로드 완료: ${re.locale}`)}).catch(r=>{Je.warn(`다국어 파일 로드 실패 (${re.locale}):`,r instanceof Error?r.message:r)})];re.locale!==e&&n.push(re.translationEngine.loadTranslations(s.templateId,e).then(()=>{Je.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Je.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),Je.log("템플릿 메타데이터 로드 중...",s.templateId),re.templateMetadata=await Bx(s.templateId),re.isInitialized=!0,Je.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Je.error("템플릿 엔진 초기화 실패",e),re.isInitialized=!1,re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,e}}let Cs=null;const fb="g7-layout-editor-bundle";function nh(){const s=window.G7Core;return s?.__LayoutEditorChrome?Promise.resolve(s.__LayoutEditorChrome):Cs||(Cs=(async()=>{const e=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js";document.getElementById(fb)?.remove(),window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=()=>{};try{await Cr(e,{id:fb},{label:"layout-editor bundle"})}catch(r){throw Cs=null,Je.error(`편집기 번들 로드 실패 (${e})`,r),new Error("편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.")}const n=window.G7Core?.__LayoutEditorChrome;if(!n)throw Cs=null,Je.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${e})`),new Error("편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.");return n})(),Cs)}async function Es(s){try{if(Je.log("템플릿 렌더링 시작",s),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!s.containerId)throw new Error("containerId는 필수입니다.");if(!s.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(s.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${s.containerId}`);const n=db();if(re.containerId=s.containerId,re.currentLayoutJson=s.layoutJson,re.currentDataContext={...n,...s.dataContext||{}},re.translationContext=s.translationContext||{templateId:re.templateId||"",locale:re.locale},re.reactRoot||(Je.log("React Root 생성"),re.reactRoot=Ad.createRoot(e)),typeof window<"u"){const l=tb(window.location.pathname);if(l){Je.log("레이아웃 편집기 모드 진입",l);let c;try{c=await nh()}catch(f){Je.error("레이아웃 편집기 번들 로드 실패",f),Jf.render(s.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Ko});return}const d=We.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:re.locale});re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext,children:We.createElement(Sf,{children:We.createElement(Rc,{children:We.createElement(Vf,{children:d})})})}));return}}const r=s.layoutJson.components||[];if(r.length===0){Je.warn("렌더링할 컴포넌트가 없습니다.");return}const i=s.layoutJson.modals||[];if(Je.log("modals 배열:",i),Je.log("modals 개수:",i.length),Je.log("DynamicRenderer로 렌더링 시작"),re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Sf,null,We.createElement(Rc,null,We.createElement(Vf,null,[...r.map((l,c)=>{const d=re.currentLayoutJson?.layout_name||"";return We.createElement(Vr,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),We.createElement(qm,{key:"__modal_parent_context_provider"},i.map(l=>{const c=re.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||re.currentDataContext._global?.activeModal===l.id,p=c.indexOf(l.id),m=p>=0?50+p:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,v=We.createElement(Vr,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?We.createElement(Zy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Ko,children:v}):v}))]))))),Je.log("템플릿 렌더링 완료"),Wo.length>0){Je.log(`대기 중인 데이터 업데이트 ${Wo.length}건 적용`);const l=[...Wo];Wo.length=0;for(const{data:c,options:d}of l)_s(c,d)}}catch(e){throw Je.error("템플릿 렌더링 실패",e),e}}function _s(s,e){try{if(Je.log("템플릿 데이터 업데이트 시작",Object.keys(s)),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!re.reactRoot||!re.currentLayoutJson){Je.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(s)),Wo.push({data:s,options:e});return}const n=db(),r={...re.currentDataContext._global||{},...s._global||{}},i=iE(re.currentDataContext._localInit,s._localInit);re.currentDataContext={...n,...re.currentDataContext,...s,_global:r,_localInit:i},r._local!==void 0&&(re.currentDataContext._local=r._local),r._computed!==void 0&&(re.currentDataContext._computed=r._computed);const l=re.currentLayoutJson.components||[],c=re.currentLayoutJson.modals||[];Je.log("updateTemplateData - modals 배열:",c),Je.log("updateTemplateData - modals 개수:",c.length),Je.log("updateTemplateData - activeModal:",re.currentDataContext._global?.activeModal);const d=()=>{re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Sf,null,We.createElement(Rc,null,We.createElement(Vf,null,[...l.map((f,p)=>{const m=re.currentLayoutJson?.layout_name||"";return We.createElement(Vr,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:p===0,layoutKey:m})}),We.createElement(qm,{key:"__modal_parent_context_provider_update"},c.map(f=>{const p=re.currentDataContext._global?.modalStack||[],y=p.includes(f.id)||re.currentDataContext._global?.activeModal===f.id,C=p.indexOf(f.id),S=C>=0?50+C:50,v=window.__g7LayoutContextStack||[],w=v[v.length-1]?.dataContext,R=We.createElement(Vr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:S},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:w});return f.data_sources&&f.data_sources.length>0?We.createElement(Zy,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Ko,children:R}):R}))])))))};e?.sync?(Je.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Je.log("재렌더링 시작 (with startTransition)"),M.startTransition(()=>{d()})),Je.log("템플릿 데이터 업데이트 완료")}catch(n){throw Je.error("템플릿 데이터 업데이트 실패",n),n}}function Qc(){try{Je.log("템플릿 정리 시작"),re.reactRoot&&(Je.log("React Root 언마운트"),re.reactRoot.unmount(),re.reactRoot=null),re.templateId=null,re.locale="ko",re.isInitialized=!1,re.containerId=null,re.currentLayoutJson=null,re.currentDataContext={},re.translationContext={templateId:"",locale:"ko"},re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,re.templateMetadata=null,Je.log("템플릿 정리 완료")}catch(s){throw Je.error("템플릿 정리 실패",s),s}}function ca(){return Object.freeze({...re})}function hb(){return re.actionDispatcher}const Xo={initTemplateEngine:Yo,renderTemplate:Es,updateTemplateData:_s,destroyTemplate:Qc,getState:ca};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Xo,Ix({getState:()=>({translationEngine:re.translationEngine,translationContext:re.translationContext,bindingEngine:re.bindingEngine,actionDispatcher:re.actionDispatcher,templateMetadata:re.templateMetadata}),transitionManager:Gr,responsiveManager:_i,webSocketManager:Vc}),Je.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Wr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Dr,LayoutLoader:Gf,TemplateApp:Go,TemplateEngine:Xo,default:Xo,destroyTemplate:Qc,getActionDispatcher:hb,getState:ca,initTemplateApp:th,initTemplateEngine:Yo,loadLayoutEditorBundle:nh,renderTemplate:Es,updateTemplateData:_s},Symbol.toStringTag,{value:"Module"}));Yt.DataSourceManager=Dr,Yt.LayoutLoader=Gf,Yt.TemplateApp=Go,Yt.TemplateEngine=Xo,Yt.default=Xo,Yt.destroyTemplate=Qc,Yt.getActionDispatcher=hb,Yt.getState=ca,Yt.initTemplateApp=th,Yt.initTemplateEngine=Yo,Yt.loadLayoutEditorBundle=nh,Yt.renderTemplate=Es,Yt.updateTemplateData=_s,Object.defineProperties(Yt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{});