@cimulate/copilot-widget 1.33.9 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  `@cimulate/copilot-widget` follows [Semantic Versioning](https://semver.org/). Each entry is a released `package.json` version (deployed on merge to `master`), newest first.
4
4
 
5
+ ## 1.34.0 — 2026-09-08
6
+
7
+ - Agentforce messaging mode now stores JWT tokens and conversation IDs in localStorage (was sessionStorage), enabling cross-tab session sharing. Multiple tabs or windows on the same storefront now share the same conversation — navigate from main page to PDP and back, the conversation continues seamlessly. Existing sessions migrate automatically on first page load.
8
+
5
9
  ## 1.33.9 — 2026-09-04
6
10
 
7
11
  - Handle edit cart behaviors normally and remove silent-mode data flow from it. Resolves messages in chat getting lost due to message reconciliation errors when trying to edit cart message in place.
@@ -6389,13 +6389,13 @@ function Jh(e, t) {
6389
6389
  }
6390
6390
  function oO(e, t, n) {
6391
6391
  try {
6392
- const r = tm(e, t), s = sessionStorage.getItem(r);
6392
+ const r = tm(e, t), s = localStorage.getItem(r);
6393
6393
  if (!s) return null;
6394
6394
  const a = JSON.parse(s);
6395
6395
  if (!a || typeof a != "object" || !("conversationId" in a) || !("storedAt" in a))
6396
6396
  return null;
6397
6397
  const u = a;
6398
- return typeof u.conversationId != "string" || !u.conversationId ? null : typeof u.storedAt != "number" || Jh(u.storedAt, n) ? (sessionStorage.removeItem(r), null) : u;
6398
+ return typeof u.conversationId != "string" || !u.conversationId ? null : typeof u.storedAt != "number" || Jh(u.storedAt, n) ? (localStorage.removeItem(r), null) : u;
6399
6399
  } catch (r) {
6400
6400
  return null;
6401
6401
  }
@@ -6406,14 +6406,14 @@ function Cl(e, t, n) {
6406
6406
  conversationId: n,
6407
6407
  storedAt: Date.now()
6408
6408
  };
6409
- sessionStorage.setItem(r, JSON.stringify(s));
6409
+ localStorage.setItem(r, JSON.stringify(s));
6410
6410
  } catch (r) {
6411
6411
  }
6412
6412
  }
6413
6413
  function ah(e, t) {
6414
6414
  try {
6415
6415
  const n = tm(e, t);
6416
- sessionStorage.removeItem(n);
6416
+ localStorage.removeItem(n);
6417
6417
  } catch (n) {
6418
6418
  }
6419
6419
  }
@@ -6440,13 +6440,13 @@ function lO(e) {
6440
6440
  }
6441
6441
  function wE(e, t) {
6442
6442
  try {
6443
- const n = nm(e, t), r = sessionStorage.getItem(n);
6443
+ const n = nm(e, t), r = localStorage.getItem(n);
6444
6444
  if (!r) return null;
6445
6445
  const s = JSON.parse(r);
6446
6446
  if (!s || typeof s != "object" || !("accessToken" in s) || !("lastEventId" in s) || !("storedAt" in s))
6447
6447
  return null;
6448
6448
  const a = s;
6449
- return typeof a.accessToken != "string" || !a.accessToken || typeof a.lastEventId != "string" || !a.lastEventId || typeof a.storedAt != "number" ? null : uO(a.accessToken) === "expired" ? (sessionStorage.removeItem(n), null) : a;
6449
+ return typeof a.accessToken != "string" || !a.accessToken || typeof a.lastEventId != "string" || !a.lastEventId || typeof a.storedAt != "number" ? null : uO(a.accessToken) === "expired" ? (localStorage.removeItem(n), null) : a;
6450
6450
  } catch (n) {
6451
6451
  return null;
6452
6452
  }
@@ -6458,14 +6458,14 @@ function cO(e, t, n, r) {
6458
6458
  lastEventId: r,
6459
6459
  storedAt: Date.now()
6460
6460
  };
6461
- sessionStorage.setItem(s, JSON.stringify(a));
6461
+ localStorage.setItem(s, JSON.stringify(a));
6462
6462
  } catch (s) {
6463
6463
  }
6464
6464
  }
6465
6465
  function dO(e, t) {
6466
6466
  try {
6467
6467
  const n = nm(e, t);
6468
- sessionStorage.removeItem(n);
6468
+ localStorage.removeItem(n);
6469
6469
  } catch (n) {
6470
6470
  }
6471
6471
  }
@@ -13,7 +13,7 @@
13
13
  `);return u===-1?"":s.stack.slice(u+1)})();try{if(!r.stack)r.stack=a;else if(a){const u=a.indexOf(`
14
14
  `),l=u===-1?-1:a.indexOf(`
15
15
  `,u+1),d=l===-1?"":a.slice(l+1);String(r.stack).endsWith(d)||(r.stack+=`
