@tagadapay/plugin-sdk 3.0.3 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/build-cdn.js +113 -0
  2. package/dist/config/basisTheory.d.ts +26 -0
  3. package/dist/config/basisTheory.js +29 -0
  4. package/dist/external-tracker.js +4947 -0
  5. package/dist/external-tracker.min.js +11 -0
  6. package/dist/external-tracker.min.js.map +7 -0
  7. package/dist/react/config/payment.d.ts +8 -8
  8. package/dist/react/config/payment.js +17 -21
  9. package/dist/react/hooks/useApplePay.js +1 -1
  10. package/dist/react/hooks/usePayment.js +1 -3
  11. package/dist/react/hooks/useThreeds.js +2 -2
  12. package/dist/v2/core/client.d.ts +30 -3
  13. package/dist/v2/core/client.js +219 -8
  14. package/dist/v2/core/config/environment.d.ts +16 -3
  15. package/dist/v2/core/config/environment.js +72 -3
  16. package/dist/v2/core/funnelClient.d.ts +4 -0
  17. package/dist/v2/core/funnelClient.js +106 -4
  18. package/dist/v2/core/resources/funnel.d.ts +22 -0
  19. package/dist/v2/core/resources/offers.d.ts +64 -3
  20. package/dist/v2/core/resources/offers.js +112 -10
  21. package/dist/v2/core/resources/postPurchases.js +4 -1
  22. package/dist/v2/core/utils/configHotReload.d.ts +39 -0
  23. package/dist/v2/core/utils/configHotReload.js +75 -0
  24. package/dist/v2/core/utils/eventBus.d.ts +11 -0
  25. package/dist/v2/core/utils/eventBus.js +34 -0
  26. package/dist/v2/core/utils/pluginConfig.d.ts +14 -5
  27. package/dist/v2/core/utils/pluginConfig.js +74 -59
  28. package/dist/v2/core/utils/previewMode.d.ts +114 -0
  29. package/dist/v2/core/utils/previewMode.js +379 -0
  30. package/dist/v2/core/utils/sessionStorage.d.ts +5 -0
  31. package/dist/v2/core/utils/sessionStorage.js +22 -0
  32. package/dist/v2/index.d.ts +4 -1
  33. package/dist/v2/index.js +3 -1
  34. package/dist/v2/react/hooks/useOfferQuery.js +50 -17
  35. package/dist/v2/react/hooks/usePaymentQuery.js +1 -3
  36. package/dist/v2/react/hooks/usePreviewOffer.d.ts +84 -0
  37. package/dist/v2/react/hooks/usePreviewOffer.js +290 -0
  38. package/dist/v2/react/hooks/useThreeds.js +2 -2
  39. package/dist/v2/react/index.d.ts +2 -0
  40. package/dist/v2/react/index.js +1 -0
  41. package/dist/v2/react/providers/TagadaProvider.js +49 -32
  42. package/dist/v2/standalone/external-tracker.d.ts +119 -0
  43. package/dist/v2/standalone/external-tracker.js +260 -0
  44. package/dist/v2/standalone/index.d.ts +2 -0
  45. package/dist/v2/standalone/index.js +6 -0
  46. package/package.json +11 -3
  47. package/dist/v2/react/hooks/useOffersQuery.d.ts +0 -12
  48. package/dist/v2/react/hooks/useOffersQuery.js +0 -404
@@ -0,0 +1,11 @@
1
+ /**
2
+ * TagadaPay External Tracker v3.0.9
3
+ * CDN Bundle - Standalone tracking for external pages
4
+ * @license MIT
5
+ */
6
+ "use strict";var TagadaTrackerBundle=(()=>{var Ae=Object.defineProperty,Gn=Object.defineProperties,Wn=Object.getOwnPropertyDescriptor,Jn=Object.getOwnPropertyDescriptors,Yn=Object.getOwnPropertyNames,Mt=Object.getOwnPropertySymbols;var Kt=Object.prototype.hasOwnProperty,Zn=Object.prototype.propertyIsEnumerable;var W=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Xn=t=>{throw TypeError(t)};var zt=(t,e,n)=>e in t?Ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,S=(t,e)=>{for(var n in e||(e={}))Kt.call(e,n)&&zt(t,n,e[n]);if(Mt)for(var n of Mt(e))Zn.call(e,n)&&zt(t,n,e[n]);return t},x=(t,e)=>Gn(t,Jn(e));var $t=(t,e)=>{for(var n in e)Ae(t,n,{get:e[n],enumerable:!0})},Qn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yn(e))!Kt.call(t,i)&&i!==n&&Ae(t,i,{get:()=>e[i],enumerable:!(r=Wn(e,i))||r.enumerable});return t};var er=t=>Qn(Ae({},"__esModule",{value:!0}),t);var V=function(t,e){this[0]=t,this[1]=e},tt=(t,e,n)=>{var r=(s,a,u,d)=>{try{var c=n[s](a),p=(a=c.value)instanceof V,C=c.done;Promise.resolve(p?a[0]:a).then(h=>p?r(s==="return"?s:"next",a[1]?{done:h.done,value:h.value}:h,u,d):u({value:h,done:C})).catch(h=>r("throw",h,u,d))}catch(h){d(h)}},i=s=>o[s]=a=>new Promise((u,d)=>r(s,a,u,d)),o={};return n=n.apply(t,e),o[W("asyncIterator")]=()=>o,i("next"),i("throw"),i("return"),o},nt=t=>{var e=t[W("asyncIterator")],n=!1,r,i={};return e==null?(e=t[W("iterator")](),r=o=>i[o]=s=>e[o](s)):(e=e.call(t),r=o=>i[o]=s=>{if(n){if(n=!1,o==="throw")throw s;return s}return n=!0,{done:!1,value:new V(new Promise(a=>{var u=e[o](s);u instanceof Object||Xn("Object expected"),a(u)}),1)}}),i[W("iterator")]=()=>i,r("next"),"throw"in e?r("throw"):i.throw=o=>{throw o},"return"in e&&r("return"),i},Ht=(t,e,n)=>(e=t[W("asyncIterator")])?e.call(t):(t=t[W("iterator")](),e={},n=(r,i)=>(i=t[r])&&(e[r]=o=>new Promise((s,a,u)=>(o=i.call(t,o),u=o.done,Promise.resolve(o.value).then(d=>s({value:d,done:u}),a)))),n("next"),n("return"),e);var Oi={};$t(Oi,{TagadaExternalTracker:()=>Te,TagadaTracker:()=>Nt});function jt(t){var r;if(typeof document=="undefined")return null;let n="; ".concat(document.cookie).split("; ".concat(t,"="));return n.length===2&&((r=n.pop())==null?void 0:r.split(";").shift())||null}var Vt={production:{baseUrl:"https://app.tagadapay.com",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionStatus:"/api/v1/checkout/session/status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},development:{baseUrl:"https://app.tagadapay.dev",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionStatus:"/api/v1/checkout/session/status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}},local:{baseUrl:"http://app.localhost:3000",endpoints:{checkout:{sessionInit:"/api/v1/checkout/session/init",sessionStatus:"/api/v1/checkout/session/status"},customer:{profile:"/api/v1/customer/profile",session:"/api/v1/customer/session"},store:{config:"/api/v1/store/config"}}}};function qt(t="local"){let e=Vt[t];if(!e)return console.warn("Unknown environment: ".concat(t,". Falling back to local.")),{environment:"local",apiConfig:Vt.local};let n=null;if(typeof window!="undefined"&&(n=new URLSearchParams(window.location.search).get("tagadaClientBaseUrl"),!n))try{n=localStorage.getItem("tgd_client_base_url")||jt("tgd_client_base_url")}catch(i){}return n?(console.log("[SDK] Using custom API base URL override: ".concat(n)),{environment:t,apiConfig:x(S({},e),{baseUrl:n})}):{environment:t,apiConfig:e}}function oe(){var i;if(typeof window=="undefined")return"local";let e=new URLSearchParams(window.location.search).get("tagadaClientEnv");if(e&&(e==="production"||e==="development"||e==="local"))return console.log("[SDK] Using explicit environment override: ".concat(e)),e;try{let o=localStorage.getItem("tgd_client_env")||jt("tgd_client_env");if(o&&(o==="production"||o==="development"||o==="local"))return console.log("[SDK] Using persisted environment override: ".concat(o)),o}catch(o){}let n=window.location.hostname,r=window.location.href;if(n==="localhost"||n.startsWith("127.")||n.startsWith("192.168.")||n.startsWith("10.")||n.includes(".local")||n===""||n==="0.0.0.0"){if(typeof window!="undefined"&&((i=window==null?void 0:window.__TAGADA_ENV__)!=null&&i.TAGADA_ENVIRONMENT)){let o=window.__TAGADA_ENV__.TAGADA_ENVIRONMENT.toLowerCase();if(o==="production"||o==="development"||o==="local")return console.log("[SDK] Local override detected: ".concat(o)),o}return"local"}return n==="app.tagadapay.com"||n.includes("tagadapay.com")||n.includes("yourproductiondomain.com")?"production":n==="app.tagadapay.dev"||n.includes("tagadapay.dev")||n.includes("vercel.app")||n.includes("netlify.app")||n.includes("surge.sh")||n.includes("github.io")||n.includes("herokuapp.com")||n.includes("railway.app")||r.includes("?env=dev")||r.includes("?dev=true")||r.includes("#dev")?"development":(console.warn("[SDK] Unknown domain: ".concat(n,", defaulting to production")),"production")}function se(t=!1){return oe()!=="local"?!1:t&&typeof window!="undefined"?!window.location.hostname.includes(".cdn."):!0}var xe=class{constructor(e){this.apiClient=e}async initialize(e){return this.apiClient.post("/api/v1/funnel/initialize",e)}async navigate(e){return this.apiClient.post("/api/v1/funnel/navigate",e)}async updateContext(e,n){return this.apiClient.patch("/api/v1/funnel/context/".concat(e),n)}async endSession(e){return this.apiClient.delete("/api/v1/funnel/session/".concat(e))}async getSession(e,n,r){let i=new URLSearchParams;n&&i.append("currentUrl",n),r&&i.append("includeDebugData","true");let o="/api/v1/funnel/session/".concat(e).concat(i.toString()?"?".concat(i):"");return this.apiClient.get(o)}};var J=class{constructor(){this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){this.listeners.forEach(n=>{try{n(e)}catch(r){console.error("Error in event listener:",r)}})}clear(){this.listeners.clear()}};var rt="tgd-funnel-session-id";function Gt(t){typeof document!="undefined"&&(document.cookie="".concat(rt,"=").concat(t,"; path=/; max-age=2592000; SameSite=Lax"))}function Wt(){if(typeof document=="undefined")return;let t=document.cookie.split("; ").find(e=>e.startsWith("".concat(rt,"=")));return t?t.split("=")[1]:void 0}function Jt(){typeof document!="undefined"&&(document.cookie="".concat(rt,"=; path=/; max-age=0"))}var it="cms_token";function j(t){if(typeof window!="undefined")try{localStorage.setItem(it,t),window.dispatchEvent(new Event("storage"))}catch(e){console.error("Failed to save token to localStorage:",e)}}function ae(){if(typeof window!="undefined")try{return localStorage.getItem(it)}catch(t){return console.error("Failed to get token from localStorage:",t),null}return null}function Pe(){if(typeof window!="undefined")try{localStorage.removeItem(it)}catch(t){console.error("Failed to clear token from localStorage:",t)}}var A={DRAFT:"tgd_draft",FUNNEL_TRACKING:"tgd_funnel_tracking",FORCE_RESET:"tgd_force_reset",CLIENT_ENV:"tgd_client_env",CLIENT_BASE_URL:"tgd_client_base_url"};function ve(t){if(typeof window=="undefined")return null;try{return localStorage.getItem(t)}catch(e){return null}}function le(t,e){if(typeof window!="undefined")try{localStorage.setItem(t,e)}catch(n){}}function ke(t){var r;if(typeof document=="undefined")return null;let n=document.cookie.split(";").find(i=>i.trim().startsWith("".concat(t,"=")));return n?(r=n.split("=")[1])==null?void 0:r.trim():null}function De(t,e,n=86400){typeof document!="undefined"&&(document.cookie="".concat(t,"=").concat(e,"; path=/; max-age=").concat(n))}function tr(t){typeof document!="undefined"&&(document.cookie="".concat(t,"=; path=/; max-age=0"))}function Ne(){if(typeof window=="undefined")return{};let t=new URLSearchParams(window.location.search),e,n=t.get("draft");if(n!==null)e=n==="true";else{let h=ve(A.DRAFT)||ke(A.DRAFT);h!==null&&(e=h==="true")}let r,i=t.get("funnelTracking");if(i!==null)r=i!=="false";else{let h=ve(A.FUNNEL_TRACKING)||ke(A.FUNNEL_TRACKING);h!==null&&(r=h!=="false")}let o=t.get("token")||ae()||null,s=t.get("funnelSessionId")||null,a=t.get("funnelId")||null,u=t.get("forceReset")==="true",d,c=t.get("tagadaClientEnv");if(c&&(c==="production"||c==="development"||c==="local"))d=c;else{let h=ve(A.CLIENT_ENV)||ke(A.CLIENT_ENV);h&&(h==="production"||h==="development"||h==="local")&&(d=h)}let p,C=t.get("tagadaClientBaseUrl");if(C)p=C;else{let h=ve(A.CLIENT_BASE_URL)||ke(A.CLIENT_BASE_URL);h&&(p=h)}return{forceReset:u,token:o,funnelSessionId:s,funnelId:a,draft:e,funnelTracking:r,tagadaClientEnv:d,tagadaClientBaseUrl:p}}function ot(){var e;return(e=Ne().draft)!=null?e:!1}function st(t){typeof window!="undefined"&&(t?(le(A.DRAFT,"true"),De(A.DRAFT,"true",86400)):(le(A.DRAFT,"false"),tr(A.DRAFT)))}function Zt(t=!1){let e=Ne(),n=e.forceReset||!1;return!n&&!e.token?(Yt(),!1):(t&&console.log("[SDK] Detected params:",e),n&&(t&&console.log("[SDK] Force reset: Clearing all stored state"),Pe(),Jt(),typeof window!="undefined"&&window.localStorage&&Object.keys(localStorage).forEach(i=>{(i.startsWith("tagadapay_")||i.startsWith("tgd_"))&&(t&&console.log("[SDK] Clearing localStorage: ".concat(i)),localStorage.removeItem(i))})),e.token!==null&&e.token!==void 0?(t&&console.log("[SDK] Using token from URL:",e.token.substring(0,20)+"..."),e.token===""||e.token==="null"?Pe():j(e.token)):n&&(t&&console.log("[SDK] Force reset mode (no token)"),Pe()),Yt(),e.funnelSessionId&&t&&console.log("[SDK] Using funnelSessionId from URL:",e.funnelSessionId),n)}function Yt(){if(typeof window=="undefined")return;let t=new URLSearchParams(window.location.search),e=t.get("draft");e!==null&&st(e==="true");let n=t.get("funnelTracking");n!==null&&nr(n!=="false");let r=t.get("tagadaClientEnv");r&&(r==="production"||r==="development"||r==="local")&&rr(r);let i=t.get("tagadaClientBaseUrl");i&&ir(i)}function nr(t){if(typeof window=="undefined")return;let e=t?"true":"false";le(A.FUNNEL_TRACKING,e),De(A.FUNNEL_TRACKING,e,86400)}function rr(t){typeof window!="undefined"&&(le(A.CLIENT_ENV,t),De(A.CLIENT_ENV,t,86400))}function ir(t){typeof window!="undefined"&&(le(A.CLIENT_BASE_URL,t),De(A.CLIENT_BASE_URL,t,86400))}function sr(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_ID__)return window.__TGD_FUNNEL_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}function Xt(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_VARIANT_ID__)return window.__TGD_FUNNEL_VARIANT_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-variant-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}function Qt(){if(typeof window!="undefined"){if(window.__TGD_FUNNEL_STEP_ID__)return window.__TGD_FUNNEL_STEP_ID__;if(typeof document!="undefined"){let t=document.querySelector('meta[name="x-funnel-step-id"]');return(t==null?void 0:t.getAttribute("content"))||void 0}}}var Oe=class{constructor(e){this.eventDispatcher=new J;this.isInitializing=!1;this.initializationAttempted=!1;this.config=e,this.resource=new xe(e.apiClient),this.state={context:null,isLoading:!1,isInitialized:!1,isNavigating:!1,error:null,sessionError:null}}setConfig(e){this.config=S(S({},this.config),e)}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}async autoInitialize(e,n,r){if(this.state.context)return this.state.context;if(this.isInitializing||this.initializationAttempted)return null;this.initializationAttempted=!0,this.isInitializing=!0,this.updateState({isLoading:!0,error:null});try{let i=new URLSearchParams(typeof window!="undefined"?window.location.search:""),s=i.get("funnelId")||r,a=i.get("funnelSessionId");a||(a=Wt()||null);let u=sr(),d=Xt(),c=Qt(),p=Ne(),C=u||s;this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-initializing...",{existingSessionId:a,effectiveFunnelId:C,funnelVariantId:d,funnelStepId:c,draft:p.draft,funnelTracking:p.funnelTracking});let h=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:n.id,accountId:n.accountId},funnelId:C,existingSessionId:a||void 0,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:d,funnelStepId:c,draft:p.draft,funnelTracking:p.funnelTracking});if(h.success&&h.context){let f=this.enrichContext(h.context);return this.handleSessionSuccess(f),f}else throw new Error(h.error||"Failed to initialize funnel session")}catch(i){let o=i instanceof Error?i:new Error(String(i));throw this.updateState({error:o,isLoading:!1}),this.config.debugMode&&console.error("\u274C [FunnelClient] Init failed:",o),o}finally{this.isInitializing=!1}}async initialize(e,n,r,i){this.updateState({isLoading:!0,error:null});try{let o=Xt(),s=Qt();this.config.debugMode&&(o&&console.log("\u{1F3AF} [FunnelClient] Detected A/B test variant:",o),s&&console.log("\u{1F3AF} [FunnelClient] Detected step ID:",s));let a=await this.resource.initialize({cmsSession:{customerId:e.customerId,sessionId:e.sessionId,storeId:n.id,accountId:n.accountId},funnelId:r,entryStepId:i,currentUrl:typeof window!="undefined"?window.location.href:void 0,funnelVariantId:o,funnelStepId:s});if(a.success&&a.context){let u=this.enrichContext(a.context);return this.handleSessionSuccess(u),u}else throw new Error(a.error||"Failed to initialize")}catch(o){let s=o instanceof Error?o:new Error(String(o));throw this.updateState({error:s,isLoading:!1}),s}}async navigate(e){var n;if(!((n=this.state.context)!=null&&n.sessionId))throw new Error("No active session");this.updateState({isNavigating:!0,isLoading:!0});try{let r=await this.resource.navigate({sessionId:this.state.context.sessionId,event:e});if(r.success&&r.result){await this.refreshSession(),this.updateState({isNavigating:!1,isLoading:!1});let i=r.result;return this.config.autoRedirect!==!1&&(i!=null&&i.url)&&typeof window!="undefined"&&(this.config.debugMode&&console.log("\u{1F680} [FunnelClient] Auto-redirecting to:",i.url),window.location.href=i.url),i}throw new Error(r.error||"Navigation failed")}catch(r){let i=r instanceof Error?r:new Error(String(r));throw this.updateState({error:i,isNavigating:!1,isLoading:!1}),i}}async goToStep(e){return this.navigate({type:"direct_navigation",data:{targetStepId:e}})}async refreshSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{let n=await this.resource.getSession(this.state.context.sessionId);if(n.success&&n.context){let r=this.enrichContext(n.context);return this.updateState({context:r,sessionError:null}),r}}catch(n){this.updateState({sessionError:n instanceof Error?n:new Error(String(n))})}}async updateContext(e){var n;if(!((n=this.state.context)!=null&&n.sessionId))throw new Error("No active session");this.updateState({isLoading:!0});try{let r=await this.resource.updateContext(this.state.context.sessionId,{contextUpdates:e});if(r.success)await this.refreshSession();else throw new Error(r.error||"Failed to update context")}finally{this.updateState({isLoading:!1})}}async endSession(){var e;if((e=this.state.context)!=null&&e.sessionId)try{await this.resource.endSession(this.state.context.sessionId)}finally{this.state.context=null,this.updateState({context:null,isInitialized:!1})}}updateState(e){this.state=S(S({},this.state),e),this.eventDispatcher.notify(this.state)}handleSessionSuccess(e){Gt(e.sessionId),this.updateState({context:e,isLoading:!1,isInitialized:!0,error:null,sessionError:null})}enrichContext(e){var s,a;if((((s=this.config.environment)==null?void 0:s.environment)||oe())!=="local")return e;let r=((a=this.config.pluginConfig)==null?void 0:a.staticResources)||{};if(Object.keys(r).length===0)return e;let i=e.static||{};return Object.keys(r).every(u=>i[u]===r[u])&&Object.keys(i).length===Object.keys(r).length?e:x(S({},e),{static:S(S({},r),i)})}};function ue(t,e){return function(){return t.apply(e,arguments)}}var{toString:ar}=Object.prototype,{getPrototypeOf:lt}=Object,{iterator:_e,toStringTag:tn}=Symbol,Le=(t=>e=>{let n=ar.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),N=t=>(t=t.toLowerCase(),e=>Le(e)===t),Ue=t=>e=>typeof e===t,{isArray:Z}=Array,Y=Ue("undefined");function ce(t){return t!==null&&!Y(t)&&t.constructor!==null&&!Y(t.constructor)&&v(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var nn=N("ArrayBuffer");function lr(t){let e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&nn(t.buffer),e}var ur=Ue("string"),v=Ue("function"),rn=Ue("number"),de=t=>t!==null&&typeof t=="object",cr=t=>t===!0||t===!1,Fe=t=>{if(Le(t)!=="object")return!1;let e=lt(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(tn in t)&&!(_e in t)},dr=t=>{if(!de(t)||ce(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch(e){return!1}},fr=N("Date"),pr=N("File"),gr=N("Blob"),mr=N("FileList"),hr=t=>de(t)&&v(t.pipe),yr=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||v(t.append)&&((e=Le(t))==="formdata"||e==="object"&&v(t.toString)&&t.toString()==="[object FormData]"))},Sr=N("URLSearchParams"),[Cr,wr,br,Tr]=["ReadableStream","Request","Response","Headers"].map(N),Er=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fe(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t=="undefined")return;let r,i;if(typeof t!="object"&&(t=[t]),Z(t))for(r=0,i=t.length;r<i;r++)e.call(null,t[r],r,t);else{if(ce(t))return;let o=n?Object.getOwnPropertyNames(t):Object.keys(t),s=o.length,a;for(r=0;r<s;r++)a=o[r],e.call(null,t[a],a,t)}}function on(t,e){if(ce(t))return null;e=e.toLowerCase();let n=Object.keys(t),r=n.length,i;for(;r-- >0;)if(i=n[r],e===i.toLowerCase())return i;return null}var q=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:global,sn=t=>!Y(t)&&t!==q;function at(){let{caseless:t,skipUndefined:e}=sn(this)&&this||{},n={},r=(i,o)=>{let s=t&&on(n,o)||o;Fe(n[s])&&Fe(i)?n[s]=at(n[s],i):Fe(i)?n[s]=at({},i):Z(i)?n[s]=i.slice():(!e||!Y(i))&&(n[s]=i)};for(let i=0,o=arguments.length;i<o;i++)arguments[i]&&fe(arguments[i],r);return n}var Rr=(t,e,n,{allOwnKeys:r}={})=>(fe(e,(i,o)=>{n&&v(i)?t[o]=ue(i,n):t[o]=i},{allOwnKeys:r}),t),Ir=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ar=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},xr=(t,e,n,r)=>{let i,o,s,a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),o=i.length;o-- >0;)s=i[o],(!r||r(s,t,e))&&!a[s]&&(e[s]=t[s],a[s]=!0);t=n!==!1&&lt(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},Pr=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;let r=t.indexOf(e,n);return r!==-1&&r===n},vr=t=>{if(!t)return null;if(Z(t))return t;let e=t.length;if(!rn(e))return null;let n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},kr=(t=>e=>t&&e instanceof t)(typeof Uint8Array!="undefined"&&lt(Uint8Array)),Dr=(t,e)=>{let r=(t&&t[_e]).call(t),i;for(;(i=r.next())&&!i.done;){let o=i.value;e.call(t,o[0],o[1])}},Nr=(t,e)=>{let n,r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Or=N("HTMLFormElement"),Fr=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),en=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),_r=N("RegExp"),an=(t,e)=>{let n=Object.getOwnPropertyDescriptors(t),r={};fe(n,(i,o)=>{let s;(s=e(i,o,t))!==!1&&(r[o]=s||i)}),Object.defineProperties(t,r)},Lr=t=>{an(t,(e,n)=>{if(v(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;let r=t[n];if(v(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+"'")})}})},Ur=(t,e)=>{let n={},r=i=>{i.forEach(o=>{n[o]=!0})};return Z(t)?r(t):r(String(t).split(e)),n},Br=()=>{},Mr=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function zr(t){return!!(t&&v(t.append)&&t[tn]==="FormData"&&t[_e])}var Kr=t=>{let e=new Array(10),n=(r,i)=>{if(de(r)){if(e.indexOf(r)>=0)return;if(ce(r))return r;if(!("toJSON"in r)){e[i]=r;let o=Z(r)?[]:{};return fe(r,(s,a)=>{let u=n(s,i+1);!Y(u)&&(o[a]=u)}),e[i]=void 0,o}}return r};return n(t,0)},$r=N("AsyncFunction"),Hr=t=>t&&(de(t)||v(t))&&v(t.then)&&v(t.catch),ln=((t,e)=>t?setImmediate:e?((n,r)=>(q.addEventListener("message",({source:i,data:o})=>{i===q&&o===n&&r.length&&r.shift()()},!1),i=>{r.push(i),q.postMessage(n,"*")}))("axios@".concat(Math.random()),[]):n=>setTimeout(n))(typeof setImmediate=="function",v(q.postMessage)),Vr=typeof queueMicrotask!="undefined"?queueMicrotask.bind(q):typeof process!="undefined"&&process.nextTick||ln,jr=t=>t!=null&&v(t[_e]),l={isArray:Z,isArrayBuffer:nn,isBuffer:ce,isFormData:yr,isArrayBufferView:lr,isString:ur,isNumber:rn,isBoolean:cr,isObject:de,isPlainObject:Fe,isEmptyObject:dr,isReadableStream:Cr,isRequest:wr,isResponse:br,isHeaders:Tr,isUndefined:Y,isDate:fr,isFile:pr,isBlob:gr,isRegExp:_r,isFunction:v,isStream:hr,isURLSearchParams:Sr,isTypedArray:kr,isFileList:mr,forEach:fe,merge:at,extend:Rr,trim:Er,stripBOM:Ir,inherits:Ar,toFlatObject:xr,kindOf:Le,kindOfTest:N,endsWith:Pr,toArray:vr,forEachEntry:Dr,matchAll:Nr,isHTMLForm:Or,hasOwnProperty:en,hasOwnProp:en,reduceDescriptors:an,freezeMethods:Lr,toObjectSet:Ur,toCamelCase:Fr,noop:Br,toFiniteNumber:Mr,findKey:on,global:q,isContextDefined:sn,isSpecCompliantForm:zr,toJSONObject:Kr,isAsyncFn:$r,isThenable:Hr,setImmediate:ln,asap:Vr,isIterable:jr};function X(t,e,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,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)}l.inherits(X,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:l.toJSONObject(this.config),code:this.code,status:this.status}}});var un=X.prototype,cn={};["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(t=>{cn[t]={value:t}});Object.defineProperties(X,cn);Object.defineProperty(un,"isAxiosError",{value:!0});X.from=(t,e,n,r,i,o)=>{let s=Object.create(un);l.toFlatObject(t,s,function(c){return c!==Error.prototype},d=>d!=="isAxiosError");let a=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return X.call(s,a,u,n,r,i),t&&s.cause==null&&Object.defineProperty(s,"cause",{value:t,configurable:!0}),s.name=t&&t.name||"Error",o&&Object.assign(s,o),s};var y=X;var Be=null;function ut(t){return l.isPlainObject(t)||l.isArray(t)}function fn(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function dn(t,e,n){return t?t.concat(e).map(function(i,o){return i=fn(i),!n&&o?"["+i+"]":i}).join(n?".":""):e}function qr(t){return l.isArray(t)&&!t.some(ut)}var Gr=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function Wr(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new(Be||FormData),n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,g){return!l.isUndefined(g[m])});let r=n.metaTokens,i=n.visitor||c,o=n.dots,s=n.indexes,u=(n.Blob||typeof Blob!="undefined"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(i))throw new TypeError("visitor must be a function");function d(f){if(f===null)return"";if(l.isDate(f))return f.toISOString();if(l.isBoolean(f))return f.toString();if(!u&&l.isBlob(f))throw new y("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(f)||l.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function c(f,m,g){let w=f;if(f&&!g&&typeof f=="object"){if(l.endsWith(m,"{}"))m=r?m:m.slice(0,-2),f=JSON.stringify(f);else if(l.isArray(f)&&qr(f)||(l.isFileList(f)||l.endsWith(m,"[]"))&&(w=l.toArray(f)))return m=fn(m),w.forEach(function(b,P){!(l.isUndefined(b)||b===null)&&e.append(s===!0?dn([m],P,o):s===null?m:m+"[]",d(b))}),!1}return ut(f)?!0:(e.append(dn(g,m,o),d(f)),!1)}let p=[],C=Object.assign(Gr,{defaultVisitor:c,convertValue:d,isVisitable:ut});function h(f,m){if(!l.isUndefined(f)){if(p.indexOf(f)!==-1)throw Error("Circular reference detected in "+m.join("."));p.push(f),l.forEach(f,function(w,I){(!(l.isUndefined(w)||w===null)&&i.call(e,w,l.isString(I)?I.trim():I,m,C))===!0&&h(w,m?m.concat(I):[I])}),p.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return h(t),e}var K=Wr;function pn(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function gn(t,e){this._pairs=[],t&&K(t,this,e)}var mn=gn.prototype;mn.append=function(e,n){this._pairs.push([e,n])};mn.toString=function(e){let n=e?function(r){return e.call(this,r,pn)}:pn;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};var Me=gn;function Jr(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function pe(t,e,n){if(!e)return t;let r=n&&n.encode||Jr;l.isFunction(n)&&(n={serialize:n});let i=n&&n.serialize,o;if(i?o=i(e,n):o=l.isURLSearchParams(e)?e.toString():new Me(e,n).toString(r),o){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}var ct=class{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){l.forEach(this.handlers,function(r){r!==null&&e(r)})}},dt=ct;var ze={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var hn=typeof URLSearchParams!="undefined"?URLSearchParams:Me;var yn=typeof FormData!="undefined"?FormData:null;var Sn=typeof Blob!="undefined"?Blob:null;var Cn={isBrowser:!0,classes:{URLSearchParams:hn,FormData:yn,Blob:Sn},protocols:["http","https","file","blob","url","data"]};var gt={};$t(gt,{hasBrowserEnv:()=>pt,hasStandardBrowserEnv:()=>Yr,hasStandardBrowserWebWorkerEnv:()=>Zr,navigator:()=>ft,origin:()=>Xr});var pt=typeof window!="undefined"&&typeof document!="undefined",ft=typeof navigator=="object"&&navigator||void 0,Yr=pt&&(!ft||["ReactNative","NativeScript","NS"].indexOf(ft.product)<0),Zr=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Xr=pt&&window.location.href||"http://localhost";var T=S(S({},gt),Cn);function mt(t,e){return K(t,new T.classes.URLSearchParams,S({visitor:function(n,r,i,o){return T.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},e))}function Qr(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function ei(t){let e={},n=Object.keys(t),r,i=n.length,o;for(r=0;r<i;r++)o=n[r],e[o]=t[o];return e}function ti(t){function e(n,r,i,o){let s=n[o++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),u=o>=n.length;return s=!s&&l.isArray(i)?i.length:s,u?(l.hasOwnProp(i,s)?i[s]=[i[s],r]:i[s]=r,!a):((!i[s]||!l.isObject(i[s]))&&(i[s]=[]),e(n,r,i[s],o)&&l.isArray(i[s])&&(i[s]=ei(i[s])),!a)}if(l.isFormData(t)&&l.isFunction(t.entries)){let n={};return l.forEachEntry(t,(r,i)=>{e(Qr(r),i,n,0)}),n}return null}var Ke=ti;function ni(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}var ht={transitional:ze,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){let r=n.getContentType()||"",i=r.indexOf("application/json")>-1,o=l.isObject(e);if(o&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return i?JSON.stringify(Ke(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return mt(e,this.formSerializer).toString();if((a=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return K(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return o||i?(n.setContentType("application/json",!1),ni(e)):e}],transformResponse:[function(e){let n=this.transitional||ht.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||i)){let s=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(a){if(s)throw a.name==="SyntaxError"?y.from(a,y.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:T.classes.FormData,Blob:T.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{ht.headers[t]={}});var Q=ht;var ri=l.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"]),wn=t=>{let e={},n,r,i;return t&&t.split("\n").forEach(function(s){i=s.indexOf(":"),n=s.substring(0,i).trim().toLowerCase(),r=s.substring(i+1).trim(),!(!n||e[n]&&ri[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e};var bn=Symbol("internals");function ge(t){return t&&String(t).trim().toLowerCase()}function $e(t){return t===!1||t==null?t:l.isArray(t)?t.map($e):String(t)}function ii(t){let e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}var oi=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function yt(t,e,n,r,i){if(l.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function si(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function ai(t,e){let n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(i,o,s){return this[r].call(this,e,i,o,s)},configurable:!0})})}var ee=class{constructor(e){e&&this.set(e)}set(e,n,r){let i=this;function o(a,u,d){let c=ge(u);if(!c)throw new Error("header name must be a non-empty string");let p=l.findKey(i,c);(!p||i[p]===void 0||d===!0||d===void 0&&i[p]!==!1)&&(i[p||u]=$e(a))}let s=(a,u)=>l.forEach(a,(d,c)=>o(d,c,u));if(l.isPlainObject(e)||e instanceof this.constructor)s(e,n);else if(l.isString(e)&&(e=e.trim())&&!oi(e))s(wn(e),n);else if(l.isObject(e)&&l.isIterable(e)){let a={},u,d;for(let c of e){if(!l.isArray(c))throw TypeError("Object iterator must return a key-value pair");a[d=c[0]]=(u=a[d])?l.isArray(u)?[...u,c[1]]:[u,c[1]]:c[1]}s(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=ge(e),e){let r=l.findKey(this,e);if(r){let i=this[r];if(!n)return i;if(n===!0)return ii(i);if(l.isFunction(n))return n.call(this,i,r);if(l.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ge(e),e){let r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||yt(this,this[r],r,n)))}return!1}delete(e,n){let r=this,i=!1;function o(s){if(s=ge(s),s){let a=l.findKey(r,s);a&&(!n||yt(r,r[a],a,n))&&(delete r[a],i=!0)}}return l.isArray(e)?e.forEach(o):o(e),i}clear(e){let n=Object.keys(this),r=n.length,i=!1;for(;r--;){let o=n[r];(!e||yt(this,this[o],o,e,!0))&&(delete this[o],i=!0)}return i}normalize(e){let n=this,r={};return l.forEach(this,(i,o)=>{let s=l.findKey(r,o);if(s){n[s]=$e(i),delete n[o];return}let a=e?si(o):String(o).trim();a!==o&&delete n[o],n[a]=$e(i),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let n=Object.create(null);return l.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&l.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("\n")}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){let r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){let r=(this[bn]=this[bn]={accessors:{}}).accessors,i=this.prototype;function o(s){let a=ge(s);r[a]||(ai(i,s),r[a]=!0)}return l.isArray(e)?e.forEach(o):o(e),this}};ee.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(ee.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(ee);var R=ee;function me(t,e){let n=this||Q,r=e||n,i=R.from(r.headers),o=r.data;return l.forEach(t,function(a){o=a.call(n,o,i.normalize(),e?e.status:void 0)}),i.normalize(),o}function he(t){return!!(t&&t.__CANCEL__)}function Tn(t,e,n){y.call(this,t==null?"canceled":t,y.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(Tn,y,{__CANCEL__:!0});var _=Tn;function ye(t,e,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new y("Request failed with status code "+n.status,[y.ERR_BAD_REQUEST,y.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function St(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function li(t,e){t=t||10;let n=new Array(t),r=new Array(t),i=0,o=0,s;return e=e!==void 0?e:1e3,function(u){let d=Date.now(),c=r[o];s||(s=d),n[i]=u,r[i]=d;let p=o,C=0;for(;p!==i;)C+=n[p++],p=p%t;if(i=(i+1)%t,i===o&&(o=(o+1)%t),d-s<e)return;let h=c&&d-c;return h?Math.round(C*1e3/h):void 0}}var En=li;function ui(t,e){let n=0,r=1e3/e,i,o,s=(d,c=Date.now())=>{n=c,i=null,o&&(clearTimeout(o),o=null),t(...d)};return[(...d)=>{let c=Date.now(),p=c-n;p>=r?s(d,c):(i=d,o||(o=setTimeout(()=>{o=null,s(i)},r-p)))},()=>i&&s(i)]}var Rn=ui;var te=(t,e,n=3)=>{let r=0,i=En(50,250);return Rn(o=>{let s=o.loaded,a=o.lengthComputable?o.total:void 0,u=s-r,d=i(u),c=s<=a;r=s;let p={loaded:s,total:a,progress:a?s/a:void 0,bytes:u,rate:d||void 0,estimated:d&&a&&c?(a-s)/d:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(p)},n)},Ct=(t,e)=>{let n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},wt=t=>(...e)=>l.asap(()=>t(...e));var In=T.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,T.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(T.origin),T.navigator&&/(msie|trident)/i.test(T.navigator.userAgent)):()=>!0;var An=T.hasStandardBrowserEnv?{write(t,e,n,r,i,o,s){if(typeof document=="undefined")return;let a=["".concat(t,"=").concat(encodeURIComponent(e))];l.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),l.isString(r)&&a.push("path=".concat(r)),l.isString(i)&&a.push("domain=".concat(i)),o===!0&&a.push("secure"),l.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(t){if(typeof document=="undefined")return null;let e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function bt(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Tt(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Se(t,e,n){let r=!bt(e);return t&&(r||n==!1)?Tt(t,e):e}var xn=t=>t instanceof R?S({},t):t;function O(t,e){e=e||{};let n={};function r(d,c,p,C){return l.isPlainObject(d)&&l.isPlainObject(c)?l.merge.call({caseless:C},d,c):l.isPlainObject(c)?l.merge({},c):l.isArray(c)?c.slice():c}function i(d,c,p,C){if(l.isUndefined(c)){if(!l.isUndefined(d))return r(void 0,d,p,C)}else return r(d,c,p,C)}function o(d,c){if(!l.isUndefined(c))return r(void 0,c)}function s(d,c){if(l.isUndefined(c)){if(!l.isUndefined(d))return r(void 0,d)}else return r(void 0,c)}function a(d,c,p){if(p in e)return r(d,c);if(p in t)return r(void 0,d)}let u={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(d,c,p)=>i(xn(d),xn(c),p,!0)};return l.forEach(Object.keys(S(S({},t),e)),function(c){let p=u[c]||i,C=p(t[c],e[c],c);l.isUndefined(C)&&p!==a||(n[c]=C)}),n}var He=t=>{let e=O({},t),{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=e;if(e.headers=s=R.from(s),e.url=pe(Se(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),l.isFormData(n)){if(T.hasStandardBrowserEnv||T.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(l.isFunction(n.getHeaders)){let u=n.getHeaders(),d=["content-type","content-length"];Object.entries(u).forEach(([c,p])=>{d.includes(c.toLowerCase())&&s.set(c,p)})}}if(T.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&In(e.url))){let u=i&&o&&An.read(o);u&&s.set(i,u)}return e};var ci=typeof XMLHttpRequest!="undefined",Pn=ci&&function(t){return new Promise(function(n,r){let i=He(t),o=i.data,s=R.from(i.headers).normalize(),{responseType:a,onUploadProgress:u,onDownloadProgress:d}=i,c,p,C,h,f;function m(){h&&h(),f&&f(),i.cancelToken&&i.cancelToken.unsubscribe(c),i.signal&&i.signal.removeEventListener("abort",c)}let g=new XMLHttpRequest;g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout;function w(){if(!g)return;let b=R.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),D={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:b,config:t,request:g};ye(function(k){n(k),m()},function(k){r(k),m()},D),g=null}"onloadend"in g?g.onloadend=w:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(w)},g.onabort=function(){g&&(r(new y("Request aborted",y.ECONNABORTED,t,g)),g=null)},g.onerror=function(P){let D=P&&P.message?P.message:"Network Error",$=new y(D,y.ERR_NETWORK,t,g);$.event=P||null,r($),g=null},g.ontimeout=function(){let P=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",D=i.transitional||ze;i.timeoutErrorMessage&&(P=i.timeoutErrorMessage),r(new y(P,D.clarifyTimeoutError?y.ETIMEDOUT:y.ECONNABORTED,t,g)),g=null},o===void 0&&s.setContentType(null),"setRequestHeader"in g&&l.forEach(s.toJSON(),function(P,D){g.setRequestHeader(D,P)}),l.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),a&&a!=="json"&&(g.responseType=i.responseType),d&&([C,f]=te(d,!0),g.addEventListener("progress",C)),u&&g.upload&&([p,h]=te(u),g.upload.addEventListener("progress",p),g.upload.addEventListener("loadend",h)),(i.cancelToken||i.signal)&&(c=b=>{g&&(r(!b||b.type?new _(null,t,g):b),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(c),i.signal&&(i.signal.aborted?c():i.signal.addEventListener("abort",c)));let I=St(i.url);if(I&&T.protocols.indexOf(I)===-1){r(new y("Unsupported protocol "+I+":",y.ERR_BAD_REQUEST,t));return}g.send(o||null)})};var di=(t,e)=>{let{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,i,o=function(d){if(!i){i=!0,a();let c=d instanceof Error?d:this.reason;r.abort(c instanceof y?c:new _(c instanceof Error?c.message:c))}},s=e&&setTimeout(()=>{s=null,o(new y("timeout ".concat(e," of ms exceeded"),y.ETIMEDOUT))},e),a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(d=>{d.unsubscribe?d.unsubscribe(o):d.removeEventListener("abort",o)}),t=null)};t.forEach(d=>d.addEventListener("abort",o));let{signal:u}=r;return u.unsubscribe=()=>l.asap(a),u}},vn=di;var fi=function*(t,e){let n=t.byteLength;if(!e||n<e){yield t;return}let r=0,i;for(;r<n;)i=r+e,yield t.slice(r,i),r=i},pi=function(t,e){return tt(this,null,function*(){try{for(var n=Ht(gi(t)),r,i,o;r=!(i=yield new V(n.next())).done;r=!1){let s=i.value;yield*nt(fi(s,e))}}catch(i){o=[i]}finally{try{r&&(i=n.return)&&(yield new V(i.call(n)))}finally{if(o)throw o[0]}}})},gi=function(t){return tt(this,null,function*(){if(t[Symbol.asyncIterator]){yield*nt(t);return}let e=t.getReader();try{for(;;){let{done:n,value:r}=yield new V(e.read());if(n)break;yield r}}finally{yield new V(e.cancel())}})},Et=(t,e,n,r)=>{let i=pi(t,e),o=0,s,a=u=>{s||(s=!0,r&&r(u))};return new ReadableStream({async pull(u){try{let{done:d,value:c}=await i.next();if(d){a(),u.close();return}let p=c.byteLength;if(n){let C=o+=p;n(C)}u.enqueue(new Uint8Array(c))}catch(d){throw a(d),d}},cancel(u){return a(u),i.return()}},{highWaterMark:2})};var kn=64*1024,{isFunction:Ve}=l,mi=(({Request:t,Response:e})=>({Request:t,Response:e}))(l.global),{ReadableStream:Dn,TextEncoder:Nn}=l.global,On=(t,...e)=>{try{return!!t(...e)}catch(n){return!1}},hi=t=>{t=l.merge.call({skipUndefined:!0},mi,t);let{fetch:e,Request:n,Response:r}=t,i=e?Ve(e):typeof fetch=="function",o=Ve(n),s=Ve(r);if(!i)return!1;let a=i&&Ve(Dn),u=i&&(typeof Nn=="function"?(f=>m=>f.encode(m))(new Nn):async f=>new Uint8Array(await new n(f).arrayBuffer())),d=o&&a&&On(()=>{let f=!1,m=new n(T.origin,{body:new Dn,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),c=s&&a&&On(()=>l.isReadableStream(new r("").body)),p={stream:c&&(f=>f.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!p[f]&&(p[f]=(m,g)=>{let w=m&&m[f];if(w)return w.call(m);throw new y("Response type '".concat(f,"' is not supported"),y.ERR_NOT_SUPPORT,g)})});let C=async f=>{if(f==null)return 0;if(l.isBlob(f))return f.size;if(l.isSpecCompliantForm(f))return(await new n(T.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(l.isArrayBufferView(f)||l.isArrayBuffer(f))return f.byteLength;if(l.isURLSearchParams(f)&&(f=f+""),l.isString(f))return(await u(f)).byteLength},h=async(f,m)=>{let g=l.toFiniteNumber(f.getContentLength());return g==null?C(m):g};return async f=>{let{url:m,method:g,data:w,signal:I,cancelToken:b,timeout:P,onDownloadProgress:D,onUploadProgress:$,responseType:k,headers:Qe,withCredentials:Ee="same-origin",fetchOptions:Ot}=He(f),Ft=e||fetch;k=k?(k+"").toLowerCase():"text";let Re=vn([I,b&&b.toAbortSignal()],P),ie=null,H=Re&&Re.unsubscribe&&(()=>{Re.unsubscribe()}),_t;try{if($&&d&&g!=="get"&&g!=="head"&&(_t=await h(Qe,w))!==0){let z=new n(m,{method:"POST",body:w,duplex:"half"}),G;if(l.isFormData(w)&&(G=z.headers.get("content-type"))&&Qe.setContentType(G),z.body){let[et,Ie]=Ct(_t,te(wt($)));w=Et(z.body,kn,et,Ie)}}l.isString(Ee)||(Ee=Ee?"include":"omit");let F=o&&"credentials"in n.prototype,Lt=x(S({},Ot),{signal:Re,method:g.toUpperCase(),headers:Qe.normalize().toJSON(),body:w,duplex:"half",credentials:F?Ee:void 0});ie=o&&new n(m,Lt);let M=await(o?Ft(ie,Ot):Ft(m,Lt)),Ut=c&&(k==="stream"||k==="response");if(c&&(D||Ut&&H)){let z={};["status","statusText","headers"].forEach(Bt=>{z[Bt]=M[Bt]});let G=l.toFiniteNumber(M.headers.get("content-length")),[et,Ie]=D&&Ct(G,te(wt(D),!0))||[];M=new r(Et(M.body,kn,et,()=>{Ie&&Ie(),H&&H()}),z)}k=k||"text";let qn=await p[l.findKey(p,k)||"text"](M,f);return!Ut&&H&&H(),await new Promise((z,G)=>{ye(z,G,{data:qn,headers:R.from(M.headers),status:M.status,statusText:M.statusText,config:f,request:ie})})}catch(F){throw H&&H(),F&&F.name==="TypeError"&&/Load failed|fetch/i.test(F.message)?Object.assign(new y("Network Error",y.ERR_NETWORK,f,ie),{cause:F.cause||F}):y.from(F,F&&F.code,f,ie)}}},yi=new Map,Rt=t=>{let e=t&&t.env||{},{fetch:n,Request:r,Response:i}=e,o=[r,i,n],s=o.length,a=s,u,d,c=yi;for(;a--;)u=o[a],d=c.get(u),d===void 0&&c.set(u,d=a?new Map:hi(e)),c=d;return d},ua=Rt();var It={http:Be,xhr:Pn,fetch:{get:Rt}};l.forEach(It,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(n){}Object.defineProperty(t,"adapterName",{value:e})}});var Fn=t=>"- ".concat(t),Ci=t=>l.isFunction(t)||t===null||t===!1;function wi(t,e){t=l.isArray(t)?t:[t];let{length:n}=t,r,i,o={};for(let s=0;s<n;s++){r=t[s];let a;if(i=r,!Ci(r)&&(i=It[(a=String(r)).toLowerCase()],i===void 0))throw new y("Unknown adapter '".concat(a,"'"));if(i&&(l.isFunction(i)||(i=i.get(e))))break;o[a||"#"+s]=i}if(!i){let s=Object.entries(o).map(([u,d])=>"adapter ".concat(u," ")+(d===!1?"is not supported by the environment":"is not available in the build")),a=n?s.length>1?"since :\n"+s.map(Fn).join("\n"):" "+Fn(s[0]):"as no adapter specified";throw new y("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}var je={getAdapter:wi,adapters:It};function At(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new _(null,t)}function qe(t){return At(t),t.headers=R.from(t.headers),t.data=me.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),je.getAdapter(t.adapter||Q.adapter,t)(t).then(function(r){return At(t),r.data=me.call(t,t.transformResponse,r),r.headers=R.from(r.headers),r},function(r){return he(r)||(At(t),r&&r.response&&(r.response.data=me.call(t,t.transformResponse,r.response),r.response.headers=R.from(r.response.headers))),Promise.reject(r)})}var Ge="1.13.0";var We={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{We[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var _n={};We.transitional=function(e,n,r){function i(o,s){return"[Axios v"+Ge+"] Transitional option '"+o+"'"+s+(r?". "+r:"")}return(o,s,a)=>{if(e===!1)throw new y(i(s," has been removed"+(n?" in "+n:"")),y.ERR_DEPRECATED);return n&&!_n[s]&&(_n[s]=!0,console.warn(i(s," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,s,a):!0}};We.spelling=function(e){return(n,r)=>(console.warn("".concat(r," is likely a misspelling of ").concat(e)),!0)};function bi(t,e,n){if(typeof t!="object")throw new y("options must be an object",y.ERR_BAD_OPTION_VALUE);let r=Object.keys(t),i=r.length;for(;i-- >0;){let o=r[i],s=e[o];if(s){let a=t[o],u=a===void 0||s(a,o,t);if(u!==!0)throw new y("option "+o+" must be "+u,y.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new y("Unknown option "+o,y.ERR_BAD_OPTION)}}var Ce={assertOptions:bi,validators:We};var L=Ce.validators,ne=class{constructor(e){this.defaults=e||{},this.interceptors={request:new dt,response:new dt}}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;let o=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+o):r.stack=o}catch(s){}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=O(this.defaults,n);let{transitional:r,paramsSerializer:i,headers:o}=n;r!==void 0&&Ce.assertOptions(r,{silentJSONParsing:L.transitional(L.boolean),forcedJSONParsing:L.transitional(L.boolean),clarifyTimeoutError:L.transitional(L.boolean)},!1),i!=null&&(l.isFunction(i)?n.paramsSerializer={serialize:i}:Ce.assertOptions(i,{encode:L.function,serialize:L.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ce.assertOptions(n,{baseUrl:L.spelling("baseURL"),withXsrfToken:L.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=o&&l.merge(o.common,o[n.method]);o&&l.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=R.concat(s,o);let a=[],u=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(u=u&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});let d=[];this.interceptors.response.forEach(function(m){d.push(m.fulfilled,m.rejected)});let c,p=0,C;if(!u){let f=[qe.bind(this),void 0];for(f.unshift(...a),f.push(...d),C=f.length,c=Promise.resolve(n);p<C;)c=c.then(f[p++],f[p++]);return c}C=a.length;let h=n;for(;p<C;){let f=a[p++],m=a[p++];try{h=f(h)}catch(g){m.call(this,g);break}}try{c=qe.call(this,h)}catch(f){return Promise.reject(f)}for(p=0,C=d.length;p<C;)c=c.then(d[p++],d[p++]);return c}getUri(e){e=O(this.defaults,e);let n=Se(e.baseURL,e.url,e.allowAbsoluteUrls);return pe(n,e.params,e.paramsSerializer)}};l.forEach(["delete","get","head","options"],function(e){ne.prototype[e]=function(n,r){return this.request(O(r||{},{method:e,url:n,data:(r||{}).data}))}});l.forEach(["post","put","patch"],function(e){function n(r){return function(o,s,a){return this.request(O(a||{},{method:e,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:s}))}}ne.prototype[e]=n(),ne.prototype[e+"Form"]=n(!0)});var we=ne;var xt=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});let r=this;this.promise.then(i=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](i);r._listeners=null}),this.promise.then=i=>{let o,s=new Promise(a=>{r.subscribe(a),o=a}).then(i);return s.cancel=function(){r.unsubscribe(o)},s},e(function(o,s,a){r.reason||(r.reason=new _(o,s,a),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;let n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let 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 t(function(i){e=i}),cancel:e}}},Ln=xt;function Pt(t){return function(n){return t.apply(null,n)}}function vt(t){return l.isObject(t)&&t.isAxiosError===!0}var kt={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(kt).forEach(([t,e])=>{kt[e]=t});var Un=kt;function Bn(t){let e=new we(t),n=ue(we.prototype.request,e);return l.extend(n,we.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return Bn(O(t,i))},n}var E=Bn(Q);E.Axios=we;E.CanceledError=_;E.CancelToken=Ln;E.isCancel=he;E.VERSION=Ge;E.toFormData=K;E.AxiosError=y;E.Cancel=E.CanceledError;E.all=function(e){return Promise.all(e)};E.spread=Pt;E.isAxiosError=vt;E.mergeConfig=O;E.AxiosHeaders=R;E.formToJSON=t=>Ke(l.isHTMLForm(t)?new FormData(t):t);E.getAdapter=je.getAdapter;E.HttpStatusCode=Un;E.default=E;var Je=E;var{Axios:al,AxiosError:ll,CanceledError:ul,isCancel:cl,CancelToken:dl,VERSION:fl,all:pl,Cancel:gl,isAxiosError:ml,spread:hl,toFormData:yl,AxiosHeaders:Sl,HttpStatusCode:Cl,formToJSON:wl,getAdapter:bl,mergeConfig:Tl}=Je;var be=class{constructor(e){this.currentToken=null;this.tokenProvider=null;this.requestHistory=new Map;this.WINDOW_MS=5e3;this.MAX_REQUESTS=30;this.axios=Je.create({baseURL:e.baseURL,timeout:e.timeout||3e4,headers:S({"Content-Type":"application/json"},e.headers)}),typeof setInterval!="undefined"&&setInterval(()=>this.cleanupHistory(),1e4),this.axios.interceptors.request.use(async n=>{var r,i;if(n.url)try{this.checkRequestLimit("".concat((r=n.method)==null?void 0:r.toUpperCase(),":").concat(n.url))}catch(o){return console.error("[SDK] \u{1F6D1} Request blocked by Circuit Breaker:",o),Promise.reject(o)}if(!n.skipAuth&&!this.currentToken&&this.tokenProvider)try{console.log("[SDK] Waiting for token...");let o=await this.tokenProvider();o&&(this.updateToken(o),n.headers["x-cms-token"]=o)}catch(o){console.error("[SDK] Failed to get token from provider:",o)}return!n.skipAuth&&this.currentToken&&(n.headers["x-cms-token"]=this.currentToken),console.log("[SDK] Making ".concat((i=n.method)==null?void 0:i.toUpperCase()," request to: ").concat(n.baseURL||"").concat(n.url)),n},n=>(console.error("[SDK] Request error:",n),Promise.reject(n instanceof Error?n:new Error(String(n))))),this.axios.interceptors.response.use(n=>n,n=>(console.error("[SDK] Response error:",n.message),Promise.reject(n instanceof Error?n:new Error(String(n)))))}setTokenProvider(e){this.tokenProvider=e}async get(e,n){return(await this.axios.get(e,n)).data}async post(e,n,r){return(await this.axios.post(e,n,r)).data}async put(e,n,r){return(await this.axios.put(e,n,r)).data}async patch(e,n,r){return(await this.axios.patch(e,n,r)).data}async delete(e,n){return(await this.axios.delete(e,n)).data}setHeader(e,n){this.axios.defaults.headers.common[e]=n}removeHeader(e){delete this.axios.defaults.headers.common[e]}updateToken(e){this.currentToken=e,e?this.setHeader("x-cms-token",e):(this.removeHeader("x-cms-token"),console.log("[SDK] Token removed from ApiClient"))}getCurrentToken(){return this.currentToken}updateConfig(e){e.baseURL&&(this.axios.defaults.baseURL=e.baseURL),e.timeout&&(this.axios.defaults.timeout=e.timeout),e.headers&&Object.assign(this.axios.defaults.headers.common,e.headers),console.log("[SDK] ApiClient configuration updated")}checkRequestLimit(e){let n=Date.now(),r=this.requestHistory.get(e);if(!r){this.requestHistory.set(e,{count:1,firstRequestTime:n});return}if(n-r.firstRequestTime>this.WINDOW_MS){this.requestHistory.set(e,{count:1,firstRequestTime:n});return}if(r.count++,r.count>this.MAX_REQUESTS){let i=new Error("Circuit Breaker: Too many requests to ".concat(e," (").concat(r.count," in ").concat(this.WINDOW_MS,"ms)"));throw i.isCircuitBreaker=!0,i}}cleanupHistory(){let e=Date.now();for(let[n,r]of this.requestHistory.entries())e-r.firstRequestTime>this.WINDOW_MS&&this.requestHistory.delete(n)}};function Ti(){let t=navigator.userAgent;if(t.includes("Chrome")){let e=/Chrome\/(\d+)/.exec(t);return{name:"Chrome",version:e?e[1]:"unknown"}}if(t.includes("Firefox")){let e=/Firefox\/(\d+)/.exec(t);return{name:"Firefox",version:e?e[1]:"unknown"}}if(t.includes("Safari")&&!t.includes("Chrome")){let e=/Version\/(\d+)/.exec(t);return{name:"Safari",version:e?e[1]:"unknown"}}if(t.includes("Edge")){let e=/Edge\/(\d+)/.exec(t);return{name:"Edge",version:e?e[1]:"unknown"}}return{name:"unknown",version:"unknown"}}function Ei(){let t=navigator.userAgent;if(t.includes("Windows"))return t.includes("Windows NT 10.0")?{name:"Windows",version:"10"}:t.includes("Windows NT 6.3")?{name:"Windows",version:"8.1"}:t.includes("Windows NT 6.2")?{name:"Windows",version:"8"}:t.includes("Windows NT 6.1")?{name:"Windows",version:"7"}:{name:"Windows",version:"unknown"};if(t.includes("Mac OS X")){let e=/Mac OS X (\d+[._]\d+)/.exec(t);return{name:"macOS",version:e?e[1].replace("_","."):"unknown"}}if(t.includes("iPhone")||t.includes("iPad")){let e=/OS (\d+[._]\d+)/.exec(t);return{name:"iOS",version:e?e[1].replace("_","."):"unknown"}}if(t.includes("Android")){let e=/Android (\d+[.\d]*)/.exec(t);return{name:"Android",version:e?e[1]:"unknown"}}return t.includes("Linux")?{name:"Linux",version:"unknown"}:{name:"unknown",version:"unknown"}}function Ri(){let t=navigator.userAgent;if(t.includes("iPhone"))return{type:"mobile",model:"iPhone"};if(t.includes("iPad"))return{type:"tablet",model:"iPad"};if(t.includes("Android"))return t.includes("Mobile")?{type:"mobile",model:"Android"}:{type:"tablet",model:"Android"}}function Ii(){return{width:window.screen.width,height:window.screen.height}}function Ai(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return console.error("Failed to get timezone:",t),"UTC"}}function Mn(){try{return navigator.language||"en-US"}catch(t){return console.error("Failed to get browser locale:",t),"en-US"}}function zn(){return typeof window=="undefined"?{userAgent:{browser:{name:"unknown",version:"unknown"},os:{name:"unknown",version:"unknown"}},screenResolution:{width:0,height:0},timeZone:"UTC"}:{userAgent:{browser:Ti(),os:Ei(),device:Ri()},screenResolution:Ii(),timeZone:Ai()}}function Kn(){if(typeof window=="undefined")return{};let t=new URLSearchParams(window.location.search);return{locale:t.get("locale")||void 0,currency:t.get("currency")||void 0,utmSource:t.get("utm_source")||void 0,utmMedium:t.get("utm_medium")||void 0,utmCampaign:t.get("utm_campaign")||void 0}}var Ye=class{constructor(){this.listeners=new Map}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>this.off(e,n)}off(e,n){this.listeners.has(e)&&this.listeners.get(e).delete(n)}async emit(e,n){if(this.listeners.has(e)){let r=Array.from(this.listeners.get(e));await Promise.all(r.map(i=>{try{return Promise.resolve(i(n))}catch(o){return console.error('[EventBus] Error in listener for event "'.concat(e,'":'),o),Promise.resolve()}}))}}clear(){this.listeners.clear()}};function Dt(t){try{let e=t.split(".");if(e.length!==3)return console.error("Invalid JWT token format"),null;let n=e[1],r=n+"=".repeat((4-n.length%4)%4),i=atob(r),o=JSON.parse(i);return o.exp&&Date.now()>=o.exp*1e3?(console.warn("JWT token is expired"),null):{sessionId:o.sessionId,storeId:o.storeId,accountId:o.accountId,customerId:o.customerId,role:o.role,isValid:!0,isLoading:!1}}catch(e){return console.error("Failed to decode JWT token:",e),null}}function $n(t){try{let e=t.split(".");if(e.length!==3)return!0;let n=e[1],r=n+"=".repeat((4-n.length%4)%4),i=atob(r),o=JSON.parse(i);return o.exp?Date.now()>=o.exp*1e3:!1}catch(e){return console.error("Failed to check token expiration:",e),!0}}var re={},xi=["","VITE_","REACT_APP_","NEXT_PUBLIC_"];function U(t,e=xi){var n,r,i;for(let o of e){let s=o?"".concat(o).concat(t):t;if(typeof process!="undefined"&&((n=process==null?void 0:process.env)!=null&&n[s]))return console.log("process.env[".concat(s,"]"),process.env[s]),process.env[s];if(typeof re!="undefined"&&((r=re==null?void 0:re.env)!=null&&r[s]))return console.log("import.meta.env[".concat(s,"]"),re.env[s]),re.env[s];if(typeof window!="undefined"&&((i=window==null?void 0:window.__TAGADA_ENV__)!=null&&i[s]))return console.log("window.__TAGADA_ENV__[".concat(s,"]"),window.__TAGADA_ENV__[s]),window.__TAGADA_ENV__[s]}}var Pi=async(t="default")=>{try{if((U("TAGADA_ENV")||U("TAGADA_ENVIRONMENT"))==="production"||!se(!0))return null;let n=await fetch("/.local.json");if(!n.ok)return null;let r=await n.json(),i={},o=!1;try{let a=await fetch("/config/".concat(t,".tgd.json"));a.ok||(a=await fetch("/config/".concat(t,".json"))),a.ok&&(i=await a.json(),o=!0)}catch(a){}if(!o&&t!=="default"){console.warn("\u26A0\uFE0F Config variant '".concat(t,"' not found, falling back to 'default'"));try{let a=await fetch("/config/default.tgd.json");a.ok||(a=await fetch("/config/default.json")),a.ok&&(i=await a.json(),o=!0,console.log("\u2705 Fallback to 'default' config successful"))}catch(a){}}o||console.warn(t==="default"?"\u26A0\uFE0F No 'default' config found. Create /config/default.tgd.json":"\u26A0\uFE0F Neither '".concat(t,"' nor 'default' config found. Create /config/default.tgd.json"));let s={storeId:r.storeId,accountId:r.accountId,basePath:r.basePath,config:i};return console.log("\u{1F6E0}\uFE0F Using local development plugin config:",s),s}catch(e){return null}},vi=async()=>{try{if((U("TAGADA_ENV")||U("TAGADA_ENVIRONMENT"))==="production"||!se(!0))return null;console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/resources.static.json...");let e=await fetch("/config/resources.static.json");if(!e.ok)return console.log("\u{1F6E0}\uFE0F [V2] resources.static.json not found or failed to load"),null;let n=await e.json();return console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded local static resources:",n),n}catch(t){return console.error("\u{1F6E0}\uFE0F [V2] \u274C Error loading static resources:",t),null}},Ze=t=>{let e=document.querySelector('meta[name="'.concat(t,'"]'));return(e==null?void 0:e.getAttribute("content"))||void 0},ki=async()=>{try{if(typeof document=="undefined")return null;let t=Ze("x-plugin-store-id"),e=Ze("x-plugin-account-id");if(!t)return null;let n=Ze("x-plugin-base-path")||"/",r={};try{let o=Ze("x-plugin-config");if(o){let s=decodeURIComponent(o);r=JSON.parse(s)}}catch(o){console.warn("\u26A0\uFE0F Failed to parse plugin config from meta tag:",o)}e||console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");let i={storeId:t,accountId:e,basePath:n,config:r};return console.log("\u{1F680} [HIGHEST PRIORITY] Plugin config loaded from meta tags (runtime injected config):",{storeId:t,accountId:e,basePath:n,configKeys:Object.keys(r),configSize:JSON.stringify(r).length}),i}catch(t){return console.warn("\u26A0\uFE0F Error loading production config from meta tags:",t),null}},Hn=async(t="default",e)=>{var s,a;console.log("\u{1F527} [V2] loadPluginConfig called with variant:",t);let n=await vi(),r=await ki();if(r){let u=x(S({},r),{staticResources:n!=null?n:void 0});return console.log("\u2705 [V2] Using INJECTED config from meta tags (HIGHEST PRIORITY)"),u}if(e){let u={storeId:e.storeId,accountId:e.accountId,basePath:(s=e.basePath)!=null?s:"/",config:(a=e.config)!=null?a:{},staticResources:n!=null?n:void 0};return console.log("\u2705 [V2] Using raw config parameter (PRIORITY 2)"),u}let i=await Ni();if(i){let u=x(S({},i),{staticResources:n!=null?n:void 0});return console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)"),u}let o=await Pi(t);if(o){let u=x(S({},o),{staticResources:n!=null?n:void 0});return console.log("\u2705 [V2] Using local dev config files (PRIORITY 4)"),u}return console.warn("\u26A0\uFE0F [V2] No plugin config found - using defaults"),{basePath:"/",config:{},staticResources:n!=null?n:void 0}};async function Di(t="default",e){try{if(!se())return null;if(e)return e;let n=["/config/".concat(t,".config.json"),"/config/".concat(t,".tgd.json"),"/config/".concat(t,".json")];for(let r of n)try{let i=await fetch(r);if(i.ok)return await i.json()}catch(i){continue}return console.warn("\u26A0\uFE0F [loadLocalConfig] No config found for '".concat(t,"'")),null}catch(n){return console.error("[loadLocalConfig] Error loading config:",n),null}}async function Ni(){try{if(!se())return;let t=U("TAGADA_STORE_ID"),e=U("TAGADA_ACCOUNT_ID"),n=U("TAGADA_BASE_PATH"),r=U("TAGADA_CONFIG_NAME");if(!t||!e)return;let i=await Di(r);if(!i)return;let o={storeId:t,accountId:e,basePath:n||"/",config:i};return console.log("\u{1F6E0}\uFE0F [createRawPluginConfig] Using environment variables (build-time config):",{hasStoreId:!!o.storeId,hasAccountId:!!o.accountId,basePath:o.basePath,hasConfig:!!o.config}),o}catch(t){console.error("[createRawPluginConfig] Error creating config:",t);return}}var Xe=class{constructor(e={}){this.bus=new Ye;this.eventDispatcher=new J;this.tokenPromise=null;this.tokenResolver=null;this.isInitializingSession=!1;this.lastSessionInitError=null;this.sessionInitRetryCount=0;this.MAX_SESSION_INIT_RETRIES=3;var a,u;this.config=e,this.instanceId=Math.random().toString(36).substr(2,9),this.boundHandleStorageChange=this.handleStorageChange.bind(this),this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Initializing...")),Zt(this.config.debugMode)&&this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Preview mode active - state cleared"));let r=this.resolveEnvironment(),i=qt(r);e.customApiConfig&&(i=x(S(S({},i),e.customApiConfig),{apiConfig:S(S({},i.apiConfig),e.customApiConfig.apiConfig)}),this.config.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Applied custom API config:"),i.apiConfig.baseUrl)),this.state={auth:{isAuthenticated:!1,isLoading:!1,customer:null,session:null},session:null,customer:null,locale:{locale:"en-US",language:"en",region:"US",messages:{}},currency:{code:"USD",symbol:"$",name:"US Dollar"},store:null,environment:i,isLoading:!0,isInitialized:!1,isSessionInitialized:!1,pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!e.rawPluginConfig,debugMode:(a=e.debugMode)!=null?a:r!=="production",token:null},this.apiClient=new be({baseURL:i.apiConfig.baseUrl});let o=(u=e.features)==null?void 0:u.funnel;if(o!==!1){let d=typeof o=="object"?o:{};this.funnel=new Oe({apiClient:this.apiClient,debugMode:this.state.debugMode,pluginConfig:this.state.pluginConfig,environment:this.state.environment,autoRedirect:d.autoRedirect})}this.apiClient.setTokenProvider(this.waitForToken.bind(this)),typeof window!="undefined"&&window.addEventListener("storage",this.boundHandleStorageChange),this.setupConfigHotReload(),this.initialize()}destroy(){typeof window!="undefined"&&window.removeEventListener("storage",this.boundHandleStorageChange),this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Destroyed")),this.eventDispatcher.clear(),this.bus.clear()}handleStorageChange(){if(ae()===this.state.token){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Token unchanged (ignoring event)"));return}if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping storage change"));return}if(this.sessionInitRetryCount>=this.MAX_SESSION_INIT_RETRIES&&this.lastSessionInitError){this.state.debugMode&&console.error("[TagadaClient ".concat(this.instanceId,"] Max session init retries reached, giving up"),this.lastSessionInitError);return}this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Storage changed, re-initializing token...")),this.initializeToken()}subscribe(e){return this.eventDispatcher.subscribe(e)}getState(){return this.state}updateState(e){this.state=S(S({},this.state),e),this.eventDispatcher.notify(this.state)}resolveEnvironment(){return this.config.environment?this.config.environment:oe()}async initialize(){try{await this.initializePluginConfig(),this.state.pluginConfig.storeId?await this.initializeToken():(console.warn("[TagadaClient] No store ID found in plugin config. Skipping token initialization."),this.updateState({isLoading:!1,isInitialized:!0}))}catch(e){console.error("[TagadaClient] Initialization failed:",e),this.updateState({isLoading:!1,isInitialized:!0})}}async initializePluginConfig(){if(this.state.pluginConfigLoading)try{let e=this.config.localConfig||"default",n=await Hn(e,this.config.rawPluginConfig);this.updateState({pluginConfig:n,pluginConfigLoading:!1}),this.funnel&&this.funnel.setConfig({pluginConfig:n,environment:this.state.environment}),this.state.debugMode&&console.log("[TagadaClient] Plugin config loaded:",n)}catch(e){console.error("[TagadaClient] Failed to load plugin config:",e),this.updateState({pluginConfig:{basePath:"/",config:{}},pluginConfigLoading:!1})}}async initializeToken(){let e=ae(),r=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("token");this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Initializing token..."),{hasExistingToken:!!e,hasQueryToken:!!r});let i=null,o=!1;if(r?(i=r,o=!0):e&&!$n(e)&&(i=e),i){this.setToken(i),o&&(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Persisting query token to storage...")),j(i));let s=Dt(i);s?(this.updateState({session:s}),await this.initializeSession(s)):(console.error("[TagadaClient] Failed to decode token"),this.updateState({isInitialized:!0,isLoading:!1}))}else{let s=this.state.pluginConfig.storeId;s?(this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Creating anonymous token for store:"),s),await this.createAnonymousToken(s)):this.updateState({isInitialized:!0,isLoading:!1})}}setToken(e){this.apiClient.updateToken(e),this.updateState({token:e}),this.tokenResolver&&(this.tokenResolver(e),this.tokenPromise=null,this.tokenResolver=null)}waitForToken(){return this.apiClient.getCurrentToken()?Promise.resolve(this.apiClient.getCurrentToken()):(this.tokenPromise||(this.tokenPromise=new Promise(e=>{this.tokenResolver=e})),this.tokenPromise)}async createAnonymousToken(e){if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization in progress, skipping anonymous token creation"));return}try{let n=ot();this.state.debugMode&&console.log("[TagadaClient] Creating anonymous token for store:",e,{draft:n});let r=await this.apiClient.post("/api/v1/cms/session/anonymous",{storeId:e,role:"anonymous",draft:n},{skipAuth:!0});this.setToken(r.token),j(r.token);let i=Dt(r.token);i&&(this.updateState({session:i}),await this.initializeSession(i)),this.updateState({isSessionInitialized:!0})}catch(n){console.error("[TagadaClient] Failed to create anonymous token:",n),this.updateState({isInitialized:!0,isLoading:!1})}}async initializeSession(e){var n,r;if(this.isInitializingSession){this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Session initialization already in progress, skipping"));return}this.isInitializingSession=!0;try{this.state.debugMode&&console.log("[TagadaClient ".concat(this.instanceId,"] Initializing session..."),{sessionId:e.sessionId});let i=zn(),o=Kn(),s=Mn(),a=ot(),u=new URLSearchParams(window.location.search).get("draft");u!==null&&st(u==="true");let d={storeId:e.storeId,accountId:e.accountId,customerId:e.customerId,role:e.role,browserLocale:s,queryLocale:o.locale,queryCurrency:o.currency,utmSource:o.utmSource,utmMedium:o.utmMedium,utmCampaign:o.utmCampaign,browser:i.userAgent.browser.name,browserVersion:i.userAgent.browser.version,os:i.userAgent.os.name,osVersion:i.userAgent.os.version,deviceType:(n=i.userAgent.device)==null?void 0:n.type,deviceModel:(r=i.userAgent.device)==null?void 0:r.model,screenWidth:i.screenResolution.width,screenHeight:i.screenResolution.height,timeZone:i.timeZone,draft:a},c=await this.apiClient.post("/api/v1/cms/session/init",d);this.lastSessionInitError=null,this.sessionInitRetryCount=0,this.updateSessionState(c,e),this.updateState({isInitialized:!0,isSessionInitialized:!0,isLoading:!1}),this.state.debugMode&&console.log("[TagadaClient] Session initialized successfully")}catch(i){this.lastSessionInitError=i,this.sessionInitRetryCount++,console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount,"/").concat(this.MAX_SESSION_INIT_RETRIES,"):"),i),this.updateState({isInitialized:!0,isLoading:!1})}finally{this.isInitializingSession=!1}}updateSessionState(e,n){var o,s,a,u,d,c,p,C,h;if(e.store){let f=e.store,m=x(S({},e.store),{accountId:f.accountId||((o=this.state.pluginConfig)==null?void 0:o.accountId)||n.accountId||"",presentmentCurrencies:f.presentmentCurrencies||[e.store.currency||"USD"],chargeCurrencies:f.chargeCurrencies||[e.store.currency||"USD"]});this.updateState({store:m})}let r={locale:e.locale,language:e.locale.split("-")[0],region:(s=e.locale.split("-")[1])!=null?s:"US",messages:(a=e.messages)!=null?a:{}};if(this.updateState({locale:r}),e.store){let f={code:e.store.currency,symbol:this.getCurrencySymbol(e.store.currency),name:this.getCurrencyName(e.store.currency)};this.updateState({currency:f})}let i={isAuthenticated:(d=(u=e.customer)==null?void 0:u.isAuthenticated)!=null?d:!1,isLoading:!1,customer:(c=e.customer)!=null?c:null,session:n};if(this.updateState({customer:(p=e.customer)!=null?p:null,auth:i}),this.funnel&&n.customerId&&((C=e.store)!=null&&C.id)){let f=e.store.accountId||((h=this.state.pluginConfig)==null?void 0:h.accountId)||n.accountId||"";if(f){let g=new URLSearchParams(typeof window!="undefined"?window.location.search:"").get("funnelId")||void 0;this.state.debugMode&&console.log("[TagadaClient] Auto-initializing funnel...",{customerId:n.customerId,storeId:e.store.id,accountId:f,funnelId:g||"auto-detect"}),this.funnel.autoInitialize({customerId:n.customerId,sessionId:n.sessionId},{id:e.store.id,accountId:f},g).catch(w=>{console.error("[TagadaClient] Funnel auto-initialization failed:",w)})}else console.warn("[TagadaClient] Cannot auto-initialize funnel: accountId is missing")}}getCurrencySymbol(e){return{USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$"}[e]||e}getCurrencyName(e){return{USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar"}[e]||e}getAccountId(){var e,n,r;return((e=this.state.store)==null?void 0:e.accountId)||((n=this.state.pluginConfig)==null?void 0:n.accountId)||((r=this.state.session)==null?void 0:r.accountId)||""}updatePluginConfig(e){this.state.debugMode&&console.log("[TagadaClient] Hot-reloading config:",e);let n=S(S({},this.state.pluginConfig.config),e);this.updateState({pluginConfig:x(S({},this.state.pluginConfig),{config:n})}),this.bus.emit("CONFIG_UPDATED",n),this.state.debugMode&&console.log("[TagadaClient] Config updated successfully")}setupConfigHotReload(){if(typeof window=="undefined")return;let e=n=>{var r,i;if(((r=n.data)==null?void 0:r.type)==="TAGADAPAY_CONFIG_UPDATE"){let{config:o}=n.data;this.state.debugMode&&console.log("[TagadaClient] Received config update from parent:",o),this.updatePluginConfig(o)}else if(((i=n.data)==null?void 0:i.type)==="APPLY_STYLES_TO_ELEMENT"){let{elementId:o,styles:s}=n.data;this.state.debugMode&&console.log("[TagadaClient] Received style application request:",{elementId:o,styles:s}),this.applyStylesToElement(o,s)}};window.addEventListener("message",e),this.state.debugMode&&console.log("[TagadaClient] Config hot-reload and style manipulation listeners enabled")}applyStylesToElement(e,n){var f;if(typeof document=="undefined")return;let r=document.querySelector('[editor-id~="'.concat(e,'"]'));if(!r){this.state.debugMode&&console.warn('[TagadaClient] Element with editor-id containing "'.concat(e,'" not found'));return}let o=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]).has(r.tagName.toLowerCase()),s=r,a=null;if(o){let m=r.parentElement;if((m==null?void 0:m.getAttribute("data-tagada-highlight-wrapper"))==="true")s=m;else{a=document.createElement("div"),a.setAttribute("data-tagada-highlight-wrapper","true");let w=window.getComputedStyle(r),I=w.display;if(I==="inline"?a.style.display="inline-block":a.style.display=I,a.style.position="relative",I==="inline"||I.includes("inline")){let b=w.verticalAlign;b&&b!=="baseline"&&(a.style.verticalAlign=b)}(f=r.parentNode)==null||f.insertBefore(a,r),a.appendChild(r),s=a}}let u=getComputedStyle(o?r:s);(s.style.position==="static"||!s.style.position)&&(s.style.position="relative");let d="tagada-editor-highlight",c=document.getElementById(d);c&&c.remove();let p=document.createElement("div");p.id=d,p.style.position="absolute",p.style.inset="0",p.style.pointerEvents="none",p.style.zIndex="9999",p.style.boxSizing="border-box",p.style.background="none",p.style.border="none",p.style.outline="none";let C=u.borderRadius;C&&(p.style.borderRadius=C),s.appendChild(p);let h=n||{boxShadow:"0 0 0 2px rgb(239 68 68)"};if(Object.entries(h).forEach(([m,g])=>{let w=m.includes("-")?m.replace(/-([a-z])/g,(I,b)=>b.toUpperCase()):m;m.includes("-")?p.style.setProperty(m,g):p.style[w]=g}),r.scrollIntoView({behavior:"smooth",block:"center"}),this.state.debugMode){let m=Object.entries(h).map(([g,w])=>"".concat(g,": ").concat(w)).join("; ");console.log("[TagadaClient] Applied styles to highlight div of element #".concat(e,":"),m)}}};function Vn(t={}){return new Xe(t)}function jn(t){return typeof window=="undefined"?null:new URLSearchParams(window.location.search).get(t)}function B(t,...e){t&&console.log("[TagadaTracker]",...e)}var Te=class{constructor(){this.config=null;this.client=null;this.initialized=!1;this.initializing=!1}async init(e){var n,r,i,o;if(this.initialized||this.initializing)return B(e.debug||!1,"Already initialized or initializing"),this.getSession();this.initializing=!0,this.config=S({debug:!1},e),B(this.config.debug,"\u{1F680} Initializing external tracker with SDK...",e);try{let s=jn("token");s&&(j(s),B(this.config.debug,"\u{1F511} Bootstrapped token from URL")),this.client=Vn({debugMode:this.config.debug,features:{funnel:!0}}),await this.waitForClientReady();let a=await this.initializeFunnel();B(this.config.debug,"\u2705 Session initialized (tracking handled by orchestrator):",a),this.initialized=!0;let u=this.getSession();return u&&((r=(n=this.config).onReady)==null||r.call(n,u)),u}catch(s){let a=s instanceof Error?s:new Error(String(s));throw B(this.config.debug,"\u274C Initialization failed:",a),(o=(i=this.config).onError)==null||o.call(i,a),a}finally{this.initializing=!1}}getSession(){var n,r;if(!((r=(n=this.client)==null?void 0:n.funnel)!=null&&r.state.context))return null;let e=this.client.funnel.state.context;return{sessionId:e.sessionId,customerId:e.customerId,storeId:e.storeId,funnelId:e.funnelId,currentStepId:e.currentStepId,cmsToken:this.client.state.token||void 0}}isReady(){var e,n;return this.initialized&&!!((n=(e=this.client)==null?void 0:e.funnel)!=null&&n.state.context)}async navigate(e){if(!this.isReady())throw new Error("Tracker not initialized. Call init() first.");B(this.config.debug,"\u{1F680} Navigating:",e);try{let n=await this.client.funnel.navigate({type:e.eventType,data:e.eventData||{}});return n!=null&&n.url?(B(this.config.debug,"\u2705 Navigation result:",n.url),typeof window!="undefined"&&(window.location.href=e.returnUrl||n.url),{url:n.url}):null}catch(n){throw B(this.config.debug,"\u274C Navigation failed:",n),n}}getCustomerId(){var e,n,r,i,o;return((n=(e=this.client)==null?void 0:e.state.auth.customer)==null?void 0:n.id)||((o=(i=(r=this.client)==null?void 0:r.funnel)==null?void 0:i.state.context)==null?void 0:o.customerId)||null}getFunnelSessionId(){var e,n,r;return((r=(n=(e=this.client)==null?void 0:e.funnel)==null?void 0:n.state.context)==null?void 0:r.sessionId)||null}buildUrl(e,n){let r=this.getSession();if(!r)return e;let i=new URL(e,typeof window!="undefined"?window.location.origin:void 0);return i.searchParams.set("funnelSessionId",r.sessionId),r.cmsToken&&i.searchParams.set("token",r.cmsToken),r.funnelId&&i.searchParams.set("funnelId",r.funnelId),i.searchParams.set("storeId",r.storeId),n&&Object.entries(n).forEach(([o,s])=>{i.searchParams.set(o,s)}),i.toString()}getClient(){return this.client}async waitForClientReady(){if(this.client)return new Promise(e=>{let n=0,r=()=>{var i,o;(i=this.client)!=null&&i.state.isInitialized||(o=this.client)!=null&&o.state.token||n>40?e():(n++,setTimeout(r,50))};r()})}async initializeFunnel(){var i,o,s;if(!((i=this.client)!=null&&i.funnel))return null;let e={customerId:((o=this.client.state.auth.customer)==null?void 0:o.id)||"anon_placeholder",sessionId:((s=this.client.state.auth.session)==null?void 0:s.sessionId)||"sess_placeholder"},n={id:this.config.storeId,accountId:this.config.accountId||""},r=this.config.stepId;if(!r)throw new Error("stepId is required for external page tracking (URL mapping does not work for external pages)");return B(this.config.debug,"\u{1F50D} Initializing external page at step:",r),this.client.funnel.initialize(e,n,this.config.funnelId||jn("funnelId")||void 0,r)}},Nt=new Te;typeof window!="undefined"&&(window.TagadaTracker=Nt);return er(Oi);})();
7
+ // Expose TagadaTracker globally (if not already done in bundle)
8
+ if (typeof window !== 'undefined' && TagadaTrackerBundle && TagadaTrackerBundle.TagadaTracker) {
9
+ window.TagadaTracker = TagadaTrackerBundle.TagadaTracker;
10
+ }
11
+ //# sourceMappingURL=external-tracker.min.js.map