16
- `+a)}}catch(u){}}throw r}})}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Yi(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:a}=n;r!==void 0&&Xu.assertOptions(r,{silentJSONParsing:ln.transitional(ln.boolean),forcedJSONParsing:ln.transitional(ln.boolean),clarifyTimeoutError:ln.transitional(ln.boolean),legacyInterceptorReqResOrdering:ln.transitional(ln.boolean),advertiseZstdAcceptEncoding:ln.transitional(ln.boolean),validateStatusUndefinedResolves:ln.transitional(ln.boolean)},!1),s!=null&&(Y.isFunction(s)?n.paramsSerializer={serialize:s}:Xu.assertOptions(s,{encode:ln.function,serialize:ln.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Xu.assertOptions(n,{baseUrl:ln.spelling("baseURL"),withXsrfToken:ln.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let u=a&&Y.merge(a.common,a[n.method]);a&&Y.forEach(["delete","get","head","post","put","patch","query","common"],x=>{delete a[x]}),n.headers=un.concat(u,a);const l=[];let d=!0;this.interceptors.request.forEach(function(S){if(typeof S.runWhen=="function"&&S.runWhen(n)===!1)return;d=d&&S.synchronous;const A=n.transitional||Kd;A&&A.legacyInterceptorReqResOrdering?l.unshift(S.fulfilled,S.rejected):l.push(S.fulfilled,S.rejected)});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,b;if(!d){const x=[Ig.bind(this),void 0];for(x.unshift(...l),x.push(...f),b=x.length,m=Promise.resolve(n);p<b;)m=m.then(x[p++],x[p++]);return m}b=l.length;let y=n;for(;p<b;){const x=l[p++],S=l[p++];try{y=x(y)}catch(A){S.call(this,A);break}}try{m=Ig.call(this,y)}catch(x){return Promise.reject(x)}for(p=0,b=f.length;p<b;)m=m.then(f[p++],f[p++]);return m}getUri(t){t=Yi(this.defaults,t);const n=wg(t.baseURL,t.url,t.allowAbsoluteUrls,t);return dg(n,t.params,t.paramsSerializer)}};Y.forEach(["delete","get","head","options"],function(t){Wi.prototype[t]=function(n,r){return this.request(Yi(r||{},{method:t,url:n,data:r&&Y.hasOwnProp(r,"data")?r.data:void 0}))}}),Y.forEach(["post","put","patch","query"],function(t){function n(r){return function(a,u,l){return this.request(Yi(l||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:a,data:u}))}}Wi.prototype[t]=n(),t!=="query"&&(Wi.prototype[t+"Form"]=n(!0))});let KA=class F2{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(a){n=a});const r=this;this.promise.then(s=>{if(!r._listeners)return;let a=r._listeners.length;for(;a-- >0;)r._listeners[a](s);r._listeners=null}),this.promise.then=s=>{let a;const u=new Promise(l=>{r.subscribe(l),a=l}).then(s);return u.cancel=function(){r.unsubscribe(a)},u},t(function(a,u,l){r.reason||(r.reason=new ia(a,u,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new F2(function(s){t=s}),cancel:t}}};function QA(e){return function(n){return e.apply(null,n)}}function JA(e){return Y.isObject(e)&&e.isAxiosError===!0}const rf={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(rf).forEach(([e,t])=>{rf[t]=e});function Rg(e){const t=new Wi(e),n=G0(Wi.prototype.request,t);return Y.extend(n,Wi.prototype,t,{allOwnKeys:!0}),Y.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Rg(Yi(e,s))},n}const Dt=Rg(ra);Dt.Axios=Wi,Dt.CanceledError=ia,Dt.CancelToken=KA,Dt.isCancel=gg,Dt.VERSION=ef,Dt.toFormData=Vu,Dt.AxiosError=Ce,Dt.Cancel=Dt.CanceledError,Dt.all=function(t){return Promise.all(t)},Dt.spread=QA,Dt.isAxiosError=JA,Dt.mergeConfig=Yi,Dt.AxiosHeaders=un,Dt.formToJSON=e=>mg(Y.isHTMLForm(e)?new FormData(e):e),Dt.getAdapter=Og.getAdapter,Dt.HttpStatusCode=rf,Dt.default=Dt;const{Axios:yU,AxiosError:TU,CanceledError:bU,isCancel:wU,CancelToken:xU,VERSION:_U,all:SU,Cancel:vU,isAxiosError:AU,spread:kU,toFormData:CU,AxiosHeaders:NU,HttpStatusCode:OU,formToJSON:IU,getAdapter:PU,mergeConfig:RU,create:LU}=Dt;class ZA{constructor(t,n,r,s=!1,a,u){Je(this,"CIMULATE_API_HEADER","x-cimulate-api-key");Je(this,"CIMULATE_SEARCH_API_HOST","search.cimulate");Je(this,"CIMULATE_SEARCH_API_PATH","api/v1");Je(this,"baseApiUrl");Je(this,"headers",{});Je(this,"fetchConfig",()=>Fe(this,null,function*(){try{const t=yield Dt.get(`${this.apiUrl}/configs/copilot`,{headers:this.headers}),{customer_config:n}=t.data,r=atob(n);return JSON.parse(r)}catch(t){throw console.error("Error fetching customer config:",t),t}}));Je(this,"_mapCopilotUrlToSearchUrl",(t="",n=!1)=>{if(t.endsWith("io")){const s=new URL(t);return s.hostname=s.hostname.replace(/^copilot\./,"api."),s.origin}return n?`https://staging.${this.CIMULATE_SEARCH_API_HOST}.ai`:`https://prod.${this.CIMULATE_SEARCH_API_HOST}.ai`});if(n&&r||!n&&!r)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");n?this.headers[this.CIMULATE_API_HEADER]=n:r&&(this.headers.Authorization=`Bearer ${r}`),a&&(this.headers["x-cimulate-customer-id"]=a),u&&(this.headers["Tenant-ID"]=u),this.baseApiUrl=this._mapCopilotUrlToSearchUrl(t,s)}get apiUrl(){return`${this.baseApiUrl}/${this.CIMULATE_SEARCH_API_PATH}`}}class ek{constructor(t,n,r,s=!1,a,u){Je(this,"apiService");Je(this,"config",null);Je(this,"getConfig",()=>Fe(this,null,function*(){if(this.config)return this.config;try{const t=yield this.apiService.fetchConfig();return this.config=t,this.config}catch(t){throw console.error("Failed to fetch customer config:",t),t}}));Je(this,"getPid",t=>this.getProductFieldValue(t,"pidCol"));Je(this,"getName",t=>this.getProductFieldValue(t,"nameCol"));Je(this,"getDescription",t=>this.getProductFieldValue(t,"description"));Je(this,"getBrand",t=>this.getProductFieldValue(t,"productBrandCol"));Je(this,"getPrice",t=>this.getProductFieldValue(t,"priceCol"));Je(this,"getRelativePdp",t=>this.getProductFieldValue(t,"relativePdpCol"));Je(this,"getPdp",t=>this.getProductFieldValue(t,"pdpCol"));Je(this,"getImage",t=>this.getProductFieldValue(t,"imageCol"));Je(this,"getProductHiddenFields",()=>{const t=this.getProductField("productHiddenFields");return Array.isArray(t)?t:[]});Je(this,"getProductField",t=>this.config?this.config[t]:"");Je(this,"getProductFieldValue",(t,n)=>{const r=this.getProductField(n);return r&&t[r]||""});this.apiService=new ZA(t,n,r,s,a,u)}getPriceDisplay(t){const n=this.getPrice(t);return n?typeof n=="string"?n.includes("$")?n:`$${n}`:typeof n=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(n):n:""}}const tk={copilot:"Your Search Assistant",messaging:"Commerce Client"},Lg=R.createContext(null),nk=({mode:e,logoUrl:t,headerText:n,headerConfig:r,globalClassName:s="",entryMessage:a,openLinksInNewTab:u=!1,disclaimerText:l,disclaimerMarkdown:d,clientContext:f,baseCatalogParams:m,searchPlaceholder:p,searchButtonLabel:b,searchConfig:y,suggestionButtonConfig:x,progressStepsLimit:S=3,messageAlignment:A="start",autoScroll:_=!0,showProductDescription:C=!1,componentConfig:O,conversationHistory:z,resetConversationMessage:W="",apiKey:D,apiToken:V,baseUrl:K,customerId:ae,tenantId:j,theme:se,isDevelopment:ie,__features:ce,routingAttributes:fe,enableDownloadTranscript:ne=!0,enableEscalationToAgent:Se=!1,showProductCaptions:de=!1,staticQuestions:J,staticQuestionsStrategy:le="append",children:k})=>{const M=e==="messaging",Z=R.useMemo(()=>{const He=fe==null?void 0:fe.isCartMgmtSupported;return He===!0||He==="true"},[fe]),P=R.useMemo(()=>M?{config:null}:new ek(K,D,V,ie,ae,j),[M,K,D,V,ie,ae,j]),ve=R.useMemo(()=>new MS(ie),[ie]);R.useEffect(()=>{M||!P||P.config||P.getConfig()},[P,M]);const Pe=R.useMemo(()=>$S(se),[se]),he=R.useMemo(()=>{const He=(y==null?void 0:y.placeholder)||p,nt=(y==null?void 0:y.buttonLabel)||b;let Nt="icon";return y!=null&&y.buttonType?Nt=y.buttonType:b&&(Nt="text"),ue(U({},y||{}),{placeholder:He,buttonLabel:nt,buttonType:Nt})},[y,p,b]),ke=R.useMemo(()=>ue(U({},r||{}),{logoUrl:t||(r==null?void 0:r.logoUrl),headerText:(r==null?void 0:r.headerText)||n||tk[e!=null?e:"copilot"]}),[r,t,n,e]),Me=R.useMemo(()=>({configModule:P,mode:e!=null?e:"copilot",headerConfig:ke,entryMessage:a,staticQuestions:J||[],staticQuestionsStrategy:le,globalClassName:s,openLinksInNewTab:u,disclaimerText:l,disclaimerMarkdown:d,clientContext:f,baseCatalogParams:m,themeVariables:Pe,logger:ve,searchConfig:he,suggestionButtonConfig:x,progressStepsLimit:S,messageAlignment:A,autoScroll:_,showProductDescription:!!C,enableMinimize:!!(O!=null&&O.enableMinimize),enableDownloadTranscript:ne,enableEscalationToAgent:Se,showProductCaptions:!!de,resetConversationMessage:W,conversationHistory:{sinceHours:typeof(z==null?void 0:z.sinceHours)=="number"?z.sinceHours:M?24:1,limit:z==null?void 0:z.limit},features:ce,isCartMgmtSupported:Z}),[P,e,ke,a,J,le,s,f,m,l,d,u,he,x,A,_,C,O,ne,Se,S,de,W,ve,Pe,z,ce,Z]);return w.jsx(Lg.Provider,{value:Me,children:k})},ct=()=>{const e=R.useContext(Lg);if(!e)throw new Error("useConfig must be used within a ConfigProvider");return e},Dg=["markdown","product_carousel","product_tile","product_comparison","suggestions","cart","order_confirmation","tool_results"],li=-1;function Mg(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.text=="string"?t.text:"",r=typeof t.message=="string"?t.message:"";return n||r||null}function Fg(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(t&&typeof t=="object"){if(!Array.isArray(t)&&typeof t.type=="string"&&typeof t.index=="number"&&Dg.includes(t.type))return t;const n=Mg(t);return n?{type:"markdown",index:li,data:{content:n}}:null}}catch(t){}return{type:"markdown",index:li,data:{content:e}}}function Bg(e){let t;try{t=JSON.parse(e)}catch(s){return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(typeof n.type!="string"||!Dg.includes(n.type))return null;const r=typeof n.index=="number"?n.index:0;return ue(U({},n),{type:n.type,index:r})}function Ku(e){let t;try{t=JSON.parse(e)}catch(n){return null}return t&&typeof t=="object"&&Array.isArray(t.response)?t:null}function rk(e){var s,a;if(e.type!=="markdown")return[e];const t=(a=(s=e.data)==null?void 0:s.content)!=null?a:"",n=Ku(t);if(n)return n.response;const r=Bg(t);return[r&&r.type!=="markdown"?r:e]}function Ug(e,t){var n,r;return(r=(n=Ku(e))==null?void 0:n.response.some(s=>s.type===t))!=null?r:!1}function ik(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.role==="agent"&&Ug(r.content,t))return r.id}}function Hg(e){const t=e.trimStart();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{return JSON.parse(e),!1}catch(n){return!0}}function sk(e){return e.type==="markdown"&&e.index===li?!Hg(e.data.content):!0}function ok(e){var s;const t=(s=Ku(e))==null?void 0:s.response;if(!t)return null;const n=t.find(a=>a.type==="product_carousel");if(n)return{kind:"search",productIds:n.data.products.map(a=>a.id)};const r=t.find(a=>a.type==="product_tile");return r?{kind:"detail",productIds:[r.data.id]}:null}function ak(e,t){if(t.index===li){const s=e[e.length-1];if(s&&s.type==="markdown"&&s.index===li&&t.type==="markdown"){const a={type:"markdown",index:li,data:{content:s.data.content+t.data.content}};return[...e.slice(0,-1),a]}return[...e,t]}const n=e.findIndex(s=>s.index===t.index);return[...n>=0?e.map((s,a)=>a===n?t:s):[...e,t]].sort((s,a)=>s.index-a.index)}function jg(e,t){return t.serverId!==void 0&&e.some(n=>n.serverId===t.serverId)}const zg={connectionStatus:"disconnected",loading:!1,conversationId:null,messages:[],streamingBlocks:[],isAgentTyping:!1,progressMessage:"",progressSteps:[],routingResult:null,error:null,sendError:null,sessionExpired:!1};function uk(e,t){switch(t.type){case"SET_CONNECTION_STATUS":return U(ue(U({},e),{connectionStatus:t.status}),t.status==="connected"||t.status==="connecting"?{error:null}:{});case"SET_LOADING":return ue(U({},e),{loading:t.isLoading});case"SET_CONVERSATION_ID":return ue(U({},e),{conversationId:t.id});case"ADD_MESSAGE":return jg(e.messages,t.message)?e:ue(U({},e),{messages:[...e.messages,ue(U({},t.message),{type:"ADD_MESSAGE"})]});case"APPEND_STREAMING_TOKEN":{const n=Fg(t.token);return n?ue(U({},e),{streamingBlocks:ak(e.streamingBlocks,n)}):e}case"FLUSH_STREAMING":{const n={streamingBlocks:[],isAgentTyping:!1,loading:!1,progressMessage:"",progressSteps:[],sendError:null};if(jg(e.messages,t.message))return U(U({},e),n);const r=ue(U({},t.message),{type:"FLUSH_STREAMING"}),s=t.replaceMessageId?e.messages.findIndex(a=>a.id===t.replaceMessageId):-1;if(s>=0){const a=[...e.messages];return a[s]=ue(U({},r),{id:e.messages[s].id}),U(ue(U({},e),{messages:a}),n)}return U(ue(U({},e),{messages:[...e.messages,r]}),n)}case"SET_AGENT_TYPING":return ue(U({},e),{isAgentTyping:t.isTyping,loading:t.isTyping});case"SET_PROGRESS_MESSAGE":return U(ue(U({},e),{progressMessage:t.message}),t.message===""?{progressSteps:[]}:{});case"ADD_PROGRESS_STEP":return e.progressSteps[e.progressSteps.length-1]===t.message?e:ue(U({},e),{progressSteps:[...e.progressSteps,t.message],progressMessage:t.message});case"SET_ROUTING_RESULT":return ue(U({},e),{routingResult:t.result});case"SET_ERROR":return ue(U({},e),{error:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"SET_SEND_ERROR":return ue(U({},e),{sendError:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"CLEAR_SEND_ERROR":return ue(U({},e),{sendError:null});case"LOAD_HISTORY":return ue(U({},e),{messages:t.messages,loading:!1});case"SET_SESSION_EXPIRED":return ue(U({},e),{sessionExpired:t.expired});case"RESET":return ue(U({},zg),{connectionStatus:e.connectionStatus});default:return e}}const $g=R.createContext({connectionStatus:"disconnected",isConnected:!1,isAgentTyping:!1,conversationId:null,messages:[],streamingBlocks:[],progressMessage:"",progressSteps:[],loading:!0,error:null,sendError:null,sessionExpired:!1,canInitialize:!0,sendMessage:()=>Fe(null,null,function*(){return{outcome:"failure",message:"Messaging is unavailable"}}),addToCart:()=>{},resetConversation:()=>Fe(null,null,function*(){}),retryLastMessage:()=>{},retryConnection:()=>{},downloadTranscript:()=>Fe(null,null,function*(){}),getAuthLinkKey:()=>Fe(null,null,function*(){throw new Error("getAuthLinkKey called without a MessagingProvider")})}),lk=4320*60*1e3;function sf(e,t){return`cim_af_conv_${e}_${t}`}function of(e,t){return Date.now()-e>t}function ck(e,t,n){try{const r=sf(e,t),s=sessionStorage.getItem(r);if(!s)return null;const a=JSON.parse(s);if(!a||typeof a!="object"||!("conversationId"in a)||!("storedAt"in a))return null;const u=a;return typeof u.conversationId!="string"||!u.conversationId?null:typeof u.storedAt!="number"||of(u.storedAt,n)?(sessionStorage.removeItem(r),null):u}catch(r){return null}}function Qu(e,t,n){try{const r=sf(e,t),s={conversationId:n,storedAt:Date.now()};sessionStorage.setItem(r,JSON.stringify(s))}catch(r){}}function af(e,t){try{const n=sf(e,t);sessionStorage.removeItem(n)}catch(n){}}function uf(e,t){return`cim_af_ct_${e}_${t}`}function dk(e){try{const t=e.split(".")[1];if(!t)return null;const n=JSON.parse(hk(t));return typeof n.exp=="number"?n.exp*1e3:null}catch(t){return null}}function fk(e){const t=dk(e);return t===null?"unknown":Date.now()>=t?"expired":"valid"}function hk(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(t.length+(4-t.length%4)%4,"=");return atob(n)}function Vg(e,t){try{const n=uf(e,t),r=sessionStorage.getItem(n);if(!r)return null;const s=JSON.parse(r);if(!s||typeof s!="object"||!("accessToken"in s)||!("lastEventId"in s)||!("storedAt"in s))return null;const a=s;return typeof a.accessToken!="string"||!a.accessToken||typeof a.lastEventId!="string"||!a.lastEventId||typeof a.storedAt!="number"?null:fk(a.accessToken)==="expired"?(sessionStorage.removeItem(n),null):a}catch(n){return null}}function pk(e,t,n,r){try{const s=uf(e,t),a={accessToken:n,lastEventId:r,storedAt:Date.now()};sessionStorage.setItem(s,JSON.stringify(a))}catch(s){}}function mk(e,t){try{const n=uf(e,t);sessionStorage.removeItem(n)}catch(n){}}function gk(e,t){return`cim_af_conv_${e}_${t}`}function Ek(e,t){try{if(typeof BroadcastChannel=="undefined")return null;const n=gk(e,t);return new BroadcastChannel(n)}catch(n){return null}}function yk(e,t=500){return e?new Promise(n=>{let r=!1;const s=setTimeout(()=>{r||(r=!0,e.removeEventListener("message",a),n(null))},t);function a(u){var l;r||((l=u.data)==null?void 0:l.type)==="conversation_response"&&(r=!0,clearTimeout(s),e.removeEventListener("message",a),n({conversationId:u.data.conversationId,storedAt:u.data.storedAt,continuationToken:u.data.continuationToken,lastEventId:u.data.lastEventId}))}e.addEventListener("message",a);try{e.postMessage({type:"request_conversation"})}catch(u){r||(r=!0,clearTimeout(s),e.removeEventListener("message",a),n(null))}}):Promise.resolve(null)}function Tk(e,t,n){if(!e)return()=>{};function r(s){var a;if((a=s.data)!=null&&a.type)switch(s.data.type){case"request_conversation":{const u=t();if(u!=null&&u.conversationId)try{e.postMessage({type:"conversation_response",conversationId:u.conversationId,storedAt:Date.now(),continuationToken:u.continuationToken,lastEventId:u.lastEventId})}catch(l){}break}case"conversation_cleared":{n==null||n();break}}}return e.addEventListener("message",r),()=>{e.removeEventListener("message",r)}}function bk(e){if(e)try{e.postMessage({type:"conversation_cleared"})}catch(t){}}function wk(e){if(e)try{e.close()}catch(t){}}function xk(e){switch(e){case"EndUser":case"Customer":return"user";case"Agent":case"Chatbot":return"agent";default:return"system"}}function _k(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch(t){return{}}return e}function qg(e,...t){let n=e;for(const r of t){if(n==null||typeof n!="object")return"";n=n[r]}return typeof n=="string"?n:""}function Sk(e){if(e.entryType!=="Message")return null;const n=_k(e.entryPayload).abstractMessage;if(!n)return null;const r=qg(n,"staticContent","text")||qg(n,"content","text")||"";if(!r)return null;const s=xk(e.sender.role);return{id:e.identifier,serverId:e.identifier,role:s,content:r,timestamp:new Date(e.transcriptedTimestamp).toISOString(),sender:{role:e.sender.role,name:e.senderDisplayName}}}function vk(e){const t=[];for(const n of e){const r=Sk(n);r&&t.push(r)}return t}const Ak=5e3,sa=Symbol("cimulate-abort-conversation");function Ju(e={}){const{routingAttributes:t,timeoutMs:n=Ak}=e;if(typeof window=="undefined"||typeof window.dispatchEvent!="function")return Promise.resolve(t);const r=U({},t!=null?t:{});return new Promise(s=>{const a={settled:!1},u=()=>{if(a.settled)return;a.settled=!0,a.timer!==void 0&&clearTimeout(a.timer);const p=Object.keys(r).length>0;s(p?r:t)},d={routingAttributes:t,setHiddenPrechatFields:p=>{a.settled||!p||Object.assign(r,p)},done:u,abort:()=>{a.settled||(a.settled=!0,a.timer!==void 0&&clearTimeout(a.timer),s(sa))}},f=new CustomEvent($0,{detail:d,cancelable:!0});if(!!window.dispatchEvent(f)){u();return}a.timer=setTimeout(u,n)})}const kk=200,Ck=1e3;function Nk(e){const{orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:s}=e,a=R.useRef(null),u=R.useRef(null),l=R.useRef(null),d=s.sinceHours*60*60*1e3,f=lk,m=R.useCallback(()=>(l.current||(l.current=yk(a.current)),l.current),[]);R.useEffect(()=>{const _=Ek(t,n);a.current=_,l.current=null;const C=Tk(_,()=>{const O=u.current;if(!O)return null;const z=Vg(t,n);return{conversationId:O,continuationToken:z==null?void 0:z.accessToken,lastEventId:z==null?void 0:z.lastEventId}},()=>{af(t,n),u.current=null});return()=>{C(),wk(_),a.current=null}},[t,n]);const p=R.useCallback((_,C)=>Fe(null,null,function*(){var D,V,K;const O=(D=C==null?void 0:C.createIfMissing)!=null?D:!0,z=(V=C==null?void 0:C.isCurrent)!=null?V:(()=>!0);let W=ck(t,n,f);if(!W){const ae=yield m();ae&&!of(ae.storedAt,f)&&(W=ae)}if(!W){if(!O)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const ae=yield Ju({routingAttributes:r});if(ae===sa)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const j=yield _.createConversation(ae);return z()?(Qu(t,n,j),u.current=j,{conversationId:j,restoredMessages:[],resumed:!1,outcome:"created"}):(yield _.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}try{const ae=yield _.listConversations({conversationId:W.conversationId,startTimestamp:Date.now()-f});if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const j=ae.conversations.find(ie=>ie.conversationId===W.conversationId&&!ie.isConversationClosed);if(!j){if(af(t,n),!O)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const ie=yield Ju({routingAttributes:r});if(ie===sa)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const ce=yield _.createConversation(ie);return z()?(Qu(t,n,ce),u.current=ce,{conversationId:ce,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"}):(yield _.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}_.resumeConversation(j.conversationId),u.current=j.conversationId,Qu(t,n,j.conversationId);let se=[];try{const ie=yield _.listConversationEntries(j.conversationId,{limit:Math.min((K=s.limit)!=null?K:kk,Ck),startTimestamp:Date.now()-d,direction:"FromEnd"});se=vk(ie.conversationEntries).reverse()}catch(ie){}return{conversationId:j.conversationId,restoredMessages:se,resumed:!0,outcome:"resumed"}}catch(ae){return{conversationId:W.conversationId,restoredMessages:[],resumed:!1,outcome:"unverified-error",error:ae}}}),[t,n,r,s,d,f,m]),b=R.useCallback(_=>{Qu(t,n,_),u.current=_},[t,n]),y=R.useCallback(()=>{af(t,n),mk(t,n),bk(a.current),u.current=null},[t,n]),x=R.useCallback(()=>{const _=Vg(t,n);return _?{continuationToken:_.accessToken,lastEventId:_.lastEventId}:null},[t,n]),S=R.useCallback(()=>Fe(null,null,function*(){const _=yield m();return!(_!=null&&_.continuationToken)||of(_.storedAt,f)?null:{continuationToken:_.continuationToken,lastEventId:_.lastEventId}}),[f,m]),A=R.useCallback((_,C=()=>!0)=>Fe(null,null,function*(){try{const{accessToken:O,lastEventId:z}=yield _.generateContinuationToken();if(!C())return;pk(t,n,O,z)}catch(O){}}),[t,n]);return{initializeConversation:p,persistConversationId:b,clearPersistedConversation:y,getStoredConnectOptions:x,getPeerConnectOptions:S,persistContinuationToken:A}}const Ok="Your session ended due to inactivity. Starting a new session…",Ik=300*1e3,Pk=2e3,Rk=1e4,Lk=15e3,Dk=2;function Yg(e,t,n){return e||t||n===!0}function oa(e){const t=e.find(r=>!r.timedOut),n=e[e.length-1];return t!=null?t:n}function Mk(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{const n=JSON.parse(t);return typeof n=="object"&&n!==null}catch(n){return!1}}function Wg(e){if(!e||typeof e!="object")return!1;const t=e,n=t.type==="auth",r=t.type==="api"&&(t.statusCode===401||t.statusCode===403);return n||r}function lf(e){if(Wg(e))return!0;const t=e instanceof Error?e.message:"";return/\(401\)/.test(t)}function Fk(e){var b;const t=e.productName||"this product",n=e.quantity&&e.quantity>1?e.quantity:void 0,r=((b=e.variants)!=null?b:[]).filter(y=>y.value),s=r.map(y=>`${y.label}: ${y.value}`).join(", "),a=r.map(y=>y.value).join(", "),u=s?` (${s})`:"",l=a?` (${a})`:"",d=n?`Add ${n} of`:"Add",f=e.sku?` [SKU: ${e.sku}]`:"",m=`${d} ${t} to my cart${u}${f}`,p=`Add ${n?`${n} × `:""}${t} to cart${l}`;return{prompt:m,display:p}}function Bk({connectionStatus:e,loading:t,hasMessages:n,sessionExpired:r,bootstrapSettled:s,resumeUsedLastEventId:a,recoverySteps:u,onExhausted:l,timeoutMs:d=Lk,logger:f,isRecoveryInFlight:m}){const p=R.useRef(u);p.current=u;const b=R.useRef(l);b.current=l;const y=R.useRef(f);y.current=f;const x=R.useRef(m);x.current=m;const S=R.useRef(0),A=R.useRef(!1),_=R.useRef(0),[C,O]=R.useState(0);R.useEffect(()=>{if(!t||n){S.current=0,A.current=!1,_.current=0;return}const z=a||S.current>0;if(!(s&&z&&e==="connected"&&!r&&!A.current))return;const D=setTimeout(()=>{Fe(null,null,function*(){var j,se;if((j=x.current)!=null&&j.call(x)){if(_.current+=1,_.current>Dk){A.current=!0,b.current();return}O(ie=>ie+1);return}const V=S.current,K=p.current;if(V>=K.length){A.current=!0,b.current();return}_.current=0,(se=y.current)==null||se.warn("🦜 connect bootstrap stalled",{attempt:V});let ae;try{yield Promise.race([Promise.resolve(K[V]()),new Promise((ie,ce)=>{ae=setTimeout(()=>{ce(new Error("connect bootstrap step timed out"))},d)})])}catch(ie){}finally{ae!==void 0&&clearTimeout(ae),S.current=V+1,O(ie=>ie+1)}})},d);return()=>{clearTimeout(D)}},[e,t,n,r,s,a,d,C])}const Sr={default:"Something went wrong. Please try again.",server:"Something went wrong. Please try again.",rateLimit:"We are getting a lot of requests right now. Please try again in a moment.",network:"You are offline or we couldn't reach the assistant. Check connection and try again.",interrupted:"Something went wrong. Please try again.",connect:"You are offline or we couldn't reach the assistant. Check connection and try again.",lost:"You are offline or we couldn't reach the assistant. Check connection and try again.",routing:"Something went wrong. Please try again."};function Uk(e){if(!e||typeof e!="object")return{};const t=e;return{type:typeof t.type=="string"?t.type:void 0,statusCode:typeof t.statusCode=="number"?t.statusCode:void 0}}function ci(e){const{type:t,statusCode:n}=Uk(e);if(t==="api"&&typeof n=="number")return n===429?Sr.rateLimit:n>=500?Sr.server:Sr.default;switch(t){case"network":return Sr.network;case"sse":return Sr.interrupted;case"auth":return Sr.connect;default:return Sr.default}}function Gg(e){switch(e.code){case"MAX_RECONNECT":return Sr.lost;case"ROUTING_FAILED":return Sr.routing;default:return Sr.connect}}let Gi=null;function Hk(e){Gi&&Gi!==e&&console.warn("[CimulateMessaging] A messaging API is already registered; overwriting it. Mounting more than one messaging widget per page is not supported."),Gi=e}function jk(e){Gi===e&&(Gi=null)}function zk(){if(!Gi)throw new Error("Cimulate messaging widget is not ready. Call this after injectMessagingWidget() has run and the widget has mounted.");return Gi}const Hs=Symbol("initialization-cancelled"),Xg=({scrt2Url:e,orgId:t,esDeveloperName:n,routingAttributes:r,capabilitiesVersion:s,enableLogging:a=!1,onConnect:u,onMessage:l,onError:d,onProductResult:f,children:m})=>{const{logger:p,conversationHistory:b}=ct(),{status:{isOpen:y}}=Vr(),[x,S]=R.useReducer(uk,zg),[A,_]=R.useState(!1),[C,O]=R.useState(!1),[z,W]=R.useState(!1),D=R.useRef(x);D.current=x;const V=Nk({orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:b}),K=R.useRef(null),ae=R.useRef(l),j=R.useRef(d),se=R.useRef(u),ie=R.useRef(f),ce=R.useRef(!1),fe=R.useRef(!1),ne=R.useRef(!1),Se=R.useRef(0),de=R.useRef(0),J=R.useRef(0),le=R.useRef(null),k=R.useRef(null),M=R.useRef(null),Z=R.useRef(0),P=R.useRef(!1),ve=R.useRef(0),Pe=R.useRef(0),he=R.useRef(()=>Promise.reject(new Error("Messaging is unavailable"))),ke=R.useRef([]),Me=R.useRef(null),He=R.useCallback((ee,_e)=>{_e.outcome==="timeout"?(ee.timedOut=!0,ke.current=ke.current.filter(Ne=>Ne===ee||!Ne.timedOut)):ke.current=ke.current.filter(Ne=>Ne!==ee),clearTimeout(ee.timeoutId),ee.resolve(_e)},[]);ae.current=l,j.current=d,se.current=u,ie.current=f,R.useEffect(()=>{const ee=new zS({baseURL:e,orgId:t,esDeveloperName:n,options:U({enableLogging:a},s?{capabilitiesVersion:s}:{})});K.current=ee,P.current=!1,W(!1),_(!1),O(!1),S({type:"RESET"}),ee.on("connected",()=>{var ge;S({type:"SET_CONNECTION_STATUS",status:"connected"}),(ge=se.current)==null||ge.call(se)}),ee.on("disconnected",()=>{S({type:"SET_CONNECTION_STATUS",status:"disconnected"})}),ee.on("reconnecting",()=>{S({type:"SET_CONNECTION_STATUS",status:"reconnecting"})}),ee.on("message",ge=>{var vo,Jr;const je=ue(U({id:ge.messageId||crypto.randomUUID()},ge.messageId?{serverId:ge.messageId}:{}),{role:"agent",content:ge.content,timestamp:ge.timestamp,sender:ge.sender,raw:ge});p==null||p.log("🦜 MessagingProvider message received (FLUSH_STREAMING)",{messageId:je.id,tokensBeforeFlush:Se.current,streamedFinalOnly:Se.current===0}),Se.current=0;const Ke=oa(ke.current),$t=Ke==null?void 0:Ke.options.reconcileMessageId;S({type:"FLUSH_STREAMING",message:je,replaceMessageId:$t}),(vo=ae.current)==null||vo.call(ae,je),Ke&&He(Ke,{outcome:"success"});const{messagingSessionId:ht}=ge,Mr=ht?ok(ge.content):null;ht&&Mr&&((Jr=ie.current)==null||Jr.call(ie,{agentSessionId:ht,kind:Mr.kind,productIds:Mr.productIds}))}),ee.on("streaming_token",ge=>{var je;if(!((je=oa(ke.current))!=null&&je.options.silent)){if(Se.current+=1,p!=null&&p.isDevelopment){const Ke=Fg(ge.token);Ke?Ke.index===li?p.debug("🦜 streaming_token → markdown fallback",{token:ge.token}):p.debug("🦜 streaming_token parsed",{type:Ke.type,index:Ke.index,outputName:Ke.type==="tool_results"?Ke.output_name:void 0}):p.debug("🦜 streaming_token dropped (empty or unrecognized payload shape)",{token:ge.token})}S({type:"APPEND_STREAMING_TOKEN",token:ge.token})}}),ee.on("typing_started",()=>{var ge;(ge=oa(ke.current))!=null&&ge.options.silent||S({type:"SET_AGENT_TYPING",isTyping:!0})}),ee.on("typing_stopped",()=>{var ge;(ge=oa(ke.current))!=null&&ge.options.silent||S({type:"SET_AGENT_TYPING",isTyping:!1})}),ee.on("progress_indicator",ge=>{var je;(je=oa(ke.current))!=null&&je.options.silent||S({type:"ADD_PROGRESS_STEP",message:ge.message})}),ee.on("routing_result",ge=>{var je;if(S({type:"SET_ROUTING_RESULT",result:ge}),!ge.isSuccessful){const Ke=`Routing failed: ${ge.failureType||"unknown"}`;S({type:"SET_ERROR",error:Gg({code:"ROUTING_FAILED"})}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(je=j.current)==null||je.call(j,Ke)}}),ee.on("participant_changed",ge=>{if(ge.participant.name==="Automated Process")return;const je=ue(U({id:crypto.randomUUID()},ge.entryId?{serverId:ge.entryId}:{}),{role:"system",content:ge.action==="add"?`${ge.participant.name||"Agent"} joined the conversation`:`${ge.participant.name||"Agent"} left the conversation`,timestamp:new Date().toISOString()});p==null||p.log("🦜 MessagingProvider participant_changed event received",{event:ge}),S({type:"ADD_MESSAGE",message:je})}),ee.on("conversation_closed",()=>{const ge={id:crypto.randomUUID(),role:"system",content:"Conversation reset",timestamp:new Date().toISOString()};S({type:"ADD_MESSAGE",message:ge}),S({type:"SET_CONVERSATION_ID",id:null}),V.clearPersistedConversation()}),ee.on("error",ge=>{var je;if(p==null||p.log("🦜 MessagingProvider ERROR event received",{event:ge}),ge.code==="SESSION_EXPIRED"){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),S({type:"SET_LOADING",isLoading:!1});return}S({type:"SET_ERROR",error:Gg(ge)}),ge.recoverable||S({type:"SET_CONNECTION_STATUS",status:"error"}),(je=j.current)==null||je.call(j,ge.message)});const _e=ge=>{if(ge!==ve.current)throw Hs},Ne=ge=>ge===ve.current,Ae=ge=>Fe(null,null,function*(){_(!1);let je=V.getStoredConnectOptions(),Ke=!1;je||(je=yield V.getPeerConnectOptions(),_e(ge),Ke=!!je);let $t=!1;try{if(yield ee.connect(je!=null?je:void 0),!Ne(ge))throw ee.disconnect(),Hs;$t=!!(je!=null&&je.lastEventId)}catch(Mr){if(_e(ge),je&&lf(Mr)){if(p==null||p.log("Stored token expired on connect — falling back to fresh connect"),Ke||V.clearPersistedConversation(),yield ee.connect(),!Ne(ge))throw ee.disconnect(),Hs;$t=!1}else throw Mr}O($t),yield V.persistContinuationToken(ee,()=>Ne(ge)),_e(ge);const ht=yield V.initializeConversation(ee,{isCurrent:()=>Ne(ge)});if(_e(ge),p==null||p.log("🦜 initial connect complete",{conversationId:ht.conversationId,resumed:ht.resumed,outcome:ht.outcome,restoredMessages:ht.restoredMessages.length}),ht.outcome==="aborted")throw S({type:"SET_LOADING",isLoading:!1}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Hs;if(ht.outcome==="unverified-error"){ht.conversationId&&(ee.resumeConversation(ht.conversationId),S({type:"SET_CONVERSATION_ID",id:ht.conversationId})),_(!0);return}S({type:"SET_CONVERSATION_ID",id:ht.conversationId}),ht.resumed&&S({type:"LOAD_HISTORY",messages:ht.restoredMessages}),_(!0),S({type:"SET_LOADING",isLoading:!1})});return k.current=Ae,()=>{ve.current+=1,Pe.current+=1,ee.disconnect(),ee.off(),K.current=null,k.current=null,M.current=null,P.current=!1}},[e,t,n,s,He]);const nt=R.useCallback(()=>{if(P.current)return Promise.resolve();if(M.current)return Z.current===ve.current?M.current:M.current.catch(Ae=>{if(Ae!==Hs)throw Ae}).then(()=>he.current());const ee=k.current;if(!ee)return Promise.reject(new Error("Messaging is unavailable"));S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_CONNECTION_STATUS",status:"connecting"});const _e=++ve.current;Z.current=_e;const Ne=ee(_e).then(()=>{P.current=!0,W(!0)}).catch(Ae=>{var je;if(Ae===Hs)throw Ae;const ge=Ae instanceof Error?Ae.message:String(Ae);throw S({type:"SET_CONNECTION_STATUS",status:"error"}),S({type:"SET_ERROR",error:ci(Ae)}),(je=j.current)==null||je.call(j,ge),Ae}).finally(()=>{M.current===Ne&&(M.current=null)});return M.current=Ne,Ne},[]);he.current=nt,R.useEffect(()=>{y&&nt().catch(()=>{})},[y,e,t,n,s,nt]);const Nt=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee)return!1;const _e=V.getStoredConnectOptions();if(!_e)return p==null||p.log("🦜 attemptResume: no stored identity — cannot resume, will start fresh"),!1;p==null||p.log("🦜 attemptResume: reconnecting on stored identity via continuation token");try{ee.disconnect(),yield ee.connect(_e)}catch(Ae){if(lf(Ae))return p==null||p.log("🦜 attemptResume: token expired (401) — will start fresh",{error:Ae instanceof Error?Ae.message:String(Ae)}),!1;throw p==null||p.log("🦜 attemptResume: transient connect failure — rethrowing, session kept",{error:Ae instanceof Error?Ae.message:String(Ae)}),Ae}yield V.persistContinuationToken(ee);const Ne=yield V.initializeConversation(ee,{createIfMissing:!1});return Ne.outcome==="not-found-or-closed"||!Ne.conversationId?(p==null||p.log("🦜 attemptResume: conversation no longer resumable (closed/not found) — will start fresh"),!1):(Ne.outcome==="unverified-error"&&(p==null||p.log("🦜 attemptResume: resume validation failed transiently — keeping live session, resuming optimistically",{conversationId:Ne.conversationId}),ee.resumeConversation(Ne.conversationId)),p==null||p.log("🦜 attemptResume: resumed conversation on same identity",{conversationId:Ne.conversationId}),S({type:"SET_CONVERSATION_ID",id:Ne.conversationId}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(Ne.conversationId),ne.current=!1,S({type:"SET_SESSION_EXPIRED",expired:!1}),!0)}),[V,p]),Ft=R.useCallback(ee=>Fe(null,null,function*(){var Ne;const _e=K.current;if(_e){ee.options.silent||(S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_PROGRESS_MESSAGE",message:""}));try{yield _e.sendMessage(ee.text)}catch(Ae){const ge=ci(Ae);S({type:"SET_SEND_ERROR",error:{text:ee.text,displayContent:ee.displayContent,options:ee.options,message:ge}}),(Ne=j.current)==null||Ne.call(j,Ae instanceof Error?Ae.message:String(Ae)),He(ee,{outcome:"failure",message:ge})}}}),[He]),xn=R.useCallback(ee=>Fe(null,null,function*(){var Ne;const _e=K.current;if(!(!_e||ce.current)){ce.current=!0,fe.current=!0;try{if(yield Nt()){ee&&(yield Ft(ee));return}p==null||p.log("🦜 recoverExpiredSession: resume failed — starting a new session + conversation"),ne.current=!1,S({type:"SET_SESSION_EXPIRED",expired:!1}),S({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"system",content:Ok,timestamp:new Date().toISOString()}}),V.clearPersistedConversation(),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),_e.disconnect(),yield _e.connect(),yield V.persistContinuationToken(_e);const Ae=yield Ju({routingAttributes:r});if(Ae===sa){S({type:"SET_CONNECTION_STATUS",status:"disconnected"});return}const ge=yield _e.createConversation(Ae);p==null||p.log("🦜 recoverExpiredSession: new conversation created",{conversationId:ge}),S({type:"SET_CONVERSATION_ID",id:ge}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(ge),ee&&(yield Ft(ee))}catch(Ae){const ge=Ae instanceof Error?Ae.message:String(Ae);S({type:"SET_ERROR",error:ci(Ae)}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(Ne=j.current)==null||Ne.call(j,ge),ee&&He(ee,{outcome:"failure",message:ci(Ae)})}finally{ce.current=!1,fe.current=!1}}}),[r,V,Nt,Ft,p,He]),pn=R.useRef(xn);pn.current=xn;const Bt=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee||!P.current||ce.current)return;if(!D.current.conversationId&&!ne.current){ee.reconnect();return}ce.current=!0;const _e=Fe(null,null,function*(){try{(yield Nt())||(ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}))}catch(Ne){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"})}finally{ce.current=!1,le.current=null}});le.current=_e,yield _e}),[Nt]),$e=R.useRef(Bt);$e.current=Bt;const St=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee||ce.current)return;const _e=V.getStoredConnectOptions(),Ne=_e==null?void 0:_e.continuationToken;if(Ne){ce.current=!0;try{ee.disconnect(),yield ee.connect({continuationToken:Ne}),yield V.persistContinuationToken(ee);const Ae=D.current.conversationId;Ae&&ee.resumeConversation(Ae)}catch(Ae){if(lf(Ae)){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),S({type:"SET_LOADING",isLoading:!1});return}p==null||p.log("🦜 reconnectOmittingLastEventId: transient connect failure — session kept",{error:Ae instanceof Error?Ae.message:String(Ae)})}finally{ce.current=!1}}}),[V,p]);R.useEffect(()=>{const ee=()=>{const Ke=Date.now();Ke-J.current<Pk||(J.current=Ke,$e.current())},_e=()=>{if(document.visibilityState==="hidden"){de.current=Date.now();return}const Ke=K.current;if(!Ke)return;const $t=de.current?Date.now()-de.current:0;de.current=0,(ne.current||!Ke.isConnected||$t>Ik)&&ee()},Ne=Ke=>{Ke.persisted&&ee()},Ae=()=>{de.current=Date.now()},ge=()=>ee(),je=()=>ee();return document.addEventListener("visibilitychange",_e),window.addEventListener("pageshow",Ne),window.addEventListener("pagehide",Ae),document.addEventListener("resume",ge),window.addEventListener("online",je),()=>{document.removeEventListener("visibilitychange",_e),window.removeEventListener("pageshow",Ne),window.removeEventListener("pagehide",Ae),document.removeEventListener("resume",ge),window.removeEventListener("online",je)}},[]);const Wt=R.useCallback((ee,_e)=>Fe(null,null,function*(){var Ae;const Ne=K.current;if(!Ne){He(ee,{outcome:"failure",message:"Messaging is unavailable"});return}if(ne.current){yield pn.current(ee);return}try{yield Ne.sendMessage(ee.text)}catch(ge){if(Wg(ge)){yield pn.current(ee);return}const je=ci(ge);S({type:"SET_SEND_ERROR",error:_e(je)}),(Ae=j.current)==null||Ae.call(j,ge instanceof Error?ge.message:String(ge)),He(ee,{outcome:"failure",message:je})}}),[He]),Ie=R.useCallback(ee=>Fe(null,null,function*(){const _e=le.current;_e&&(yield _e),yield ee()}),[]),Xe=R.useCallback((ee,_e,Ne={})=>new Promise(Ae=>{if(!K.current){Ae({outcome:"failure",message:"Messaging is unavailable"});return}const je={};Object.assign(je,{text:ee,displayContent:_e,options:Ne,resolve:Ae,timeoutId:setTimeout(()=>{S({type:"SET_LOADING",isLoading:!1}),He(je,{outcome:"timeout"})},Rk)}),ke.current.push(je),S({type:"CLEAR_SEND_ERROR"}),Ne.silent||(S({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"user",content:_e!=null?_e:ee,timestamp:new Date().toISOString()}}),S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_PROGRESS_MESSAGE",message:""})),Ie(()=>Wt(je,Ke=>({text:ee,displayContent:_e,options:Ne,message:Ke})))}),[Wt,Ie,He]),ot=R.useCallback((ee,_e)=>{if(!ee.trim())return Promise.resolve({outcome:"failure",message:"Message is empty"});const Ne=Pe.current,Ae=()=>{const Ke=()=>Ne!==Pe.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Xe(ee,_e==null?void 0:_e.displayContent,_e);return P.current?Ke():nt().then(Ke,$t=>({outcome:"failure",message:ci($t)}))},ge=Me.current?Me.current.then(Ae):Ae(),je=ge.then(()=>{});return Me.current=je,je.finally(()=>{Me.current===je&&(Me.current=null)}),ge},[Xe,nt]),ft=R.useCallback(ee=>{if(!K.current)return;const _e=Pe.current,{prompt:Ne,display:Ae}=Fk(ee);nt().then(()=>{if(_e===Pe.current)return Xe(Ne,Ae)}).catch(()=>{})},[Xe,nt]),Jn=R.useCallback(()=>{const ee=K.current,_e=D.current.sendError;if(!ee||!_e)return;const Ne=()=>fe.current?Promise.resolve({outcome:"failure",message:_e.message}):Xe(_e.text,_e.displayContent,_e.options),Ae=Me.current?Me.current.then(Ne):Ne(),ge=Ae.then(()=>{});return Me.current=ge,ge.finally(()=>{Me.current===ge&&(Me.current=null)}),Ae},[Xe]),gs=R.useCallback(()=>{const ee=K.current;ee&&(M.current||(ne.current=!1,P.current=!1,W(!1),ee.disconnect(),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),nt().catch(()=>{})))},[nt]),xi=R.useCallback(()=>{const ee=K.current;if(!ee)return Promise.resolve();if(!P.current)return ve.current+=1,Pe.current+=1,ee.disconnect(),V.clearPersistedConversation(),S({type:"RESET"}),Promise.resolve();const _e=++Pe.current;return ne.current=!1,O(!1),V.clearPersistedConversation(),S({type:"RESET"}),S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),ee.endConversation().then(()=>_e!==Pe.current||K.current!==ee?null:(ee.disconnect(),ee.connect().then(()=>ee))).then(Ne=>Fe(null,null,function*(){if(!Ne||_e!==Pe.current||(yield V.persistContinuationToken(Ne,()=>_e===Pe.current&&K.current===Ne),_e!==Pe.current||K.current!==Ne))return null;const Ae=yield Ju({routingAttributes:r});return Ae===sa?null:ee.createConversation(Ae)})).then(Ne=>{!Ne||_e!==Pe.current||K.current!==ee||(S({type:"SET_CONVERSATION_ID",id:Ne}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(Ne))}).catch(Ne=>{var Ae;_e!==Pe.current||K.current!==ee||(S({type:"SET_ERROR",error:ci(Ne)}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(Ae=j.current)==null||Ae.call(j,Ne.message))})},[r,V]);Bk({connectionStatus:x.connectionStatus,loading:x.loading,hasMessages:x.messages.length>0,sessionExpired:x.sessionExpired,bootstrapSettled:A,resumeUsedLastEventId:C,recoverySteps:[St,xi],onExhausted:()=>{var _e;const ee=ci({type:"network"});S({type:"SET_ERROR",error:ee}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(_e=j.current)==null||_e.call(j,ee)},logger:p,isRecoveryInFlight:()=>ce.current||le.current!==null});const oe=R.useCallback(()=>Fe(null,null,function*(){var Ae;const ee=K.current;if(!ee||!D.current.conversationId)return;const _e=yield ee.retrieveConversationTranscript(),Ne=URL.createObjectURL(_e);try{const ge=document.createElement("a");ge.href=Ne,ge.download=`transcript-${(Ae=ee.conversationId)!=null?Ae:"conversation"}.pdf`,document.body.appendChild(ge),ge.click(),ge.remove()}finally{URL.revokeObjectURL(Ne)}}),[]),xe=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee)throw new Error("getAuthLinkKey called before the messaging client connected");return p==null||p.debug("🦜 getAuthLinkKey: requesting single-use auth link key"),ee.getAuthLinkKey()}),[p]);R.useEffect(()=>{const ee={getAuthLinkKey:xe};return Hk(ee),()=>jk(ee)},[xe]);const Ve=x.connectionStatus==="connected"&&x.conversationId!==null;R.useEffect(()=>{V0(Ve)},[Ve]),R.useEffect(()=>()=>V0(!1),[]);const et=R.useMemo(()=>({connectionStatus:x.connectionStatus,isConnected:Ve,isAgentTyping:x.isAgentTyping,conversationId:x.conversationId,messages:x.messages,streamingBlocks:x.streamingBlocks,progressMessage:x.progressMessage,progressSteps:x.progressSteps,error:x.error,sendError:x.sendError,canInitialize:!z&&x.error===null,loading:x.loading,sessionExpired:x.sessionExpired,sendMessage:ot,addToCart:ft,resetConversation:xi,retryLastMessage:Jn,retryConnection:gs,downloadTranscript:oe,getAuthLinkKey:xe}),[x,Ve,z,ot,ft,xi,Jn,gs,oe,xe]);return w.jsx($g.Provider,{value:et,children:m})};var Kg=Symbol.for("immer-nothing"),Qg=Symbol.for("immer-draftable"),Hn=Symbol.for("immer-state");function ur(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var js=Object.getPrototypeOf;function zs(e){return!!e&&!!e[Hn]}function Xi(e){var t;return e?Jg(e)||Array.isArray(e)||!!e[Qg]||!!((t=e.constructor)!=null&&t[Qg])||aa(e)||tl(e):!1}var $k=Object.prototype.constructor.toString();function Jg(e){if(!e||typeof e!="object")return!1;const t=js(e);if(t===null)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===$k}function Zu(e,t){el(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function el(e){const t=e[Hn];return t?t.type_:Array.isArray(e)?1:aa(e)?2:tl(e)?3:0}function cf(e,t){return el(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Zg(e,t,n){const r=el(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Vk(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function aa(e){return e instanceof Map}function tl(e){return e instanceof Set}function Ki(e){return e.copy_||e.base_}function df(e,t){if(aa(e))return new Map(e);if(tl(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=Jg(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[Hn];let s=Reflect.ownKeys(r);for(let a=0;a<s.length;a++){const u=s[a],l=r[u];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[u]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[u]})}return Object.create(js(e),r)}else{const r=js(e);if(r!==null&&n)return U({},e);const s=Object.create(r);return Object.assign(s,e)}}function ff(e,t=!1){return rl(e)||zs(e)||!Xi(e)||(el(e)>1&&Object.defineProperties(e,{set:{value:nl},add:{value:nl},clear:{value:nl},delete:{value:nl}}),Object.freeze(e),t&&Object.values(e).forEach(n=>ff(n,!0))),e}function nl(){ur(2)}function rl(e){return Object.isFrozen(e)}var qk={};function Qi(e){const t=qk[e];return t||ur(0,e),t}var ua;function e1(){return ua}function Yk(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function t1(e,t){t&&(Qi("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function hf(e){pf(e),e.drafts_.forEach(Wk),e.drafts_=null}function pf(e){e===ua&&(ua=e.parent_)}function n1(e){return ua=Yk(ua,e)}function Wk(e){const t=e[Hn];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function r1(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[Hn].modified_&&(hf(t),ur(4)),Xi(e)&&(e=il(t,e),t.parent_||sl(t,e)),t.patches_&&Qi("Patches").generateReplacementPatches_(n[Hn].base_,e,t.patches_,t.inversePatches_)):e=il(t,n,[]),hf(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Kg?e:void 0}function il(e,t,n){if(rl(t))return t;const r=t[Hn];if(!r)return Zu(t,(s,a)=>i1(e,r,t,s,a,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return sl(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const s=r.copy_;let a=s,u=!1;r.type_===3&&(a=new Set(s),s.clear(),u=!0),Zu(a,(l,d)=>i1(e,r,s,l,d,n,u)),sl(e,s,!1),n&&e.patches_&&Qi("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function i1(e,t,n,r,s,a,u){if(zs(s)){const l=a&&t&&t.type_!==3&&!cf(t.assigned_,r)?a.concat(r):void 0,d=il(e,s,l);if(Zg(n,r,d),zs(d))e.canAutoFreeze_=!1;else return}else u&&n.add(s);if(Xi(s)&&!rl(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;il(e,s),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(aa(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&sl(e,s)}}function sl(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ff(t,n)}function Gk(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:e1(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=r,a=mf;n&&(s=[r],a=la);const{revoke:u,proxy:l}=Proxy.revocable(s,a);return r.draft_=l,r.revoke_=u,l}var mf={get(e,t){if(t===Hn)return e;const n=Ki(e);if(!cf(n,t))return Xk(e,n,t);const r=n[t];return e.finalized_||!Xi(r)?r:r===gf(e.base_,t)?(yf(e),e.copy_[t]=Tf(r,e)):r},has(e,t){return t in Ki(e)},ownKeys(e){return Reflect.ownKeys(Ki(e))},set(e,t,n){const r=s1(Ki(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const s=gf(Ki(e),t),a=s==null?void 0:s[Hn];if(a&&a.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Vk(n,s)&&(n!==void 0||cf(e.base_,t)))return!0;yf(e),Ef(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return gf(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,yf(e),Ef(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Ki(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ur(11)},getPrototypeOf(e){return js(e.base_)},setPrototypeOf(){ur(12)}},la={};Zu(mf,(e,t)=>{la[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),la.deleteProperty=function(e,t){return la.set.call(this,e,t,void 0)},la.set=function(e,t,n){return mf.set.call(this,e[0],t,n,e[0])};function gf(e,t){const n=e[Hn];return(n?Ki(n):e)[t]}function Xk(e,t,n){var s;const r=s1(t,n);return r?"value"in r?r.value:(s=r.get)==null?void 0:s.call(e.draft_):void 0}function s1(e,t){if(!(t in e))return;let n=js(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=js(n)}}function Ef(e){e.modified_||(e.modified_=!0,e.parent_&&Ef(e.parent_))}function yf(e){e.copy_||(e.copy_=df(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Kk=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const a=n;n=t;const u=this;return function(d=a,...f){return u.produce(d,m=>n.call(this,m,...f))}}typeof n!="function"&&ur(6),r!==void 0&&typeof r!="function"&&ur(7);let s;if(Xi(t)){const a=n1(this),u=Tf(t,void 0);let l=!0;try{s=n(u),l=!1}finally{l?hf(a):pf(a)}return t1(a,r),r1(s,a)}else if(!t||typeof t!="object"){if(s=n(t),s===void 0&&(s=t),s===Kg&&(s=void 0),this.autoFreeze_&&ff(s,!0),r){const a=[],u=[];Qi("Patches").generateReplacementPatches_(t,s,a,u),r(a,u)}return s}else ur(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(u,...l)=>this.produceWithPatches(u,d=>t(d,...l));let r,s;return[this.produce(t,n,(u,l)=>{r=u,s=l}),r,s]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Xi(e)||ur(8),zs(e)&&(e=Qk(e));const t=n1(this),n=Tf(e,void 0);return n[Hn].isManual_=!0,pf(t),n}finishDraft(e,t){const n=e&&e[Hn];(!n||!n.isManual_)&&ur(9);const{scope_:r}=n;return t1(r,t),r1(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const s=t[n];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}n>-1&&(t=t.slice(n+1));const r=Qi("Patches").applyPatches_;return zs(e)?r(e,t):this.produce(e,s=>r(s,t))}};function Tf(e,t){const n=aa(e)?Qi("MapSet").proxyMap_(e,t):tl(e)?Qi("MapSet").proxySet_(e,t):Gk(e,t);return(t?t.scope_:e1()).drafts_.push(n),n}function Qk(e){return zs(e)||ur(10,e),o1(e)}function o1(e){if(!Xi(e)||rl(e))return e;const t=e[Hn];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=df(e,t.scope_.immer_.useStrictShallowCopy_)}else n=df(e,!0);return Zu(n,(r,s)=>{Zg(n,r,o1(s))}),t&&(t.finalized_=!1),n}var Jk=new Kk,Zk=Jk.produce;function eC(e,t,n){var r=R.useMemo(function(){return Zk(e)},[e]);return R.useReducer(r,t,n)}const tC=e=>Array.from(new Set((e!=null?e:[]).map(t=>t.trim()).filter(Boolean))),a1=R.createContext(null),u1=R.createContext(null),nC=({children:e,dispatch:t})=>{const n=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_INITIALIZED,payload:x})},[t]),r=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_OPEN,payload:x})},[t]),s=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_INLINE,payload:x})},[t]),a=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ELEMENT_ID,payload:x})},[t]),u=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ENTRY_TYPE,payload:x})},[t]),l=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID,payload:x})},[t]),d=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_USER_PROMPT,payload:x})},[t]),f=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_PARAMS,payload:x})},[t]),m=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE,payload:x})},[t]),p=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE,payload:x})},[t]),b=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_RESPONSE_LOADING,payload:x})},[t]),y=R.useMemo(()=>({setIsInitialized:n,setIsOpen:r,setIsInline:s,setElementId:a,setEntryType:u,setActivePromptsId:l,setUserPrompt:d,setParams:f,setPromptsMessage:m,setResponseMessage:p,setIsResponseLoading:b}),[n,r,s,a,u,l,d,f,m,p,b]);return w.jsx(u1.Provider,{value:y,children:e})},rC=(e,t)=>{const{type:n,payload:r}=t;switch(n){case Tt.SET_PROMPTS_EXTENSION_INITIALIZED:e.isInitialized=r;break;case Tt.SET_PROMPTS_EXTENSION_OPEN:e.isOpen=r;break;case Tt.SET_PROMPTS_EXTENSION_INLINE:e.isInline=r;break;case Tt.SET_PROMPTS_EXTENSION_ELEMENT_ID:e.elementId=r;break;case Tt.SET_PROMPTS_EXTENSION_ENTRY_TYPE:e.entryType=r;break;case Tt.SET_PROMPTS_EXTENSION_PARAMS:e.params=r;break;case Tt.RESET_PROMPTS_EXTENSION_PARAMS:e.params=null;break;case Tt.SET_PROMPTS_EXTENSION_USER_PROMPT:e.userPrompt=r;break;case Tt.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=r;break;case Tt.RESET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=null;break;case Tt.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=r;break;case Tt.RESET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=null;break;case Tt.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=r;break;case Tt.RESET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=null;break;case Tt.SET_PROMPTS_EXTENSION_RESPONSE_LOADING:e.isResponseLoading=r;break}},iC=({promptsConfig:e,children:t})=>{const[n,r]=eC(rC,ue(U(U({},W0),e||{}),{staticQuestions:tC((e==null?void 0:e.staticQuestions)||[])}));return w.jsx(a1.Provider,{value:n,children:w.jsx(nC,{dispatch:r,children:t})})},sC={productId:Jo.productId,pdpLink:Jo.pdpLink},l1=R.createContext(sC),oC=({children:e})=>{const[t,n]=R.useState(Jo.productId),[r,s]=R.useState(Jo.pdpLink);R.useEffect(()=>{const u=({detail:l})=>{if((l==null?void 0:l.property)==="pdp-context"){const d=l.value;n(d.productId),s(d.pdpLink);return}(l==null?void 0:l.property)==="productId"&&n(l.value),(l==null?void 0:l.property)==="pdpLink"&&s(l.value)};return PS(u),()=>{RS(u)}},[]);const a=R.useMemo(()=>({productId:t,pdpLink:r}),[t,r]);return w.jsx(l1.Provider,{value:a,children:e})},aC=e=>new Promise(t=>{let r;try{r=new URL(e)}catch(d){_t(!0,"error",`[CimulateOverrides] Invalid URL provided: ${e}. Using default components.`),t({});return}if(r.protocol!=="https:"){_t(!0,"error",`[CimulateOverrides] Override URL must use HTTPS, got ${r.protocol}. Using default components.`),t({});return}const s=document.createElement("script");s.src=e,s.async=!0,s.crossOrigin="anonymous";let a=!1;const u=()=>{a=!0,clearTimeout(l)};s.onload=()=>{if(a)return;u();const d=window.CimulateOverrides;d&&typeof d=="object"?(_t(!0,"log","[CimulateOverrides] Override script loaded successfully."),t(d)):(_t(!0,"warn","[CimulateOverrides] Override script loaded but window.CimulateOverrides is not set. Using default components."),t({}))},s.onerror=()=>{a||(u(),_t(!0,"warn",`[CimulateOverrides] Failed to load override script from: ${e}. Using default components.`),t({}))};const l=setTimeout(()=>{a||(a=!0,_t(!0,"warn",`[CimulateOverrides] Override script timed out after 5000ms: ${e}. Using default components.`),t({}))},5e3);document.head.appendChild(s)}),c1=R.createContext({overrides:{},isInitialized:!1}),uC=({overridesUrl:e,inlineOverrides:t,children:n})=>{const[r,s]=R.useState({}),[a,u]=R.useState(!1);R.useEffect(()=>{Fe(null,null,function*(){let f={};e?(_t(!0,"log","[CimulateOverrides] Loading overrides from URL..."),f=yield aC(e)):t&&typeof t=="object"?(_t(!0,"log","[CimulateOverrides] Using inline overrides."),f=t):window.CimulateOverrides&&typeof window.CimulateOverrides=="object"&&(_t(!0,"log","[CimulateOverrides] Using window.CimulateOverrides."),f=window.CimulateOverrides),s(f),u(!0)})},[e,t]);const l=R.useMemo(()=>({overrides:r,isInitialized:a}),[r,a]);return w.jsx(c1.Provider,{value:l,children:n})},d1=({mode:e,apiKey:t,apiToken:n,baseUrl:r,logoUrl:s,headerText:a,headerConfig:u,theme:l,openLinksInNewTab:d,globalClassName:f,isDevelopment:m=!1,componentType:p,componentConfig:b,entryType:y,initialEntry:x,entryMessage:S,disclaimerText:A,disclaimerMarkdown:_,clientContext:C,searchPlaceholder:O,searchButtonLabel:z,searchConfig:W,suggestionButtonConfig:D,messageAlignment:V,autoScroll:K,promptsConfig:ae,showProductDescription:j,resetConversationMessage:se,conversationHistory:ie,messagingConfig:ce,overrides:fe,overridesUrl:ne,inlineOverrides:Se,__features:de,children:J})=>{const le=R.useRef(!1);return le.current||(le.current=!0,FS({initialEntry:x,entryType:y,isDevelopment:m})),w.jsx(nk,{mode:e,baseUrl:r,apiKey:t,apiToken:n,logoUrl:s,headerText:a,headerConfig:u,entryMessage:S,theme:l,globalClassName:f,openLinksInNewTab:d,searchPlaceholder:O,searchButtonLabel:z,searchConfig:W,suggestionButtonConfig:D,messageAlignment:V,autoScroll:K,showProductDescription:j,componentConfig:b,clientContext:C,disclaimerMarkdown:_,disclaimerText:A,resetConversationMessage:se,conversationHistory:ie,isDevelopment:m,__features:de,progressStepsLimit:ce==null?void 0:ce.progressStepsLimit,routingAttributes:ce==null?void 0:ce.routingAttributes,enableDownloadTranscript:ce==null?void 0:ce.enableDownloadTranscript,enableEscalationToAgent:ce==null?void 0:ce.enableEscalationToAgent,showProductCaptions:ce==null?void 0:ce.showProductCaptions,children:w.jsx(ov,{entryType:y!=null?y:x==null?void 0:x.type,componentConfig:b,componentType:p,children:w.jsx(oC,{children:w.jsx(iC,{promptsConfig:ae,children:w.jsx(uC,{overridesUrl:ne,inlineOverrides:Se||fe,children:w.jsx(Xg,{scrt2Url:(ce==null?void 0:ce.scrt2Url)||"",orgId:(ce==null?void 0:ce.orgId)||"",esDeveloperName:(ce==null?void 0:ce.esDeveloperName)||"",routingAttributes:(ce==null?void 0:ce.routingAttributes)||{},capabilitiesVersion:ce==null?void 0:ce.capabilitiesVersion,enableLogging:m,onProductResult:ce==null?void 0:ce.onProductResult,children:J})})})})})})};var bf={exports:{}},Cn={},wf={exports:{}},xf={};var f1;function lC(){return f1||(f1=1,(function(e){function t(J,le){var k=J.length;J.push(le);e:for(;0<k;){var M=k-1>>>1,Z=J[M];if(0<s(Z,le))J[M]=le,J[k]=Z,k=M;else break e}}function n(J){return J.length===0?null:J[0]}function r(J){if(J.length===0)return null;var le=J[0],k=J.pop();if(k!==le){J[0]=k;e:for(var M=0,Z=J.length,P=Z>>>1;M<P;){var ve=2*(M+1)-1,Pe=J[ve],he=ve+1,ke=J[he];if(0>s(Pe,k))he<Z&&0>s(ke,Pe)?(J[M]=ke,J[he]=k,M=he):(J[M]=Pe,J[ve]=k,M=ve);else if(he<Z&&0>s(ke,k))J[M]=ke,J[he]=k,M=he;else break e}}return le}function s(J,le){var k=J.sortIndex-le.sortIndex;return k!==0?k:J.id-le.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var u=Date,l=u.now();e.unstable_now=function(){return u.now()-l}}var d=[],f=[],m=1,p=null,b=3,y=!1,x=!1,S=!1,A=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function O(J){for(var le=n(f);le!==null;){if(le.callback===null)r(f);else if(le.startTime<=J)r(f),le.sortIndex=le.expirationTime,t(d,le);else break;le=n(f)}}function z(J){if(S=!1,O(J),!x)if(n(d)!==null)x=!0,Se(W);else{var le=n(f);le!==null&&de(z,le.startTime-J)}}function W(J,le){x=!1,S&&(S=!1,_(K),K=-1),y=!0;var k=b;try{for(O(le),p=n(d);p!==null&&(!(p.expirationTime>le)||J&&!se());){var M=p.callback;if(typeof M=="function"){p.callback=null,b=p.priorityLevel;var Z=M(p.expirationTime<=le);le=e.unstable_now(),typeof Z=="function"?p.callback=Z:p===n(d)&&r(d),O(le)}else r(d);p=n(d)}if(p!==null)var P=!0;else{var ve=n(f);ve!==null&&de(z,ve.startTime-le),P=!1}return P}finally{p=null,b=k,y=!1}}var D=!1,V=null,K=-1,ae=5,j=-1;function se(){return!(e.unstable_now()-j<ae)}function ie(){if(V!==null){var J=e.unstable_now();j=J;var le=!0;try{le=V(!0,J)}finally{le?ce():(D=!1,V=null)}}else D=!1}var ce;if(typeof C=="function")ce=function(){C(ie)};else if(typeof MessageChannel!="undefined"){var fe=new MessageChannel,ne=fe.port2;fe.port1.onmessage=ie,ce=function(){ne.postMessage(null)}}else ce=function(){A(ie,0)};function Se(J){V=J,D||(D=!0,ce())}function de(J,le){K=A(function(){J(e.unstable_now())},le)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(J){J.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,Se(W))},e.unstable_forceFrameRate=function(J){0>J||125<J?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ae=0<J?Math.floor(1e3/J):5},e.unstable_getCurrentPriorityLevel=function(){return b},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(J){switch(b){case 1:case 2:case 3:var le=3;break;default:le=b}var k=b;b=le;try{return J()}finally{b=k}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(J,le){switch(J){case 1:case 2:case 3:case 4:case 5:break;default:J=3}var k=b;b=J;try{return le()}finally{b=k}},e.unstable_scheduleCallback=function(J,le,k){var M=e.unstable_now();switch(typeof k=="object"&&k!==null?(k=k.delay,k=typeof k=="number"&&0<k?M+k:M):k=M,J){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=k+Z,J={id:m++,callback:le,priorityLevel:J,startTime:k,expirationTime:Z,sortIndex:-1},k>M?(J.sortIndex=k,t(f,J),n(d)===null&&J===n(f)&&(S?(_(K),K=-1):S=!0,de(z,k-M))):(J.sortIndex=Z,t(d,J),x||y||(x=!0,Se(W))),J},e.unstable_shouldYield=se,e.unstable_wrapCallback=function(J){var le=b;return function(){var k=b;b=le;try{return J.apply(this,arguments)}finally{b=k}}}})(xf)),xf}var h1;function cC(){return h1||(h1=1,wf.exports=lC()),wf.exports}var p1;function dC(){if(p1)return Cn;p1=1;var e=sr(),t=cC();function n(i){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+i,c=1;c<arguments.length;c++)o+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+i+"; visit "+o+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,s={};function a(i,o){u(i,o),u(i+"Capture",o)}function u(i,o){for(s[i]=o,i=0;i<o.length;i++)r.add(o[i])}var l=!(typeof window=="undefined"||typeof window.document=="undefined"||typeof window.document.createElement=="undefined"),d=Object.prototype.hasOwnProperty,f=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,m={},p={};function b(i){return d.call(p,i)?!0:d.call(m,i)?!1:f.test(i)?p[i]=!0:(m[i]=!0,!1)}function y(i,o,c,h){if(c!==null&&c.type===0)return!1;switch(typeof o){case"function":case"symbol":return!0;case"boolean":return h?!1:c!==null?!c.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function x(i,o,c,h){if(o===null||typeof o=="undefined"||y(i,o,c,h))return!0;if(h)return!1;if(c!==null)switch(c.type){case 3:return!o;case 4:return o===!1;case 5:return isNaN(o);case 6:return isNaN(o)||1>o}return!1}function S(i,o,c,h,E,T,v){this.acceptsBooleans=o===2||o===3||o===4,this.attributeName=h,this.attributeNamespace=E,this.mustUseProperty=c,this.propertyName=i,this.type=o,this.sanitizeURL=T,this.removeEmptyString=v}var A={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){A[i]=new S(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var o=i[0];A[o]=new S(o,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){A[i]=new S(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){A[i]=new S(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){A[i]=new S(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){A[i]=new S(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){A[i]=new S(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){A[i]=new S(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){A[i]=new S(i,5,!1,i.toLowerCase(),null,!1,!1)});var _=/[\-:]([a-z])/g;function C(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){A[i]=new S(i,1,!1,i.toLowerCase(),null,!1,!1)}),A.xlinkHref=new S("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){A[i]=new S(i,1,!1,i.toLowerCase(),null,!0,!0)});function O(i,o,c,h){var E=A.hasOwnProperty(o)?A[o]:null;(E!==null?E.type!==0:h||!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(x(o,c,E,h)&&(c=null),h||E===null?b(o)&&(c===null?i.removeAttribute(o):i.setAttribute(o,""+c)):E.mustUseProperty?i[E.propertyName]=c===null?E.type===3?!1:"":c:(o=E.attributeName,h=E.attributeNamespace,c===null?i.removeAttribute(o):(E=E.type,c=E===3||E===4&&c===!0?"":""+c,h?i.setAttributeNS(h,o,c):i.setAttribute(o,c))))}var z=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),D=Symbol.for("react.portal"),V=Symbol.for("react.fragment"),K=Symbol.for("react.strict_mode"),ae=Symbol.for("react.profiler"),j=Symbol.for("react.provider"),se=Symbol.for("react.context"),ie=Symbol.for("react.forward_ref"),ce=Symbol.for("react.suspense"),fe=Symbol.for("react.suspense_list"),ne=Symbol.for("react.memo"),Se=Symbol.for("react.lazy"),de=Symbol.for("react.offscreen"),J=Symbol.iterator;function le(i){return i===null||typeof i!="object"?null:(i=J&&i[J]||i["@@iterator"],typeof i=="function"?i:null)}var k=Object.assign,M;function Z(i){if(M===void 0)try{throw Error()}catch(c){var o=c.stack.trim().match(/\n( *(at )?)/);M=o&&o[1]||""}return`
16
+ `+a)}}catch(u){}}throw r}})}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Yi(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:a}=n;r!==void 0&&Xu.assertOptions(r,{silentJSONParsing:ln.transitional(ln.boolean),forcedJSONParsing:ln.transitional(ln.boolean),clarifyTimeoutError:ln.transitional(ln.boolean),legacyInterceptorReqResOrdering:ln.transitional(ln.boolean),advertiseZstdAcceptEncoding:ln.transitional(ln.boolean),validateStatusUndefinedResolves:ln.transitional(ln.boolean)},!1),s!=null&&(Y.isFunction(s)?n.paramsSerializer={serialize:s}:Xu.assertOptions(s,{encode:ln.function,serialize:ln.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Xu.assertOptions(n,{baseUrl:ln.spelling("baseURL"),withXsrfToken:ln.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let u=a&&Y.merge(a.common,a[n.method]);a&&Y.forEach(["delete","get","head","post","put","patch","query","common"],x=>{delete a[x]}),n.headers=un.concat(u,a);const l=[];let d=!0;this.interceptors.request.forEach(function(S){if(typeof S.runWhen=="function"&&S.runWhen(n)===!1)return;d=d&&S.synchronous;const A=n.transitional||Kd;A&&A.legacyInterceptorReqResOrdering?l.unshift(S.fulfilled,S.rejected):l.push(S.fulfilled,S.rejected)});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,b;if(!d){const x=[Ig.bind(this),void 0];for(x.unshift(...l),x.push(...f),b=x.length,m=Promise.resolve(n);p<b;)m=m.then(x[p++],x[p++]);return m}b=l.length;let y=n;for(;p<b;){const x=l[p++],S=l[p++];try{y=x(y)}catch(A){S.call(this,A);break}}try{m=Ig.call(this,y)}catch(x){return Promise.reject(x)}for(p=0,b=f.length;p<b;)m=m.then(f[p++],f[p++]);return m}getUri(t){t=Yi(this.defaults,t);const n=wg(t.baseURL,t.url,t.allowAbsoluteUrls,t);return dg(n,t.params,t.paramsSerializer)}};Y.forEach(["delete","get","head","options"],function(t){Wi.prototype[t]=function(n,r){return this.request(Yi(r||{},{method:t,url:n,data:r&&Y.hasOwnProp(r,"data")?r.data:void 0}))}}),Y.forEach(["post","put","patch","query"],function(t){function n(r){return function(a,u,l){return this.request(Yi(l||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:a,data:u}))}}Wi.prototype[t]=n(),t!=="query"&&(Wi.prototype[t+"Form"]=n(!0))});let KA=class F2{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(a){n=a});const r=this;this.promise.then(s=>{if(!r._listeners)return;let a=r._listeners.length;for(;a-- >0;)r._listeners[a](s);r._listeners=null}),this.promise.then=s=>{let a;const u=new Promise(l=>{r.subscribe(l),a=l}).then(s);return u.cancel=function(){r.unsubscribe(a)},u},t(function(a,u,l){r.reason||(r.reason=new ia(a,u,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new F2(function(s){t=s}),cancel:t}}};function QA(e){return function(n){return e.apply(null,n)}}function JA(e){return Y.isObject(e)&&e.isAxiosError===!0}const rf={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(rf).forEach(([e,t])=>{rf[t]=e});function Rg(e){const t=new Wi(e),n=G0(Wi.prototype.request,t);return Y.extend(n,Wi.prototype,t,{allOwnKeys:!0}),Y.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Rg(Yi(e,s))},n}const Dt=Rg(ra);Dt.Axios=Wi,Dt.CanceledError=ia,Dt.CancelToken=KA,Dt.isCancel=gg,Dt.VERSION=ef,Dt.toFormData=Vu,Dt.AxiosError=Ce,Dt.Cancel=Dt.CanceledError,Dt.all=function(t){return Promise.all(t)},Dt.spread=QA,Dt.isAxiosError=JA,Dt.mergeConfig=Yi,Dt.AxiosHeaders=un,Dt.formToJSON=e=>mg(Y.isHTMLForm(e)?new FormData(e):e),Dt.getAdapter=Og.getAdapter,Dt.HttpStatusCode=rf,Dt.default=Dt;const{Axios:yU,AxiosError:TU,CanceledError:bU,isCancel:wU,CancelToken:xU,VERSION:_U,all:SU,Cancel:vU,isAxiosError:AU,spread:kU,toFormData:CU,AxiosHeaders:NU,HttpStatusCode:OU,formToJSON:IU,getAdapter:PU,mergeConfig:RU,create:LU}=Dt;class ZA{constructor(t,n,r,s=!1,a,u){Je(this,"CIMULATE_API_HEADER","x-cimulate-api-key");Je(this,"CIMULATE_SEARCH_API_HOST","search.cimulate");Je(this,"CIMULATE_SEARCH_API_PATH","api/v1");Je(this,"baseApiUrl");Je(this,"headers",{});Je(this,"fetchConfig",()=>Fe(this,null,function*(){try{const t=yield Dt.get(`${this.apiUrl}/configs/copilot`,{headers:this.headers}),{customer_config:n}=t.data,r=atob(n);return JSON.parse(r)}catch(t){throw console.error("Error fetching customer config:",t),t}}));Je(this,"_mapCopilotUrlToSearchUrl",(t="",n=!1)=>{if(t.endsWith("io")){const s=new URL(t);return s.hostname=s.hostname.replace(/^copilot\./,"api."),s.origin}return n?`https://staging.${this.CIMULATE_SEARCH_API_HOST}.ai`:`https://prod.${this.CIMULATE_SEARCH_API_HOST}.ai`});if(n&&r||!n&&!r)throw new Error("Provide exactly one authentication method: either 'apiKey' or 'apiToken', but not both.");n?this.headers[this.CIMULATE_API_HEADER]=n:r&&(this.headers.Authorization=`Bearer ${r}`),a&&(this.headers["x-cimulate-customer-id"]=a),u&&(this.headers["Tenant-ID"]=u),this.baseApiUrl=this._mapCopilotUrlToSearchUrl(t,s)}get apiUrl(){return`${this.baseApiUrl}/${this.CIMULATE_SEARCH_API_PATH}`}}class ek{constructor(t,n,r,s=!1,a,u){Je(this,"apiService");Je(this,"config",null);Je(this,"getConfig",()=>Fe(this,null,function*(){if(this.config)return this.config;try{const t=yield this.apiService.fetchConfig();return this.config=t,this.config}catch(t){throw console.error("Failed to fetch customer config:",t),t}}));Je(this,"getPid",t=>this.getProductFieldValue(t,"pidCol"));Je(this,"getName",t=>this.getProductFieldValue(t,"nameCol"));Je(this,"getDescription",t=>this.getProductFieldValue(t,"description"));Je(this,"getBrand",t=>this.getProductFieldValue(t,"productBrandCol"));Je(this,"getPrice",t=>this.getProductFieldValue(t,"priceCol"));Je(this,"getRelativePdp",t=>this.getProductFieldValue(t,"relativePdpCol"));Je(this,"getPdp",t=>this.getProductFieldValue(t,"pdpCol"));Je(this,"getImage",t=>this.getProductFieldValue(t,"imageCol"));Je(this,"getProductHiddenFields",()=>{const t=this.getProductField("productHiddenFields");return Array.isArray(t)?t:[]});Je(this,"getProductField",t=>this.config?this.config[t]:"");Je(this,"getProductFieldValue",(t,n)=>{const r=this.getProductField(n);return r&&t[r]||""});this.apiService=new ZA(t,n,r,s,a,u)}getPriceDisplay(t){const n=this.getPrice(t);return n?typeof n=="string"?n.includes("$")?n:`$${n}`:typeof n=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(n):n:""}}const tk={copilot:"Your Search Assistant",messaging:"Commerce Client"},Lg=R.createContext(null),nk=({mode:e,logoUrl:t,headerText:n,headerConfig:r,globalClassName:s="",entryMessage:a,openLinksInNewTab:u=!1,disclaimerText:l,disclaimerMarkdown:d,clientContext:f,baseCatalogParams:m,searchPlaceholder:p,searchButtonLabel:b,searchConfig:y,suggestionButtonConfig:x,progressStepsLimit:S=3,messageAlignment:A="start",autoScroll:_=!0,showProductDescription:C=!1,componentConfig:O,conversationHistory:z,resetConversationMessage:W="",apiKey:D,apiToken:V,baseUrl:K,customerId:ae,tenantId:j,theme:se,isDevelopment:ie,__features:ce,routingAttributes:fe,enableDownloadTranscript:ne=!0,enableEscalationToAgent:Se=!1,showProductCaptions:de=!1,staticQuestions:J,staticQuestionsStrategy:le="append",children:k})=>{const M=e==="messaging",Z=R.useMemo(()=>{const He=fe==null?void 0:fe.isCartMgmtSupported;return He===!0||He==="true"},[fe]),P=R.useMemo(()=>M?{config:null}:new ek(K,D,V,ie,ae,j),[M,K,D,V,ie,ae,j]),ve=R.useMemo(()=>new MS(ie),[ie]);R.useEffect(()=>{M||!P||P.config||P.getConfig()},[P,M]);const Pe=R.useMemo(()=>$S(se),[se]),he=R.useMemo(()=>{const He=(y==null?void 0:y.placeholder)||p,nt=(y==null?void 0:y.buttonLabel)||b;let Nt="icon";return y!=null&&y.buttonType?Nt=y.buttonType:b&&(Nt="text"),ue(U({},y||{}),{placeholder:He,buttonLabel:nt,buttonType:Nt})},[y,p,b]),ke=R.useMemo(()=>ue(U({},r||{}),{logoUrl:t||(r==null?void 0:r.logoUrl),headerText:(r==null?void 0:r.headerText)||n||tk[e!=null?e:"copilot"]}),[r,t,n,e]),Me=R.useMemo(()=>({configModule:P,mode:e!=null?e:"copilot",headerConfig:ke,entryMessage:a,staticQuestions:J||[],staticQuestionsStrategy:le,globalClassName:s,openLinksInNewTab:u,disclaimerText:l,disclaimerMarkdown:d,clientContext:f,baseCatalogParams:m,themeVariables:Pe,logger:ve,searchConfig:he,suggestionButtonConfig:x,progressStepsLimit:S,messageAlignment:A,autoScroll:_,showProductDescription:!!C,enableMinimize:!!(O!=null&&O.enableMinimize),enableDownloadTranscript:ne,enableEscalationToAgent:Se,showProductCaptions:!!de,resetConversationMessage:W,conversationHistory:{sinceHours:typeof(z==null?void 0:z.sinceHours)=="number"?z.sinceHours:M?24:1,limit:z==null?void 0:z.limit},features:ce,isCartMgmtSupported:Z}),[P,e,ke,a,J,le,s,f,m,l,d,u,he,x,A,_,C,O,ne,Se,S,de,W,ve,Pe,z,ce,Z]);return w.jsx(Lg.Provider,{value:Me,children:k})},ct=()=>{const e=R.useContext(Lg);if(!e)throw new Error("useConfig must be used within a ConfigProvider");return e},Dg=["markdown","product_carousel","product_tile","product_comparison","suggestions","cart","order_confirmation","tool_results"],li=-1;function Mg(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.text=="string"?t.text:"",r=typeof t.message=="string"?t.message:"";return n||r||null}function Fg(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(t&&typeof t=="object"){if(!Array.isArray(t)&&typeof t.type=="string"&&typeof t.index=="number"&&Dg.includes(t.type))return t;const n=Mg(t);return n?{type:"markdown",index:li,data:{content:n}}:null}}catch(t){}return{type:"markdown",index:li,data:{content:e}}}function Bg(e){let t;try{t=JSON.parse(e)}catch(s){return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(typeof n.type!="string"||!Dg.includes(n.type))return null;const r=typeof n.index=="number"?n.index:0;return ue(U({},n),{type:n.type,index:r})}function Ku(e){let t;try{t=JSON.parse(e)}catch(n){return null}return t&&typeof t=="object"&&Array.isArray(t.response)?t:null}function rk(e){var s,a;if(e.type!=="markdown")return[e];const t=(a=(s=e.data)==null?void 0:s.content)!=null?a:"",n=Ku(t);if(n)return n.response;const r=Bg(t);return[r&&r.type!=="markdown"?r:e]}function Ug(e,t){var n,r;return(r=(n=Ku(e))==null?void 0:n.response.some(s=>s.type===t))!=null?r:!1}function ik(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.role==="agent"&&Ug(r.content,t))return r.id}}function Hg(e){const t=e.trimStart();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{return JSON.parse(e),!1}catch(n){return!0}}function sk(e){return e.type==="markdown"&&e.index===li?!Hg(e.data.content):!0}function ok(e){var s;const t=(s=Ku(e))==null?void 0:s.response;if(!t)return null;const n=t.find(a=>a.type==="product_carousel");if(n)return{kind:"search",productIds:n.data.products.map(a=>a.id)};const r=t.find(a=>a.type==="product_tile");return r?{kind:"detail",productIds:[r.data.id]}:null}function ak(e,t){if(t.index===li){const s=e[e.length-1];if(s&&s.type==="markdown"&&s.index===li&&t.type==="markdown"){const a={type:"markdown",index:li,data:{content:s.data.content+t.data.content}};return[...e.slice(0,-1),a]}return[...e,t]}const n=e.findIndex(s=>s.index===t.index);return[...n>=0?e.map((s,a)=>a===n?t:s):[...e,t]].sort((s,a)=>s.index-a.index)}function jg(e,t){return t.serverId!==void 0&&e.some(n=>n.serverId===t.serverId)}const zg={connectionStatus:"disconnected",loading:!1,conversationId:null,messages:[],streamingBlocks:[],isAgentTyping:!1,progressMessage:"",progressSteps:[],routingResult:null,error:null,sendError:null,sessionExpired:!1};function uk(e,t){switch(t.type){case"SET_CONNECTION_STATUS":return U(ue(U({},e),{connectionStatus:t.status}),t.status==="connected"||t.status==="connecting"?{error:null}:{});case"SET_LOADING":return ue(U({},e),{loading:t.isLoading});case"SET_CONVERSATION_ID":return ue(U({},e),{conversationId:t.id});case"ADD_MESSAGE":return jg(e.messages,t.message)?e:ue(U({},e),{messages:[...e.messages,ue(U({},t.message),{type:"ADD_MESSAGE"})]});case"APPEND_STREAMING_TOKEN":{const n=Fg(t.token);return n?ue(U({},e),{streamingBlocks:ak(e.streamingBlocks,n)}):e}case"FLUSH_STREAMING":{const n={streamingBlocks:[],isAgentTyping:!1,loading:!1,progressMessage:"",progressSteps:[],sendError:null};if(jg(e.messages,t.message))return U(U({},e),n);const r=ue(U({},t.message),{type:"FLUSH_STREAMING"}),s=t.replaceMessageId?e.messages.findIndex(a=>a.id===t.replaceMessageId):-1;if(s>=0){const a=[...e.messages];return a[s]=ue(U({},r),{id:e.messages[s].id}),U(ue(U({},e),{messages:a}),n)}return U(ue(U({},e),{messages:[...e.messages,r]}),n)}case"SET_AGENT_TYPING":return ue(U({},e),{isAgentTyping:t.isTyping,loading:t.isTyping});case"SET_PROGRESS_MESSAGE":return U(ue(U({},e),{progressMessage:t.message}),t.message===""?{progressSteps:[]}:{});case"ADD_PROGRESS_STEP":return e.progressSteps[e.progressSteps.length-1]===t.message?e:ue(U({},e),{progressSteps:[...e.progressSteps,t.message],progressMessage:t.message});case"SET_ROUTING_RESULT":return ue(U({},e),{routingResult:t.result});case"SET_ERROR":return ue(U({},e),{error:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"SET_SEND_ERROR":return ue(U({},e),{sendError:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"CLEAR_SEND_ERROR":return ue(U({},e),{sendError:null});case"LOAD_HISTORY":return ue(U({},e),{messages:t.messages,loading:!1});case"SET_SESSION_EXPIRED":return ue(U({},e),{sessionExpired:t.expired});case"RESET":return ue(U({},zg),{connectionStatus:e.connectionStatus});default:return e}}const $g=R.createContext({connectionStatus:"disconnected",isConnected:!1,isAgentTyping:!1,conversationId:null,messages:[],streamingBlocks:[],progressMessage:"",progressSteps:[],loading:!0,error:null,sendError:null,sessionExpired:!1,canInitialize:!0,sendMessage:()=>Fe(null,null,function*(){return{outcome:"failure",message:"Messaging is unavailable"}}),addToCart:()=>{},resetConversation:()=>Fe(null,null,function*(){}),retryLastMessage:()=>{},retryConnection:()=>{},downloadTranscript:()=>Fe(null,null,function*(){}),getAuthLinkKey:()=>Fe(null,null,function*(){throw new Error("getAuthLinkKey called without a MessagingProvider")})}),lk=4320*60*1e3;function sf(e,t){return`cim_af_conv_${e}_${t}`}function of(e,t){return Date.now()-e>t}function ck(e,t,n){try{const r=sf(e,t),s=localStorage.getItem(r);if(!s)return null;const a=JSON.parse(s);if(!a||typeof a!="object"||!("conversationId"in a)||!("storedAt"in a))return null;const u=a;return typeof u.conversationId!="string"||!u.conversationId?null:typeof u.storedAt!="number"||of(u.storedAt,n)?(localStorage.removeItem(r),null):u}catch(r){return null}}function Qu(e,t,n){try{const r=sf(e,t),s={conversationId:n,storedAt:Date.now()};localStorage.setItem(r,JSON.stringify(s))}catch(r){}}function af(e,t){try{const n=sf(e,t);localStorage.removeItem(n)}catch(n){}}function uf(e,t){return`cim_af_ct_${e}_${t}`}function dk(e){try{const t=e.split(".")[1];if(!t)return null;const n=JSON.parse(hk(t));return typeof n.exp=="number"?n.exp*1e3:null}catch(t){return null}}function fk(e){const t=dk(e);return t===null?"unknown":Date.now()>=t?"expired":"valid"}function hk(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(t.length+(4-t.length%4)%4,"=");return atob(n)}function Vg(e,t){try{const n=uf(e,t),r=localStorage.getItem(n);if(!r)return null;const s=JSON.parse(r);if(!s||typeof s!="object"||!("accessToken"in s)||!("lastEventId"in s)||!("storedAt"in s))return null;const a=s;return typeof a.accessToken!="string"||!a.accessToken||typeof a.lastEventId!="string"||!a.lastEventId||typeof a.storedAt!="number"?null:fk(a.accessToken)==="expired"?(localStorage.removeItem(n),null):a}catch(n){return null}}function pk(e,t,n,r){try{const s=uf(e,t),a={accessToken:n,lastEventId:r,storedAt:Date.now()};localStorage.setItem(s,JSON.stringify(a))}catch(s){}}function mk(e,t){try{const n=uf(e,t);localStorage.removeItem(n)}catch(n){}}function gk(e,t){return`cim_af_conv_${e}_${t}`}function Ek(e,t){try{if(typeof BroadcastChannel=="undefined")return null;const n=gk(e,t);return new BroadcastChannel(n)}catch(n){return null}}function yk(e,t=500){return e?new Promise(n=>{let r=!1;const s=setTimeout(()=>{r||(r=!0,e.removeEventListener("message",a),n(null))},t);function a(u){var l;r||((l=u.data)==null?void 0:l.type)==="conversation_response"&&(r=!0,clearTimeout(s),e.removeEventListener("message",a),n({conversationId:u.data.conversationId,storedAt:u.data.storedAt,continuationToken:u.data.continuationToken,lastEventId:u.data.lastEventId}))}e.addEventListener("message",a);try{e.postMessage({type:"request_conversation"})}catch(u){r||(r=!0,clearTimeout(s),e.removeEventListener("message",a),n(null))}}):Promise.resolve(null)}function Tk(e,t,n){if(!e)return()=>{};function r(s){var a;if((a=s.data)!=null&&a.type)switch(s.data.type){case"request_conversation":{const u=t();if(u!=null&&u.conversationId)try{e.postMessage({type:"conversation_response",conversationId:u.conversationId,storedAt:Date.now(),continuationToken:u.continuationToken,lastEventId:u.lastEventId})}catch(l){}break}case"conversation_cleared":{n==null||n();break}}}return e.addEventListener("message",r),()=>{e.removeEventListener("message",r)}}function bk(e){if(e)try{e.postMessage({type:"conversation_cleared"})}catch(t){}}function wk(e){if(e)try{e.close()}catch(t){}}function xk(e){switch(e){case"EndUser":case"Customer":return"user";case"Agent":case"Chatbot":return"agent";default:return"system"}}function _k(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch(t){return{}}return e}function qg(e,...t){let n=e;for(const r of t){if(n==null||typeof n!="object")return"";n=n[r]}return typeof n=="string"?n:""}function Sk(e){if(e.entryType!=="Message")return null;const n=_k(e.entryPayload).abstractMessage;if(!n)return null;const r=qg(n,"staticContent","text")||qg(n,"content","text")||"";if(!r)return null;const s=xk(e.sender.role);return{id:e.identifier,serverId:e.identifier,role:s,content:r,timestamp:new Date(e.transcriptedTimestamp).toISOString(),sender:{role:e.sender.role,name:e.senderDisplayName}}}function vk(e){const t=[];for(const n of e){const r=Sk(n);r&&t.push(r)}return t}const Ak=5e3,sa=Symbol("cimulate-abort-conversation");function Ju(e={}){const{routingAttributes:t,timeoutMs:n=Ak}=e;if(typeof window=="undefined"||typeof window.dispatchEvent!="function")return Promise.resolve(t);const r=U({},t!=null?t:{});return new Promise(s=>{const a={settled:!1},u=()=>{if(a.settled)return;a.settled=!0,a.timer!==void 0&&clearTimeout(a.timer);const p=Object.keys(r).length>0;s(p?r:t)},d={routingAttributes:t,setHiddenPrechatFields:p=>{a.settled||!p||Object.assign(r,p)},done:u,abort:()=>{a.settled||(a.settled=!0,a.timer!==void 0&&clearTimeout(a.timer),s(sa))}},f=new CustomEvent($0,{detail:d,cancelable:!0});if(!!window.dispatchEvent(f)){u();return}a.timer=setTimeout(u,n)})}const kk=200,Ck=1e3;function Nk(e){const{orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:s}=e,a=R.useRef(null),u=R.useRef(null),l=R.useRef(null),d=s.sinceHours*60*60*1e3,f=lk,m=R.useCallback(()=>(l.current||(l.current=yk(a.current)),l.current),[]);R.useEffect(()=>{const _=Ek(t,n);a.current=_,l.current=null;const C=Tk(_,()=>{const O=u.current;if(!O)return null;const z=Vg(t,n);return{conversationId:O,continuationToken:z==null?void 0:z.accessToken,lastEventId:z==null?void 0:z.lastEventId}},()=>{af(t,n),u.current=null});return()=>{C(),wk(_),a.current=null}},[t,n]);const p=R.useCallback((_,C)=>Fe(null,null,function*(){var D,V,K;const O=(D=C==null?void 0:C.createIfMissing)!=null?D:!0,z=(V=C==null?void 0:C.isCurrent)!=null?V:(()=>!0);let W=ck(t,n,f);if(!W){const ae=yield m();ae&&!of(ae.storedAt,f)&&(W=ae)}if(!W){if(!O)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const ae=yield Ju({routingAttributes:r});if(ae===sa)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const j=yield _.createConversation(ae);return z()?(Qu(t,n,j),u.current=j,{conversationId:j,restoredMessages:[],resumed:!1,outcome:"created"}):(yield _.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}try{const ae=yield _.listConversations({conversationId:W.conversationId,startTimestamp:Date.now()-f});if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const j=ae.conversations.find(ie=>ie.conversationId===W.conversationId&&!ie.isConversationClosed);if(!j){if(af(t,n),!O)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const ie=yield Ju({routingAttributes:r});if(ie===sa)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!z())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const ce=yield _.createConversation(ie);return z()?(Qu(t,n,ce),u.current=ce,{conversationId:ce,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"}):(yield _.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}_.resumeConversation(j.conversationId),u.current=j.conversationId,Qu(t,n,j.conversationId);let se=[];try{const ie=yield _.listConversationEntries(j.conversationId,{limit:Math.min((K=s.limit)!=null?K:kk,Ck),startTimestamp:Date.now()-d,direction:"FromEnd"});se=vk(ie.conversationEntries).reverse()}catch(ie){}return{conversationId:j.conversationId,restoredMessages:se,resumed:!0,outcome:"resumed"}}catch(ae){return{conversationId:W.conversationId,restoredMessages:[],resumed:!1,outcome:"unverified-error",error:ae}}}),[t,n,r,s,d,f,m]),b=R.useCallback(_=>{Qu(t,n,_),u.current=_},[t,n]),y=R.useCallback(()=>{af(t,n),mk(t,n),bk(a.current),u.current=null},[t,n]),x=R.useCallback(()=>{const _=Vg(t,n);return _?{continuationToken:_.accessToken,lastEventId:_.lastEventId}:null},[t,n]),S=R.useCallback(()=>Fe(null,null,function*(){const _=yield m();return!(_!=null&&_.continuationToken)||of(_.storedAt,f)?null:{continuationToken:_.continuationToken,lastEventId:_.lastEventId}}),[f,m]),A=R.useCallback((_,C=()=>!0)=>Fe(null,null,function*(){try{const{accessToken:O,lastEventId:z}=yield _.generateContinuationToken();if(!C())return;pk(t,n,O,z)}catch(O){}}),[t,n]);return{initializeConversation:p,persistConversationId:b,clearPersistedConversation:y,getStoredConnectOptions:x,getPeerConnectOptions:S,persistContinuationToken:A}}const Ok="Your session ended due to inactivity. Starting a new session…",Ik=300*1e3,Pk=2e3,Rk=1e4,Lk=15e3,Dk=2;function Yg(e,t,n){return e||t||n===!0}function oa(e){const t=e.find(r=>!r.timedOut),n=e[e.length-1];return t!=null?t:n}function Mk(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{const n=JSON.parse(t);return typeof n=="object"&&n!==null}catch(n){return!1}}function Wg(e){if(!e||typeof e!="object")return!1;const t=e,n=t.type==="auth",r=t.type==="api"&&(t.statusCode===401||t.statusCode===403);return n||r}function lf(e){if(Wg(e))return!0;const t=e instanceof Error?e.message:"";return/\(401\)/.test(t)}function Fk(e){var b;const t=e.productName||"this product",n=e.quantity&&e.quantity>1?e.quantity:void 0,r=((b=e.variants)!=null?b:[]).filter(y=>y.value),s=r.map(y=>`${y.label}: ${y.value}`).join(", "),a=r.map(y=>y.value).join(", "),u=s?` (${s})`:"",l=a?` (${a})`:"",d=n?`Add ${n} of`:"Add",f=e.sku?` [SKU: ${e.sku}]`:"",m=`${d} ${t} to my cart${u}${f}`,p=`Add ${n?`${n} × `:""}${t} to cart${l}`;return{prompt:m,display:p}}function Bk({connectionStatus:e,loading:t,hasMessages:n,sessionExpired:r,bootstrapSettled:s,resumeUsedLastEventId:a,recoverySteps:u,onExhausted:l,timeoutMs:d=Lk,logger:f,isRecoveryInFlight:m}){const p=R.useRef(u);p.current=u;const b=R.useRef(l);b.current=l;const y=R.useRef(f);y.current=f;const x=R.useRef(m);x.current=m;const S=R.useRef(0),A=R.useRef(!1),_=R.useRef(0),[C,O]=R.useState(0);R.useEffect(()=>{if(!t||n){S.current=0,A.current=!1,_.current=0;return}const z=a||S.current>0;if(!(s&&z&&e==="connected"&&!r&&!A.current))return;const D=setTimeout(()=>{Fe(null,null,function*(){var j,se;if((j=x.current)!=null&&j.call(x)){if(_.current+=1,_.current>Dk){A.current=!0,b.current();return}O(ie=>ie+1);return}const V=S.current,K=p.current;if(V>=K.length){A.current=!0,b.current();return}_.current=0,(se=y.current)==null||se.warn("🦜 connect bootstrap stalled",{attempt:V});let ae;try{yield Promise.race([Promise.resolve(K[V]()),new Promise((ie,ce)=>{ae=setTimeout(()=>{ce(new Error("connect bootstrap step timed out"))},d)})])}catch(ie){}finally{ae!==void 0&&clearTimeout(ae),S.current=V+1,O(ie=>ie+1)}})},d);return()=>{clearTimeout(D)}},[e,t,n,r,s,a,d,C])}const Sr={default:"Something went wrong. Please try again.",server:"Something went wrong. Please try again.",rateLimit:"We are getting a lot of requests right now. Please try again in a moment.",network:"You are offline or we couldn't reach the assistant. Check connection and try again.",interrupted:"Something went wrong. Please try again.",connect:"You are offline or we couldn't reach the assistant. Check connection and try again.",lost:"You are offline or we couldn't reach the assistant. Check connection and try again.",routing:"Something went wrong. Please try again."};function Uk(e){if(!e||typeof e!="object")return{};const t=e;return{type:typeof t.type=="string"?t.type:void 0,statusCode:typeof t.statusCode=="number"?t.statusCode:void 0}}function ci(e){const{type:t,statusCode:n}=Uk(e);if(t==="api"&&typeof n=="number")return n===429?Sr.rateLimit:n>=500?Sr.server:Sr.default;switch(t){case"network":return Sr.network;case"sse":return Sr.interrupted;case"auth":return Sr.connect;default:return Sr.default}}function Gg(e){switch(e.code){case"MAX_RECONNECT":return Sr.lost;case"ROUTING_FAILED":return Sr.routing;default:return Sr.connect}}let Gi=null;function Hk(e){Gi&&Gi!==e&&console.warn("[CimulateMessaging] A messaging API is already registered; overwriting it. Mounting more than one messaging widget per page is not supported."),Gi=e}function jk(e){Gi===e&&(Gi=null)}function zk(){if(!Gi)throw new Error("Cimulate messaging widget is not ready. Call this after injectMessagingWidget() has run and the widget has mounted.");return Gi}const Hs=Symbol("initialization-cancelled"),Xg=({scrt2Url:e,orgId:t,esDeveloperName:n,routingAttributes:r,capabilitiesVersion:s,enableLogging:a=!1,onConnect:u,onMessage:l,onError:d,onProductResult:f,children:m})=>{const{logger:p,conversationHistory:b}=ct(),{status:{isOpen:y}}=Vr(),[x,S]=R.useReducer(uk,zg),[A,_]=R.useState(!1),[C,O]=R.useState(!1),[z,W]=R.useState(!1),D=R.useRef(x);D.current=x;const V=Nk({orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:b}),K=R.useRef(null),ae=R.useRef(l),j=R.useRef(d),se=R.useRef(u),ie=R.useRef(f),ce=R.useRef(!1),fe=R.useRef(!1),ne=R.useRef(!1),Se=R.useRef(0),de=R.useRef(0),J=R.useRef(0),le=R.useRef(null),k=R.useRef(null),M=R.useRef(null),Z=R.useRef(0),P=R.useRef(!1),ve=R.useRef(0),Pe=R.useRef(0),he=R.useRef(()=>Promise.reject(new Error("Messaging is unavailable"))),ke=R.useRef([]),Me=R.useRef(null),He=R.useCallback((ee,_e)=>{_e.outcome==="timeout"?(ee.timedOut=!0,ke.current=ke.current.filter(Ne=>Ne===ee||!Ne.timedOut)):ke.current=ke.current.filter(Ne=>Ne!==ee),clearTimeout(ee.timeoutId),ee.resolve(_e)},[]);ae.current=l,j.current=d,se.current=u,ie.current=f,R.useEffect(()=>{const ee=new zS({baseURL:e,orgId:t,esDeveloperName:n,options:U({enableLogging:a},s?{capabilitiesVersion:s}:{})});K.current=ee,P.current=!1,W(!1),_(!1),O(!1),S({type:"RESET"}),ee.on("connected",()=>{var ge;S({type:"SET_CONNECTION_STATUS",status:"connected"}),(ge=se.current)==null||ge.call(se)}),ee.on("disconnected",()=>{S({type:"SET_CONNECTION_STATUS",status:"disconnected"})}),ee.on("reconnecting",()=>{S({type:"SET_CONNECTION_STATUS",status:"reconnecting"})}),ee.on("message",ge=>{var vo,Jr;const je=ue(U({id:ge.messageId||crypto.randomUUID()},ge.messageId?{serverId:ge.messageId}:{}),{role:"agent",content:ge.content,timestamp:ge.timestamp,sender:ge.sender,raw:ge});p==null||p.log("🦜 MessagingProvider message received (FLUSH_STREAMING)",{messageId:je.id,tokensBeforeFlush:Se.current,streamedFinalOnly:Se.current===0}),Se.current=0;const Ke=oa(ke.current),$t=Ke==null?void 0:Ke.options.reconcileMessageId;S({type:"FLUSH_STREAMING",message:je,replaceMessageId:$t}),(vo=ae.current)==null||vo.call(ae,je),Ke&&He(Ke,{outcome:"success"});const{messagingSessionId:ht}=ge,Mr=ht?ok(ge.content):null;ht&&Mr&&((Jr=ie.current)==null||Jr.call(ie,{agentSessionId:ht,kind:Mr.kind,productIds:Mr.productIds}))}),ee.on("streaming_token",ge=>{var je;if(!((je=oa(ke.current))!=null&&je.options.silent)){if(Se.current+=1,p!=null&&p.isDevelopment){const Ke=Fg(ge.token);Ke?Ke.index===li?p.debug("🦜 streaming_token → markdown fallback",{token:ge.token}):p.debug("🦜 streaming_token parsed",{type:Ke.type,index:Ke.index,outputName:Ke.type==="tool_results"?Ke.output_name:void 0}):p.debug("🦜 streaming_token dropped (empty or unrecognized payload shape)",{token:ge.token})}S({type:"APPEND_STREAMING_TOKEN",token:ge.token})}}),ee.on("typing_started",()=>{var ge;(ge=oa(ke.current))!=null&&ge.options.silent||S({type:"SET_AGENT_TYPING",isTyping:!0})}),ee.on("typing_stopped",()=>{var ge;(ge=oa(ke.current))!=null&&ge.options.silent||S({type:"SET_AGENT_TYPING",isTyping:!1})}),ee.on("progress_indicator",ge=>{var je;(je=oa(ke.current))!=null&&je.options.silent||S({type:"ADD_PROGRESS_STEP",message:ge.message})}),ee.on("routing_result",ge=>{var je;if(S({type:"SET_ROUTING_RESULT",result:ge}),!ge.isSuccessful){const Ke=`Routing failed: ${ge.failureType||"unknown"}`;S({type:"SET_ERROR",error:Gg({code:"ROUTING_FAILED"})}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(je=j.current)==null||je.call(j,Ke)}}),ee.on("participant_changed",ge=>{if(ge.participant.name==="Automated Process")return;const je=ue(U({id:crypto.randomUUID()},ge.entryId?{serverId:ge.entryId}:{}),{role:"system",content:ge.action==="add"?`${ge.participant.name||"Agent"} joined the conversation`:`${ge.participant.name||"Agent"} left the conversation`,timestamp:new Date().toISOString()});p==null||p.log("🦜 MessagingProvider participant_changed event received",{event:ge}),S({type:"ADD_MESSAGE",message:je})}),ee.on("conversation_closed",()=>{const ge={id:crypto.randomUUID(),role:"system",content:"Conversation reset",timestamp:new Date().toISOString()};S({type:"ADD_MESSAGE",message:ge}),S({type:"SET_CONVERSATION_ID",id:null}),V.clearPersistedConversation()}),ee.on("error",ge=>{var je;if(p==null||p.log("🦜 MessagingProvider ERROR event received",{event:ge}),ge.code==="SESSION_EXPIRED"){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),S({type:"SET_LOADING",isLoading:!1});return}S({type:"SET_ERROR",error:Gg(ge)}),ge.recoverable||S({type:"SET_CONNECTION_STATUS",status:"error"}),(je=j.current)==null||je.call(j,ge.message)});const _e=ge=>{if(ge!==ve.current)throw Hs},Ne=ge=>ge===ve.current,Ae=ge=>Fe(null,null,function*(){_(!1);let je=V.getStoredConnectOptions(),Ke=!1;je||(je=yield V.getPeerConnectOptions(),_e(ge),Ke=!!je);let $t=!1;try{if(yield ee.connect(je!=null?je:void 0),!Ne(ge))throw ee.disconnect(),Hs;$t=!!(je!=null&&je.lastEventId)}catch(Mr){if(_e(ge),je&&lf(Mr)){if(p==null||p.log("Stored token expired on connect — falling back to fresh connect"),Ke||V.clearPersistedConversation(),yield ee.connect(),!Ne(ge))throw ee.disconnect(),Hs;$t=!1}else throw Mr}O($t),yield V.persistContinuationToken(ee,()=>Ne(ge)),_e(ge);const ht=yield V.initializeConversation(ee,{isCurrent:()=>Ne(ge)});if(_e(ge),p==null||p.log("🦜 initial connect complete",{conversationId:ht.conversationId,resumed:ht.resumed,outcome:ht.outcome,restoredMessages:ht.restoredMessages.length}),ht.outcome==="aborted")throw S({type:"SET_LOADING",isLoading:!1}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Hs;if(ht.outcome==="unverified-error"){ht.conversationId&&(ee.resumeConversation(ht.conversationId),S({type:"SET_CONVERSATION_ID",id:ht.conversationId})),_(!0);return}S({type:"SET_CONVERSATION_ID",id:ht.conversationId}),ht.resumed&&S({type:"LOAD_HISTORY",messages:ht.restoredMessages}),_(!0),S({type:"SET_LOADING",isLoading:!1})});return k.current=Ae,()=>{ve.current+=1,Pe.current+=1,ee.disconnect(),ee.off(),K.current=null,k.current=null,M.current=null,P.current=!1}},[e,t,n,s,He]);const nt=R.useCallback(()=>{if(P.current)return Promise.resolve();if(M.current)return Z.current===ve.current?M.current:M.current.catch(Ae=>{if(Ae!==Hs)throw Ae}).then(()=>he.current());const ee=k.current;if(!ee)return Promise.reject(new Error("Messaging is unavailable"));S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_CONNECTION_STATUS",status:"connecting"});const _e=++ve.current;Z.current=_e;const Ne=ee(_e).then(()=>{P.current=!0,W(!0)}).catch(Ae=>{var je;if(Ae===Hs)throw Ae;const ge=Ae instanceof Error?Ae.message:String(Ae);throw S({type:"SET_CONNECTION_STATUS",status:"error"}),S({type:"SET_ERROR",error:ci(Ae)}),(je=j.current)==null||je.call(j,ge),Ae}).finally(()=>{M.current===Ne&&(M.current=null)});return M.current=Ne,Ne},[]);he.current=nt,R.useEffect(()=>{y&&nt().catch(()=>{})},[y,e,t,n,s,nt]);const Nt=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee)return!1;const _e=V.getStoredConnectOptions();if(!_e)return p==null||p.log("🦜 attemptResume: no stored identity — cannot resume, will start fresh"),!1;p==null||p.log("🦜 attemptResume: reconnecting on stored identity via continuation token");try{ee.disconnect(),yield ee.connect(_e)}catch(Ae){if(lf(Ae))return p==null||p.log("🦜 attemptResume: token expired (401) — will start fresh",{error:Ae instanceof Error?Ae.message:String(Ae)}),!1;throw p==null||p.log("🦜 attemptResume: transient connect failure — rethrowing, session kept",{error:Ae instanceof Error?Ae.message:String(Ae)}),Ae}yield V.persistContinuationToken(ee);const Ne=yield V.initializeConversation(ee,{createIfMissing:!1});return Ne.outcome==="not-found-or-closed"||!Ne.conversationId?(p==null||p.log("🦜 attemptResume: conversation no longer resumable (closed/not found) — will start fresh"),!1):(Ne.outcome==="unverified-error"&&(p==null||p.log("🦜 attemptResume: resume validation failed transiently — keeping live session, resuming optimistically",{conversationId:Ne.conversationId}),ee.resumeConversation(Ne.conversationId)),p==null||p.log("🦜 attemptResume: resumed conversation on same identity",{conversationId:Ne.conversationId}),S({type:"SET_CONVERSATION_ID",id:Ne.conversationId}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(Ne.conversationId),ne.current=!1,S({type:"SET_SESSION_EXPIRED",expired:!1}),!0)}),[V,p]),Ft=R.useCallback(ee=>Fe(null,null,function*(){var Ne;const _e=K.current;if(_e){ee.options.silent||(S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_PROGRESS_MESSAGE",message:""}));try{yield _e.sendMessage(ee.text)}catch(Ae){const ge=ci(Ae);S({type:"SET_SEND_ERROR",error:{text:ee.text,displayContent:ee.displayContent,options:ee.options,message:ge}}),(Ne=j.current)==null||Ne.call(j,Ae instanceof Error?Ae.message:String(Ae)),He(ee,{outcome:"failure",message:ge})}}}),[He]),xn=R.useCallback(ee=>Fe(null,null,function*(){var Ne;const _e=K.current;if(!(!_e||ce.current)){ce.current=!0,fe.current=!0;try{if(yield Nt()){ee&&(yield Ft(ee));return}p==null||p.log("🦜 recoverExpiredSession: resume failed — starting a new session + conversation"),ne.current=!1,S({type:"SET_SESSION_EXPIRED",expired:!1}),S({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"system",content:Ok,timestamp:new Date().toISOString()}}),V.clearPersistedConversation(),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),_e.disconnect(),yield _e.connect(),yield V.persistContinuationToken(_e);const Ae=yield Ju({routingAttributes:r});if(Ae===sa){S({type:"SET_CONNECTION_STATUS",status:"disconnected"});return}const ge=yield _e.createConversation(Ae);p==null||p.log("🦜 recoverExpiredSession: new conversation created",{conversationId:ge}),S({type:"SET_CONVERSATION_ID",id:ge}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(ge),ee&&(yield Ft(ee))}catch(Ae){const ge=Ae instanceof Error?Ae.message:String(Ae);S({type:"SET_ERROR",error:ci(Ae)}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(Ne=j.current)==null||Ne.call(j,ge),ee&&He(ee,{outcome:"failure",message:ci(Ae)})}finally{ce.current=!1,fe.current=!1}}}),[r,V,Nt,Ft,p,He]),pn=R.useRef(xn);pn.current=xn;const Bt=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee||!P.current||ce.current)return;if(!D.current.conversationId&&!ne.current){ee.reconnect();return}ce.current=!0;const _e=Fe(null,null,function*(){try{(yield Nt())||(ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}))}catch(Ne){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"})}finally{ce.current=!1,le.current=null}});le.current=_e,yield _e}),[Nt]),$e=R.useRef(Bt);$e.current=Bt;const St=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee||ce.current)return;const _e=V.getStoredConnectOptions(),Ne=_e==null?void 0:_e.continuationToken;if(Ne){ce.current=!0;try{ee.disconnect(),yield ee.connect({continuationToken:Ne}),yield V.persistContinuationToken(ee);const Ae=D.current.conversationId;Ae&&ee.resumeConversation(Ae)}catch(Ae){if(lf(Ae)){ne.current=!0,S({type:"SET_SESSION_EXPIRED",expired:!0}),S({type:"SET_CONNECTION_STATUS",status:"disconnected"}),S({type:"SET_LOADING",isLoading:!1});return}p==null||p.log("🦜 reconnectOmittingLastEventId: transient connect failure — session kept",{error:Ae instanceof Error?Ae.message:String(Ae)})}finally{ce.current=!1}}}),[V,p]);R.useEffect(()=>{const ee=()=>{const Ke=Date.now();Ke-J.current<Pk||(J.current=Ke,$e.current())},_e=()=>{if(document.visibilityState==="hidden"){de.current=Date.now();return}const Ke=K.current;if(!Ke)return;const $t=de.current?Date.now()-de.current:0;de.current=0,(ne.current||!Ke.isConnected||$t>Ik)&&ee()},Ne=Ke=>{Ke.persisted&&ee()},Ae=()=>{de.current=Date.now()},ge=()=>ee(),je=()=>ee();return document.addEventListener("visibilitychange",_e),window.addEventListener("pageshow",Ne),window.addEventListener("pagehide",Ae),document.addEventListener("resume",ge),window.addEventListener("online",je),()=>{document.removeEventListener("visibilitychange",_e),window.removeEventListener("pageshow",Ne),window.removeEventListener("pagehide",Ae),document.removeEventListener("resume",ge),window.removeEventListener("online",je)}},[]);const Wt=R.useCallback((ee,_e)=>Fe(null,null,function*(){var Ae;const Ne=K.current;if(!Ne){He(ee,{outcome:"failure",message:"Messaging is unavailable"});return}if(ne.current){yield pn.current(ee);return}try{yield Ne.sendMessage(ee.text)}catch(ge){if(Wg(ge)){yield pn.current(ee);return}const je=ci(ge);S({type:"SET_SEND_ERROR",error:_e(je)}),(Ae=j.current)==null||Ae.call(j,ge instanceof Error?ge.message:String(ge)),He(ee,{outcome:"failure",message:je})}}),[He]),Ie=R.useCallback(ee=>Fe(null,null,function*(){const _e=le.current;_e&&(yield _e),yield ee()}),[]),Xe=R.useCallback((ee,_e,Ne={})=>new Promise(Ae=>{if(!K.current){Ae({outcome:"failure",message:"Messaging is unavailable"});return}const je={};Object.assign(je,{text:ee,displayContent:_e,options:Ne,resolve:Ae,timeoutId:setTimeout(()=>{S({type:"SET_LOADING",isLoading:!1}),He(je,{outcome:"timeout"})},Rk)}),ke.current.push(je),S({type:"CLEAR_SEND_ERROR"}),Ne.silent||(S({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"user",content:_e!=null?_e:ee,timestamp:new Date().toISOString()}}),S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_PROGRESS_MESSAGE",message:""})),Ie(()=>Wt(je,Ke=>({text:ee,displayContent:_e,options:Ne,message:Ke})))}),[Wt,Ie,He]),ot=R.useCallback((ee,_e)=>{if(!ee.trim())return Promise.resolve({outcome:"failure",message:"Message is empty"});const Ne=Pe.current,Ae=()=>{const Ke=()=>Ne!==Pe.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Xe(ee,_e==null?void 0:_e.displayContent,_e);return P.current?Ke():nt().then(Ke,$t=>({outcome:"failure",message:ci($t)}))},ge=Me.current?Me.current.then(Ae):Ae(),je=ge.then(()=>{});return Me.current=je,je.finally(()=>{Me.current===je&&(Me.current=null)}),ge},[Xe,nt]),ft=R.useCallback(ee=>{if(!K.current)return;const _e=Pe.current,{prompt:Ne,display:Ae}=Fk(ee);nt().then(()=>{if(_e===Pe.current)return Xe(Ne,Ae)}).catch(()=>{})},[Xe,nt]),Jn=R.useCallback(()=>{const ee=K.current,_e=D.current.sendError;if(!ee||!_e)return;const Ne=()=>fe.current?Promise.resolve({outcome:"failure",message:_e.message}):Xe(_e.text,_e.displayContent,_e.options),Ae=Me.current?Me.current.then(Ne):Ne(),ge=Ae.then(()=>{});return Me.current=ge,ge.finally(()=>{Me.current===ge&&(Me.current=null)}),Ae},[Xe]),gs=R.useCallback(()=>{const ee=K.current;ee&&(M.current||(ne.current=!1,P.current=!1,W(!1),ee.disconnect(),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),nt().catch(()=>{})))},[nt]),xi=R.useCallback(()=>{const ee=K.current;if(!ee)return Promise.resolve();if(!P.current)return ve.current+=1,Pe.current+=1,ee.disconnect(),V.clearPersistedConversation(),S({type:"RESET"}),Promise.resolve();const _e=++Pe.current;return ne.current=!1,O(!1),V.clearPersistedConversation(),S({type:"RESET"}),S({type:"SET_LOADING",isLoading:!0}),S({type:"SET_CONNECTION_STATUS",status:"connecting"}),ee.endConversation().then(()=>_e!==Pe.current||K.current!==ee?null:(ee.disconnect(),ee.connect().then(()=>ee))).then(Ne=>Fe(null,null,function*(){if(!Ne||_e!==Pe.current||(yield V.persistContinuationToken(Ne,()=>_e===Pe.current&&K.current===Ne),_e!==Pe.current||K.current!==Ne))return null;const Ae=yield Ju({routingAttributes:r});return Ae===sa?null:ee.createConversation(Ae)})).then(Ne=>{!Ne||_e!==Pe.current||K.current!==ee||(S({type:"SET_CONVERSATION_ID",id:Ne}),S({type:"SET_CONNECTION_STATUS",status:"connected"}),V.persistConversationId(Ne))}).catch(Ne=>{var Ae;_e!==Pe.current||K.current!==ee||(S({type:"SET_ERROR",error:ci(Ne)}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(Ae=j.current)==null||Ae.call(j,Ne.message))})},[r,V]);Bk({connectionStatus:x.connectionStatus,loading:x.loading,hasMessages:x.messages.length>0,sessionExpired:x.sessionExpired,bootstrapSettled:A,resumeUsedLastEventId:C,recoverySteps:[St,xi],onExhausted:()=>{var _e;const ee=ci({type:"network"});S({type:"SET_ERROR",error:ee}),S({type:"SET_CONNECTION_STATUS",status:"error"}),(_e=j.current)==null||_e.call(j,ee)},logger:p,isRecoveryInFlight:()=>ce.current||le.current!==null});const oe=R.useCallback(()=>Fe(null,null,function*(){var Ae;const ee=K.current;if(!ee||!D.current.conversationId)return;const _e=yield ee.retrieveConversationTranscript(),Ne=URL.createObjectURL(_e);try{const ge=document.createElement("a");ge.href=Ne,ge.download=`transcript-${(Ae=ee.conversationId)!=null?Ae:"conversation"}.pdf`,document.body.appendChild(ge),ge.click(),ge.remove()}finally{URL.revokeObjectURL(Ne)}}),[]),xe=R.useCallback(()=>Fe(null,null,function*(){const ee=K.current;if(!ee)throw new Error("getAuthLinkKey called before the messaging client connected");return p==null||p.debug("🦜 getAuthLinkKey: requesting single-use auth link key"),ee.getAuthLinkKey()}),[p]);R.useEffect(()=>{const ee={getAuthLinkKey:xe};return Hk(ee),()=>jk(ee)},[xe]);const Ve=x.connectionStatus==="connected"&&x.conversationId!==null;R.useEffect(()=>{V0(Ve)},[Ve]),R.useEffect(()=>()=>V0(!1),[]);const et=R.useMemo(()=>({connectionStatus:x.connectionStatus,isConnected:Ve,isAgentTyping:x.isAgentTyping,conversationId:x.conversationId,messages:x.messages,streamingBlocks:x.streamingBlocks,progressMessage:x.progressMessage,progressSteps:x.progressSteps,error:x.error,sendError:x.sendError,canInitialize:!z&&x.error===null,loading:x.loading,sessionExpired:x.sessionExpired,sendMessage:ot,addToCart:ft,resetConversation:xi,retryLastMessage:Jn,retryConnection:gs,downloadTranscript:oe,getAuthLinkKey:xe}),[x,Ve,z,ot,ft,xi,Jn,gs,oe,xe]);return w.jsx($g.Provider,{value:et,children:m})};var Kg=Symbol.for("immer-nothing"),Qg=Symbol.for("immer-draftable"),Hn=Symbol.for("immer-state");function ur(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var js=Object.getPrototypeOf;function zs(e){return!!e&&!!e[Hn]}function Xi(e){var t;return e?Jg(e)||Array.isArray(e)||!!e[Qg]||!!((t=e.constructor)!=null&&t[Qg])||aa(e)||tl(e):!1}var $k=Object.prototype.constructor.toString();function Jg(e){if(!e||typeof e!="object")return!1;const t=js(e);if(t===null)return!0;const n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===$k}function Zu(e,t){el(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function el(e){const t=e[Hn];return t?t.type_:Array.isArray(e)?1:aa(e)?2:tl(e)?3:0}function cf(e,t){return el(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Zg(e,t,n){const r=el(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Vk(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function aa(e){return e instanceof Map}function tl(e){return e instanceof Set}function Ki(e){return e.copy_||e.base_}function df(e,t){if(aa(e))return new Map(e);if(tl(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=Jg(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[Hn];let s=Reflect.ownKeys(r);for(let a=0;a<s.length;a++){const u=s[a],l=r[u];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[u]={configurable:!0,writable:!0,enumerable:l.enumerable,value:e[u]})}return Object.create(js(e),r)}else{const r=js(e);if(r!==null&&n)return U({},e);const s=Object.create(r);return Object.assign(s,e)}}function ff(e,t=!1){return rl(e)||zs(e)||!Xi(e)||(el(e)>1&&Object.defineProperties(e,{set:{value:nl},add:{value:nl},clear:{value:nl},delete:{value:nl}}),Object.freeze(e),t&&Object.values(e).forEach(n=>ff(n,!0))),e}function nl(){ur(2)}function rl(e){return Object.isFrozen(e)}var qk={};function Qi(e){const t=qk[e];return t||ur(0,e),t}var ua;function e1(){return ua}function Yk(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function t1(e,t){t&&(Qi("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function hf(e){pf(e),e.drafts_.forEach(Wk),e.drafts_=null}function pf(e){e===ua&&(ua=e.parent_)}function n1(e){return ua=Yk(ua,e)}function Wk(e){const t=e[Hn];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function r1(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[Hn].modified_&&(hf(t),ur(4)),Xi(e)&&(e=il(t,e),t.parent_||sl(t,e)),t.patches_&&Qi("Patches").generateReplacementPatches_(n[Hn].base_,e,t.patches_,t.inversePatches_)):e=il(t,n,[]),hf(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Kg?e:void 0}function il(e,t,n){if(rl(t))return t;const r=t[Hn];if(!r)return Zu(t,(s,a)=>i1(e,r,t,s,a,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return sl(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const s=r.copy_;let a=s,u=!1;r.type_===3&&(a=new Set(s),s.clear(),u=!0),Zu(a,(l,d)=>i1(e,r,s,l,d,n,u)),sl(e,s,!1),n&&e.patches_&&Qi("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function i1(e,t,n,r,s,a,u){if(zs(s)){const l=a&&t&&t.type_!==3&&!cf(t.assigned_,r)?a.concat(r):void 0,d=il(e,s,l);if(Zg(n,r,d),zs(d))e.canAutoFreeze_=!1;else return}else u&&n.add(s);if(Xi(s)&&!rl(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;il(e,s),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(aa(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&sl(e,s)}}function sl(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ff(t,n)}function Gk(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:e1(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=r,a=mf;n&&(s=[r],a=la);const{revoke:u,proxy:l}=Proxy.revocable(s,a);return r.draft_=l,r.revoke_=u,l}var mf={get(e,t){if(t===Hn)return e;const n=Ki(e);if(!cf(n,t))return Xk(e,n,t);const r=n[t];return e.finalized_||!Xi(r)?r:r===gf(e.base_,t)?(yf(e),e.copy_[t]=Tf(r,e)):r},has(e,t){return t in Ki(e)},ownKeys(e){return Reflect.ownKeys(Ki(e))},set(e,t,n){const r=s1(Ki(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const s=gf(Ki(e),t),a=s==null?void 0:s[Hn];if(a&&a.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Vk(n,s)&&(n!==void 0||cf(e.base_,t)))return!0;yf(e),Ef(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return gf(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,yf(e),Ef(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Ki(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ur(11)},getPrototypeOf(e){return js(e.base_)},setPrototypeOf(){ur(12)}},la={};Zu(mf,(e,t)=>{la[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),la.deleteProperty=function(e,t){return la.set.call(this,e,t,void 0)},la.set=function(e,t,n){return mf.set.call(this,e[0],t,n,e[0])};function gf(e,t){const n=e[Hn];return(n?Ki(n):e)[t]}function Xk(e,t,n){var s;const r=s1(t,n);return r?"value"in r?r.value:(s=r.get)==null?void 0:s.call(e.draft_):void 0}function s1(e,t){if(!(t in e))return;let n=js(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=js(n)}}function Ef(e){e.modified_||(e.modified_=!0,e.parent_&&Ef(e.parent_))}function yf(e){e.copy_||(e.copy_=df(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Kk=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const a=n;n=t;const u=this;return function(d=a,...f){return u.produce(d,m=>n.call(this,m,...f))}}typeof n!="function"&&ur(6),r!==void 0&&typeof r!="function"&&ur(7);let s;if(Xi(t)){const a=n1(this),u=Tf(t,void 0);let l=!0;try{s=n(u),l=!1}finally{l?hf(a):pf(a)}return t1(a,r),r1(s,a)}else if(!t||typeof t!="object"){if(s=n(t),s===void 0&&(s=t),s===Kg&&(s=void 0),this.autoFreeze_&&ff(s,!0),r){const a=[],u=[];Qi("Patches").generateReplacementPatches_(t,s,a,u),r(a,u)}return s}else ur(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(u,...l)=>this.produceWithPatches(u,d=>t(d,...l));let r,s;return[this.produce(t,n,(u,l)=>{r=u,s=l}),r,s]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Xi(e)||ur(8),zs(e)&&(e=Qk(e));const t=n1(this),n=Tf(e,void 0);return n[Hn].isManual_=!0,pf(t),n}finishDraft(e,t){const n=e&&e[Hn];(!n||!n.isManual_)&&ur(9);const{scope_:r}=n;return t1(r,t),r1(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const s=t[n];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}n>-1&&(t=t.slice(n+1));const r=Qi("Patches").applyPatches_;return zs(e)?r(e,t):this.produce(e,s=>r(s,t))}};function Tf(e,t){const n=aa(e)?Qi("MapSet").proxyMap_(e,t):tl(e)?Qi("MapSet").proxySet_(e,t):Gk(e,t);return(t?t.scope_:e1()).drafts_.push(n),n}function Qk(e){return zs(e)||ur(10,e),o1(e)}function o1(e){if(!Xi(e)||rl(e))return e;const t=e[Hn];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=df(e,t.scope_.immer_.useStrictShallowCopy_)}else n=df(e,!0);return Zu(n,(r,s)=>{Zg(n,r,o1(s))}),t&&(t.finalized_=!1),n}var Jk=new Kk,Zk=Jk.produce;function eC(e,t,n){var r=R.useMemo(function(){return Zk(e)},[e]);return R.useReducer(r,t,n)}const tC=e=>Array.from(new Set((e!=null?e:[]).map(t=>t.trim()).filter(Boolean))),a1=R.createContext(null),u1=R.createContext(null),nC=({children:e,dispatch:t})=>{const n=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_INITIALIZED,payload:x})},[t]),r=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_OPEN,payload:x})},[t]),s=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_INLINE,payload:x})},[t]),a=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ELEMENT_ID,payload:x})},[t]),u=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ENTRY_TYPE,payload:x})},[t]),l=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID,payload:x})},[t]),d=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_USER_PROMPT,payload:x})},[t]),f=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_PARAMS,payload:x})},[t]),m=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE,payload:x})},[t]),p=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE,payload:x})},[t]),b=R.useCallback(x=>{t({type:Tt.SET_PROMPTS_EXTENSION_RESPONSE_LOADING,payload:x})},[t]),y=R.useMemo(()=>({setIsInitialized:n,setIsOpen:r,setIsInline:s,setElementId:a,setEntryType:u,setActivePromptsId:l,setUserPrompt:d,setParams:f,setPromptsMessage:m,setResponseMessage:p,setIsResponseLoading:b}),[n,r,s,a,u,l,d,f,m,p,b]);return w.jsx(u1.Provider,{value:y,children:e})},rC=(e,t)=>{const{type:n,payload:r}=t;switch(n){case Tt.SET_PROMPTS_EXTENSION_INITIALIZED:e.isInitialized=r;break;case Tt.SET_PROMPTS_EXTENSION_OPEN:e.isOpen=r;break;case Tt.SET_PROMPTS_EXTENSION_INLINE:e.isInline=r;break;case Tt.SET_PROMPTS_EXTENSION_ELEMENT_ID:e.elementId=r;break;case Tt.SET_PROMPTS_EXTENSION_ENTRY_TYPE:e.entryType=r;break;case Tt.SET_PROMPTS_EXTENSION_PARAMS:e.params=r;break;case Tt.RESET_PROMPTS_EXTENSION_PARAMS:e.params=null;break;case Tt.SET_PROMPTS_EXTENSION_USER_PROMPT:e.userPrompt=r;break;case Tt.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=r;break;case Tt.RESET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=null;break;case Tt.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=r;break;case Tt.RESET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=null;break;case Tt.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=r;break;case Tt.RESET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=null;break;case Tt.SET_PROMPTS_EXTENSION_RESPONSE_LOADING:e.isResponseLoading=r;break}},iC=({promptsConfig:e,children:t})=>{const[n,r]=eC(rC,ue(U(U({},W0),e||{}),{staticQuestions:tC((e==null?void 0:e.staticQuestions)||[])}));return w.jsx(a1.Provider,{value:n,children:w.jsx(nC,{dispatch:r,children:t})})},sC={productId:Jo.productId,pdpLink:Jo.pdpLink},l1=R.createContext(sC),oC=({children:e})=>{const[t,n]=R.useState(Jo.productId),[r,s]=R.useState(Jo.pdpLink);R.useEffect(()=>{const u=({detail:l})=>{if((l==null?void 0:l.property)==="pdp-context"){const d=l.value;n(d.productId),s(d.pdpLink);return}(l==null?void 0:l.property)==="productId"&&n(l.value),(l==null?void 0:l.property)==="pdpLink"&&s(l.value)};return PS(u),()=>{RS(u)}},[]);const a=R.useMemo(()=>({productId:t,pdpLink:r}),[t,r]);return w.jsx(l1.Provider,{value:a,children:e})},aC=e=>new Promise(t=>{let r;try{r=new URL(e)}catch(d){_t(!0,"error",`[CimulateOverrides] Invalid URL provided: ${e}. Using default components.`),t({});return}if(r.protocol!=="https:"){_t(!0,"error",`[CimulateOverrides] Override URL must use HTTPS, got ${r.protocol}. Using default components.`),t({});return}const s=document.createElement("script");s.src=e,s.async=!0,s.crossOrigin="anonymous";let a=!1;const u=()=>{a=!0,clearTimeout(l)};s.onload=()=>{if(a)return;u();const d=window.CimulateOverrides;d&&typeof d=="object"?(_t(!0,"log","[CimulateOverrides] Override script loaded successfully."),t(d)):(_t(!0,"warn","[CimulateOverrides] Override script loaded but window.CimulateOverrides is not set. Using default components."),t({}))},s.onerror=()=>{a||(u(),_t(!0,"warn",`[CimulateOverrides] Failed to load override script from: ${e}. Using default components.`),t({}))};const l=setTimeout(()=>{a||(a=!0,_t(!0,"warn",`[CimulateOverrides] Override script timed out after 5000ms: ${e}. Using default components.`),t({}))},5e3);document.head.appendChild(s)}),c1=R.createContext({overrides:{},isInitialized:!1}),uC=({overridesUrl:e,inlineOverrides:t,children:n})=>{const[r,s]=R.useState({}),[a,u]=R.useState(!1);R.useEffect(()=>{Fe(null,null,function*(){let f={};e?(_t(!0,"log","[CimulateOverrides] Loading overrides from URL..."),f=yield aC(e)):t&&typeof t=="object"?(_t(!0,"log","[CimulateOverrides] Using inline overrides."),f=t):window.CimulateOverrides&&typeof window.CimulateOverrides=="object"&&(_t(!0,"log","[CimulateOverrides] Using window.CimulateOverrides."),f=window.CimulateOverrides),s(f),u(!0)})},[e,t]);const l=R.useMemo(()=>({overrides:r,isInitialized:a}),[r,a]);return w.jsx(c1.Provider,{value:l,children:n})},d1=({mode:e,apiKey:t,apiToken:n,baseUrl:r,logoUrl:s,headerText:a,headerConfig:u,theme:l,openLinksInNewTab:d,globalClassName:f,isDevelopment:m=!1,componentType:p,componentConfig:b,entryType:y,initialEntry:x,entryMessage:S,disclaimerText:A,disclaimerMarkdown:_,clientContext:C,searchPlaceholder:O,searchButtonLabel:z,searchConfig:W,suggestionButtonConfig:D,messageAlignment:V,autoScroll:K,promptsConfig:ae,showProductDescription:j,resetConversationMessage:se,conversationHistory:ie,messagingConfig:ce,overrides:fe,overridesUrl:ne,inlineOverrides:Se,__features:de,children:J})=>{const le=R.useRef(!1);return le.current||(le.current=!0,FS({initialEntry:x,entryType:y,isDevelopment:m})),w.jsx(nk,{mode:e,baseUrl:r,apiKey:t,apiToken:n,logoUrl:s,headerText:a,headerConfig:u,entryMessage:S,theme:l,globalClassName:f,openLinksInNewTab:d,searchPlaceholder:O,searchButtonLabel:z,searchConfig:W,suggestionButtonConfig:D,messageAlignment:V,autoScroll:K,showProductDescription:j,componentConfig:b,clientContext:C,disclaimerMarkdown:_,disclaimerText:A,resetConversationMessage:se,conversationHistory:ie,isDevelopment:m,__features:de,progressStepsLimit:ce==null?void 0:ce.progressStepsLimit,routingAttributes:ce==null?void 0:ce.routingAttributes,enableDownloadTranscript:ce==null?void 0:ce.enableDownloadTranscript,enableEscalationToAgent:ce==null?void 0:ce.enableEscalationToAgent,showProductCaptions:ce==null?void 0:ce.showProductCaptions,children:w.jsx(ov,{entryType:y!=null?y:x==null?void 0:x.type,componentConfig:b,componentType:p,children:w.jsx(oC,{children:w.jsx(iC,{promptsConfig:ae,children:w.jsx(uC,{overridesUrl:ne,inlineOverrides:Se||fe,children:w.jsx(Xg,{scrt2Url:(ce==null?void 0:ce.scrt2Url)||"",orgId:(ce==null?void 0:ce.orgId)||"",esDeveloperName:(ce==null?void 0:ce.esDeveloperName)||"",routingAttributes:(ce==null?void 0:ce.routingAttributes)||{},capabilitiesVersion:ce==null?void 0:ce.capabilitiesVersion,enableLogging:m,onProductResult:ce==null?void 0:ce.onProductResult,children:J})})})})})})};var bf={exports:{}},Cn={},wf={exports:{}},xf={};var f1;function lC(){return f1||(f1=1,(function(e){function t(J,le){var k=J.length;J.push(le);e:for(;0<k;){var M=k-1>>>1,Z=J[M];if(0<s(Z,le))J[M]=le,J[k]=Z,k=M;else break e}}function n(J){return J.length===0?null:J[0]}function r(J){if(J.length===0)return null;var le=J[0],k=J.pop();if(k!==le){J[0]=k;e:for(var M=0,Z=J.length,P=Z>>>1;M<P;){var ve=2*(M+1)-1,Pe=J[ve],he=ve+1,ke=J[he];if(0>s(Pe,k))he<Z&&0>s(ke,Pe)?(J[M]=ke,J[he]=k,M=he):(J[M]=Pe,J[ve]=k,M=ve);else if(he<Z&&0>s(ke,k))J[M]=ke,J[he]=k,M=he;else break e}}return le}function s(J,le){var k=J.sortIndex-le.sortIndex;return k!==0?k:J.id-le.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var u=Date,l=u.now();e.unstable_now=function(){return u.now()-l}}var d=[],f=[],m=1,p=null,b=3,y=!1,x=!1,S=!1,A=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function O(J){for(var le=n(f);le!==null;){if(le.callback===null)r(f);else if(le.startTime<=J)r(f),le.sortIndex=le.expirationTime,t(d,le);else break;le=n(f)}}function z(J){if(S=!1,O(J),!x)if(n(d)!==null)x=!0,Se(W);else{var le=n(f);le!==null&&de(z,le.startTime-J)}}function W(J,le){x=!1,S&&(S=!1,_(K),K=-1),y=!0;var k=b;try{for(O(le),p=n(d);p!==null&&(!(p.expirationTime>le)||J&&!se());){var M=p.callback;if(typeof M=="function"){p.callback=null,b=p.priorityLevel;var Z=M(p.expirationTime<=le);le=e.unstable_now(),typeof Z=="function"?p.callback=Z:p===n(d)&&r(d),O(le)}else r(d);p=n(d)}if(p!==null)var P=!0;else{var ve=n(f);ve!==null&&de(z,ve.startTime-le),P=!1}return P}finally{p=null,b=k,y=!1}}var D=!1,V=null,K=-1,ae=5,j=-1;function se(){return!(e.unstable_now()-j<ae)}function ie(){if(V!==null){var J=e.unstable_now();j=J;var le=!0;try{le=V(!0,J)}finally{le?ce():(D=!1,V=null)}}else D=!1}var ce;if(typeof C=="function")ce=function(){C(ie)};else if(typeof MessageChannel!="undefined"){var fe=new MessageChannel,ne=fe.port2;fe.port1.onmessage=ie,ce=function(){ne.postMessage(null)}}else ce=function(){A(ie,0)};function Se(J){V=J,D||(D=!0,ce())}function de(J,le){K=A(function(){J(e.unstable_now())},le)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(J){J.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,Se(W))},e.unstable_forceFrameRate=function(J){0>J||125<J?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ae=0<J?Math.floor(1e3/J):5},e.unstable_getCurrentPriorityLevel=function(){return b},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(J){switch(b){case 1:case 2:case 3:var le=3;break;default:le=b}var k=b;b=le;try{return J()}finally{b=k}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(J,le){switch(J){case 1:case 2:case 3:case 4:case 5:break;default:J=3}var k=b;b=J;try{return le()}finally{b=k}},e.unstable_scheduleCallback=function(J,le,k){var M=e.unstable_now();switch(typeof k=="object"&&k!==null?(k=k.delay,k=typeof k=="number"&&0<k?M+k:M):k=M,J){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=k+Z,J={id:m++,callback:le,priorityLevel:J,startTime:k,expirationTime:Z,sortIndex:-1},k>M?(J.sortIndex=k,t(f,J),n(d)===null&&J===n(f)&&(S?(_(K),K=-1):S=!0,de(z,k-M))):(J.sortIndex=Z,t(d,J),x||y||(x=!0,Se(W))),J},e.unstable_shouldYield=se,e.unstable_wrapCallback=function(J){var le=b;return function(){var k=b;b=le;try{return J.apply(this,arguments)}finally{b=k}}}})(xf)),xf}var h1;function cC(){return h1||(h1=1,wf.exports=lC()),wf.exports}var p1;function dC(){if(p1)return Cn;p1=1;var e=sr(),t=cC();function n(i){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+i,c=1;c<arguments.length;c++)o+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+i+"; visit "+o+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,s={};function a(i,o){u(i,o),u(i+"Capture",o)}function u(i,o){for(s[i]=o,i=0;i<o.length;i++)r.add(o[i])}var l=!(typeof window=="undefined"||typeof window.document=="undefined"||typeof window.document.createElement=="undefined"),d=Object.prototype.hasOwnProperty,f=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,m={},p={};function b(i){return d.call(p,i)?!0:d.call(m,i)?!1:f.test(i)?p[i]=!0:(m[i]=!0,!1)}function y(i,o,c,h){if(c!==null&&c.type===0)return!1;switch(typeof o){case"function":case"symbol":return!0;case"boolean":return h?!1:c!==null?!c.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function x(i,o,c,h){if(o===null||typeof o=="undefined"||y(i,o,c,h))return!0;if(h)return!1;if(c!==null)switch(c.type){case 3:return!o;case 4:return o===!1;case 5:return isNaN(o);case 6:return isNaN(o)||1>o}return!1}function S(i,o,c,h,E,T,v){this.acceptsBooleans=o===2||o===3||o===4,this.attributeName=h,this.attributeNamespace=E,this.mustUseProperty=c,this.propertyName=i,this.type=o,this.sanitizeURL=T,this.removeEmptyString=v}var A={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){A[i]=new S(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var o=i[0];A[o]=new S(o,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){A[i]=new S(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){A[i]=new S(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){A[i]=new S(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){A[i]=new S(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){A[i]=new S(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){A[i]=new S(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){A[i]=new S(i,5,!1,i.toLowerCase(),null,!1,!1)});var _=/[\-:]([a-z])/g;function C(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var o=i.replace(_,C);A[o]=new S(o,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){A[i]=new S(i,1,!1,i.toLowerCase(),null,!1,!1)}),A.xlinkHref=new S("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){A[i]=new S(i,1,!1,i.toLowerCase(),null,!0,!0)});function O(i,o,c,h){var E=A.hasOwnProperty(o)?A[o]:null;(E!==null?E.type!==0:h||!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(x(o,c,E,h)&&(c=null),h||E===null?b(o)&&(c===null?i.removeAttribute(o):i.setAttribute(o,""+c)):E.mustUseProperty?i[E.propertyName]=c===null?E.type===3?!1:"":c:(o=E.attributeName,h=E.attributeNamespace,c===null?i.removeAttribute(o):(E=E.type,c=E===3||E===4&&c===!0?"":""+c,h?i.setAttributeNS(h,o,c):i.setAttribute(o,c))))}var z=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),D=Symbol.for("react.portal"),V=Symbol.for("react.fragment"),K=Symbol.for("react.strict_mode"),ae=Symbol.for("react.profiler"),j=Symbol.for("react.provider"),se=Symbol.for("react.context"),ie=Symbol.for("react.forward_ref"),ce=Symbol.for("react.suspense"),fe=Symbol.for("react.suspense_list"),ne=Symbol.for("react.memo"),Se=Symbol.for("react.lazy"),de=Symbol.for("react.offscreen"),J=Symbol.iterator;function le(i){return i===null||typeof i!="object"?null:(i=J&&i[J]||i["@@iterator"],typeof i=="function"?i:null)}var k=Object.assign,M;function Z(i){if(M===void 0)try{throw Error()}catch(c){var o=c.stack.trim().match(/\n( *(at )?)/);M=o&&o[1]||""}return`
17
17
  `+M+i}var P=!1;function ve(i,o){if(!i||P)return"";P=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(o)if(o=function(){throw Error()},Object.defineProperty(o.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(o,[])}catch(te){var h=te}Reflect.construct(i,[],o)}else{try{o.call()}catch(te){h=te}i.call(o.prototype)}else{try{throw Error()}catch(te){h=te}i()}}catch(te){if(te&&h&&typeof te.stack=="string"){for(var E=te.stack.split(`
18
18
  `),T=h.stack.split(`
19
19
  `),v=E.length-1,B=T.length-1;1<=v&&0<=B&&E[v]!==T[B];)B--;for(;1<=v&&0<=B;v--,B--)if(E[v]!==T[B]){if(v!==1||B!==1)do if(v--,B--,0>B||E[v]!==T[B]){var $=`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cimulate/copilot-widget",
3
3
  "description": "A frontend SDK for Cimulate Copilot",
4
- "version": "1.33.9",
4
+ "version": "1.34.0",
5
5
  "keywords": [
6
6
  "cimulate",
7
7
  "copilot",