@cimulate/copilot-widget 1.60.1 → 1.60.2

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.60.2 — 2026-11-23
6
+
7
+ - Restore the messaging composer and remove the processing indicator when an agent turn reaches the existing completion timeout without sending `typing_stopped` or a final response.
8
+
5
9
  ## 1.60.1 — 2026-11-23
6
10
 
7
11
  - Early shopper messages are answered in cases that previously dropped them: a late welcome treated as the reply, a resumed conversation with no agent message, and a joined chatbot that never sends a welcome. A brand-new conversation still waits so a late welcome is not treated as the reply. If the chatbot never joins, the send fails after 12 seconds.
@@ -9515,7 +9515,7 @@ const ii = /* @__PURE__ */ Symbol("initialization-cancelled"), iC = 3e4, sC = "I
9515
9515
  resolve: Te,
9516
9516
  timeoutId: setTimeout(() => {
9517
9517
  var Ke;
9518
- (Ke = X.current) == null || Ke.failure("send_timeout"), S({ type: "SET_LOADING", isLoading: !1 }), Nt(_t, { outcome: "timeout" });
9518
+ (Ke = X.current) == null || Ke.failure("send_timeout"), S({ type: "SET_AGENT_TYPING", isTyping: !1 }), Nt(_t, { outcome: "timeout" });
9519
9519
  }, vg)
9520
9520
  }), jt.current.push(_t), S({ type: "CLEAR_SEND_ERROR" }), !ve.silent) {
9521
9521
  if (!Ee) {
@@ -13,7 +13,7 @@
13
13
  `);u=c===-1?"":s.slice(c+1)}if(!r.stack)r.stack=u;else if(u){const c=u.indexOf(`
14
14
  `),d=c===-1?-1:u.indexOf(`
15
15
  `,c+1),f=d===-1?"":u.slice(d+1);String(r.stack).endsWith(f)||(r.stack+=`
16
- `+u)}}catch(i){}throw r}})}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Mo(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&gl.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),i!=null&&(X.isFunction(i)?n.paramsSerializer={serialize:i}:gl.assertOptions(i,{encode:Ln.function,serialize:Ln.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),gl.assertOptions(n,{baseUrl:Ln.spelling("baseURL"),withXsrfToken:Ln.spelling("withXSRFToken")},!0),n.method=(X.getSafeProp(n,"method")||X.getSafeProp(this.defaults,"method")||"get").toLowerCase();let u=s&&X.merge(s.common,s[n.method]);s&&X.forEach(Ky.concat("common"),x=>{delete s[x]}),n.headers=Rn.concat(u,s);const c=[];let d=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(n)===!1)return;d=d&&A.synchronous;const k=n.transitional||Pp;k&&k.legacyInterceptorReqResOrdering?c.unshift(A.fulfilled,A.rejected):c.push(A.fulfilled,A.rejected)});const f=[];this.interceptors.response.forEach(function(A){f.push(A.fulfilled,A.rejected)});let m,h=0,y;if(!d){const x=[jp.bind(this),void 0];for(x.unshift(...c),x.push(...f),y=x.length,m=Promise.resolve(n);h<y;)m=m.then(x[h++],x[h++]);return m}y=c.length;let E=n;for(;h<y;){const x=c[h++],A=c[h++];try{E=x?x(E):E}catch(k){if(!A){m=Promise.reject(k);break}try{const v=A.call(this,k);X.isThenable(v)&&(m=Promise.resolve(v).then(()=>jp.call(this,E)))}catch(v){m=Promise.reject(v)}break}}if(!m)try{m=jp.call(this,E)}catch(x){m=Promise.reject(x)}for(h=0,y=f.length;h<y;)m=m.then(f[h++],f[h++]);return m}getUri(t){t=Mo(this.defaults,t);const n=rE(t.baseURL,t.url,t.allowAbsoluteUrls,t);return zy(n,t.params,t.paramsSerializer)}};X.forEach(["delete","get","head","options"],function(t){Fo.prototype[t]=function(n,r){return this.request(Mo(r||{},{method:t,url:n,data:r&&X.hasOwnProp(r,"data")?r.data:void 0}))}}),X.forEach(["post","put","patch","query"],function(t){function n(r){return function(s,u,c){return this.request(Mo(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:u}))}}Fo.prototype[t]=n(),t!=="query"&&(Fo.prototype[t+"Form"]=n(!0))});let uI=class HA{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const u=new Promise(c=>{r.subscribe(c),s=c}).then(i);return u.cancel=function(){r.unsubscribe(s)},u},t(function(s,u,c){r.reason||(r.reason=new au(s,u,c),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 HA(function(i){t=i}),cancel:t}}};function cI(e){return function(n){return e.apply(null,n)}}function lI(e){return X.isObject(e)&&e.isAxiosError===!0}const yl={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(yl).forEach(([e,t])=>{yl[t]===void 0&&(yl[t]=e)});function yE(e){const t=new Fo(e),n=vy(Fo.prototype.request,t);return X.extend(n,Fo.prototype,t,{allOwnKeys:!0}),X.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return yE(Mo(e,i))},n}const tn=yE(su);tn.Axios=Fo,tn.CanceledError=au,tn.CancelToken=uI,tn.isCancel=Qy,tn.VERSION=Fp,tn.toFormData=fl,tn.AxiosError=Pe,tn.Cancel=tn.CanceledError,tn.all=function(t){return Promise.all(t)},tn.spread=cI,tn.isAxiosError=lI,tn.mergeConfig=Mo,tn.AxiosHeaders=Rn,tn.formToJSON=e=>Xy(X.isHTMLForm(e)?new FormData(e):e),tn.getAdapter=hE.getAdapter,tn.HttpStatusCode=yl,tn.default=tn;const{Axios:Mq,AxiosError:Fq,CanceledError:Bq,isCancel:Uq,CancelToken:jq,VERSION:Hq,all:$q,Cancel:zq,isAxiosError:Vq,spread:qq,toFormData:Wq,AxiosHeaders:Yq,HttpStatusCode:Gq,formToJSON:Xq,getAdapter:Kq,mergeConfig:Qq,create:Jq}=tn;class dI{constructor(t,n,r,i=!1,s,u){Ze(this,"CIMULATE_API_HEADER","x-cimulate-api-key");Ze(this,"CIMULATE_SEARCH_API_HOST","search.cimulate");Ze(this,"CIMULATE_SEARCH_API_PATH","api/v1");Ze(this,"baseApiUrl");Ze(this,"headers",{});Ze(this,"fetchConfig",()=>Ce(this,null,function*(){try{const t=yield tn.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}}));Ze(this,"_mapCopilotUrlToSearchUrl",(t="",n=!1)=>{if(t.endsWith("io")){const i=new URL(t);return i.hostname=i.hostname.replace(/^copilot\./,"api."),i.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}`),s&&(this.headers["x-cimulate-customer-id"]=s),u&&(this.headers["Tenant-ID"]=u),this.baseApiUrl=this._mapCopilotUrlToSearchUrl(t,i)}get apiUrl(){return`${this.baseApiUrl}/${this.CIMULATE_SEARCH_API_PATH}`}}class fI{constructor(t,n,r,i=!1,s,u){Ze(this,"apiService");Ze(this,"config",null);Ze(this,"getConfig",()=>Ce(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}}));Ze(this,"getPid",t=>this.getProductFieldValue(t,"pidCol"));Ze(this,"getName",t=>this.getProductFieldValue(t,"nameCol"));Ze(this,"getDescription",t=>this.getProductFieldValue(t,"description"));Ze(this,"getBrand",t=>this.getProductFieldValue(t,"productBrandCol"));Ze(this,"getPrice",t=>this.getProductFieldValue(t,"priceCol"));Ze(this,"getRelativePdp",t=>this.getProductFieldValue(t,"relativePdpCol"));Ze(this,"getPdp",t=>this.getProductFieldValue(t,"pdpCol"));Ze(this,"getImage",t=>this.getProductFieldValue(t,"imageCol"));Ze(this,"getProductHiddenFields",()=>{const t=this.getProductField("productHiddenFields");return Array.isArray(t)?t:[]});Ze(this,"getProductField",t=>this.config?this.config[t]:"");Ze(this,"getProductFieldValue",(t,n)=>{const r=this.getProductField(n);return r&&t[r]||""});this.apiService=new dI(t,n,r,i,s,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 pI={copilot:"Your Search Assistant",messaging:"Commerce Client"},EE=_.createContext(null),mI=({mode:e,logoUrl:t,headerText:n,headerConfig:r,globalClassName:i="",entryMessage:s,openLinksInNewTab:u=!1,onNavigate:c,disclaimerText:d,disclaimerMarkdown:f,clientContext:m,baseCatalogParams:h,searchPlaceholder:y,searchButtonLabel:E,searchConfig:x,suggestionButtonConfig:A,progressStepsLimit:k=3,messageAlignment:v="start",autoScroll:N=!0,showProductDescription:L=!1,componentConfig:P,conversationHistory:z,resetConversationMessage:D="",apiKey:q,apiToken:V,baseUrl:G,customerId:I,tenantId:W,theme:Q,isDevelopment:K,__features:ae,routingAttributes:oe,enableDownloadTranscript:he=!0,enablePageContext:se=!1,enableEscalationToAgent:ee=!1,enableImageUpload:ce=!1,showProductCaptions:O=!1,connectingMessages:j,staticQuestions:te,staticQuestionsStrategy:M="append",children:ge})=>{const Oe=e==="messaging",ne=_.useMemo(()=>{const Xe=oe==null?void 0:oe.isCartMgmtSupported;return Xe===!0||Xe==="true"},[oe]),be=_.useMemo(()=>Oe?{config:null}:new fI(G,q,V,K,I,W),[Oe,G,q,V,K,I,W]),_e=_.useMemo(()=>new Mk(K),[K]);_.useEffect(()=>{Oe||!be||be.config||be.getConfig()},[be,Oe]);const je=_.useMemo(()=>Q1(Q),[Q]),ft=je.cssVariables,It=_.useMemo(()=>{const Xe=(x==null?void 0:x.placeholder)||y,Zt=(x==null?void 0:x.buttonLabel)||E;let qe="icon";return x!=null&&x.buttonType?qe=x.buttonType:E&&(qe="text"),pe(B({},x||{}),{placeholder:Xe,buttonLabel:Zt,buttonType:qe})},[x,y,E]),bt=_.useMemo(()=>pe(B({},r||{}),{logoUrl:t||(r==null?void 0:r.logoUrl),headerText:(r==null?void 0:r.headerText)||n||pI[e!=null?e:"copilot"]}),[r,t,n,e]),Ge=_.useMemo(()=>({configModule:be,mode:e!=null?e:"copilot",themeVariants:je.compatibility&&e!=="messaging"?pe(B({},je.variants),{carousel:"chevron"}):je.variants,themeTokens:je.compatibility==="legacy"?void 0:je.tokens,themeClassName:je.transcriptClassName,headerConfig:bt,entryMessage:s,staticQuestions:te||[],staticQuestionsStrategy:M,globalClassName:i,openLinksInNewTab:u,onNavigate:c,disclaimerText:d,disclaimerMarkdown:f,clientContext:m,baseCatalogParams:h,themeVariables:ft,logger:_e,searchConfig:It,suggestionButtonConfig:A,progressStepsLimit:k,messageAlignment:v,autoScroll:N,showProductDescription:!!L,enableMinimize:!!(P!=null&&P.enableMinimize),launcherAriaLabel:P==null?void 0:P.launcherAriaLabel,enableDownloadTranscript:he,enablePageContext:se,enableEscalationToAgent:ee,enableImageUpload:ce,showProductCaptions:!!O,connectingMessages:j,resetConversationMessage:D,conversationHistory:{sinceHours:typeof(z==null?void 0:z.sinceHours)=="number"?z.sinceHours:Oe?24:1,limit:z==null?void 0:z.limit},features:ae,isCartMgmtSupported:ne}),[be,e,bt,s,te,M,i,m,h,d,f,u,c,It,A,v,N,L,P,he,se,ee,ce,k,O,j,D,_e,ft,je,z,ae,ne,Oe]);return w.jsx(EE.Provider,{value:Ge,children:ge})},at=()=>{const e=_.useContext(EE);if(!e)throw new Error("useConfig must be used within a ConfigProvider");return e},bE=["markdown","product_carousel","product_tile","product_comparison","suggestions","cart","order_confirmation","tool_results"],Yi=-1;function Hp(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 wE(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"&&bE.includes(t.type))return t;const n=Hp(t);return n?{type:"markdown",index:Yi,data:{content:n}}:null}}catch(t){}return{type:"markdown",index:Yi,data:{content:e}}}function El(e){let t;try{t=JSON.parse(e)}catch(i){return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(typeof n.type!="string"||!bE.includes(n.type))return null;const r=typeof n.index=="number"?n.index:0;return pe(B({},n),{type:n.type,index:r})}function Ls(e){let t;try{t=JSON.parse(e)}catch(n){return null}return t&&typeof t=="object"&&Array.isArray(t.response)?t:null}function $p(e){var i,s;if(e.type!=="markdown")return[e];const t=(s=(i=e.data)==null?void 0:i.content)!=null?s:"",n=Ls(t);if(n)return n.response;const r=El(t);return[r&&r.type!=="markdown"?r:e]}function uu(e){const t=Ls(e);if(t)return t.response.flatMap($p);const n=El(e);return n?$p(n):[]}function xE(e,t){return uu(e).some(n=>n.type===t)}function hI(e){return uu(e).map(t=>t.type)}function gI(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.role==="agent"&&xE(r.content,t))return r.id}}function TE(e){const t=e.trimStart();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{return JSON.parse(e),!1}catch(n){return!0}}function yI(e){return e.type==="markdown"&&e.index===Yi?!TE(e.data.content):!0}function EI(e){var i;const t=(i=Ls(e))==null?void 0:i.response;if(!t)return null;const n=t.find(s=>s.type==="product_carousel");if(n)return{kind:"search",productIds:n.data.products.map(s=>s.id)};const r=t.find(s=>s.type==="product_tile");return r?{kind:"detail",productIds:[r.data.id]}:null}function bI(e){var s,u,c,d,f;const t=uu(e).find(m=>m.type==="product_tile");if(!t)return null;const n=(u=(s=t.data)==null?void 0:s.id)==null?void 0:u.trim();if(!n)return null;const r=t.data.data,i=(r==null?void 0:r.imageUrl)||((d=(c=r==null?void 0:r.imgGroups)==null?void 0:c.filter(m=>{var h;return((h=m.viewType)==null?void 0:h.toLowerCase())!=="swatch"}).flatMap(m=>{var h;return(h=m.imgs)!=null?h:[]}).find(m=>{var h;return(h=m.url)==null?void 0:h.trim()}))==null?void 0:d.url);return B({type:"pdp",id:n,name:((f=r==null?void 0:r.name)==null?void 0:f.trim())||n},i?{imageUrl:Ja(r==null?void 0:r.baseUrl,i)}:{})}function vE(e){var n,r,i,s,u,c,d,f,m,h;const t=uu(e).find(y=>y.type==="cart");return t?{status:(c=(u=(r=(n=t.data)==null?void 0:n.cart)==null?void 0:r.__action_execution_status__)!=null?u:(s=(i=t.data)==null?void 0:i.cart)==null?void 0:s.action_execution_status)!=null?c:null,cartDetails:(h=(m=(f=(d=t.data)==null?void 0:d.cart)==null?void 0:f.cartSummary)==null?void 0:m.cartDetails)!=null?h:null}:null}function wI(e){var i,s,u;const t=uu(e).find(c=>c.type==="cart"),n=(u=(s=(i=t==null?void 0:t.data)==null?void 0:i.cart)==null?void 0:s.cartSummary)==null?void 0:u.cartOperation,r=typeof n=="string"?n.toLowerCase():null;return r==="add"||r==="remove"?r:null}function xI(e,t){if(t.index===Yi){const i=e[e.length-1];if(i&&i.type==="markdown"&&i.index===Yi&&t.type==="markdown"){const s={type:"markdown",index:Yi,data:{content:i.data.content+t.data.content}};return[...e.slice(0,-1),s]}return[...e,t]}const n=e.findIndex(i=>i.index===t.index);return[...n>=0?e.map((i,s)=>s===n?t:i):[...e,t]].sort((i,s)=>i.index-s.index)}function _E(e,t){return t.serverId!==void 0&&e.some(n=>n.serverId===t.serverId)}const SE={connectionStatus:"disconnected",loading:!1,humanHandoff:!1,conversationId:null,messagingSessionId:null,messages:[],streamingBlocks:[],isAgentTyping:!1,progressMessage:"",progressSteps:[],routingResult:null,error:null,sendError:null,sessionExpired:!1};function TI(e,t){switch(t.type){case"SET_CONNECTION_STATUS":return B(pe(B({},e),{connectionStatus:t.status}),t.status==="connected"||t.status==="connecting"?{error:null}:{});case"SET_HUMAN_HANDOFF":return pe(B({},e),{humanHandoff:t.active,loading:!1,isAgentTyping:!1,progressMessage:"",progressSteps:[]});case"SET_LOADING":return pe(B({},e),{loading:t.isLoading});case"SET_CONVERSATION_ID":return e.conversationId===t.id?e:pe(B({},e),{conversationId:t.id,messagingSessionId:null});case"SET_MESSAGING_SESSION_ID":return e.messagingSessionId===t.id?e:pe(B({},e),{messagingSessionId:t.id});case"ADD_MESSAGE":return _E(e.messages,t.message)?e:pe(B({},e),{messages:[...e.messages,pe(B({},t.message),{type:"ADD_MESSAGE"})]});case"UPDATE_MESSAGE":return pe(B({},e),{messages:e.messages.map(n=>n.id===t.id?B(B({},n),t.patch):n)});case"APPEND_STREAMING_TOKEN":{const n=wE(t.token);return n?pe(B({},e),{streamingBlocks:xI(e.streamingBlocks,n)}):e}case"FLUSH_STREAMING":{const n={streamingBlocks:[],isAgentTyping:!1,loading:!1,progressMessage:"",progressSteps:[],sendError:e.humanHandoff?e.sendError:null};if(_E(e.messages,t.message))return B(B({},e),n);const r=pe(B({},t.message),{type:"FLUSH_STREAMING"}),i=t.replaceMessageId?e.messages.findIndex(s=>s.id===t.replaceMessageId):-1;if(i>=0){const s=[...e.messages];return s[i]=pe(B({},r),{id:e.messages[i].id}),B(pe(B({},e),{messages:s}),n)}return B(pe(B({},e),{messages:[...e.messages,r]}),n)}case"SET_AGENT_TYPING":return pe(B({},e),{isAgentTyping:t.isTyping,loading:e.humanHandoff?e.loading:t.isTyping});case"SET_PROGRESS_MESSAGE":return B(pe(B({},e),{progressMessage:t.message}),t.message===""?{progressSteps:[]}:{});case"ADD_PROGRESS_STEP":return e.progressSteps[e.progressSteps.length-1]===t.message?e:pe(B({},e),{progressSteps:[...e.progressSteps,t.message],progressMessage:t.message});case"SET_ROUTING_RESULT":return pe(B({},e),{routingResult:t.result});case"SET_ERROR":return pe(B({},e),{error:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"SET_SEND_ERROR":return pe(B({},e),{sendError:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"CLEAR_SEND_ERROR":return pe(B({},e),{sendError:null});case"LOAD_HISTORY":return pe(B({},e),{messages:t.messages.map(n=>pe(B({},n),{restored:!0})),loading:!1});case"SET_SESSION_EXPIRED":return pe(B({},e),{sessionExpired:t.expired});case"RESET":return pe(B({},SE),{connectionStatus:e.connectionStatus});default:return e}}const vI=e=>typeof e=="string"?e:e.code,AE=e=>{var t;return((t=e==null?void 0:e.couponsApplied)!=null?t:[]).map(vI)},kE=e=>{var n;const t=new Map;for(const r of(n=e==null?void 0:e.items)!=null?n:[])t.set(r.itemId,r);return t};function _I(e,t){const n=kE(e),r=kE(t),i=[];for(const[f,m]of r){const h=n.get(f);h?h.quantity!==m.quantity&&i.push({type:"quantity",itemId:f,productId:m.productId,name:m.name,quantityBefore:h.quantity,quantityAfter:m.quantity}):i.push({type:"add",itemId:f,productId:m.productId,name:m.name,quantityBefore:0,quantityAfter:m.quantity})}for(const[f,m]of n)r.has(f)||i.push({type:"remove",itemId:f,productId:m.productId,name:m.name,quantityBefore:m.quantity,quantityAfter:0});const s=AE(e),u=AE(t),c=u.filter(f=>!s.includes(f)),d=s.filter(f=>!u.includes(f));if(c.length||d.length){const f={type:"coupon",added:c,removed:d};i.push(f)}return i}function SI(e){if(e.length===0)return"unknown";const t=new Set(e.map(n=>n.type));if(t.size===1){const[n]=[...t];return n}return"mixed"}function CE(e,t,n=null){if(!e&&t&&n)return{status:"success",action:n,changes:[]};if(!e||!t)return{status:"success",action:"unknown",changes:[]};const r=_I(e,t);return{status:"success",action:SI(r),changes:r}}let zp=null;function AI(){const e=zp;return zp=null,e}function kI(e){!e||typeof e!="object"||!Array.isArray(e.items)||(zp=e,window.dispatchEvent(new CustomEvent(Qa,{detail:e})))}const NE=4320*60*1e3;function Vp(e,t){return`cim_af_conv_${e}_${t}`}function qp(e,t){return Date.now()-e>t}function Wp(e,t,n){try{const r=Vp(e,t),i=localStorage.getItem(r);if(!i)return null;const s=JSON.parse(i);if(!s||typeof s!="object"||!("conversationId"in s)||!("storedAt"in s))return null;const u=s;return typeof u.conversationId!="string"||!u.conversationId?null:typeof u.storedAt!="number"||qp(u.storedAt,n)?(localStorage.removeItem(r),null):u}catch(r){return null}}function cu(e,t,n){try{const r=Vp(e,t),i={conversationId:n,storedAt:Date.now()};localStorage.setItem(r,JSON.stringify(i))}catch(r){}}function Yp(e,t){try{const n=Vp(e,t);localStorage.removeItem(n)}catch(n){}}function Gp(e,t){return`cim_af_ct_${e}_${t}`}function CI(e){try{const t=e.split(".")[1];if(!t)return null;const n=JSON.parse(NI(t));return typeof n.exp=="number"?n.exp*1e3:null}catch(t){return null}}function IE(e){const t=CI(e);return t===null?"unknown":Date.now()>=t?"expired":"valid"}function NI(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(t.length+(4-t.length%4)%4,"=");return atob(n)}function Xp(e,t){try{const n=Gp(e,t),r=localStorage.getItem(n);if(!r)return null;const i=JSON.parse(r);if(!i||typeof i!="object"||!("accessToken"in i)||!("lastEventId"in i)||!("storedAt"in i))return null;const s=i;return typeof s.accessToken!="string"||!s.accessToken||typeof s.lastEventId!="string"||typeof s.storedAt!="number"?null:IE(s.accessToken)==="expired"?(localStorage.removeItem(n),null):s}catch(n){return null}}function OE(e,t,n,r){try{const i=Gp(e,t),s={accessToken:n,lastEventId:r,storedAt:Date.now()};localStorage.setItem(i,JSON.stringify(s))}catch(i){}}function II(e,t){try{const n=Gp(e,t);localStorage.removeItem(n)}catch(n){}}function OI(e,t){return`cim_af_conv_${e}_${t}`}function PI(e,t){try{if(typeof BroadcastChannel=="undefined")return null;const n=OI(e,t);return new BroadcastChannel(n)}catch(n){return null}}function RI(e,t=500){return e?new Promise(n=>{let r=!1;const i=setTimeout(()=>{r||(r=!0,e.removeEventListener("message",s),n(null))},t);function s(u){var c;r||((c=u.data)==null?void 0:c.type)==="conversation_response"&&(r=!0,clearTimeout(i),e.removeEventListener("message",s),n({conversationId:u.data.conversationId,storedAt:u.data.storedAt,continuationToken:u.data.continuationToken,lastEventId:u.data.lastEventId}))}e.addEventListener("message",s);try{e.postMessage({type:"request_conversation"})}catch(u){r||(r=!0,clearTimeout(i),e.removeEventListener("message",s),n(null))}}):Promise.resolve(null)}function LI(e,t,n){if(!e)return()=>{};function r(i){var s;if((s=i.data)!=null&&s.type)switch(i.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(c){}break}case"conversation_cleared":{n==null||n();break}}}return e.addEventListener("message",r),()=>{e.removeEventListener("message",r)}}function DI(e){if(e)try{e.postMessage({type:"conversation_cleared"})}catch(t){}}function MI(e){if(e)try{e.close()}catch(t){}}function bl(e){switch(e){case"Agent":return!0;case"Chatbot":return!1;default:return}}function PE(e){if(!e||typeof e!="object")return;const t=e;if(String(t.routingType).toLowerCase()!=="transfer")return;const n=t.routingConfigurationDetails;return(n==null?void 0:n.routingConfigurationType)!=="BotRoutingType"}function RE(e){var r,i,s,u,c;let t=!1;const n=[...e].sort((d,f)=>d.transcriptedTimestamp-f.transcriptedTimestamp);for(const d of n){let f;try{if(f=typeof d.entryPayload=="string"?JSON.parse(d.entryPayload):d.entryPayload,!f||typeof f!="object")continue}catch(m){continue}if(d.entryType==="RoutingResult")(!f.failureType||["None","NO_ERROR"].includes(String(f.failureType)))&&(t=(r=PE(f))!=null?r:t);else if(d.entryType==="ParticipantChanged"&&Array.isArray(f.entries))for(const m of f.entries)!m||typeof m!="object"||["","add","join","joined","transfer"].includes(String((s=(i=m.operation)!=null?i:m.event)!=null?s:"").toLowerCase())&&(t=(c=bl((u=m.participant)==null?void 0:u.role))!=null?c:t);else d.entryType==="Message"?bl(d.sender.role)===!0&&(t=!0):d.entryType==="CloseConversation"&&(t=!1)}return t}function FI(e){switch(e){case"EndUser":case"Customer":return"user";case"Agent":case"Chatbot":return"agent";default:return"system"}}function BI(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch(t){return{}}return e}function LE(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 UI(e){const t=e.staticContent;if(!t||typeof t!="object")return!1;const n=t.attachments;return Array.isArray(n)&&n.length>0}function jI(e){if(e.entryType!=="Message")return null;const n=BI(e.entryPayload).abstractMessage;if(!n)return null;const r=LE(n,"staticContent","text")||LE(n,"content","text")||"";if(!r&&!UI(n))return null;const i=FI(e.sender.role);return{id:e.identifier,serverId:e.identifier,role:i,content:r,timestamp:new Date(e.transcriptedTimestamp).toISOString(),sender:{role:e.sender.role,name:e.senderDisplayName}}}function HI(e){const t=[];for(const n of e){const r=jI(n);r&&t.push(r)}return t}function Kp(e,t,n){return`cim_af_dividers_${e}_${t}_${n}`}function DE(e,t,n){try{const r=Kp(e,t,n),i=localStorage.getItem(r);if(!i)return{};const s=JSON.parse(i);return!s||typeof s.storedAt!="number"||Date.now()-s.storedAt>NE||!s.byMessageId||typeof s.byMessageId!="object"?(localStorage.removeItem(r),{}):s.byMessageId}catch(r){return{}}}function $I(e,t,n,r,i){if(!(!n||!r))try{const s=Kp(e,t,n),u=DE(e,t,n);localStorage.setItem(s,JSON.stringify({storedAt:Date.now(),byMessageId:pe(B({},u),{[r]:i})}))}catch(s){}}function zI(e,t,n){try{localStorage.removeItem(Kp(e,t,n))}catch(r){return}}const VI="cim_widget_thumbnails",wl="thumbnails",qI=1,Qp="byConversation",ME="byStoredAt",WI=2e3;function YI(e,t){return`${e}::${t}`}function GI(){return new Promise(e=>{try{if(typeof indexedDB=="undefined"||!indexedDB){e(null);return}let t=!1;const n=s=>{t||(t=!0,e(s))},r=setTimeout(()=>n(null),WI),i=indexedDB.open(VI,qI);i.onupgradeneeded=()=>{const s=i.result;if(!s.objectStoreNames.contains(wl)){const u=s.createObjectStore(wl,{keyPath:"key"});u.createIndex(Qp,"conversationId",{unique:!1}),u.createIndex(ME,"storedAt",{unique:!1})}},i.onsuccess=()=>{clearTimeout(r),n(i.result)},i.onerror=()=>{clearTimeout(r),n(null)},i.onblocked=()=>{clearTimeout(r),n(null)}}catch(t){e(null)}})}function xl(e,t,n){return Ce(this,null,function*(){const r=yield GI();return r?new Promise(i=>{let s=t,u=!1;const c=d=>{u||(u=!0,i(d))};try{const d=r.transaction(wl,e),f=d.objectStore(wl);d.oncomplete=()=>{r.close(),c(s)},d.onerror=()=>{r.close(),c(t)},d.onabort=()=>{r.close(),c(t)},n(f,m=>{s=m})}catch(d){try{r.close()}catch(f){}c(t)}}):t})}function XI(e,t,n){return Ce(this,null,function*(){if(!e||!t||!n)return;const r={key:YI(e,t),conversationId:e,messageId:t,dataUrl:n,storedAt:Date.now()};yield xl("readwrite",void 0,i=>{i.put(r)})})}function KI(e){return Ce(this,null,function*(){return e?xl("readonly",{},(t,n)=>{const r={},s=t.index(Qp).openCursor(IDBKeyRange.only(e));s.onsuccess=()=>{const u=s.result;if(u){const c=u.value;c!=null&&c.messageId&&(c!=null&&c.dataUrl)&&(r[c.messageId]=c.dataUrl),u.continue()}else n(r)}}):{}})}function FE(e){return Ce(this,null,function*(){e&&(yield xl("readwrite",void 0,t=>{const r=t.index(Qp).openCursor(IDBKeyRange.only(e));r.onsuccess=()=>{const i=r.result;i&&(i.delete(),i.continue())}}))})}function QI(e){return Ce(this,null,function*(){const t=Date.now()-e;yield xl("readwrite",void 0,n=>{const i=n.index(ME).openCursor(IDBKeyRange.upperBound(t,!0));i.onsuccess=()=>{const s=i.result;s&&(s.delete(),s.continue())}})})}const JI=5e3,lu=Symbol("cimulate-abort-conversation");function Tl(e={}){const{routingAttributes:t,timeoutMs:n=JI}=e;if(typeof window=="undefined"||typeof window.dispatchEvent!="function")return Promise.resolve(t);const r=B({},t!=null?t:{});return new Promise(i=>{const s={settled:!1},u=()=>{if(s.settled)return;s.settled=!0,s.timer!==void 0&&clearTimeout(s.timer);const h=Object.keys(r).length>0;i(h?r:t)},d={routingAttributes:t,setHiddenPrechatFields:h=>{s.settled||!h||Object.assign(r,h)},done:u,abort:()=>{s.settled||(s.settled=!0,s.timer!==void 0&&clearTimeout(s.timer),i(lu))}},f=new CustomEvent(H1,{detail:d,cancelable:!0});if(!!window.dispatchEvent(f)){u();return}s.timer=setTimeout(u,n)})}const ZI=200,eO=1e3,BE="cim_widget_thumbnails_last_sweep",tO=3600*1e3;function UE(e){try{const t=Date.now(),n=Number(localStorage.getItem(BE))||0;if(n>0&&t-n<tO)return;localStorage.setItem(BE,String(t))}catch(t){}QI(e)}function nO(e){const{orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:i,conversationId:s,continuationToken:u,lastEventId:c,onSessionUpdate:d}=e,f=_.useRef(null),m=_.useRef(null),h=_.useRef(!1),y=_.useRef(d);y.current=d;const E=_.useRef(null),x=i.sinceHours*60*60*1e3,A=NE,k=_.useCallback(()=>(E.current||(E.current=RI(f.current)),E.current),[]),v=_.useCallback(V=>{const G=y.current;if(!G)return;if(V==="ended"||V==="reset"){G({reason:V,snapshot:null});return}const I=Wp(t,n,A),W=Xp(t,n);!I||!W||G({reason:V,snapshot:{conversationId:I.conversationId,continuationToken:W.accessToken,lastEventId:W.lastEventId,storedAt:Math.max(I.storedAt,W.storedAt)}})},[t,n,A]);_.useEffect(()=>{const V=PI(t,n);f.current=V,E.current=null,h.current=!1;const G=LI(V,()=>{const I=m.current;if(!I)return null;const W=Xp(t,n);return{conversationId:I,continuationToken:W==null?void 0:W.accessToken,lastEventId:W==null?void 0:W.lastEventId}},()=>{Yp(t,n),m.current=null});return()=>{G(),MI(V),f.current=null}},[t,n]),_.useEffect(()=>{UE(A)},[A]);const N=_.useCallback((V,G)=>Ce(null,null,function*(){var K,ae,oe;const I=(K=G==null?void 0:G.createIfMissing)!=null?K:!0,W=(ae=G==null?void 0:G.isCurrent)!=null?ae:(()=>!0);UE(A);let Q=Wp(t,n,A);if(!Q){const he=yield k();he&&!qp(he.storedAt,A)&&(Q=he)}if(!Q){if(!I)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const he=yield Tl({routingAttributes:r});if(he===lu)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const se=yield V.createConversation(he);return W()?(cu(t,n,se),m.current=se,v("created"),{conversationId:se,restoredMessages:[],resumed:!1,outcome:"created"}):(yield V.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}try{const he=yield V.listConversations({conversationId:Q.conversationId,startTimestamp:Date.now()-A});if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const se=he.conversations.find(M=>M.conversationId===Q.conversationId&&!M.isConversationClosed);if(!se){if(Yp(t,n),FE(Q.conversationId),m.current=null,!I)return v("ended"),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const M=yield Tl({routingAttributes:r});if(M===lu)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const ge=yield V.createConversation(M);return W()?(cu(t,n,ge),m.current=ge,v("created"),{conversationId:ge,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"}):(yield V.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}V.resumeConversation(se.conversationId),m.current=se.conversationId,cu(t,n,se.conversationId),v("resumed");let ee=[],ce,O=[];const j=V.listConversationEntries(se.conversationId,{limit:100,startTimestamp:Date.now()-A,direction:"FromEnd",entryTypeFilter:["RoutingResult","ParticipantChanged","CloseConversation"]}).then(M=>M.conversationEntries,()=>null);try{const M=yield V.listConversationEntries(se.conversationId,{limit:Math.min((oe=i.limit)!=null?oe:ZI,eO),startTimestamp:Date.now()-x,direction:"FromEnd"});O=M.conversationEntries,ce=RE(O),ee=HI(M.conversationEntries).reverse();const ge=DE(t,n,se.conversationId);Object.keys(ge).length>0&&(ee=ee.map(ne=>ne.role==="user"&&ge[ne.id]?pe(B({},ne),{pageContextDivider:ge[ne.id]}):ne));const Oe=yield KI(se.conversationId);Object.keys(Oe).length>0&&(ee=ee.map(ne=>Oe[ne.id]?pe(B({},ne),{attachmentImageUrl:Oe[ne.id]}):ne))}catch(M){}const te=yield j;return te!=null&&te.length&&(ce=RE([...O,...te])),{conversationId:se.conversationId,restoredMessages:ee,humanHandoff:ce,resumed:!0,outcome:"resumed"}}catch(he){return{conversationId:Q.conversationId,restoredMessages:[],resumed:!1,outcome:"unverified-error",error:he}}}),[t,n,r,i,x,A,k,v]),L=_.useCallback((V,G)=>{cu(t,n,V),m.current=V,v(G)},[t,n,v]),P=_.useCallback(V=>{m.current&&(FE(m.current),zI(t,n,m.current)),Yp(t,n),II(t,n),DI(f.current),m.current=null,v(V)},[t,n,v]),z=_.useCallback(()=>{h.current||(h.current=!0,u&&s&&IE(u)!=="expired"&&(OE(t,n,u,c!=null?c:""),cu(t,n,s),m.current=s));const V=Xp(t,n);return V?B({continuationToken:V.accessToken},V.lastEventId?{lastEventId:V.lastEventId}:{}):null},[t,n,u,s,c]),D=_.useCallback(()=>Ce(null,null,function*(){const V=yield k();return!(V!=null&&V.continuationToken)||qp(V.storedAt,A)?null:{continuationToken:V.continuationToken,lastEventId:V.lastEventId}}),[A,k]),q=_.useCallback((V,G=()=>!0)=>Ce(null,null,function*(){try{const{accessToken:I,lastEventId:W}=yield V.generateContinuationToken();if(!G())return;OE(t,n,I,W),(m.current||Wp(t,n,A))&&v("refreshed")}catch(I){}}),[t,n,A,v]);return{initializeConversation:N,persistConversationId:L,clearPersistedConversation:P,getStoredConnectOptions:z,getPeerConnectOptions:D,persistContinuationToken:q}}const rO=128,iO=.7;function jE(e,t,n){return Ce(this,null,function*(){var r,i;try{if(!e||!n.type.startsWith("image/"))return;const s=(i=(r=t==null?void 0:t.conversationEntries)==null?void 0:r[0])==null?void 0:i.id;if(!s)return;const u=yield vp(n,{maxDimension:rO,quality:iO,mimeType:"image/jpeg"}),c=yield xy(u);yield XI(e,s,c)}catch(s){}})}const oO="Your session ended due to inactivity. Starting a new session…",sO="This conversation has ended.",aO=300*1e3,uO=2e3,HE=1e4,$E=15e3,cO=2;function zE(e,t,n){return e||t||n===!0}function vl(e){return e.some(t=>t.role==="agent")}function Ds(e){e.acknowledged=!1,e.sentAt=performance.now(),e.firstTokenAt=void 0}function du(e){const t=e.find(r=>!r.timedOut),n=e[e.length-1];return t!=null?t:n}function lO(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 VE(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 Jp(e){if(VE(e))return!0;const t=e instanceof Error?e.message:"";return/\(401\)/.test(t)}function dO(e){var y;const t=e.productName||"this product",n=e.quantity&&e.quantity>1?e.quantity:void 0,r=((y=e.variants)!=null?y:[]).filter(E=>E.value),i=r.map(E=>`${E.label}: ${E.value}`).join(", "),s=r.map(E=>E.value).join(", "),u=i?` (${i})`:"",c=s?` (${s})`:"",d=n?`Add ${n} of`:"Add",f=e.sku?` [SKU: ${e.sku}]`:"",m=`${d} ${t} to my cart${u}${f}`,h=`Add ${n?`${n} × `:""}${t} to cart${c}`;return{prompt:m,display:h}}function Zp(e,t){return t?{prompt:`${e} (Viewing product details for: ${t})`,display:e}:{prompt:e}}function fO({connectionStatus:e,loading:t,hasMessages:n,sessionExpired:r,bootstrapSettled:i,resumeUsedLastEventId:s,recoverySteps:u,onExhausted:c,timeoutMs:d=$E,logger:f,isRecoveryInFlight:m}){const h=_.useRef(u);h.current=u;const y=_.useRef(c);y.current=c;const E=_.useRef(f);E.current=f;const x=_.useRef(m);x.current=m;const A=_.useRef(0),k=_.useRef(!1),v=_.useRef(0),[N,L]=_.useState(0);_.useEffect(()=>{if(!t||n){A.current=0,k.current=!1,v.current=0;return}const P=s||A.current>0;if(!(i&&P&&e==="connected"&&!r&&!k.current))return;const D=setTimeout(()=>{Ce(null,null,function*(){var I,W;if((I=x.current)!=null&&I.call(x)){if(v.current+=1,v.current>cO){k.current=!0,y.current();return}L(Q=>Q+1);return}const q=A.current,V=h.current;if(q>=V.length){k.current=!0,y.current();return}v.current=0,(W=E.current)==null||W.warn("🦜 connect bootstrap stalled",{attempt:q});let G;try{yield Promise.race([Promise.resolve(V[q]()),new Promise((Q,K)=>{G=setTimeout(()=>{K(new Error("connect bootstrap step timed out"))},d)})])}catch(Q){}finally{G!==void 0&&clearTimeout(G),A.current=q+1,L(Q=>Q+1)}})},d);return()=>{clearTimeout(D)}},[e,t,n,r,i,s,d,N])}const pO=(e,t,n)=>e==="chat"?"open":t?n?"minimized":"open":"closed",mO=(e,t,n,r,i)=>e==="error"||n?"error":t&&i===0?"connecting":r||t?"processing":e==="reconnecting"?"reconnecting":"transcript",hO=e=>{for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.role!=="agent")continue;const r=hI(n.content);if(r.includes("order_confirmation"))return"order";if(r.includes("cart"))return"cart";if(r.includes("product_comparison"))return"comparison";if(r.includes("product_carousel")||r.includes("product_tile"))return"products"}return"text"};function gO({telemetryRef:e,connectionStatus:t,loading:n,sendError:r,isAgentTyping:i,messages:s}){const{status:{isOpen:u,isMinimized:c,type:d}}=qn(),f=pO(d,u,c);_.useEffect(()=>{var y;(y=e.current)==null||y.uiState(f)},[e,f]);const m=mO(t,n,r,i,s.length);_.useEffect(()=>{var y;(y=e.current)==null||y.viewState(m)},[e,m]);const h=_.useMemo(()=>hO(s),[s]);_.useEffect(()=>{var y;(y=e.current)==null||y.contentState(h)},[e,h])}const yO=e=>typeof e=="number"?e:typeof e!="string"?NaN:/^\d+$/.test(e)?Number(e):Date.parse(e),em=(e,t=Date.now())=>{for(let n=e.length-1;n>=0;n--){const{role:r,timestamp:i}=e[n];if(r==="system")continue;const s=yO(i);return Number.isFinite(s)?Math.max(0,t-s):null}return null};function EO({telemetryRef:e,stateRef:t}){const n=_.useRef(null),r=_.useCallback(i=>{var u;const s=t.current;!(s!=null&&s.conversationId)||s.conversationId===n.current||(n.current=s.conversationId,(u=e.current)==null||u.conversationEnded(i,em(s.messages)))},[e,t]);return _.useEffect(()=>{const i=performance.now();let s=!1;const u=d=>{var f,m,h;s||(s=!0,(h=e.current)==null||h.sessionEnded(d,Math.round(performance.now()-i),em((m=(f=t.current)==null?void 0:f.messages)!=null?m:[])))},c=()=>u("navigated_away");return window.addEventListener("pagehide",c),()=>{window.removeEventListener("pagehide",c),u("unmounted")}},[e,t]),r}const bO=100,wO=4e3,xO=12e3;function qE(e,t){const n=e.current;e.current=[],n.forEach(({text:r,options:i,file:s,resolve:u})=>{const c=t.current;if(!c){u==null||u({outcome:"failure",message:"Messaging is unavailable"});return}c(r,i==null?void 0:i.displayContent,i,void 0,s).then(d=>u==null?void 0:u(d),d=>u==null?void 0:u({outcome:"failure",message:d instanceof Error?d.message:String(d)}))})}function WE(e,t){const n=e.current;n.length!==0&&(e.current=[],n.forEach(({resolve:r})=>{r==null||r({outcome:"failure",message:t})}))}function TO({isOpen:e,connectionStatus:t,conversationId:n,messages:r,deliverUserMessageRef:i,onWelcomeTimeout:s,welcomeNotExpected:u=!1,agentJoined:c=!1,welcomeStreaming:d=!1}){const[f,m]=_.useState(0),h=_.useRef([]),y=_.useRef(t);y.current=t;const E=_.useRef(null),x=_.useRef(null),A=_.useRef(n);return _.useEffect(()=>{if(A.current!==n&&(A.current=n,E.current=null,x.current=null),t==="error"){E.current=null,x.current=null,WE(h,"Connection error");return}const k=t==="connected"&&n!==null,v=h.current.length>0;if(!e||!k||!v){E.current=null,x.current=null;return}if(vl(r)||u){E.current=null,x.current=null;const D=setTimeout(()=>{qE(h,i)},bO);return()=>clearTimeout(D)}if(c){if(E.current=null,d)return;const D=Date.now();x.current===null&&(x.current=D+wO);const q=Math.max(0,x.current-D),V=setTimeout(()=>{x.current=null,h.current.length!==0&&qE(h,i)},q);return()=>clearTimeout(V)}x.current=null;const N=Date.now(),L=xO;E.current===null&&(E.current=N+L);const P=Math.max(0,E.current-N),z=setTimeout(()=>{E.current=null,h.current.length!==0&&(WE(h,"Welcome timeout"),s==null||s())},P);return()=>clearTimeout(z)},[e,t,n,r,i,f,s,u,c,d]),_.useCallback((k,v,N)=>y.current==="error"?Promise.resolve({outcome:"failure",message:"Connection error"}):new Promise(L=>{h.current.push({text:k,options:v,file:N,resolve:L}),m(P=>P+1)}),[])}const vO="Cart action timed out. Please try again.";function _O(e){return new Promise(t=>{let n=!1;const r=s=>{n||(n=!0,window.clearTimeout(i),t(s))},i=window.setTimeout(()=>{r({ok:!1,error:e.action==="add"?"Cart action timed out. Open View Cart to check whether the item was added before trying again.":vO})},HE);window.dispatchEvent(new CustomEvent(Kc,{detail:pe(B({},e),{respond:r})}))})}function tm(e){var n;const t=((n=e.items)!=null?n:[]).reduce((r,i)=>r+(i.quantity||0),0);return{cartId:e.id,itemCount:t,total:e.total}}function SO(e,t){const[n,r]=_.useState(null),[i,s]=_.useState(null),[u,c]=_.useState(!1),d=_.useRef(0),f=_.useRef(e);f.current=e;const m=_.useRef(()=>Ce(null,null,function*(){})),h=_.useCallback(x=>{if(x.ok){r(x.cart),s(null),t==null||t.log("🦜 recognized cart update",tm(x.cart));return}x.cart&&r(x.cart),s(x.error),t==null||t.warn("🦜 cart update failed",B({error:x.error},x.cart?tm(x.cart):{}))},[t]),y=_.useCallback(x=>Ce(null,null,function*(){if(f.current!=="direct")return{outcome:"failure",message:"Cart actions are not direct"};const A=++d.current;c(!0);try{const k=yield _O(x);if(A===d.current)h(k);else if(x.action!=="add")return{outcome:"failure",message:"Cart update was superseded"};return k.ok?{outcome:"success"}:{outcome:"failure",message:k.error}}catch(k){if(A!==d.current)return{outcome:"failure",message:"Cart update was superseded"};const v=k instanceof Error?k.message:"Couldn't update the cart";return s(v),{outcome:"failure",message:v}}finally{A===d.current&&c(!1)}}),[h]),E=_.useCallback(()=>Ce(null,null,function*(){yield y({action:"get"})}),[y]);return m.current=E,_.useEffect(()=>{const x=A=>{if(f.current!=="direct")return;const k=A.detail;d.current+=1,r(k),s(null),c(!1),t==null||t.log("🦜 recognized cart update",tm(k))};return window.addEventListener(Qa,x),()=>window.removeEventListener(Qa,x)},[t]),{directCart:n,directCartError:i,directCartLoading:u,loadDirectCart:E,applyDirectCartChange:y,cartTransportRef:f,refreshDirectCartRef:m}}function AO(e){const t=_.useRef(e);t.current=e,_.useEffect(()=>{const n=({detail:r})=>{(r==null?void 0:r.event)===Zc.RESET_CONVERSATION&&t.current()};return F1(n),()=>{B1(n)}},[])}function kO(e){const t=_.useRef(e);t.current=e,_.useEffect(()=>{const n=({detail:r})=>{(r==null?void 0:r.event)===Zc.END_CONVERSATION&&t.current()};return F1(n),()=>{B1(n)}},[])}const oi={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 YE(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 Ms(e){const{type:t,statusCode:n}=YE(e),r=e&&typeof e=="object"&&typeof e.attemptsMade=="number"?e.attemptsMade:void 0;return{status:n,context:{errType:t!=null?t:"unknown",attempts:r}}}function si(e){const{type:t,statusCode:n}=YE(e);if(t==="api"&&typeof n=="number")return n===429?oi.rateLimit:n>=500?oi.server:oi.default;switch(t){case"network":return oi.network;case"sse":return oi.interrupted;case"auth":return oi.connect;default:return oi.default}}function GE(e){switch(e.code){case"MAX_RECONNECT":return oi.lost;case"ROUTING_FAILED":return oi.routing;default:return oi.connect}}let Bo=null;function CO(e){Bo&&Bo!==e&&console.warn("[CimulateMessaging] A messaging API is already registered; overwriting it. Mounting more than one messaging widget per page is not supported."),Bo=e}function NO(e){Bo===e&&(Bo=null)}function XE(){if(!Bo)throw new Error("Cimulate messaging widget is not ready. Call this after injectMessagingWidget() has run and the widget has mounted.");return Bo}const IO={pdp:"This is the product details page the user is currently looking at",srp:"This is the search results page the user is currently looking at"},OO="1.0.0",PO=32768;function RO(e){const t=e.type==="pdp"?{id:e.id}:B(B(B({query:e.query},e.refinements!==void 0?{refinements:e.refinements}:{}),e.minPrice!==void 0?{minPrice:e.minPrice}:{}),e.maxPrice!==void 0?{maxPrice:e.maxPrice}:{});return{page_context_type:e.type,page_context_message:IO[e.type],page_context_data:t}}function LO(e){try{return new TextEncoder().encode(JSON.stringify(e)).length<=PO}catch(t){return!1}}function DO(e,t=null){if(!e&&!t)return;const n=B({version:OO},e?RO(e):{});let r=t?pe(B({},n),{browsing_history:t}):n;if(t&&!LO(r)){if(!e)return;r=n}return[{entryType:"SessionContext",id:crypto.randomUUID(),sessionContext:{contextType:"SessionContextSet",contextVariables:[{name:"commerce_agent_context",value:{valueType:"StructuredValue",value:r}}]}}]}function MO(e){var u,c,d;const t=(d=(c=(u=e[0])==null?void 0:u.sessionContext)==null?void 0:c.contextVariables)==null?void 0:d[0],n=t==null?void 0:t.value,r=(n==null?void 0:n.valueType)==="StructuredValue"?n.value:void 0;if(!r||!("browsing_history"in r))return e;const f=r,{browsing_history:i}=f,s=kn(f,["browsing_history"]);return Object.keys(s).every(m=>m==="version")?null:[{entryType:"SessionContext",id:crypto.randomUUID(),sessionContext:{contextType:"SessionContextSet",contextVariables:[{name:"commerce_agent_context",value:{valueType:"StructuredValue",value:s}}]}}]}let Fs=null;function KE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)}function FO(e){if(typeof e!="function"&&!KE(e))throw new Error("Browsing history must be { events: [...] } or a function returning it");Fs=e}function nm(){if(!Fs)return null;let e;try{e=typeof Fs=="function"?Fs():Fs}catch(t){return null}return KE(e)?e:null}function BO(){Fs=null}function QE(e,t){return e===t?!0:!e||!t||e.type!==t.type?!1:e.type==="pdp"&&t.type==="pdp"?e.id===t.id:e.type!=="srp"||t.type!=="srp"?!1:e.query===t.query}const Bs=Symbol("initialization-cancelled"),UO=3e4,jO="Image is too large to send. Please choose a smaller image.",HO="Sorry, we couldn't process that image. Please try a PNG, JPG, or GIF.",$O=512,zO=.7,JE=e=>{if(!e)return e;const t=MO(e);return t===e?e:nm()===null?t:e},VO=e=>Ce(null,null,function*(){let t;try{t=yield vp(e)}catch(n){if(!dC.includes(e.type))return console.warn("🦜 image downsize failed; original type not SCRT2-native, rejecting",n),{error:HO};console.warn("🦜 image downsize failed; uploading original",n),t=e}return t.size>Ep?{error:jO}:{file:t}}),ZE=e=>Ce(null,null,function*(){if(e.preparedFile)return{file:e.preparedFile};const t=yield VO(e.file);return"error"in t?t:(e.preparedFile=t.file,{file:t.file})}),eb=({scrt2Url:e,orgId:t,esDeveloperName:n,routingAttributes:r,conversationId:i,continuationToken:s,lastEventId:u,capabilitiesVersion:c,enablePageContext:d=!1,enableLogging:f=!1,onConnect:m,onMessage:h,onError:y,onProductResult:E,onEndConversation:x,onSessionUpdate:A,onWelcomeTimeout:k,cartTransport:v="agent",storefrontCartPageUrl:N="",children:L})=>{const{logger:P,conversationHistory:z}=at(),{status:{isOpen:D}}=qn(),q=er(),V=_.useRef(q);V.current=q;const[G,I]=_.useReducer(TI,SE),[W,Q]=_.useState(!1),[K,ae]=_.useState(!1),[oe,he]=_.useState(!1),se=_.useRef(!1),[ee,ce]=_.useState(!1),[O,j]=_.useState(!1),te=_.useRef(!1),M=_.useRef(0),ge=_.useRef(G);ge.current=G;const Oe=_.useRef(null);Oe.current||(Oe.current=crypto.randomUUID());const ne=_.useRef(null);ne.current||(ne.current=$C({orgId:t,esDeveloperName:n,widgetSessionId:Oe.current,getIdentity:()=>({conversationId:ge.current.conversationId,messagingSessionId:ge.current.messagingSessionId})}));const be=_.useRef(null),_e=_.useRef(null),je=_.useRef(null),ft=_.useRef(0),It=_.useRef(!1);_.useEffect(()=>{const Z=G.connectionStatus,ye=be.current;be.current=Z;const Ne=ne.current;if(Ne&&!(ye===Z||ye===null&&Z==="disconnected"))switch(Ne.connectionState(Z),Z){case"connecting":_e.current=performance.now();break;case"reconnecting":je.current=performance.now();break;case"connected":ye==="reconnecting"&&je.current!==null?Ne.reconnectSucceeded(Math.round(performance.now()-je.current),ft.current):Ne.connectSucceeded(_e.current!==null?Math.round(performance.now()-_e.current):null),_e.current=null,je.current=null,ft.current=0;break}},[G.connectionStatus]),_.useEffect(()=>{var Z;(Z=ne.current)==null||Z.sessionState(G.sessionExpired)},[G.sessionExpired]),gO({telemetryRef:ne,connectionStatus:G.connectionStatus,loading:G.loading,sendError:G.sendError,isAgentTyping:G.isAgentTyping,messages:G.messages});const bt=EO({telemetryRef:ne,stateRef:ge}),Ge=nO({orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:z,conversationId:i,continuationToken:s,lastEventId:u,onSessionUpdate:A}),Xe=_.useRef(null),Zt=_.useRef(h),qe=_.useRef(y),At=_.useRef(m),$e=_.useRef(E),it=_.useRef(x),Qe=_.useRef(!1),Ot=_.useRef(!1),Dt=_.useRef(!1),Bn=_.useRef(0),Re=_.useRef(0),Je=_.useRef(0),de=_.useRef(null),Te=_.useRef(null),ze=_.useRef(null),lt=_.useRef(0),ot=_.useRef(!1),Ht=_.useRef(0),kt=_.useRef(0),Gn=_.useRef(()=>Promise.reject(new Error("Messaging is unavailable"))),Wr=_.useRef(),bi=_.useRef(()=>Ce(null,null,function*(){return{outcome:"failure",message:"Messaging is unavailable"}})),Yt=_.useRef(null),In=_.useCallback((Z,ye,Ne)=>{var Le,Be;const Ee=Z.options.pageContextDivider,le=(Be=(Le=ye==null?void 0:ye.conversationEntries)==null?void 0:Le[0])==null?void 0:Be.id;Ee&&Ne&&le&&$I(t,n,Ne,le,Ee)},[t,n]),Un=_.useCallback((Z={})=>{if(!d)return Z;const ye=Cs();if(!ye)return pe(B({},Z),{pageContextSnapshot:null});const Ne=pe(B({},Z),{pageContextSnapshot:ye});if(Z.silent)return Ne;let Ee;switch(ye.type){case"pdp":{const le=ty();Ee={context:ye,label:(le==null?void 0:le.label)||ye.id,imageUrl:le==null?void 0:le.imageUrl};break}case"srp":Ee={context:ye,label:ye.query};break}return pe(B({},Ne),{pageContextDivider:Ee})},[d]),vn=_.useRef([]),fn=_.useRef(null),Yr=_.useRef(null),Gr=_.useRef(!1),oo=_.useRef(0);_.useEffect(()=>{const Z=ye=>{var Ee;const Ne=(Ee=AI())!=null?Ee:ye==null?void 0:ye.detail;!Ne||typeof Ne!="object"||!Array.isArray(Ne.items)||(Yr.current=Ne,Gr.current=!0,oo.current+=1)};return window.addEventListener(Qa,Z),Z(),()=>window.removeEventListener(Qa,Z)},[]);const{directCart:Ju,directCartError:Zu,directCartLoading:ec,loadDirectCart:tc,applyDirectCartChange:ba,cartTransportRef:jd,refreshDirectCartRef:cs}=SO(v,P),rn=_.useCallback((Z,ye)=>{ye.outcome==="timeout"?(Z.timedOut=!0,vn.current=vn.current.filter(Ne=>Ne===Z||!Ne.timedOut)):vn.current=vn.current.filter(Ne=>Ne!==Z),clearTimeout(Z.timeoutId),Z.resolve(ye)},[]),Xt=_.useCallback(Z=>{if(M.current+=1,te.current!==Z&&(te.current=Z,I({type:"SET_HUMAN_HANDOFF",active:Z}),Z))for(const ye of[...vn.current])ye.completeOnAcknowledgment=!0,ye.acknowledged&&rn(ye,{outcome:"success"})},[rn]),wa=_.useCallback(Z=>{vn.current.includes(Z)&&(Z.acknowledged=!0,(te.current||Z.completeOnAcknowledgment)&&(I({type:"SET_LOADING",isLoading:!1}),rn(Z,{outcome:"success"})))},[rn]);Zt.current=h,qe.current=y,At.current=m,$e.current=E,it.current=x,_.useEffect(()=>{const Z=new bC({baseURL:e,orgId:t,esDeveloperName:n,options:B({enableLogging:f},c?{capabilitiesVersion:c}:{})});Xe.current=Z,ot.current=!1,It.current=!1,j(!1),Q(!1),se.current=!1,ce(!1),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),Z.on("connected",()=>{var le,Le;I({type:"SET_CONNECTION_STATUS",status:"connected"}),It.current||(It.current=!0,(le=ne.current)==null||le.sessionStarted()),(Le=At.current)==null||Le.call(At)}),Z.on("disconnected",()=>{I({type:"SET_CONNECTION_STATUS",status:"disconnected"})}),Z.on("reconnecting",le=>{ft.current=le.attempt,I({type:"SET_CONNECTION_STATUS",status:"reconnecting"})}),Z.on("message",le=>{var Gd,_a,_t,ac,uc,Sa,cc;const Le=Yr.current,Be=oo.current,ht=le.messageId!==void 0&&ge.current.messages.some(ao=>ao.serverId===le.messageId);if(d&&!ht){const ao=bI(le.content);ao&&!QE(ao,Cs())&&il(ao)}const wt=pe(B({id:le.messageId||crypto.randomUUID()},le.messageId?{serverId:le.messageId}:{}),{role:"agent",content:le.content,timestamp:le.timestamp,sender:le.sender,raw:le});P==null||P.log("🦜 MessagingProvider message received (FLUSH_STREAMING)",{messageId:wt.id,tokensBeforeFlush:Bn.current,streamedFinalOnly:Bn.current===0}),Bn.current=0,bl((Gd=le.sender)==null?void 0:Gd.role)===!0&&!te.current&&Xt(!0);const Ye=te.current?void 0:du(vn.current),un=Ye==null?void 0:Ye.options.reconcileMessageId;I({type:"FLUSH_STREAMING",message:wt,replaceMessageId:un}),(_a=Zt.current)==null||_a.call(Zt,wt),Ye&&(Ye.sentAt!==void 0&&!Ye.options.silent&&((_t=ne.current)==null||_t.agentReplied(Math.round(performance.now()-Ye.sentAt),Ye.firstTokenAt!==void 0?Math.round(Ye.firstTokenAt-Ye.sentAt):null)),rn(Ye,{outcome:"success"}));const{messagingSessionId:cn}=le;cn&&I({type:"SET_MESSAGING_SESSION_ID",id:cn});const mn=EI(le.content);cn&&mn&&((ac=$e.current)==null||ac.call($e,{agentSessionId:cn,kind:mn.kind,productIds:mn.productIds}));const Tt=vE(le.content),Xn=(uc=Tt==null?void 0:Tt.cartDetails)!=null?uc:null;ht||((mn==null?void 0:mn.kind)==="search"&&mn.productIds.length===0&&((Sa=ne.current)==null||Sa.failure("no_results")),(Tt==null?void 0:Tt.status)==="failure"&&((cc=ne.current)==null||cc.failure("cart_action_failed")));const Ir=jd.current==="direct";Ir&&Tt&&!ht&&cs.current(),!(ht||!se.current&&Gr.current)&&(Xn&&Be===oo.current&&(Yr.current=Xn,Gr.current=!1,oo.current+=1),(Tt==null?void 0:Tt.status)==="success"&&(Xn||Ir)?se.current&&j1(CE(Le,Xn,wI(le.content))):!Ir&&(Ye!=null&&Ye.options.cartMutation)&&!Xn&&(Tt==null?void 0:Tt.status)!=="failure"&&se.current&&j1(CE(Le,null)))}),Z.on("streaming_token",le=>{const Le=du(vn.current);if(!(Le!=null&&Le.options.silent)){if(Le&&Le.firstTokenAt===void 0&&(Le.firstTokenAt=performance.now()),Bn.current+=1,P!=null&&P.isDevelopment){const Be=wE(le.token);Be?Be.index===Yi?P.debug("🦜 streaming_token → markdown fallback",{token:le.token}):P.debug("🦜 streaming_token parsed",{type:Be.type,index:Be.index,outputName:Be.type==="tool_results"?Be.output_name:void 0}):P.debug("🦜 streaming_token dropped (empty or unrecognized payload shape)",{token:le.token})}I({type:"APPEND_STREAMING_TOKEN",token:le.token})}}),Z.on("typing_started",()=>{var le;(le=du(vn.current))!=null&&le.options.silent||I({type:"SET_AGENT_TYPING",isTyping:!0})}),Z.on("typing_stopped",()=>{var le;(le=du(vn.current))!=null&&le.options.silent||I({type:"SET_AGENT_TYPING",isTyping:!1})}),Z.on("progress_indicator",le=>{var Le;(Le=du(vn.current))!=null&&Le.options.silent||I({type:"ADD_PROGRESS_STEP",message:le.message})}),Z.on("routing_result",le=>{var Be,ht;I({type:"SET_ROUTING_RESULT",result:le});const Le=PE(le.raw);if(le.isSuccessful&&Le!==void 0&&Xt(Le),!le.isSuccessful){const wt=`Routing failed: ${le.failureType||"unknown"}`;(Be=ne.current)==null||Be.failure("routing_failed",{context:{failureType:le.failureType||"unknown"}}),I({type:"SET_ERROR",error:GE({code:"ROUTING_FAILED"})}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(ht=qe.current)==null||ht.call(qe,wt)}}),Z.on("participant_changed",le=>{var ht,wt;if(le.participant.name==="Automated Process")return;const Le=bl(le.participant.role);le.action==="add"&&Le!==void 0&&Xt(Le),Le===!1&&ae(le.action==="add");const Be=pe(B({id:crypto.randomUUID()},le.entryId?{serverId:le.entryId}:{}),{role:"system",content:le.action==="add"?ol(V.current.session.participantJoined,{name:le.participant.name||V.current.session.participantFallbackName}):ol(V.current.session.participantLeft,{name:le.participant.name||V.current.session.participantFallbackName}),timestamp:new Date().toISOString()});P==null||P.log("🦜 MessagingProvider participant_changed event received",{event:le}),le.action==="add"?(ht=ne.current)==null||ht.participantJoined(le.participant.name||"Agent"):(wt=ne.current)==null||wt.participantLeft(le.participant.name||"Agent",em(ge.current.messages)),I({type:"ADD_MESSAGE",message:Be})}),Z.on("conversation_closed",()=>{const le={id:crypto.randomUUID(),role:"system",content:V.current.session.conversationEnded,timestamp:new Date().toISOString()};Xt(!1),bt("server_closed"),I({type:"ADD_MESSAGE",message:le}),I({type:"SET_CONVERSATION_ID",id:null}),Ge.clearPersistedConversation("ended")}),Z.on("error",le=>{var Le,Be,ht;if(P==null||P.log("🦜 MessagingProvider ERROR event received",{event:le}),le.code==="SESSION_EXPIRED"){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),I({type:"SET_LOADING",isLoading:!1});return}(Be=ne.current)==null||Be.failure("sdk_error",{context:{code:(Le=le.code)!=null?Le:"unknown",recoverable:le.recoverable}}),I({type:"SET_ERROR",error:GE(le)}),le.recoverable||I({type:"SET_CONNECTION_STATUS",status:"error"}),(ht=qe.current)==null||ht.call(qe,le.message)});const ye=le=>{if(le!==Ht.current)throw Bs},Ne=le=>le===Ht.current,Ee=le=>Ce(null,null,function*(){var Ye,un,cn,mn;const Le=M.current;Q(!1),se.current=!1;let Be=Ge.getStoredConnectOptions(),ht=!1;Be||(Be=yield Ge.getPeerConnectOptions(),ye(le),ht=!!Be);let wt=!1;try{if(yield Z.connect(Be!=null?Be:void 0),!Ne(le))throw Z.disconnect(),Bs;wt=!!(Be!=null&&Be.lastEventId)}catch(Tt){if(ye(le),Be&&Jp(Tt)){if(P==null||P.log("Stored token expired on connect — falling back to fresh connect"),ht||Ge.clearPersistedConversation("reset"),yield Z.connect(),!Ne(le))throw Z.disconnect(),Bs;wt=!1}else throw Tt}ce(wt),yield Ge.persistContinuationToken(Z,()=>Ne(le)),ye(le);const We=yield Ge.initializeConversation(Z,{isCurrent:()=>Ne(le)});if(ye(le),P==null||P.log("🦜 initial connect complete",{conversationId:We.conversationId,resumed:We.resumed,outcome:We.outcome,restoredMessages:We.restoredMessages.length}),(Ye=ne.current)==null||Ye.sessionInitialized(We.outcome,We.restoredMessages.length),We.outcome==="aborted")throw I({type:"SET_LOADING",isLoading:!1}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Bs;if(We.outcome==="unverified-error"){We.conversationId&&(Z.resumeConversation(We.conversationId),I({type:"SET_CONVERSATION_ID",id:We.conversationId})),Q(!0),se.current=!0;return}if(I({type:"SET_CONVERSATION_ID",id:We.conversationId}),We.resumed){Le===M.current&&We.humanHandoff!==void 0&&Xt(We.humanHandoff);const Tt=(un=[...We.restoredMessages].reverse().find(Xn=>Xn.pageContextDivider))==null?void 0:un.pageContextDivider;if(Yt.current=(cn=Tt==null?void 0:Tt.context)!=null?cn:null,!Gr.current)for(const Xn of[...We.restoredMessages].reverse()){const Ir=(mn=vE(Xn.content))==null?void 0:mn.cartDetails;if(Ir){Yr.current=Ir,oo.current+=1;break}}I({type:"LOAD_HISTORY",messages:We.restoredMessages}),he(!vl(We.restoredMessages)),Q(!0),se.current=!0}else Le===M.current&&Xt(!1),Yt.current=null,he(!1),Q(!0),se.current=!0;I({type:"SET_LOADING",isLoading:!1})});return Te.current=Ee,()=>{Ht.current+=1,kt.current+=1,Z.disconnect(),Z.off(),Xe.current=null,Te.current=null,ze.current=null,ot.current=!1}},[e,t,n,c,rn]);const pn=_.useCallback(()=>{if(ot.current)return Promise.resolve();if(ze.current)return lt.current===Ht.current?ze.current:ze.current.catch(Ee=>{if(Ee!==Bs)throw Ee}).then(()=>Gn.current());const Z=Te.current;if(!Z)return Promise.reject(new Error("Messaging is unavailable"));I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_CONNECTION_STATUS",status:"connecting"});const ye=++Ht.current;lt.current=ye;const Ne=Z(ye).then(()=>{ot.current=!0,j(!0)}).catch(Ee=>{var Le,Be;if(Ee===Bs)throw Ee;const le=Ee instanceof Error?Ee.message:String(Ee);throw(Le=ne.current)==null||Le.failure("connect_failed",Ms(Ee)),I({type:"SET_CONNECTION_STATUS",status:"error"}),I({type:"SET_ERROR",error:si(Ee)}),(Be=qe.current)==null||Be.call(qe,le),Ee}).finally(()=>{ze.current===Ne&&(ze.current=null)});return ze.current=Ne,Ne},[]);Gn.current=pn,_.useEffect(()=>{D&&pn().catch(()=>{})},[D,e,t,n,c,pn]);const Pi=TO({isOpen:D,connectionStatus:G.connectionStatus,conversationId:G.conversationId,messages:G.messages,deliverUserMessageRef:Wr,onWelcomeTimeout:k,welcomeNotExpected:oe,agentJoined:K,welcomeStreaming:G.streamingBlocks.length>0}),Ri=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)return!1;const ye=M.current,Ne=Ge.getStoredConnectOptions();if(!Ne)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{Z.disconnect(),yield Z.connect(Ne)}catch(le){if(Jp(le))return P==null||P.log("🦜 attemptResume: token expired (401) — will start fresh",{error:le instanceof Error?le.message:String(le)}),!1;throw P==null||P.log("🦜 attemptResume: transient connect failure — rethrowing, session kept",{error:le instanceof Error?le.message:String(le)}),le}yield Ge.persistContinuationToken(Z);const Ee=yield Ge.initializeConversation(Z,{createIfMissing:!1});return Ee.outcome==="not-found-or-closed"||!Ee.conversationId?(P==null||P.log("🦜 attemptResume: conversation no longer resumable (closed/not found) — will start fresh"),!1):(Ee.outcome==="unverified-error"&&(P==null||P.log("🦜 attemptResume: resume validation failed transiently — keeping live session, resuming optimistically",{conversationId:Ee.conversationId}),Z.resumeConversation(Ee.conversationId)),P==null||P.log("🦜 attemptResume: resumed conversation on same identity",{conversationId:Ee.conversationId}),I({type:"SET_CONVERSATION_ID",id:Ee.conversationId}),Ee.outcome==="resumed"&&ye===M.current&&Ee.humanHandoff!==void 0&&Xt(Ee.humanHandoff),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ee.outcome!=="resumed"&&Ge.persistConversationId(Ee.conversationId,"resumed"),Dt.current=!1,I({type:"SET_SESSION_EXPIRED",expired:!1}),!0)}),[Ge,P,Xt]),ls=_.useCallback(Z=>Ce(null,null,function*(){var Ne,Ee,le,Le,Be,ht,wt;const ye=Xe.current;if(ye){Z.options.silent||(I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_PROGRESS_MESSAGE",message:""})),Z.sessionContext=JE(Z.sessionContext);try{if(Z.file){const We=yield ZE(Z);if("error"in We){I({type:"SET_SEND_ERROR",error:{text:Z.text,displayContent:Z.displayContent,options:Z.options,sessionContext:Z.sessionContext,file:Z.file,message:We.error}}),(Ne=ne.current)==null||Ne.failure("file_rejected"),(Ee=qe.current)==null||Ee.call(qe,We.error),rn(Z,{outcome:"failure",message:We.error});return}Ds(Z);const Ye=yield ye.sendFile(We.file,Z.text.trim()?{text:Z.text}:void 0);jE((le=ye.conversationId)!=null?le:ge.current.conversationId,Ye,Z.file)}else if(Z.sessionContext){Ds(Z);const We=yield ye.sendMessage(Z.text,Z.sessionContext);In(Z,We,(Le=ye.conversationId)!=null?Le:ge.current.conversationId)}else{Ds(Z);const We=yield ye.sendMessage(Z.text);In(Z,We,(Be=ye.conversationId)!=null?Be:ge.current.conversationId)}wa(Z)}catch(We){(ht=ne.current)==null||ht.failure("send_failed",Ms(We));const Ye=si(We);I({type:"SET_SEND_ERROR",error:{text:Z.text,displayContent:Z.displayContent,options:Z.options,sessionContext:Z.sessionContext,file:Z.file,message:Ye}}),(wt=qe.current)==null||wt.call(qe,We instanceof Error?We.message:String(We)),rn(Z,{outcome:"failure",message:Ye})}}}),[rn,In,wa]),Hd=_.useCallback(Z=>Ce(null,null,function*(){var Ne,Ee,le;const ye=Xe.current;if(!(!ye||Qe.current)){Qe.current=!0,Ot.current=!0;try{if(yield Ri()){Z&&(yield ls(Z));return}P==null||P.log("🦜 recoverExpiredSession: resume failed — starting a new session + conversation"),bt("expired"),Dt.current=!1,I({type:"SET_SESSION_EXPIRED",expired:!1}),I({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"system",content:V.current.session.sessionEnded,timestamp:new Date().toISOString()}}),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),ye.disconnect(),yield ye.connect(),yield Ge.persistContinuationToken(ye);const Le=yield Tl({routingAttributes:r});if(Le===lu){I({type:"SET_CONNECTION_STATUS",status:"disconnected"});return}const Be=yield ye.createConversation(Le);P==null||P.log("🦜 recoverExpiredSession: new conversation created",{conversationId:Be}),I({type:"SET_CONVERSATION_ID",id:Be}),(Ne=ne.current)==null||Ne.conversationStarted("recovery"),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ge.persistConversationId(Be,"created"),Z&&(Z.completeOnAcknowledgment=!1,yield ls(Z))}catch(Le){(Ee=ne.current)==null||Ee.failure("session_recovery_failed",Ms(Le));const Be=Le instanceof Error?Le.message:String(Le);I({type:"SET_ERROR",error:si(Le)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(le=qe.current)==null||le.call(qe,Be),Z&&rn(Z,{outcome:"failure",message:si(Le)})}finally{Qe.current=!1,Ot.current=!1}}}),[r,Ge,Ri,ls,P,rn,bt,Xt]),nc=_.useRef(Hd);nc.current=Hd;const $d=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z||!ot.current||Qe.current)return;if(!ge.current.conversationId&&!Dt.current){Z.reconnect();return}Qe.current=!0;const ye=Ce(null,null,function*(){try{(yield Ri())||(Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}))}catch(Ne){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"})}finally{Qe.current=!1,de.current=null}});de.current=ye,yield ye}),[Ri]),wi=_.useRef($d);wi.current=$d;const zd=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z||Qe.current)return;const ye=Ge.getStoredConnectOptions(),Ne=ye==null?void 0:ye.continuationToken;if(Ne){Qe.current=!0;try{Z.disconnect(),yield Z.connect({continuationToken:Ne}),yield Ge.persistContinuationToken(Z);const Ee=ge.current.conversationId;Ee&&Z.resumeConversation(Ee)}catch(Ee){if(Jp(Ee)){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),I({type:"SET_LOADING",isLoading:!1});return}P==null||P.log("🦜 reconnectOmittingLastEventId: transient connect failure — session kept",{error:Ee instanceof Error?Ee.message:String(Ee)})}finally{Qe.current=!1}}}),[Ge,P]);_.useEffect(()=>{const Z=()=>{const Be=Date.now();Be-Je.current<uO||(Je.current=Be,wi.current())},ye=()=>{if(document.visibilityState==="hidden"){Re.current=Date.now();return}const Be=Xe.current;if(!Be)return;const ht=Re.current?Date.now()-Re.current:0;Re.current=0,(Dt.current||!Be.isConnected||ht>aO)&&Z()},Ne=Be=>{Be.persisted&&Z()},Ee=()=>{Re.current=Date.now()},le=()=>Z(),Le=()=>Z();return document.addEventListener("visibilitychange",ye),window.addEventListener("pageshow",Ne),window.addEventListener("pagehide",Ee),document.addEventListener("resume",le),window.addEventListener("online",Le),()=>{document.removeEventListener("visibilitychange",ye),window.removeEventListener("pageshow",Ne),window.removeEventListener("pagehide",Ee),document.removeEventListener("resume",le),window.removeEventListener("online",Le)}},[]);const rc=_.useCallback((Z,ye)=>Ce(null,null,function*(){var Ee,le,Le,Be,ht,wt,We;const Ne=Xe.current;if(!Ne){rn(Z,{outcome:"failure",message:"Messaging is unavailable"});return}if(Dt.current){yield nc.current(Z);return}try{if(Z.file){const Ye=yield ZE(Z);if("error"in Ye){I({type:"SET_SEND_ERROR",error:ye(Ye.error)}),(Ee=ne.current)==null||Ee.failure("file_rejected"),(le=qe.current)==null||le.call(qe,Ye.error),rn(Z,{outcome:"failure",message:Ye.error});return}Ds(Z);const un=yield Ne.sendFile(Ye.file,Z.text.trim()?{text:Z.text}:void 0);jE((Le=Ne.conversationId)!=null?Le:ge.current.conversationId,un,Z.file)}else if(Z.sessionContext){Ds(Z);const Ye=yield Ne.sendMessage(Z.text,Z.sessionContext);In(Z,Ye,(Be=Ne.conversationId)!=null?Be:ge.current.conversationId)}else{Ds(Z);const Ye=yield Ne.sendMessage(Z.text);In(Z,Ye,(ht=Ne.conversationId)!=null?ht:ge.current.conversationId)}wa(Z)}catch(Ye){if(VE(Ye)){yield nc.current(Z);return}(wt=ne.current)==null||wt.failure("send_failed",Ms(Ye));const un=si(Ye);I({type:"SET_SEND_ERROR",error:ye(un)}),(We=qe.current)==null||We.call(qe,Ye instanceof Error?Ye.message:String(Ye)),rn(Z,{outcome:"failure",message:un})}}),[rn,In,wa]),Vd=_.useCallback(Z=>Ce(null,null,function*(){const ye=de.current;ye&&(yield ye),yield Z()}),[]),Nr=_.useCallback((Z,ye,Ne={},Ee,le,Le=!1)=>new Promise(Be=>{var mn;if(!Xe.current){Be({outcome:"failure",message:"Messaging is unavailable"});return}if(!Z.trim()&&!le){Be({outcome:"failure",message:"Message is empty"});return}const wt=Ne.pageContextDivider,We=!Le&&!le&&wt!==void 0&&!QE(wt.context,Yt.current),Ye=!Le&&wt!==void 0&&!We?pe(B({},Ne),{pageContextDivider:void 0}):Ne;let un=Le&&Ee?JE(Ee):Ee;if(un===void 0&&(un=null,d)){const Tt=Ye.pageContextSnapshot===void 0?Cs():Ye.pageContextSnapshot;un=(mn=DO(Tt,nm()))!=null?mn:null}const cn={};if(Object.assign(cn,{text:Z,displayContent:ye,options:Ye,completeOnAcknowledgment:te.current,sessionContext:un,file:le,resolve:Be,timeoutId:setTimeout(()=>{var Tt;(Tt=ne.current)==null||Tt.failure("send_timeout"),I({type:"SET_LOADING",isLoading:!1}),rn(cn,{outcome:"timeout"})},HE)}),vn.current.push(cn),I({type:"CLEAR_SEND_ERROR"}),!Ye.silent){if(!Le){const Tt=crypto.randomUUID();I({type:"ADD_MESSAGE",message:{id:Tt,role:"user",content:ye!=null?ye:Z,timestamp:new Date().toISOString(),pageContextDivider:Ye.pageContextDivider}}),We&&wt&&(Yt.current=wt.context),le&&le.type.startsWith("image/")&&vp(le,{maxDimension:$O,quality:zO}).then(xy).then(Xn=>I({type:"UPDATE_MESSAGE",id:Tt,patch:{attachmentImageUrl:Xn}})).catch(()=>{})}I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_PROGRESS_MESSAGE",message:""})}Vd(()=>rc(cn,Tt=>({text:Z,displayContent:ye,options:Ye,sessionContext:cn.sessionContext,file:le,message:Tt})))}),[rc,Vd,d,rn]);Wr.current=Nr;const so=_.useCallback((Z,ye)=>{var wt;if(!Z.trim())return Promise.resolve({outcome:"failure",message:"Message is empty"});const Ne=Un(ye),Ee=pe(B({},Ne),{displayContent:(wt=Ne.displayContent)!=null?wt:Z});if(!D||!te.current&&!vl(ge.current.messages)){const We=Pi(Z,Ee);return ot.current||pn().catch(()=>{}),D?We:Promise.resolve({outcome:"success"})}const le=kt.current,Le=()=>{const We=()=>le!==kt.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Nr(Z,Ee.displayContent,Ee);return ot.current?We():pn().then(We,Ye=>({outcome:"failure",message:si(Ye)}))},Be=fn.current?fn.current.then(Le):Le(),ht=Be.then(()=>{});return fn.current=ht,ht.finally(()=>{fn.current===ht&&(fn.current=null)}),Be},[Nr,pn,D,Pi,Un]);bi.current=so;const ic=_.useCallback(Z=>{if(!Xe.current)return Promise.resolve({outcome:"failure",message:"Messaging is unavailable"});const{text:Ne,file:Ee,displayContent:le}=Z;if(!Ee)return Ne.trim()?so(Ne):Promise.resolve({outcome:"failure",message:"Message is empty"});const Le=Ne.trim(),Be=(le!=null?le:Ne).trim()||Ee.name,ht={displayContent:Be};if(!D||!te.current&&!vl(ge.current.messages)){const cn=Pi(Le,ht,Ee);return ot.current||pn().catch(()=>{}),D?cn:Promise.resolve({outcome:"success"})}const wt=kt.current,We=()=>{const cn=()=>wt!==kt.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Nr(Le,Be,ht,null,Ee);return ot.current?cn():pn().then(cn,mn=>({outcome:"failure",message:si(mn)}))},Ye=fn.current?fn.current.then(We):We(),un=Ye.then(()=>{});return fn.current=un,un.finally(()=>{fn.current===un&&(fn.current=null)}),Ye},[Nr,so,pn,D,Pi]),oc=_.useCallback(Z=>{if(!Xe.current)return;const ye=kt.current,{prompt:Ne,display:Ee}=dO(Z);pn().then(()=>{if(ye===kt.current)return Nr(Ne,Ee)}).catch(()=>{})},[Nr,pn]),qd=_.useCallback(()=>{const Z=Xe.current,ye=ge.current.sendError;if(!Z||!ye)return;const Ne=()=>Ot.current?Promise.resolve({outcome:"failure",message:ye.message}):Nr(ye.text,ye.displayContent,ye.options,ye.sessionContext,ye.file,!0),Ee=fn.current?fn.current.then(Ne):Ne(),le=Ee.then(()=>{});return fn.current=le,le.finally(()=>{fn.current===le&&(fn.current=null)}),Ee},[Nr]),Wd=_.useCallback(()=>{const Z=Xe.current;Z&&(ze.current||(Dt.current=!1,ot.current=!1,j(!1),Z.disconnect(),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),pn().catch(()=>{})))},[pn]),$t=_.useCallback(Z=>{const ye=Xe.current;if(!ye)return Promise.resolve();if(vn.current=[],Yt.current=null,bt(Z),!ot.current)return Ht.current+=1,kt.current+=1,ye.disconnect(),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),Promise.resolve();const Ne=++kt.current;return Dt.current=!1,ce(!1),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),ye.endConversation().then(()=>Ne!==kt.current||Xe.current!==ye?null:(ye.disconnect(),ye.connect().then(()=>ye))).then(Ee=>Ce(null,null,function*(){if(!Ee||Ne!==kt.current||(yield Ge.persistContinuationToken(Ee,()=>Ne===kt.current&&Xe.current===Ee),Ne!==kt.current||Xe.current!==Ee))return null;const le=yield Tl({routingAttributes:r});return le===lu?null:ye.createConversation(le)})).then(Ee=>{var le;!Ee||Ne!==kt.current||Xe.current!==ye||(I({type:"SET_CONVERSATION_ID",id:Ee}),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ge.persistConversationId(Ee,"created"),(le=ne.current)==null||le.conversationStarted("reset"))}).catch(Ee=>{var le,Le;Ne!==kt.current||Xe.current!==ye||((le=ne.current)==null||le.failure("conversation_create_failed",Ms(Ee)),I({type:"SET_ERROR",error:si(Ee)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Le=qe.current)==null||Le.call(qe,Ee.message))})},[r,Ge,bt,Xt]),sc=_.useCallback(()=>$t("reset"),[$t]);AO(sc),fO({connectionStatus:G.connectionStatus,loading:G.loading,hasMessages:G.messages.length>0,sessionExpired:G.sessionExpired,bootstrapSettled:W,resumeUsedLastEventId:ee,recoverySteps:[zd,()=>$t("resume_timeout")],onExhausted:()=>{var ye,Ne;(ye=ne.current)==null||ye.failure("resume_timeout");const Z=si({type:"network"});I({type:"SET_ERROR",error:Z}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Ne=qe.current)==null||Ne.call(qe,Z)},logger:P,isRecoveryInFlight:()=>Qe.current||de.current!==null});const xa=_.useCallback(()=>Ce(null,null,function*(){var Ee;const Z=Xe.current;if(!Z||!ge.current.conversationId)return;const ye=yield Z.retrieveConversationTranscript(),Ne=URL.createObjectURL(ye);try{const le=document.createElement("a");le.href=Ne,le.download=`transcript-${(Ee=Z.conversationId)!=null?Ee:"conversation"}.pdf`,document.body.appendChild(le),le.click(),le.remove()}finally{URL.revokeObjectURL(Ne)}}),[]),Ta=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)return Promise.resolve();if(vn.current=[],Yt.current=null,bt("ended"),!ot.current)return Ht.current+=1,kt.current+=1,Z.disconnect(),Ge.clearPersistedConversation("ended"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Promise.resolve();const ye=++kt.current;if(Dt.current=!1,ce(!1),it.current)try{yield Promise.race([it.current(ge.current.conversationId),new Promise(Ee=>setTimeout(Ee,UO))])}catch(Ee){P==null||P.error("onEndConversation callback failed",Ee)}Ge.clearPersistedConversation("ended"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"});const Ne={id:crypto.randomUUID(),role:"system",content:V.current.session.conversationEnded,timestamp:new Date().toISOString()};return I({type:"ADD_MESSAGE",message:Ne}),ot.current=!1,j(!1),Z.endConversation().then(()=>{ye!==kt.current||Xe.current!==Z||Z.disconnect()}).catch(Ee=>{var le,Le;ye!==kt.current||Xe.current!==Z||((le=ne.current)==null||le.failure("end_conversation_failed",Ms(Ee)),I({type:"SET_ERROR",error:si(Ee)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Le=qe.current)==null||Le.call(qe,Ee.message))})}),[P,Ge,ce,bt,Xt]);kO(Ta);const Li=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)throw new Error("getAuthLinkKey called before the messaging client connected");return P==null||P.debug("🦜 getAuthLinkKey: requesting single-use auth link key"),Z.getAuthLinkKey()}),[P]);_.useEffect(()=>{const Z={getAuthLinkKey:Li,sendMessage:(ye,Ne)=>bi.current(ye,Ne)};return CO(Z),()=>NO(Z)},[Li]);const va=G.connectionStatus==="connected"&&G.conversationId!==null;_.useEffect(()=>{ey(va)},[va]),_.useEffect(()=>()=>ey(!1),[]);const Yd=_.useMemo(()=>({connectionStatus:G.connectionStatus,isConnected:va,isAgentTyping:G.isAgentTyping,conversationId:G.conversationId,messages:G.messages,streamingBlocks:G.streamingBlocks,progressMessage:G.progressMessage,progressSteps:G.progressSteps,error:G.error,sendError:G.sendError,canInitialize:!O&&G.error===null,loading:G.loading,humanHandoff:G.humanHandoff,sessionExpired:G.sessionExpired,sendMessage:so,sendFile:ic,addToCart:oc,resetConversation:sc,endConversation:Ta,retryLastMessage:qd,retryConnection:Wd,downloadTranscript:xa,getAuthLinkKey:Li,cartTransport:v,storefrontCartPageUrl:N,directCart:Ju,directCartError:Zu,directCartLoading:ec,loadDirectCart:tc,applyDirectCartChange:ba}),[G,va,O,so,ic,oc,sc,Ta,qd,Wd,xa,Li,v,N,Ju,Zu,ec,tc,ba]);return w.jsx(sl.Provider,{value:ne.current,children:w.jsx(uy.Provider,{value:Yd,children:L})})};var tb=Symbol.for("immer-nothing"),nb=Symbol.for("immer-draftable"),pr=Symbol.for("immer-state");function Ur(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Us=Object.getPrototypeOf;function js(e){return!!e&&!!e[pr]}function Uo(e){var t;return e?rb(e)||Array.isArray(e)||!!e[nb]||!!((t=e.constructor)!=null&&t[nb])||fu(e)||Al(e):!1}var qO=Object.prototype.constructor.toString();function rb(e){if(!e||typeof e!="object")return!1;const t=Us(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)===qO}function _l(e,t){Sl(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Sl(e){const t=e[pr];return t?t.type_:Array.isArray(e)?1:fu(e)?2:Al(e)?3:0}function rm(e,t){return Sl(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ib(e,t,n){const r=Sl(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function WO(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function fu(e){return e instanceof Map}function Al(e){return e instanceof Set}function jo(e){return e.copy_||e.base_}function im(e,t){if(fu(e))return new Map(e);if(Al(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=rb(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[pr];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const u=i[s],c=r[u];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[u]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[u]})}return Object.create(Us(e),r)}else{const r=Us(e);if(r!==null&&n)return B({},e);const i=Object.create(r);return Object.assign(i,e)}}function om(e,t=!1){return Cl(e)||js(e)||!Uo(e)||(Sl(e)>1&&Object.defineProperties(e,{set:{value:kl},add:{value:kl},clear:{value:kl},delete:{value:kl}}),Object.freeze(e),t&&Object.values(e).forEach(n=>om(n,!0))),e}function kl(){Ur(2)}function Cl(e){return Object.isFrozen(e)}var YO={};function Ho(e){const t=YO[e];return t||Ur(0,e),t}var pu;function ob(){return pu}function GO(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function sb(e,t){t&&(Ho("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function sm(e){am(e),e.drafts_.forEach(XO),e.drafts_=null}function am(e){e===pu&&(pu=e.parent_)}function ab(e){return pu=GO(pu,e)}function XO(e){const t=e[pr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ub(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[pr].modified_&&(sm(t),Ur(4)),Uo(e)&&(e=Nl(t,e),t.parent_||Il(t,e)),t.patches_&&Ho("Patches").generateReplacementPatches_(n[pr].base_,e,t.patches_,t.inversePatches_)):e=Nl(t,n,[]),sm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==tb?e:void 0}function Nl(e,t,n){if(Cl(t))return t;const r=t[pr];if(!r)return _l(t,(i,s)=>cb(e,r,t,i,s,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Il(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const i=r.copy_;let s=i,u=!1;r.type_===3&&(s=new Set(i),i.clear(),u=!0),_l(s,(c,d)=>cb(e,r,i,c,d,n,u)),Il(e,i,!1),n&&e.patches_&&Ho("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function cb(e,t,n,r,i,s,u){if(js(i)){const c=s&&t&&t.type_!==3&&!rm(t.assigned_,r)?s.concat(r):void 0,d=Nl(e,i,c);if(ib(n,r,d),js(d))e.canAutoFreeze_=!1;else return}else u&&n.add(i);if(Uo(i)&&!Cl(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Nl(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(fu(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&Il(e,i)}}function Il(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&om(t,n)}function KO(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:ob(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,s=um;n&&(i=[r],s=mu);const{revoke:u,proxy:c}=Proxy.revocable(i,s);return r.draft_=c,r.revoke_=u,c}var um={get(e,t){if(t===pr)return e;const n=jo(e);if(!rm(n,t))return QO(e,n,t);const r=n[t];return e.finalized_||!Uo(r)?r:r===cm(e.base_,t)?(dm(e),e.copy_[t]=fm(r,e)):r},has(e,t){return t in jo(e)},ownKeys(e){return Reflect.ownKeys(jo(e))},set(e,t,n){const r=lb(jo(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const i=cm(jo(e),t),s=i==null?void 0:i[pr];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(WO(n,i)&&(n!==void 0||rm(e.base_,t)))return!0;dm(e),lm(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 cm(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,dm(e),lm(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=jo(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 Us(e.base_)},setPrototypeOf(){Ur(12)}},mu={};_l(um,(e,t)=>{mu[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),mu.deleteProperty=function(e,t){return mu.set.call(this,e,t,void 0)},mu.set=function(e,t,n){return um.set.call(this,e[0],t,n,e[0])};function cm(e,t){const n=e[pr];return(n?jo(n):e)[t]}function QO(e,t,n){var i;const r=lb(t,n);return r?"value"in r?r.value:(i=r.get)==null?void 0:i.call(e.draft_):void 0}function lb(e,t){if(!(t in e))return;let n=Us(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Us(n)}}function lm(e){e.modified_||(e.modified_=!0,e.parent_&&lm(e.parent_))}function dm(e){e.copy_||(e.copy_=im(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var JO=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const s=n;n=t;const u=this;return function(d=s,...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 i;if(Uo(t)){const s=ab(this),u=fm(t,void 0);let c=!0;try{i=n(u),c=!1}finally{c?sm(s):am(s)}return sb(s,r),ub(i,s)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===tb&&(i=void 0),this.autoFreeze_&&om(i,!0),r){const s=[],u=[];Ho("Patches").generateReplacementPatches_(t,i,s,u),r(s,u)}return i}else Ur(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(u,...c)=>this.produceWithPatches(u,d=>t(d,...c));let r,i;return[this.produce(t,n,(u,c)=>{r=u,i=c}),r,i]},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){Uo(e)||Ur(8),js(e)&&(e=ZO(e));const t=ab(this),n=fm(e,void 0);return n[pr].isManual_=!0,am(t),n}finishDraft(e,t){const n=e&&e[pr];(!n||!n.isManual_)&&Ur(9);const{scope_:r}=n;return sb(r,t),ub(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 i=t[n];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}n>-1&&(t=t.slice(n+1));const r=Ho("Patches").applyPatches_;return js(e)?r(e,t):this.produce(e,i=>r(i,t))}};function fm(e,t){const n=fu(e)?Ho("MapSet").proxyMap_(e,t):Al(e)?Ho("MapSet").proxySet_(e,t):KO(e,t);return(t?t.scope_:ob()).drafts_.push(n),n}function ZO(e){return js(e)||Ur(10,e),db(e)}function db(e){if(!Uo(e)||Cl(e))return e;const t=e[pr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=im(e,t.scope_.immer_.useStrictShallowCopy_)}else n=im(e,!0);return _l(n,(r,i)=>{ib(n,r,db(i))}),t&&(t.finalized_=!1),n}var eP=new JO,tP=eP.produce;function nP(e,t,n){var r=_.useMemo(function(){return tP(e)},[e]);return _.useReducer(r,t,n)}const rP=e=>Array.from(new Set((e!=null?e:[]).map(t=>t.trim()).filter(Boolean))),fb=_.createContext(null),pb=_.createContext(null),iP=({children:e,dispatch:t})=>{const n=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_INITIALIZED,payload:x})},[t]),r=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_OPEN,payload:x})},[t]),i=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_INLINE,payload:x})},[t]),s=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ELEMENT_ID,payload:x})},[t]),u=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ENTRY_TYPE,payload:x})},[t]),c=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID,payload:x})},[t]),d=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_USER_PROMPT,payload:x})},[t]),f=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_PARAMS,payload:x})},[t]),m=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE,payload:x})},[t]),h=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE,payload:x})},[t]),y=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_RESPONSE_LOADING,payload:x})},[t]),E=_.useMemo(()=>({setIsInitialized:n,setIsOpen:r,setIsInline:i,setElementId:s,setEntryType:u,setActivePromptsId:c,setUserPrompt:d,setParams:f,setPromptsMessage:m,setResponseMessage:h,setIsResponseLoading:y}),[n,r,i,s,u,c,d,f,m,h,y]);return w.jsx(pb.Provider,{value:E,children:e})},oP=(e,t)=>{const{type:n,payload:r}=t;switch(n){case Ft.SET_PROMPTS_EXTENSION_INITIALIZED:e.isInitialized=r;break;case Ft.SET_PROMPTS_EXTENSION_OPEN:e.isOpen=r;break;case Ft.SET_PROMPTS_EXTENSION_INLINE:e.isInline=r;break;case Ft.SET_PROMPTS_EXTENSION_ELEMENT_ID:e.elementId=r;break;case Ft.SET_PROMPTS_EXTENSION_ENTRY_TYPE:e.entryType=r;break;case Ft.SET_PROMPTS_EXTENSION_PARAMS:e.params=r;break;case Ft.RESET_PROMPTS_EXTENSION_PARAMS:e.params=null;break;case Ft.SET_PROMPTS_EXTENSION_USER_PROMPT:e.userPrompt=r;break;case Ft.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=r;break;case Ft.RESET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=null;break;case Ft.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=r;break;case Ft.RESET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=null;break;case Ft.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=r;break;case Ft.RESET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=null;break;case Ft.SET_PROMPTS_EXTENSION_RESPONSE_LOADING:e.isResponseLoading=r;break}},sP=({promptsConfig:e,children:t})=>{const[n,r]=nP(oP,pe(B(B({},Ty),e||{}),{staticQuestions:rP((e==null?void 0:e.staticQuestions)||[])}));return w.jsx(fb.Provider,{value:n,children:w.jsx(iP,{dispatch:r,children:t})})},aP={productId:fr.productId,pdpLink:fr.pdpLink},mb=_.createContext(aP),uP=({children:e})=>{const[t,n]=_.useState(fr.productId),[r,i]=_.useState(fr.pdpLink);_.useEffect(()=>{const u=({detail:c})=>{if((c==null?void 0:c.property)==="pdp-context"){const d=c.value;n(d.productId),i(d.pdpLink);return}(c==null?void 0:c.property)==="productId"&&n(c.value),(c==null?void 0:c.property)==="pdpLink"&&i(c.value)};return L1(u),()=>{D1(u)}},[]);const s=_.useMemo(()=>({productId:t,pdpLink:r}),[t,r]);return w.jsx(mb.Provider,{value:s,children:e})},hb=({mode:e,apiKey:t,apiToken:n,baseUrl:r,logoUrl:i,headerText:s,headerConfig:u,theme:c,openLinksInNewTab:d,onNavigate:f,globalClassName:m,isDevelopment:h=!1,componentType:y,componentConfig:E,initialEntry:x,entryMessage:A,disclaimerText:k,disclaimerMarkdown:v,clientContext:N,searchPlaceholder:L,searchButtonLabel:P,searchConfig:z,suggestionButtonConfig:D,messageAlignment:q,autoScroll:V,promptsConfig:G,showProductDescription:I,resetConversationMessage:W,conversationHistory:Q,messagingConfig:K,translations:ae,overrides:oe,overridesUrl:he,inlineOverrides:se,__features:ee,children:ce})=>{var Oe,ne,be,_e;const O=h||iC(),j=_.useRef({}),te=_.useRef(!1);te.current||(te.current=!0,j.current=nC({enablePageContext:!!(K!=null&&K.enablePageContext),initialPageContext:K==null?void 0:K.initialPageContext,initialEntry:x,isDevelopment:O}));const M=(Oe=u==null?void 0:u.actions)==null?void 0:Oe.minimize,ge=_.useMemo(()=>M===void 0?E:pe(B({},E),{enableMinimize:yp(M,!!(E!=null&&E.enableMinimize))}),[E,M]);return w.jsx(mC,{translations:ae,children:w.jsx(mI,{mode:e,baseUrl:r,apiKey:t,apiToken:n,logoUrl:i,headerText:s,headerConfig:u,entryMessage:A,theme:c,globalClassName:m,openLinksInNewTab:d,onNavigate:f,searchPlaceholder:L,searchButtonLabel:P,searchConfig:z,suggestionButtonConfig:D,messageAlignment:q,autoScroll:V,showProductDescription:I,componentConfig:ge,clientContext:N,disclaimerMarkdown:v,disclaimerText:k,resetConversationMessage:W,conversationHistory:Q,isDevelopment:O,__features:ee,progressStepsLimit:K==null?void 0:K.progressStepsLimit,routingAttributes:K==null?void 0:K.routingAttributes,enableDownloadTranscript:yp((ne=u==null?void 0:u.actions)==null?void 0:ne.downloadTranscript,(be=K==null?void 0:K.enableDownloadTranscript)!=null?be:!0),enablePageContext:K==null?void 0:K.enablePageContext,enableEscalationToAgent:K==null?void 0:K.enableEscalationToAgent,enableImageUpload:K==null?void 0:K.enableImageUpload,showProductCaptions:K==null?void 0:K.showProductCaptions,connectingMessages:K==null?void 0:K.connectingMessages,children:w.jsx(QC,{entryType:(_e=j.current.entryType)!=null?_e:x==null?void 0:x.type,componentConfig:E,componentType:y,children:w.jsx(uP,{children:w.jsx(sP,{promptsConfig:G,children:w.jsx(cC,{overridesUrl:he,inlineOverrides:se||oe,children:w.jsx(eb,{scrt2Url:(K==null?void 0:K.scrt2Url)||"",orgId:(K==null?void 0:K.orgId)||"",esDeveloperName:(K==null?void 0:K.esDeveloperName)||"",routingAttributes:(K==null?void 0:K.routingAttributes)||{},conversationId:K==null?void 0:K.conversationId,continuationToken:K==null?void 0:K.continuationToken,lastEventId:K==null?void 0:K.lastEventId,capabilitiesVersion:K==null?void 0:K.capabilitiesVersion,enablePageContext:K==null?void 0:K.enablePageContext,enableLogging:O,onProductResult:K==null?void 0:K.onProductResult,onEndConversation:K==null?void 0:K.onEndConversation,onSessionUpdate:K==null?void 0:K.onSessionUpdate,cartTransport:K==null?void 0:K.cartTransport,storefrontCartPageUrl:K==null?void 0:K.storefrontCartPageUrl,children:w.jsx(fC,{children:ce})})})})})})})})};var pm={exports:{}},nr={},mm={exports:{}},hm={};var gb;function cP(){return gb||(gb=1,(function(e){function t(ee,ce){var O=ee.length;ee.push(ce);e:for(;0<O;){var j=O-1>>>1,te=ee[j];if(0<i(te,ce))ee[j]=ce,ee[O]=te,O=j;else break e}}function n(ee){return ee.length===0?null:ee[0]}function r(ee){if(ee.length===0)return null;var ce=ee[0],O=ee.pop();if(O!==ce){ee[0]=O;e:for(var j=0,te=ee.length,M=te>>>1;j<M;){var ge=2*(j+1)-1,Oe=ee[ge],ne=ge+1,be=ee[ne];if(0>i(Oe,O))ne<te&&0>i(be,Oe)?(ee[j]=be,ee[ne]=O,j=ne):(ee[j]=Oe,ee[ge]=O,j=ge);else if(ne<te&&0>i(be,O))ee[j]=be,ee[ne]=O,j=ne;else break e}}return ce}function i(ee,ce){var O=ee.sortIndex-ce.sortIndex;return O!==0?O:ee.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var d=[],f=[],m=1,h=null,y=3,E=!1,x=!1,A=!1,k=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function L(ee){for(var ce=n(f);ce!==null;){if(ce.callback===null)r(f);else if(ce.startTime<=ee)r(f),ce.sortIndex=ce.expirationTime,t(d,ce);else break;ce=n(f)}}function P(ee){if(A=!1,L(ee),!x)if(n(d)!==null)x=!0,he(z);else{var ce=n(f);ce!==null&&se(P,ce.startTime-ee)}}function z(ee,ce){x=!1,A&&(A=!1,v(V),V=-1),E=!0;var O=y;try{for(L(ce),h=n(d);h!==null&&(!(h.expirationTime>ce)||ee&&!W());){var j=h.callback;if(typeof j=="function"){h.callback=null,y=h.priorityLevel;var te=j(h.expirationTime<=ce);ce=e.unstable_now(),typeof te=="function"?h.callback=te:h===n(d)&&r(d),L(ce)}else r(d);h=n(d)}if(h!==null)var M=!0;else{var ge=n(f);ge!==null&&se(P,ge.startTime-ce),M=!1}return M}finally{h=null,y=O,E=!1}}var D=!1,q=null,V=-1,G=5,I=-1;function W(){return!(e.unstable_now()-I<G)}function Q(){if(q!==null){var ee=e.unstable_now();I=ee;var ce=!0;try{ce=q(!0,ee)}finally{ce?K():(D=!1,q=null)}}else D=!1}var K;if(typeof N=="function")K=function(){N(Q)};else if(typeof MessageChannel!="undefined"){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=Q,K=function(){oe.postMessage(null)}}else K=function(){k(Q,0)};function he(ee){q=ee,D||(D=!0,K())}function se(ee,ce){V=k(function(){ee(e.unstable_now())},ce)}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(ee){ee.callback=null},e.unstable_continueExecution=function(){x||E||(x=!0,he(z))},e.unstable_forceFrameRate=function(ee){0>ee||125<ee?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<ee?Math.floor(1e3/ee):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(ee){switch(y){case 1:case 2:case 3:var ce=3;break;default:ce=y}var O=y;y=ce;try{return ee()}finally{y=O}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(ee,ce){switch(ee){case 1:case 2:case 3:case 4:case 5:break;default:ee=3}var O=y;y=ee;try{return ce()}finally{y=O}},e.unstable_scheduleCallback=function(ee,ce,O){var j=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?j+O:j):O=j,ee){case 1:var te=-1;break;case 2:te=250;break;case 5:te=1073741823;break;case 4:te=1e4;break;default:te=5e3}return te=O+te,ee={id:m++,callback:ce,priorityLevel:ee,startTime:O,expirationTime:te,sortIndex:-1},O>j?(ee.sortIndex=O,t(f,ee),n(d)===null&&ee===n(f)&&(A?(v(V),V=-1):A=!0,se(P,O-j))):(ee.sortIndex=te,t(d,ee),x||E||(x=!0,he(z))),ee},e.unstable_shouldYield=W,e.unstable_wrapCallback=function(ee){var ce=y;return function(){var O=y;y=ce;try{return ee.apply(this,arguments)}finally{y=O}}}})(hm)),hm}var yb;function lP(){return yb||(yb=1,mm.exports=cP()),mm.exports}var Eb;function dP(){if(Eb)return nr;Eb=1;var e=Fr(),t=lP();function n(o){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+o,l=1;l<arguments.length;l++)a+="&args[]="+encodeURIComponent(arguments[l]);return"Minified React error #"+o+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function s(o,a){u(o,a),u(o+"Capture",a)}function u(o,a){for(i[o]=a,o=0;o<a.length;o++)r.add(a[o])}var c=!(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={},h={};function y(o){return d.call(h,o)?!0:d.call(m,o)?!1:f.test(o)?h[o]=!0:(m[o]=!0,!1)}function E(o,a,l,p){if(l!==null&&l.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return p?!1:l!==null?!l.acceptsBooleans:(o=o.toLowerCase().slice(0,5),o!=="data-"&&o!=="aria-");default:return!1}}function x(o,a,l,p){if(a===null||typeof a=="undefined"||E(o,a,l,p))return!0;if(p)return!1;if(l!==null)switch(l.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function A(o,a,l,p,b,T,C){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=p,this.attributeNamespace=b,this.mustUseProperty=l,this.propertyName=o,this.type=a,this.sanitizeURL=T,this.removeEmptyString=C}var k={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(o){k[o]=new A(o,0,!1,o,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(o){var a=o[0];k[a]=new A(a,1,!1,o[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(o){k[o]=new A(o,2,!1,o.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(o){k[o]=new A(o,2,!1,o,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(o){k[o]=new A(o,3,!1,o.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(o){k[o]=new A(o,3,!0,o,null,!1,!1)}),["capture","download"].forEach(function(o){k[o]=new A(o,4,!1,o,null,!1,!1)}),["cols","rows","size","span"].forEach(function(o){k[o]=new A(o,6,!1,o,null,!1,!1)}),["rowSpan","start"].forEach(function(o){k[o]=new A(o,5,!1,o.toLowerCase(),null,!1,!1)});var v=/[\-:]([a-z])/g;function N(o){return o[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(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(o){k[o]=new A(o,1,!1,o.toLowerCase(),null,!1,!1)}),k.xlinkHref=new A("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(o){k[o]=new A(o,1,!1,o.toLowerCase(),null,!0,!0)});function L(o,a,l,p){var b=k.hasOwnProperty(a)?k[a]:null;(b!==null?b.type!==0:p||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(x(a,l,b,p)&&(l=null),p||b===null?y(a)&&(l===null?o.removeAttribute(a):o.setAttribute(a,""+l)):b.mustUseProperty?o[b.propertyName]=l===null?b.type===3?!1:"":l:(a=b.attributeName,p=b.attributeNamespace,l===null?o.removeAttribute(a):(b=b.type,l=b===3||b===4&&l===!0?"":""+l,p?o.setAttributeNS(p,a,l):o.setAttribute(a,l))))}var P=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,z=Symbol.for("react.element"),D=Symbol.for("react.portal"),q=Symbol.for("react.fragment"),V=Symbol.for("react.strict_mode"),G=Symbol.for("react.profiler"),I=Symbol.for("react.provider"),W=Symbol.for("react.context"),Q=Symbol.for("react.forward_ref"),K=Symbol.for("react.suspense"),ae=Symbol.for("react.suspense_list"),oe=Symbol.for("react.memo"),he=Symbol.for("react.lazy"),se=Symbol.for("react.offscreen"),ee=Symbol.iterator;function ce(o){return o===null||typeof o!="object"?null:(o=ee&&o[ee]||o["@@iterator"],typeof o=="function"?o:null)}var O=Object.assign,j;function te(o){if(j===void 0)try{throw Error()}catch(l){var a=l.stack.trim().match(/\n( *(at )?)/);j=a&&a[1]||""}return`
16
+ `+u)}}catch(i){}throw r}})}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Mo(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&gl.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),i!=null&&(X.isFunction(i)?n.paramsSerializer={serialize:i}:gl.assertOptions(i,{encode:Ln.function,serialize:Ln.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),gl.assertOptions(n,{baseUrl:Ln.spelling("baseURL"),withXsrfToken:Ln.spelling("withXSRFToken")},!0),n.method=(X.getSafeProp(n,"method")||X.getSafeProp(this.defaults,"method")||"get").toLowerCase();let u=s&&X.merge(s.common,s[n.method]);s&&X.forEach(Ky.concat("common"),x=>{delete s[x]}),n.headers=Rn.concat(u,s);const c=[];let d=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(n)===!1)return;d=d&&A.synchronous;const k=n.transitional||Pp;k&&k.legacyInterceptorReqResOrdering?c.unshift(A.fulfilled,A.rejected):c.push(A.fulfilled,A.rejected)});const f=[];this.interceptors.response.forEach(function(A){f.push(A.fulfilled,A.rejected)});let m,h=0,y;if(!d){const x=[jp.bind(this),void 0];for(x.unshift(...c),x.push(...f),y=x.length,m=Promise.resolve(n);h<y;)m=m.then(x[h++],x[h++]);return m}y=c.length;let E=n;for(;h<y;){const x=c[h++],A=c[h++];try{E=x?x(E):E}catch(k){if(!A){m=Promise.reject(k);break}try{const v=A.call(this,k);X.isThenable(v)&&(m=Promise.resolve(v).then(()=>jp.call(this,E)))}catch(v){m=Promise.reject(v)}break}}if(!m)try{m=jp.call(this,E)}catch(x){m=Promise.reject(x)}for(h=0,y=f.length;h<y;)m=m.then(f[h++],f[h++]);return m}getUri(t){t=Mo(this.defaults,t);const n=rE(t.baseURL,t.url,t.allowAbsoluteUrls,t);return zy(n,t.params,t.paramsSerializer)}};X.forEach(["delete","get","head","options"],function(t){Fo.prototype[t]=function(n,r){return this.request(Mo(r||{},{method:t,url:n,data:r&&X.hasOwnProp(r,"data")?r.data:void 0}))}}),X.forEach(["post","put","patch","query"],function(t){function n(r){return function(s,u,c){return this.request(Mo(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:u}))}}Fo.prototype[t]=n(),t!=="query"&&(Fo.prototype[t+"Form"]=n(!0))});let uI=class HA{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const u=new Promise(c=>{r.subscribe(c),s=c}).then(i);return u.cancel=function(){r.unsubscribe(s)},u},t(function(s,u,c){r.reason||(r.reason=new au(s,u,c),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 HA(function(i){t=i}),cancel:t}}};function cI(e){return function(n){return e.apply(null,n)}}function lI(e){return X.isObject(e)&&e.isAxiosError===!0}const yl={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(yl).forEach(([e,t])=>{yl[t]===void 0&&(yl[t]=e)});function yE(e){const t=new Fo(e),n=vy(Fo.prototype.request,t);return X.extend(n,Fo.prototype,t,{allOwnKeys:!0}),X.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return yE(Mo(e,i))},n}const tn=yE(su);tn.Axios=Fo,tn.CanceledError=au,tn.CancelToken=uI,tn.isCancel=Qy,tn.VERSION=Fp,tn.toFormData=fl,tn.AxiosError=Pe,tn.Cancel=tn.CanceledError,tn.all=function(t){return Promise.all(t)},tn.spread=cI,tn.isAxiosError=lI,tn.mergeConfig=Mo,tn.AxiosHeaders=Rn,tn.formToJSON=e=>Xy(X.isHTMLForm(e)?new FormData(e):e),tn.getAdapter=hE.getAdapter,tn.HttpStatusCode=yl,tn.default=tn;const{Axios:Mq,AxiosError:Fq,CanceledError:Bq,isCancel:Uq,CancelToken:jq,VERSION:Hq,all:$q,Cancel:zq,isAxiosError:Vq,spread:qq,toFormData:Wq,AxiosHeaders:Yq,HttpStatusCode:Gq,formToJSON:Xq,getAdapter:Kq,mergeConfig:Qq,create:Jq}=tn;class dI{constructor(t,n,r,i=!1,s,u){Ze(this,"CIMULATE_API_HEADER","x-cimulate-api-key");Ze(this,"CIMULATE_SEARCH_API_HOST","search.cimulate");Ze(this,"CIMULATE_SEARCH_API_PATH","api/v1");Ze(this,"baseApiUrl");Ze(this,"headers",{});Ze(this,"fetchConfig",()=>Ce(this,null,function*(){try{const t=yield tn.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}}));Ze(this,"_mapCopilotUrlToSearchUrl",(t="",n=!1)=>{if(t.endsWith("io")){const i=new URL(t);return i.hostname=i.hostname.replace(/^copilot\./,"api."),i.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}`),s&&(this.headers["x-cimulate-customer-id"]=s),u&&(this.headers["Tenant-ID"]=u),this.baseApiUrl=this._mapCopilotUrlToSearchUrl(t,i)}get apiUrl(){return`${this.baseApiUrl}/${this.CIMULATE_SEARCH_API_PATH}`}}class fI{constructor(t,n,r,i=!1,s,u){Ze(this,"apiService");Ze(this,"config",null);Ze(this,"getConfig",()=>Ce(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}}));Ze(this,"getPid",t=>this.getProductFieldValue(t,"pidCol"));Ze(this,"getName",t=>this.getProductFieldValue(t,"nameCol"));Ze(this,"getDescription",t=>this.getProductFieldValue(t,"description"));Ze(this,"getBrand",t=>this.getProductFieldValue(t,"productBrandCol"));Ze(this,"getPrice",t=>this.getProductFieldValue(t,"priceCol"));Ze(this,"getRelativePdp",t=>this.getProductFieldValue(t,"relativePdpCol"));Ze(this,"getPdp",t=>this.getProductFieldValue(t,"pdpCol"));Ze(this,"getImage",t=>this.getProductFieldValue(t,"imageCol"));Ze(this,"getProductHiddenFields",()=>{const t=this.getProductField("productHiddenFields");return Array.isArray(t)?t:[]});Ze(this,"getProductField",t=>this.config?this.config[t]:"");Ze(this,"getProductFieldValue",(t,n)=>{const r=this.getProductField(n);return r&&t[r]||""});this.apiService=new dI(t,n,r,i,s,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 pI={copilot:"Your Search Assistant",messaging:"Commerce Client"},EE=_.createContext(null),mI=({mode:e,logoUrl:t,headerText:n,headerConfig:r,globalClassName:i="",entryMessage:s,openLinksInNewTab:u=!1,onNavigate:c,disclaimerText:d,disclaimerMarkdown:f,clientContext:m,baseCatalogParams:h,searchPlaceholder:y,searchButtonLabel:E,searchConfig:x,suggestionButtonConfig:A,progressStepsLimit:k=3,messageAlignment:v="start",autoScroll:N=!0,showProductDescription:L=!1,componentConfig:P,conversationHistory:z,resetConversationMessage:D="",apiKey:q,apiToken:V,baseUrl:G,customerId:I,tenantId:W,theme:Q,isDevelopment:K,__features:ae,routingAttributes:oe,enableDownloadTranscript:he=!0,enablePageContext:se=!1,enableEscalationToAgent:ee=!1,enableImageUpload:ce=!1,showProductCaptions:O=!1,connectingMessages:j,staticQuestions:te,staticQuestionsStrategy:M="append",children:ge})=>{const Oe=e==="messaging",ne=_.useMemo(()=>{const Xe=oe==null?void 0:oe.isCartMgmtSupported;return Xe===!0||Xe==="true"},[oe]),be=_.useMemo(()=>Oe?{config:null}:new fI(G,q,V,K,I,W),[Oe,G,q,V,K,I,W]),_e=_.useMemo(()=>new Mk(K),[K]);_.useEffect(()=>{Oe||!be||be.config||be.getConfig()},[be,Oe]);const je=_.useMemo(()=>Q1(Q),[Q]),ft=je.cssVariables,It=_.useMemo(()=>{const Xe=(x==null?void 0:x.placeholder)||y,Zt=(x==null?void 0:x.buttonLabel)||E;let qe="icon";return x!=null&&x.buttonType?qe=x.buttonType:E&&(qe="text"),pe(B({},x||{}),{placeholder:Xe,buttonLabel:Zt,buttonType:qe})},[x,y,E]),bt=_.useMemo(()=>pe(B({},r||{}),{logoUrl:t||(r==null?void 0:r.logoUrl),headerText:(r==null?void 0:r.headerText)||n||pI[e!=null?e:"copilot"]}),[r,t,n,e]),Ge=_.useMemo(()=>({configModule:be,mode:e!=null?e:"copilot",themeVariants:je.compatibility&&e!=="messaging"?pe(B({},je.variants),{carousel:"chevron"}):je.variants,themeTokens:je.compatibility==="legacy"?void 0:je.tokens,themeClassName:je.transcriptClassName,headerConfig:bt,entryMessage:s,staticQuestions:te||[],staticQuestionsStrategy:M,globalClassName:i,openLinksInNewTab:u,onNavigate:c,disclaimerText:d,disclaimerMarkdown:f,clientContext:m,baseCatalogParams:h,themeVariables:ft,logger:_e,searchConfig:It,suggestionButtonConfig:A,progressStepsLimit:k,messageAlignment:v,autoScroll:N,showProductDescription:!!L,enableMinimize:!!(P!=null&&P.enableMinimize),launcherAriaLabel:P==null?void 0:P.launcherAriaLabel,enableDownloadTranscript:he,enablePageContext:se,enableEscalationToAgent:ee,enableImageUpload:ce,showProductCaptions:!!O,connectingMessages:j,resetConversationMessage:D,conversationHistory:{sinceHours:typeof(z==null?void 0:z.sinceHours)=="number"?z.sinceHours:Oe?24:1,limit:z==null?void 0:z.limit},features:ae,isCartMgmtSupported:ne}),[be,e,bt,s,te,M,i,m,h,d,f,u,c,It,A,v,N,L,P,he,se,ee,ce,k,O,j,D,_e,ft,je,z,ae,ne,Oe]);return w.jsx(EE.Provider,{value:Ge,children:ge})},at=()=>{const e=_.useContext(EE);if(!e)throw new Error("useConfig must be used within a ConfigProvider");return e},bE=["markdown","product_carousel","product_tile","product_comparison","suggestions","cart","order_confirmation","tool_results"],Yi=-1;function Hp(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 wE(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"&&bE.includes(t.type))return t;const n=Hp(t);return n?{type:"markdown",index:Yi,data:{content:n}}:null}}catch(t){}return{type:"markdown",index:Yi,data:{content:e}}}function El(e){let t;try{t=JSON.parse(e)}catch(i){return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;if(typeof n.type!="string"||!bE.includes(n.type))return null;const r=typeof n.index=="number"?n.index:0;return pe(B({},n),{type:n.type,index:r})}function Ls(e){let t;try{t=JSON.parse(e)}catch(n){return null}return t&&typeof t=="object"&&Array.isArray(t.response)?t:null}function $p(e){var i,s;if(e.type!=="markdown")return[e];const t=(s=(i=e.data)==null?void 0:i.content)!=null?s:"",n=Ls(t);if(n)return n.response;const r=El(t);return[r&&r.type!=="markdown"?r:e]}function uu(e){const t=Ls(e);if(t)return t.response.flatMap($p);const n=El(e);return n?$p(n):[]}function xE(e,t){return uu(e).some(n=>n.type===t)}function hI(e){return uu(e).map(t=>t.type)}function gI(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.role==="agent"&&xE(r.content,t))return r.id}}function TE(e){const t=e.trimStart();if(!t.startsWith("{")&&!t.startsWith("["))return!1;try{return JSON.parse(e),!1}catch(n){return!0}}function yI(e){return e.type==="markdown"&&e.index===Yi?!TE(e.data.content):!0}function EI(e){var i;const t=(i=Ls(e))==null?void 0:i.response;if(!t)return null;const n=t.find(s=>s.type==="product_carousel");if(n)return{kind:"search",productIds:n.data.products.map(s=>s.id)};const r=t.find(s=>s.type==="product_tile");return r?{kind:"detail",productIds:[r.data.id]}:null}function bI(e){var s,u,c,d,f;const t=uu(e).find(m=>m.type==="product_tile");if(!t)return null;const n=(u=(s=t.data)==null?void 0:s.id)==null?void 0:u.trim();if(!n)return null;const r=t.data.data,i=(r==null?void 0:r.imageUrl)||((d=(c=r==null?void 0:r.imgGroups)==null?void 0:c.filter(m=>{var h;return((h=m.viewType)==null?void 0:h.toLowerCase())!=="swatch"}).flatMap(m=>{var h;return(h=m.imgs)!=null?h:[]}).find(m=>{var h;return(h=m.url)==null?void 0:h.trim()}))==null?void 0:d.url);return B({type:"pdp",id:n,name:((f=r==null?void 0:r.name)==null?void 0:f.trim())||n},i?{imageUrl:Ja(r==null?void 0:r.baseUrl,i)}:{})}function vE(e){var n,r,i,s,u,c,d,f,m,h;const t=uu(e).find(y=>y.type==="cart");return t?{status:(c=(u=(r=(n=t.data)==null?void 0:n.cart)==null?void 0:r.__action_execution_status__)!=null?u:(s=(i=t.data)==null?void 0:i.cart)==null?void 0:s.action_execution_status)!=null?c:null,cartDetails:(h=(m=(f=(d=t.data)==null?void 0:d.cart)==null?void 0:f.cartSummary)==null?void 0:m.cartDetails)!=null?h:null}:null}function wI(e){var i,s,u;const t=uu(e).find(c=>c.type==="cart"),n=(u=(s=(i=t==null?void 0:t.data)==null?void 0:i.cart)==null?void 0:s.cartSummary)==null?void 0:u.cartOperation,r=typeof n=="string"?n.toLowerCase():null;return r==="add"||r==="remove"?r:null}function xI(e,t){if(t.index===Yi){const i=e[e.length-1];if(i&&i.type==="markdown"&&i.index===Yi&&t.type==="markdown"){const s={type:"markdown",index:Yi,data:{content:i.data.content+t.data.content}};return[...e.slice(0,-1),s]}return[...e,t]}const n=e.findIndex(i=>i.index===t.index);return[...n>=0?e.map((i,s)=>s===n?t:i):[...e,t]].sort((i,s)=>i.index-s.index)}function _E(e,t){return t.serverId!==void 0&&e.some(n=>n.serverId===t.serverId)}const SE={connectionStatus:"disconnected",loading:!1,humanHandoff:!1,conversationId:null,messagingSessionId:null,messages:[],streamingBlocks:[],isAgentTyping:!1,progressMessage:"",progressSteps:[],routingResult:null,error:null,sendError:null,sessionExpired:!1};function TI(e,t){switch(t.type){case"SET_CONNECTION_STATUS":return B(pe(B({},e),{connectionStatus:t.status}),t.status==="connected"||t.status==="connecting"?{error:null}:{});case"SET_HUMAN_HANDOFF":return pe(B({},e),{humanHandoff:t.active,loading:!1,isAgentTyping:!1,progressMessage:"",progressSteps:[]});case"SET_LOADING":return pe(B({},e),{loading:t.isLoading});case"SET_CONVERSATION_ID":return e.conversationId===t.id?e:pe(B({},e),{conversationId:t.id,messagingSessionId:null});case"SET_MESSAGING_SESSION_ID":return e.messagingSessionId===t.id?e:pe(B({},e),{messagingSessionId:t.id});case"ADD_MESSAGE":return _E(e.messages,t.message)?e:pe(B({},e),{messages:[...e.messages,pe(B({},t.message),{type:"ADD_MESSAGE"})]});case"UPDATE_MESSAGE":return pe(B({},e),{messages:e.messages.map(n=>n.id===t.id?B(B({},n),t.patch):n)});case"APPEND_STREAMING_TOKEN":{const n=wE(t.token);return n?pe(B({},e),{streamingBlocks:xI(e.streamingBlocks,n)}):e}case"FLUSH_STREAMING":{const n={streamingBlocks:[],isAgentTyping:!1,loading:!1,progressMessage:"",progressSteps:[],sendError:e.humanHandoff?e.sendError:null};if(_E(e.messages,t.message))return B(B({},e),n);const r=pe(B({},t.message),{type:"FLUSH_STREAMING"}),i=t.replaceMessageId?e.messages.findIndex(s=>s.id===t.replaceMessageId):-1;if(i>=0){const s=[...e.messages];return s[i]=pe(B({},r),{id:e.messages[i].id}),B(pe(B({},e),{messages:s}),n)}return B(pe(B({},e),{messages:[...e.messages,r]}),n)}case"SET_AGENT_TYPING":return pe(B({},e),{isAgentTyping:t.isTyping,loading:e.humanHandoff?e.loading:t.isTyping});case"SET_PROGRESS_MESSAGE":return B(pe(B({},e),{progressMessage:t.message}),t.message===""?{progressSteps:[]}:{});case"ADD_PROGRESS_STEP":return e.progressSteps[e.progressSteps.length-1]===t.message?e:pe(B({},e),{progressSteps:[...e.progressSteps,t.message],progressMessage:t.message});case"SET_ROUTING_RESULT":return pe(B({},e),{routingResult:t.result});case"SET_ERROR":return pe(B({},e),{error:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"SET_SEND_ERROR":return pe(B({},e),{sendError:t.error,loading:!1,progressMessage:"",progressSteps:[]});case"CLEAR_SEND_ERROR":return pe(B({},e),{sendError:null});case"LOAD_HISTORY":return pe(B({},e),{messages:t.messages.map(n=>pe(B({},n),{restored:!0})),loading:!1});case"SET_SESSION_EXPIRED":return pe(B({},e),{sessionExpired:t.expired});case"RESET":return pe(B({},SE),{connectionStatus:e.connectionStatus});default:return e}}const vI=e=>typeof e=="string"?e:e.code,AE=e=>{var t;return((t=e==null?void 0:e.couponsApplied)!=null?t:[]).map(vI)},kE=e=>{var n;const t=new Map;for(const r of(n=e==null?void 0:e.items)!=null?n:[])t.set(r.itemId,r);return t};function _I(e,t){const n=kE(e),r=kE(t),i=[];for(const[f,m]of r){const h=n.get(f);h?h.quantity!==m.quantity&&i.push({type:"quantity",itemId:f,productId:m.productId,name:m.name,quantityBefore:h.quantity,quantityAfter:m.quantity}):i.push({type:"add",itemId:f,productId:m.productId,name:m.name,quantityBefore:0,quantityAfter:m.quantity})}for(const[f,m]of n)r.has(f)||i.push({type:"remove",itemId:f,productId:m.productId,name:m.name,quantityBefore:m.quantity,quantityAfter:0});const s=AE(e),u=AE(t),c=u.filter(f=>!s.includes(f)),d=s.filter(f=>!u.includes(f));if(c.length||d.length){const f={type:"coupon",added:c,removed:d};i.push(f)}return i}function SI(e){if(e.length===0)return"unknown";const t=new Set(e.map(n=>n.type));if(t.size===1){const[n]=[...t];return n}return"mixed"}function CE(e,t,n=null){if(!e&&t&&n)return{status:"success",action:n,changes:[]};if(!e||!t)return{status:"success",action:"unknown",changes:[]};const r=_I(e,t);return{status:"success",action:SI(r),changes:r}}let zp=null;function AI(){const e=zp;return zp=null,e}function kI(e){!e||typeof e!="object"||!Array.isArray(e.items)||(zp=e,window.dispatchEvent(new CustomEvent(Qa,{detail:e})))}const NE=4320*60*1e3;function Vp(e,t){return`cim_af_conv_${e}_${t}`}function qp(e,t){return Date.now()-e>t}function Wp(e,t,n){try{const r=Vp(e,t),i=localStorage.getItem(r);if(!i)return null;const s=JSON.parse(i);if(!s||typeof s!="object"||!("conversationId"in s)||!("storedAt"in s))return null;const u=s;return typeof u.conversationId!="string"||!u.conversationId?null:typeof u.storedAt!="number"||qp(u.storedAt,n)?(localStorage.removeItem(r),null):u}catch(r){return null}}function cu(e,t,n){try{const r=Vp(e,t),i={conversationId:n,storedAt:Date.now()};localStorage.setItem(r,JSON.stringify(i))}catch(r){}}function Yp(e,t){try{const n=Vp(e,t);localStorage.removeItem(n)}catch(n){}}function Gp(e,t){return`cim_af_ct_${e}_${t}`}function CI(e){try{const t=e.split(".")[1];if(!t)return null;const n=JSON.parse(NI(t));return typeof n.exp=="number"?n.exp*1e3:null}catch(t){return null}}function IE(e){const t=CI(e);return t===null?"unknown":Date.now()>=t?"expired":"valid"}function NI(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(t.length+(4-t.length%4)%4,"=");return atob(n)}function Xp(e,t){try{const n=Gp(e,t),r=localStorage.getItem(n);if(!r)return null;const i=JSON.parse(r);if(!i||typeof i!="object"||!("accessToken"in i)||!("lastEventId"in i)||!("storedAt"in i))return null;const s=i;return typeof s.accessToken!="string"||!s.accessToken||typeof s.lastEventId!="string"||typeof s.storedAt!="number"?null:IE(s.accessToken)==="expired"?(localStorage.removeItem(n),null):s}catch(n){return null}}function OE(e,t,n,r){try{const i=Gp(e,t),s={accessToken:n,lastEventId:r,storedAt:Date.now()};localStorage.setItem(i,JSON.stringify(s))}catch(i){}}function II(e,t){try{const n=Gp(e,t);localStorage.removeItem(n)}catch(n){}}function OI(e,t){return`cim_af_conv_${e}_${t}`}function PI(e,t){try{if(typeof BroadcastChannel=="undefined")return null;const n=OI(e,t);return new BroadcastChannel(n)}catch(n){return null}}function RI(e,t=500){return e?new Promise(n=>{let r=!1;const i=setTimeout(()=>{r||(r=!0,e.removeEventListener("message",s),n(null))},t);function s(u){var c;r||((c=u.data)==null?void 0:c.type)==="conversation_response"&&(r=!0,clearTimeout(i),e.removeEventListener("message",s),n({conversationId:u.data.conversationId,storedAt:u.data.storedAt,continuationToken:u.data.continuationToken,lastEventId:u.data.lastEventId}))}e.addEventListener("message",s);try{e.postMessage({type:"request_conversation"})}catch(u){r||(r=!0,clearTimeout(i),e.removeEventListener("message",s),n(null))}}):Promise.resolve(null)}function LI(e,t,n){if(!e)return()=>{};function r(i){var s;if((s=i.data)!=null&&s.type)switch(i.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(c){}break}case"conversation_cleared":{n==null||n();break}}}return e.addEventListener("message",r),()=>{e.removeEventListener("message",r)}}function DI(e){if(e)try{e.postMessage({type:"conversation_cleared"})}catch(t){}}function MI(e){if(e)try{e.close()}catch(t){}}function bl(e){switch(e){case"Agent":return!0;case"Chatbot":return!1;default:return}}function PE(e){if(!e||typeof e!="object")return;const t=e;if(String(t.routingType).toLowerCase()!=="transfer")return;const n=t.routingConfigurationDetails;return(n==null?void 0:n.routingConfigurationType)!=="BotRoutingType"}function RE(e){var r,i,s,u,c;let t=!1;const n=[...e].sort((d,f)=>d.transcriptedTimestamp-f.transcriptedTimestamp);for(const d of n){let f;try{if(f=typeof d.entryPayload=="string"?JSON.parse(d.entryPayload):d.entryPayload,!f||typeof f!="object")continue}catch(m){continue}if(d.entryType==="RoutingResult")(!f.failureType||["None","NO_ERROR"].includes(String(f.failureType)))&&(t=(r=PE(f))!=null?r:t);else if(d.entryType==="ParticipantChanged"&&Array.isArray(f.entries))for(const m of f.entries)!m||typeof m!="object"||["","add","join","joined","transfer"].includes(String((s=(i=m.operation)!=null?i:m.event)!=null?s:"").toLowerCase())&&(t=(c=bl((u=m.participant)==null?void 0:u.role))!=null?c:t);else d.entryType==="Message"?bl(d.sender.role)===!0&&(t=!0):d.entryType==="CloseConversation"&&(t=!1)}return t}function FI(e){switch(e){case"EndUser":case"Customer":return"user";case"Agent":case"Chatbot":return"agent";default:return"system"}}function BI(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch(t){return{}}return e}function LE(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 UI(e){const t=e.staticContent;if(!t||typeof t!="object")return!1;const n=t.attachments;return Array.isArray(n)&&n.length>0}function jI(e){if(e.entryType!=="Message")return null;const n=BI(e.entryPayload).abstractMessage;if(!n)return null;const r=LE(n,"staticContent","text")||LE(n,"content","text")||"";if(!r&&!UI(n))return null;const i=FI(e.sender.role);return{id:e.identifier,serverId:e.identifier,role:i,content:r,timestamp:new Date(e.transcriptedTimestamp).toISOString(),sender:{role:e.sender.role,name:e.senderDisplayName}}}function HI(e){const t=[];for(const n of e){const r=jI(n);r&&t.push(r)}return t}function Kp(e,t,n){return`cim_af_dividers_${e}_${t}_${n}`}function DE(e,t,n){try{const r=Kp(e,t,n),i=localStorage.getItem(r);if(!i)return{};const s=JSON.parse(i);return!s||typeof s.storedAt!="number"||Date.now()-s.storedAt>NE||!s.byMessageId||typeof s.byMessageId!="object"?(localStorage.removeItem(r),{}):s.byMessageId}catch(r){return{}}}function $I(e,t,n,r,i){if(!(!n||!r))try{const s=Kp(e,t,n),u=DE(e,t,n);localStorage.setItem(s,JSON.stringify({storedAt:Date.now(),byMessageId:pe(B({},u),{[r]:i})}))}catch(s){}}function zI(e,t,n){try{localStorage.removeItem(Kp(e,t,n))}catch(r){return}}const VI="cim_widget_thumbnails",wl="thumbnails",qI=1,Qp="byConversation",ME="byStoredAt",WI=2e3;function YI(e,t){return`${e}::${t}`}function GI(){return new Promise(e=>{try{if(typeof indexedDB=="undefined"||!indexedDB){e(null);return}let t=!1;const n=s=>{t||(t=!0,e(s))},r=setTimeout(()=>n(null),WI),i=indexedDB.open(VI,qI);i.onupgradeneeded=()=>{const s=i.result;if(!s.objectStoreNames.contains(wl)){const u=s.createObjectStore(wl,{keyPath:"key"});u.createIndex(Qp,"conversationId",{unique:!1}),u.createIndex(ME,"storedAt",{unique:!1})}},i.onsuccess=()=>{clearTimeout(r),n(i.result)},i.onerror=()=>{clearTimeout(r),n(null)},i.onblocked=()=>{clearTimeout(r),n(null)}}catch(t){e(null)}})}function xl(e,t,n){return Ce(this,null,function*(){const r=yield GI();return r?new Promise(i=>{let s=t,u=!1;const c=d=>{u||(u=!0,i(d))};try{const d=r.transaction(wl,e),f=d.objectStore(wl);d.oncomplete=()=>{r.close(),c(s)},d.onerror=()=>{r.close(),c(t)},d.onabort=()=>{r.close(),c(t)},n(f,m=>{s=m})}catch(d){try{r.close()}catch(f){}c(t)}}):t})}function XI(e,t,n){return Ce(this,null,function*(){if(!e||!t||!n)return;const r={key:YI(e,t),conversationId:e,messageId:t,dataUrl:n,storedAt:Date.now()};yield xl("readwrite",void 0,i=>{i.put(r)})})}function KI(e){return Ce(this,null,function*(){return e?xl("readonly",{},(t,n)=>{const r={},s=t.index(Qp).openCursor(IDBKeyRange.only(e));s.onsuccess=()=>{const u=s.result;if(u){const c=u.value;c!=null&&c.messageId&&(c!=null&&c.dataUrl)&&(r[c.messageId]=c.dataUrl),u.continue()}else n(r)}}):{}})}function FE(e){return Ce(this,null,function*(){e&&(yield xl("readwrite",void 0,t=>{const r=t.index(Qp).openCursor(IDBKeyRange.only(e));r.onsuccess=()=>{const i=r.result;i&&(i.delete(),i.continue())}}))})}function QI(e){return Ce(this,null,function*(){const t=Date.now()-e;yield xl("readwrite",void 0,n=>{const i=n.index(ME).openCursor(IDBKeyRange.upperBound(t,!0));i.onsuccess=()=>{const s=i.result;s&&(s.delete(),s.continue())}})})}const JI=5e3,lu=Symbol("cimulate-abort-conversation");function Tl(e={}){const{routingAttributes:t,timeoutMs:n=JI}=e;if(typeof window=="undefined"||typeof window.dispatchEvent!="function")return Promise.resolve(t);const r=B({},t!=null?t:{});return new Promise(i=>{const s={settled:!1},u=()=>{if(s.settled)return;s.settled=!0,s.timer!==void 0&&clearTimeout(s.timer);const h=Object.keys(r).length>0;i(h?r:t)},d={routingAttributes:t,setHiddenPrechatFields:h=>{s.settled||!h||Object.assign(r,h)},done:u,abort:()=>{s.settled||(s.settled=!0,s.timer!==void 0&&clearTimeout(s.timer),i(lu))}},f=new CustomEvent(H1,{detail:d,cancelable:!0});if(!!window.dispatchEvent(f)){u();return}s.timer=setTimeout(u,n)})}const ZI=200,eO=1e3,BE="cim_widget_thumbnails_last_sweep",tO=3600*1e3;function UE(e){try{const t=Date.now(),n=Number(localStorage.getItem(BE))||0;if(n>0&&t-n<tO)return;localStorage.setItem(BE,String(t))}catch(t){}QI(e)}function nO(e){const{orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:i,conversationId:s,continuationToken:u,lastEventId:c,onSessionUpdate:d}=e,f=_.useRef(null),m=_.useRef(null),h=_.useRef(!1),y=_.useRef(d);y.current=d;const E=_.useRef(null),x=i.sinceHours*60*60*1e3,A=NE,k=_.useCallback(()=>(E.current||(E.current=RI(f.current)),E.current),[]),v=_.useCallback(V=>{const G=y.current;if(!G)return;if(V==="ended"||V==="reset"){G({reason:V,snapshot:null});return}const I=Wp(t,n,A),W=Xp(t,n);!I||!W||G({reason:V,snapshot:{conversationId:I.conversationId,continuationToken:W.accessToken,lastEventId:W.lastEventId,storedAt:Math.max(I.storedAt,W.storedAt)}})},[t,n,A]);_.useEffect(()=>{const V=PI(t,n);f.current=V,E.current=null,h.current=!1;const G=LI(V,()=>{const I=m.current;if(!I)return null;const W=Xp(t,n);return{conversationId:I,continuationToken:W==null?void 0:W.accessToken,lastEventId:W==null?void 0:W.lastEventId}},()=>{Yp(t,n),m.current=null});return()=>{G(),MI(V),f.current=null}},[t,n]),_.useEffect(()=>{UE(A)},[A]);const N=_.useCallback((V,G)=>Ce(null,null,function*(){var K,ae,oe;const I=(K=G==null?void 0:G.createIfMissing)!=null?K:!0,W=(ae=G==null?void 0:G.isCurrent)!=null?ae:(()=>!0);UE(A);let Q=Wp(t,n,A);if(!Q){const he=yield k();he&&!qp(he.storedAt,A)&&(Q=he)}if(!Q){if(!I)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const he=yield Tl({routingAttributes:r});if(he===lu)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const se=yield V.createConversation(he);return W()?(cu(t,n,se),m.current=se,v("created"),{conversationId:se,restoredMessages:[],resumed:!1,outcome:"created"}):(yield V.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}try{const he=yield V.listConversations({conversationId:Q.conversationId,startTimestamp:Date.now()-A});if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const se=he.conversations.find(M=>M.conversationId===Q.conversationId&&!M.isConversationClosed);if(!se){if(Yp(t,n),FE(Q.conversationId),m.current=null,!I)return v("ended"),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"};const M=yield Tl({routingAttributes:r});if(M===lu)return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"aborted"};if(!W())return{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"};const ge=yield V.createConversation(M);return W()?(cu(t,n,ge),m.current=ge,v("created"),{conversationId:ge,restoredMessages:[],resumed:!1,outcome:"not-found-or-closed"}):(yield V.endConversation(),{conversationId:null,restoredMessages:[],resumed:!1,outcome:"unverified-error"})}V.resumeConversation(se.conversationId),m.current=se.conversationId,cu(t,n,se.conversationId),v("resumed");let ee=[],ce,O=[];const j=V.listConversationEntries(se.conversationId,{limit:100,startTimestamp:Date.now()-A,direction:"FromEnd",entryTypeFilter:["RoutingResult","ParticipantChanged","CloseConversation"]}).then(M=>M.conversationEntries,()=>null);try{const M=yield V.listConversationEntries(se.conversationId,{limit:Math.min((oe=i.limit)!=null?oe:ZI,eO),startTimestamp:Date.now()-x,direction:"FromEnd"});O=M.conversationEntries,ce=RE(O),ee=HI(M.conversationEntries).reverse();const ge=DE(t,n,se.conversationId);Object.keys(ge).length>0&&(ee=ee.map(ne=>ne.role==="user"&&ge[ne.id]?pe(B({},ne),{pageContextDivider:ge[ne.id]}):ne));const Oe=yield KI(se.conversationId);Object.keys(Oe).length>0&&(ee=ee.map(ne=>Oe[ne.id]?pe(B({},ne),{attachmentImageUrl:Oe[ne.id]}):ne))}catch(M){}const te=yield j;return te!=null&&te.length&&(ce=RE([...O,...te])),{conversationId:se.conversationId,restoredMessages:ee,humanHandoff:ce,resumed:!0,outcome:"resumed"}}catch(he){return{conversationId:Q.conversationId,restoredMessages:[],resumed:!1,outcome:"unverified-error",error:he}}}),[t,n,r,i,x,A,k,v]),L=_.useCallback((V,G)=>{cu(t,n,V),m.current=V,v(G)},[t,n,v]),P=_.useCallback(V=>{m.current&&(FE(m.current),zI(t,n,m.current)),Yp(t,n),II(t,n),DI(f.current),m.current=null,v(V)},[t,n,v]),z=_.useCallback(()=>{h.current||(h.current=!0,u&&s&&IE(u)!=="expired"&&(OE(t,n,u,c!=null?c:""),cu(t,n,s),m.current=s));const V=Xp(t,n);return V?B({continuationToken:V.accessToken},V.lastEventId?{lastEventId:V.lastEventId}:{}):null},[t,n,u,s,c]),D=_.useCallback(()=>Ce(null,null,function*(){const V=yield k();return!(V!=null&&V.continuationToken)||qp(V.storedAt,A)?null:{continuationToken:V.continuationToken,lastEventId:V.lastEventId}}),[A,k]),q=_.useCallback((V,G=()=>!0)=>Ce(null,null,function*(){try{const{accessToken:I,lastEventId:W}=yield V.generateContinuationToken();if(!G())return;OE(t,n,I,W),(m.current||Wp(t,n,A))&&v("refreshed")}catch(I){}}),[t,n,A,v]);return{initializeConversation:N,persistConversationId:L,clearPersistedConversation:P,getStoredConnectOptions:z,getPeerConnectOptions:D,persistContinuationToken:q}}const rO=128,iO=.7;function jE(e,t,n){return Ce(this,null,function*(){var r,i;try{if(!e||!n.type.startsWith("image/"))return;const s=(i=(r=t==null?void 0:t.conversationEntries)==null?void 0:r[0])==null?void 0:i.id;if(!s)return;const u=yield vp(n,{maxDimension:rO,quality:iO,mimeType:"image/jpeg"}),c=yield xy(u);yield XI(e,s,c)}catch(s){}})}const oO="Your session ended due to inactivity. Starting a new session…",sO="This conversation has ended.",aO=300*1e3,uO=2e3,HE=1e4,$E=15e3,cO=2;function zE(e,t,n){return e||t||n===!0}function vl(e){return e.some(t=>t.role==="agent")}function Ds(e){e.acknowledged=!1,e.sentAt=performance.now(),e.firstTokenAt=void 0}function du(e){const t=e.find(r=>!r.timedOut),n=e[e.length-1];return t!=null?t:n}function lO(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 VE(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 Jp(e){if(VE(e))return!0;const t=e instanceof Error?e.message:"";return/\(401\)/.test(t)}function dO(e){var y;const t=e.productName||"this product",n=e.quantity&&e.quantity>1?e.quantity:void 0,r=((y=e.variants)!=null?y:[]).filter(E=>E.value),i=r.map(E=>`${E.label}: ${E.value}`).join(", "),s=r.map(E=>E.value).join(", "),u=i?` (${i})`:"",c=s?` (${s})`:"",d=n?`Add ${n} of`:"Add",f=e.sku?` [SKU: ${e.sku}]`:"",m=`${d} ${t} to my cart${u}${f}`,h=`Add ${n?`${n} × `:""}${t} to cart${c}`;return{prompt:m,display:h}}function Zp(e,t){return t?{prompt:`${e} (Viewing product details for: ${t})`,display:e}:{prompt:e}}function fO({connectionStatus:e,loading:t,hasMessages:n,sessionExpired:r,bootstrapSettled:i,resumeUsedLastEventId:s,recoverySteps:u,onExhausted:c,timeoutMs:d=$E,logger:f,isRecoveryInFlight:m}){const h=_.useRef(u);h.current=u;const y=_.useRef(c);y.current=c;const E=_.useRef(f);E.current=f;const x=_.useRef(m);x.current=m;const A=_.useRef(0),k=_.useRef(!1),v=_.useRef(0),[N,L]=_.useState(0);_.useEffect(()=>{if(!t||n){A.current=0,k.current=!1,v.current=0;return}const P=s||A.current>0;if(!(i&&P&&e==="connected"&&!r&&!k.current))return;const D=setTimeout(()=>{Ce(null,null,function*(){var I,W;if((I=x.current)!=null&&I.call(x)){if(v.current+=1,v.current>cO){k.current=!0,y.current();return}L(Q=>Q+1);return}const q=A.current,V=h.current;if(q>=V.length){k.current=!0,y.current();return}v.current=0,(W=E.current)==null||W.warn("🦜 connect bootstrap stalled",{attempt:q});let G;try{yield Promise.race([Promise.resolve(V[q]()),new Promise((Q,K)=>{G=setTimeout(()=>{K(new Error("connect bootstrap step timed out"))},d)})])}catch(Q){}finally{G!==void 0&&clearTimeout(G),A.current=q+1,L(Q=>Q+1)}})},d);return()=>{clearTimeout(D)}},[e,t,n,r,i,s,d,N])}const pO=(e,t,n)=>e==="chat"?"open":t?n?"minimized":"open":"closed",mO=(e,t,n,r,i)=>e==="error"||n?"error":t&&i===0?"connecting":r||t?"processing":e==="reconnecting"?"reconnecting":"transcript",hO=e=>{for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.role!=="agent")continue;const r=hI(n.content);if(r.includes("order_confirmation"))return"order";if(r.includes("cart"))return"cart";if(r.includes("product_comparison"))return"comparison";if(r.includes("product_carousel")||r.includes("product_tile"))return"products"}return"text"};function gO({telemetryRef:e,connectionStatus:t,loading:n,sendError:r,isAgentTyping:i,messages:s}){const{status:{isOpen:u,isMinimized:c,type:d}}=qn(),f=pO(d,u,c);_.useEffect(()=>{var y;(y=e.current)==null||y.uiState(f)},[e,f]);const m=mO(t,n,r,i,s.length);_.useEffect(()=>{var y;(y=e.current)==null||y.viewState(m)},[e,m]);const h=_.useMemo(()=>hO(s),[s]);_.useEffect(()=>{var y;(y=e.current)==null||y.contentState(h)},[e,h])}const yO=e=>typeof e=="number"?e:typeof e!="string"?NaN:/^\d+$/.test(e)?Number(e):Date.parse(e),em=(e,t=Date.now())=>{for(let n=e.length-1;n>=0;n--){const{role:r,timestamp:i}=e[n];if(r==="system")continue;const s=yO(i);return Number.isFinite(s)?Math.max(0,t-s):null}return null};function EO({telemetryRef:e,stateRef:t}){const n=_.useRef(null),r=_.useCallback(i=>{var u;const s=t.current;!(s!=null&&s.conversationId)||s.conversationId===n.current||(n.current=s.conversationId,(u=e.current)==null||u.conversationEnded(i,em(s.messages)))},[e,t]);return _.useEffect(()=>{const i=performance.now();let s=!1;const u=d=>{var f,m,h;s||(s=!0,(h=e.current)==null||h.sessionEnded(d,Math.round(performance.now()-i),em((m=(f=t.current)==null?void 0:f.messages)!=null?m:[])))},c=()=>u("navigated_away");return window.addEventListener("pagehide",c),()=>{window.removeEventListener("pagehide",c),u("unmounted")}},[e,t]),r}const bO=100,wO=4e3,xO=12e3;function qE(e,t){const n=e.current;e.current=[],n.forEach(({text:r,options:i,file:s,resolve:u})=>{const c=t.current;if(!c){u==null||u({outcome:"failure",message:"Messaging is unavailable"});return}c(r,i==null?void 0:i.displayContent,i,void 0,s).then(d=>u==null?void 0:u(d),d=>u==null?void 0:u({outcome:"failure",message:d instanceof Error?d.message:String(d)}))})}function WE(e,t){const n=e.current;n.length!==0&&(e.current=[],n.forEach(({resolve:r})=>{r==null||r({outcome:"failure",message:t})}))}function TO({isOpen:e,connectionStatus:t,conversationId:n,messages:r,deliverUserMessageRef:i,onWelcomeTimeout:s,welcomeNotExpected:u=!1,agentJoined:c=!1,welcomeStreaming:d=!1}){const[f,m]=_.useState(0),h=_.useRef([]),y=_.useRef(t);y.current=t;const E=_.useRef(null),x=_.useRef(null),A=_.useRef(n);return _.useEffect(()=>{if(A.current!==n&&(A.current=n,E.current=null,x.current=null),t==="error"){E.current=null,x.current=null,WE(h,"Connection error");return}const k=t==="connected"&&n!==null,v=h.current.length>0;if(!e||!k||!v){E.current=null,x.current=null;return}if(vl(r)||u){E.current=null,x.current=null;const D=setTimeout(()=>{qE(h,i)},bO);return()=>clearTimeout(D)}if(c){if(E.current=null,d)return;const D=Date.now();x.current===null&&(x.current=D+wO);const q=Math.max(0,x.current-D),V=setTimeout(()=>{x.current=null,h.current.length!==0&&qE(h,i)},q);return()=>clearTimeout(V)}x.current=null;const N=Date.now(),L=xO;E.current===null&&(E.current=N+L);const P=Math.max(0,E.current-N),z=setTimeout(()=>{E.current=null,h.current.length!==0&&(WE(h,"Welcome timeout"),s==null||s())},P);return()=>clearTimeout(z)},[e,t,n,r,i,f,s,u,c,d]),_.useCallback((k,v,N)=>y.current==="error"?Promise.resolve({outcome:"failure",message:"Connection error"}):new Promise(L=>{h.current.push({text:k,options:v,file:N,resolve:L}),m(P=>P+1)}),[])}const vO="Cart action timed out. Please try again.";function _O(e){return new Promise(t=>{let n=!1;const r=s=>{n||(n=!0,window.clearTimeout(i),t(s))},i=window.setTimeout(()=>{r({ok:!1,error:e.action==="add"?"Cart action timed out. Open View Cart to check whether the item was added before trying again.":vO})},HE);window.dispatchEvent(new CustomEvent(Kc,{detail:pe(B({},e),{respond:r})}))})}function tm(e){var n;const t=((n=e.items)!=null?n:[]).reduce((r,i)=>r+(i.quantity||0),0);return{cartId:e.id,itemCount:t,total:e.total}}function SO(e,t){const[n,r]=_.useState(null),[i,s]=_.useState(null),[u,c]=_.useState(!1),d=_.useRef(0),f=_.useRef(e);f.current=e;const m=_.useRef(()=>Ce(null,null,function*(){})),h=_.useCallback(x=>{if(x.ok){r(x.cart),s(null),t==null||t.log("🦜 recognized cart update",tm(x.cart));return}x.cart&&r(x.cart),s(x.error),t==null||t.warn("🦜 cart update failed",B({error:x.error},x.cart?tm(x.cart):{}))},[t]),y=_.useCallback(x=>Ce(null,null,function*(){if(f.current!=="direct")return{outcome:"failure",message:"Cart actions are not direct"};const A=++d.current;c(!0);try{const k=yield _O(x);if(A===d.current)h(k);else if(x.action!=="add")return{outcome:"failure",message:"Cart update was superseded"};return k.ok?{outcome:"success"}:{outcome:"failure",message:k.error}}catch(k){if(A!==d.current)return{outcome:"failure",message:"Cart update was superseded"};const v=k instanceof Error?k.message:"Couldn't update the cart";return s(v),{outcome:"failure",message:v}}finally{A===d.current&&c(!1)}}),[h]),E=_.useCallback(()=>Ce(null,null,function*(){yield y({action:"get"})}),[y]);return m.current=E,_.useEffect(()=>{const x=A=>{if(f.current!=="direct")return;const k=A.detail;d.current+=1,r(k),s(null),c(!1),t==null||t.log("🦜 recognized cart update",tm(k))};return window.addEventListener(Qa,x),()=>window.removeEventListener(Qa,x)},[t]),{directCart:n,directCartError:i,directCartLoading:u,loadDirectCart:E,applyDirectCartChange:y,cartTransportRef:f,refreshDirectCartRef:m}}function AO(e){const t=_.useRef(e);t.current=e,_.useEffect(()=>{const n=({detail:r})=>{(r==null?void 0:r.event)===Zc.RESET_CONVERSATION&&t.current()};return F1(n),()=>{B1(n)}},[])}function kO(e){const t=_.useRef(e);t.current=e,_.useEffect(()=>{const n=({detail:r})=>{(r==null?void 0:r.event)===Zc.END_CONVERSATION&&t.current()};return F1(n),()=>{B1(n)}},[])}const oi={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 YE(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 Ms(e){const{type:t,statusCode:n}=YE(e),r=e&&typeof e=="object"&&typeof e.attemptsMade=="number"?e.attemptsMade:void 0;return{status:n,context:{errType:t!=null?t:"unknown",attempts:r}}}function si(e){const{type:t,statusCode:n}=YE(e);if(t==="api"&&typeof n=="number")return n===429?oi.rateLimit:n>=500?oi.server:oi.default;switch(t){case"network":return oi.network;case"sse":return oi.interrupted;case"auth":return oi.connect;default:return oi.default}}function GE(e){switch(e.code){case"MAX_RECONNECT":return oi.lost;case"ROUTING_FAILED":return oi.routing;default:return oi.connect}}let Bo=null;function CO(e){Bo&&Bo!==e&&console.warn("[CimulateMessaging] A messaging API is already registered; overwriting it. Mounting more than one messaging widget per page is not supported."),Bo=e}function NO(e){Bo===e&&(Bo=null)}function XE(){if(!Bo)throw new Error("Cimulate messaging widget is not ready. Call this after injectMessagingWidget() has run and the widget has mounted.");return Bo}const IO={pdp:"This is the product details page the user is currently looking at",srp:"This is the search results page the user is currently looking at"},OO="1.0.0",PO=32768;function RO(e){const t=e.type==="pdp"?{id:e.id}:B(B(B({query:e.query},e.refinements!==void 0?{refinements:e.refinements}:{}),e.minPrice!==void 0?{minPrice:e.minPrice}:{}),e.maxPrice!==void 0?{maxPrice:e.maxPrice}:{});return{page_context_type:e.type,page_context_message:IO[e.type],page_context_data:t}}function LO(e){try{return new TextEncoder().encode(JSON.stringify(e)).length<=PO}catch(t){return!1}}function DO(e,t=null){if(!e&&!t)return;const n=B({version:OO},e?RO(e):{});let r=t?pe(B({},n),{browsing_history:t}):n;if(t&&!LO(r)){if(!e)return;r=n}return[{entryType:"SessionContext",id:crypto.randomUUID(),sessionContext:{contextType:"SessionContextSet",contextVariables:[{name:"commerce_agent_context",value:{valueType:"StructuredValue",value:r}}]}}]}function MO(e){var u,c,d;const t=(d=(c=(u=e[0])==null?void 0:u.sessionContext)==null?void 0:c.contextVariables)==null?void 0:d[0],n=t==null?void 0:t.value,r=(n==null?void 0:n.valueType)==="StructuredValue"?n.value:void 0;if(!r||!("browsing_history"in r))return e;const f=r,{browsing_history:i}=f,s=kn(f,["browsing_history"]);return Object.keys(s).every(m=>m==="version")?null:[{entryType:"SessionContext",id:crypto.randomUUID(),sessionContext:{contextType:"SessionContextSet",contextVariables:[{name:"commerce_agent_context",value:{valueType:"StructuredValue",value:s}}]}}]}let Fs=null;function KE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)}function FO(e){if(typeof e!="function"&&!KE(e))throw new Error("Browsing history must be { events: [...] } or a function returning it");Fs=e}function nm(){if(!Fs)return null;let e;try{e=typeof Fs=="function"?Fs():Fs}catch(t){return null}return KE(e)?e:null}function BO(){Fs=null}function QE(e,t){return e===t?!0:!e||!t||e.type!==t.type?!1:e.type==="pdp"&&t.type==="pdp"?e.id===t.id:e.type!=="srp"||t.type!=="srp"?!1:e.query===t.query}const Bs=Symbol("initialization-cancelled"),UO=3e4,jO="Image is too large to send. Please choose a smaller image.",HO="Sorry, we couldn't process that image. Please try a PNG, JPG, or GIF.",$O=512,zO=.7,JE=e=>{if(!e)return e;const t=MO(e);return t===e?e:nm()===null?t:e},VO=e=>Ce(null,null,function*(){let t;try{t=yield vp(e)}catch(n){if(!dC.includes(e.type))return console.warn("🦜 image downsize failed; original type not SCRT2-native, rejecting",n),{error:HO};console.warn("🦜 image downsize failed; uploading original",n),t=e}return t.size>Ep?{error:jO}:{file:t}}),ZE=e=>Ce(null,null,function*(){if(e.preparedFile)return{file:e.preparedFile};const t=yield VO(e.file);return"error"in t?t:(e.preparedFile=t.file,{file:t.file})}),eb=({scrt2Url:e,orgId:t,esDeveloperName:n,routingAttributes:r,conversationId:i,continuationToken:s,lastEventId:u,capabilitiesVersion:c,enablePageContext:d=!1,enableLogging:f=!1,onConnect:m,onMessage:h,onError:y,onProductResult:E,onEndConversation:x,onSessionUpdate:A,onWelcomeTimeout:k,cartTransport:v="agent",storefrontCartPageUrl:N="",children:L})=>{const{logger:P,conversationHistory:z}=at(),{status:{isOpen:D}}=qn(),q=er(),V=_.useRef(q);V.current=q;const[G,I]=_.useReducer(TI,SE),[W,Q]=_.useState(!1),[K,ae]=_.useState(!1),[oe,he]=_.useState(!1),se=_.useRef(!1),[ee,ce]=_.useState(!1),[O,j]=_.useState(!1),te=_.useRef(!1),M=_.useRef(0),ge=_.useRef(G);ge.current=G;const Oe=_.useRef(null);Oe.current||(Oe.current=crypto.randomUUID());const ne=_.useRef(null);ne.current||(ne.current=$C({orgId:t,esDeveloperName:n,widgetSessionId:Oe.current,getIdentity:()=>({conversationId:ge.current.conversationId,messagingSessionId:ge.current.messagingSessionId})}));const be=_.useRef(null),_e=_.useRef(null),je=_.useRef(null),ft=_.useRef(0),It=_.useRef(!1);_.useEffect(()=>{const Z=G.connectionStatus,ye=be.current;be.current=Z;const Ne=ne.current;if(Ne&&!(ye===Z||ye===null&&Z==="disconnected"))switch(Ne.connectionState(Z),Z){case"connecting":_e.current=performance.now();break;case"reconnecting":je.current=performance.now();break;case"connected":ye==="reconnecting"&&je.current!==null?Ne.reconnectSucceeded(Math.round(performance.now()-je.current),ft.current):Ne.connectSucceeded(_e.current!==null?Math.round(performance.now()-_e.current):null),_e.current=null,je.current=null,ft.current=0;break}},[G.connectionStatus]),_.useEffect(()=>{var Z;(Z=ne.current)==null||Z.sessionState(G.sessionExpired)},[G.sessionExpired]),gO({telemetryRef:ne,connectionStatus:G.connectionStatus,loading:G.loading,sendError:G.sendError,isAgentTyping:G.isAgentTyping,messages:G.messages});const bt=EO({telemetryRef:ne,stateRef:ge}),Ge=nO({orgId:t,esDeveloperName:n,routingAttributes:r,conversationHistory:z,conversationId:i,continuationToken:s,lastEventId:u,onSessionUpdate:A}),Xe=_.useRef(null),Zt=_.useRef(h),qe=_.useRef(y),At=_.useRef(m),$e=_.useRef(E),it=_.useRef(x),Qe=_.useRef(!1),Ot=_.useRef(!1),Dt=_.useRef(!1),Bn=_.useRef(0),Re=_.useRef(0),Je=_.useRef(0),de=_.useRef(null),Te=_.useRef(null),ze=_.useRef(null),lt=_.useRef(0),ot=_.useRef(!1),Ht=_.useRef(0),kt=_.useRef(0),Gn=_.useRef(()=>Promise.reject(new Error("Messaging is unavailable"))),Wr=_.useRef(),bi=_.useRef(()=>Ce(null,null,function*(){return{outcome:"failure",message:"Messaging is unavailable"}})),Yt=_.useRef(null),In=_.useCallback((Z,ye,Ne)=>{var Le,Be;const Ee=Z.options.pageContextDivider,le=(Be=(Le=ye==null?void 0:ye.conversationEntries)==null?void 0:Le[0])==null?void 0:Be.id;Ee&&Ne&&le&&$I(t,n,Ne,le,Ee)},[t,n]),Un=_.useCallback((Z={})=>{if(!d)return Z;const ye=Cs();if(!ye)return pe(B({},Z),{pageContextSnapshot:null});const Ne=pe(B({},Z),{pageContextSnapshot:ye});if(Z.silent)return Ne;let Ee;switch(ye.type){case"pdp":{const le=ty();Ee={context:ye,label:(le==null?void 0:le.label)||ye.id,imageUrl:le==null?void 0:le.imageUrl};break}case"srp":Ee={context:ye,label:ye.query};break}return pe(B({},Ne),{pageContextDivider:Ee})},[d]),vn=_.useRef([]),fn=_.useRef(null),Yr=_.useRef(null),Gr=_.useRef(!1),oo=_.useRef(0);_.useEffect(()=>{const Z=ye=>{var Ee;const Ne=(Ee=AI())!=null?Ee:ye==null?void 0:ye.detail;!Ne||typeof Ne!="object"||!Array.isArray(Ne.items)||(Yr.current=Ne,Gr.current=!0,oo.current+=1)};return window.addEventListener(Qa,Z),Z(),()=>window.removeEventListener(Qa,Z)},[]);const{directCart:Ju,directCartError:Zu,directCartLoading:ec,loadDirectCart:tc,applyDirectCartChange:ba,cartTransportRef:jd,refreshDirectCartRef:cs}=SO(v,P),rn=_.useCallback((Z,ye)=>{ye.outcome==="timeout"?(Z.timedOut=!0,vn.current=vn.current.filter(Ne=>Ne===Z||!Ne.timedOut)):vn.current=vn.current.filter(Ne=>Ne!==Z),clearTimeout(Z.timeoutId),Z.resolve(ye)},[]),Xt=_.useCallback(Z=>{if(M.current+=1,te.current!==Z&&(te.current=Z,I({type:"SET_HUMAN_HANDOFF",active:Z}),Z))for(const ye of[...vn.current])ye.completeOnAcknowledgment=!0,ye.acknowledged&&rn(ye,{outcome:"success"})},[rn]),wa=_.useCallback(Z=>{vn.current.includes(Z)&&(Z.acknowledged=!0,(te.current||Z.completeOnAcknowledgment)&&(I({type:"SET_LOADING",isLoading:!1}),rn(Z,{outcome:"success"})))},[rn]);Zt.current=h,qe.current=y,At.current=m,$e.current=E,it.current=x,_.useEffect(()=>{const Z=new bC({baseURL:e,orgId:t,esDeveloperName:n,options:B({enableLogging:f},c?{capabilitiesVersion:c}:{})});Xe.current=Z,ot.current=!1,It.current=!1,j(!1),Q(!1),se.current=!1,ce(!1),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),Z.on("connected",()=>{var le,Le;I({type:"SET_CONNECTION_STATUS",status:"connected"}),It.current||(It.current=!0,(le=ne.current)==null||le.sessionStarted()),(Le=At.current)==null||Le.call(At)}),Z.on("disconnected",()=>{I({type:"SET_CONNECTION_STATUS",status:"disconnected"})}),Z.on("reconnecting",le=>{ft.current=le.attempt,I({type:"SET_CONNECTION_STATUS",status:"reconnecting"})}),Z.on("message",le=>{var Gd,_a,_t,ac,uc,Sa,cc;const Le=Yr.current,Be=oo.current,ht=le.messageId!==void 0&&ge.current.messages.some(ao=>ao.serverId===le.messageId);if(d&&!ht){const ao=bI(le.content);ao&&!QE(ao,Cs())&&il(ao)}const wt=pe(B({id:le.messageId||crypto.randomUUID()},le.messageId?{serverId:le.messageId}:{}),{role:"agent",content:le.content,timestamp:le.timestamp,sender:le.sender,raw:le});P==null||P.log("🦜 MessagingProvider message received (FLUSH_STREAMING)",{messageId:wt.id,tokensBeforeFlush:Bn.current,streamedFinalOnly:Bn.current===0}),Bn.current=0,bl((Gd=le.sender)==null?void 0:Gd.role)===!0&&!te.current&&Xt(!0);const Ye=te.current?void 0:du(vn.current),un=Ye==null?void 0:Ye.options.reconcileMessageId;I({type:"FLUSH_STREAMING",message:wt,replaceMessageId:un}),(_a=Zt.current)==null||_a.call(Zt,wt),Ye&&(Ye.sentAt!==void 0&&!Ye.options.silent&&((_t=ne.current)==null||_t.agentReplied(Math.round(performance.now()-Ye.sentAt),Ye.firstTokenAt!==void 0?Math.round(Ye.firstTokenAt-Ye.sentAt):null)),rn(Ye,{outcome:"success"}));const{messagingSessionId:cn}=le;cn&&I({type:"SET_MESSAGING_SESSION_ID",id:cn});const mn=EI(le.content);cn&&mn&&((ac=$e.current)==null||ac.call($e,{agentSessionId:cn,kind:mn.kind,productIds:mn.productIds}));const Tt=vE(le.content),Xn=(uc=Tt==null?void 0:Tt.cartDetails)!=null?uc:null;ht||((mn==null?void 0:mn.kind)==="search"&&mn.productIds.length===0&&((Sa=ne.current)==null||Sa.failure("no_results")),(Tt==null?void 0:Tt.status)==="failure"&&((cc=ne.current)==null||cc.failure("cart_action_failed")));const Ir=jd.current==="direct";Ir&&Tt&&!ht&&cs.current(),!(ht||!se.current&&Gr.current)&&(Xn&&Be===oo.current&&(Yr.current=Xn,Gr.current=!1,oo.current+=1),(Tt==null?void 0:Tt.status)==="success"&&(Xn||Ir)?se.current&&j1(CE(Le,Xn,wI(le.content))):!Ir&&(Ye!=null&&Ye.options.cartMutation)&&!Xn&&(Tt==null?void 0:Tt.status)!=="failure"&&se.current&&j1(CE(Le,null)))}),Z.on("streaming_token",le=>{const Le=du(vn.current);if(!(Le!=null&&Le.options.silent)){if(Le&&Le.firstTokenAt===void 0&&(Le.firstTokenAt=performance.now()),Bn.current+=1,P!=null&&P.isDevelopment){const Be=wE(le.token);Be?Be.index===Yi?P.debug("🦜 streaming_token → markdown fallback",{token:le.token}):P.debug("🦜 streaming_token parsed",{type:Be.type,index:Be.index,outputName:Be.type==="tool_results"?Be.output_name:void 0}):P.debug("🦜 streaming_token dropped (empty or unrecognized payload shape)",{token:le.token})}I({type:"APPEND_STREAMING_TOKEN",token:le.token})}}),Z.on("typing_started",()=>{var le;(le=du(vn.current))!=null&&le.options.silent||I({type:"SET_AGENT_TYPING",isTyping:!0})}),Z.on("typing_stopped",()=>{var le;(le=du(vn.current))!=null&&le.options.silent||I({type:"SET_AGENT_TYPING",isTyping:!1})}),Z.on("progress_indicator",le=>{var Le;(Le=du(vn.current))!=null&&Le.options.silent||I({type:"ADD_PROGRESS_STEP",message:le.message})}),Z.on("routing_result",le=>{var Be,ht;I({type:"SET_ROUTING_RESULT",result:le});const Le=PE(le.raw);if(le.isSuccessful&&Le!==void 0&&Xt(Le),!le.isSuccessful){const wt=`Routing failed: ${le.failureType||"unknown"}`;(Be=ne.current)==null||Be.failure("routing_failed",{context:{failureType:le.failureType||"unknown"}}),I({type:"SET_ERROR",error:GE({code:"ROUTING_FAILED"})}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(ht=qe.current)==null||ht.call(qe,wt)}}),Z.on("participant_changed",le=>{var ht,wt;if(le.participant.name==="Automated Process")return;const Le=bl(le.participant.role);le.action==="add"&&Le!==void 0&&Xt(Le),Le===!1&&ae(le.action==="add");const Be=pe(B({id:crypto.randomUUID()},le.entryId?{serverId:le.entryId}:{}),{role:"system",content:le.action==="add"?ol(V.current.session.participantJoined,{name:le.participant.name||V.current.session.participantFallbackName}):ol(V.current.session.participantLeft,{name:le.participant.name||V.current.session.participantFallbackName}),timestamp:new Date().toISOString()});P==null||P.log("🦜 MessagingProvider participant_changed event received",{event:le}),le.action==="add"?(ht=ne.current)==null||ht.participantJoined(le.participant.name||"Agent"):(wt=ne.current)==null||wt.participantLeft(le.participant.name||"Agent",em(ge.current.messages)),I({type:"ADD_MESSAGE",message:Be})}),Z.on("conversation_closed",()=>{const le={id:crypto.randomUUID(),role:"system",content:V.current.session.conversationEnded,timestamp:new Date().toISOString()};Xt(!1),bt("server_closed"),I({type:"ADD_MESSAGE",message:le}),I({type:"SET_CONVERSATION_ID",id:null}),Ge.clearPersistedConversation("ended")}),Z.on("error",le=>{var Le,Be,ht;if(P==null||P.log("🦜 MessagingProvider ERROR event received",{event:le}),le.code==="SESSION_EXPIRED"){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),I({type:"SET_LOADING",isLoading:!1});return}(Be=ne.current)==null||Be.failure("sdk_error",{context:{code:(Le=le.code)!=null?Le:"unknown",recoverable:le.recoverable}}),I({type:"SET_ERROR",error:GE(le)}),le.recoverable||I({type:"SET_CONNECTION_STATUS",status:"error"}),(ht=qe.current)==null||ht.call(qe,le.message)});const ye=le=>{if(le!==Ht.current)throw Bs},Ne=le=>le===Ht.current,Ee=le=>Ce(null,null,function*(){var Ye,un,cn,mn;const Le=M.current;Q(!1),se.current=!1;let Be=Ge.getStoredConnectOptions(),ht=!1;Be||(Be=yield Ge.getPeerConnectOptions(),ye(le),ht=!!Be);let wt=!1;try{if(yield Z.connect(Be!=null?Be:void 0),!Ne(le))throw Z.disconnect(),Bs;wt=!!(Be!=null&&Be.lastEventId)}catch(Tt){if(ye(le),Be&&Jp(Tt)){if(P==null||P.log("Stored token expired on connect — falling back to fresh connect"),ht||Ge.clearPersistedConversation("reset"),yield Z.connect(),!Ne(le))throw Z.disconnect(),Bs;wt=!1}else throw Tt}ce(wt),yield Ge.persistContinuationToken(Z,()=>Ne(le)),ye(le);const We=yield Ge.initializeConversation(Z,{isCurrent:()=>Ne(le)});if(ye(le),P==null||P.log("🦜 initial connect complete",{conversationId:We.conversationId,resumed:We.resumed,outcome:We.outcome,restoredMessages:We.restoredMessages.length}),(Ye=ne.current)==null||Ye.sessionInitialized(We.outcome,We.restoredMessages.length),We.outcome==="aborted")throw I({type:"SET_LOADING",isLoading:!1}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Bs;if(We.outcome==="unverified-error"){We.conversationId&&(Z.resumeConversation(We.conversationId),I({type:"SET_CONVERSATION_ID",id:We.conversationId})),Q(!0),se.current=!0;return}if(I({type:"SET_CONVERSATION_ID",id:We.conversationId}),We.resumed){Le===M.current&&We.humanHandoff!==void 0&&Xt(We.humanHandoff);const Tt=(un=[...We.restoredMessages].reverse().find(Xn=>Xn.pageContextDivider))==null?void 0:un.pageContextDivider;if(Yt.current=(cn=Tt==null?void 0:Tt.context)!=null?cn:null,!Gr.current)for(const Xn of[...We.restoredMessages].reverse()){const Ir=(mn=vE(Xn.content))==null?void 0:mn.cartDetails;if(Ir){Yr.current=Ir,oo.current+=1;break}}I({type:"LOAD_HISTORY",messages:We.restoredMessages}),he(!vl(We.restoredMessages)),Q(!0),se.current=!0}else Le===M.current&&Xt(!1),Yt.current=null,he(!1),Q(!0),se.current=!0;I({type:"SET_LOADING",isLoading:!1})});return Te.current=Ee,()=>{Ht.current+=1,kt.current+=1,Z.disconnect(),Z.off(),Xe.current=null,Te.current=null,ze.current=null,ot.current=!1}},[e,t,n,c,rn]);const pn=_.useCallback(()=>{if(ot.current)return Promise.resolve();if(ze.current)return lt.current===Ht.current?ze.current:ze.current.catch(Ee=>{if(Ee!==Bs)throw Ee}).then(()=>Gn.current());const Z=Te.current;if(!Z)return Promise.reject(new Error("Messaging is unavailable"));I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_CONNECTION_STATUS",status:"connecting"});const ye=++Ht.current;lt.current=ye;const Ne=Z(ye).then(()=>{ot.current=!0,j(!0)}).catch(Ee=>{var Le,Be;if(Ee===Bs)throw Ee;const le=Ee instanceof Error?Ee.message:String(Ee);throw(Le=ne.current)==null||Le.failure("connect_failed",Ms(Ee)),I({type:"SET_CONNECTION_STATUS",status:"error"}),I({type:"SET_ERROR",error:si(Ee)}),(Be=qe.current)==null||Be.call(qe,le),Ee}).finally(()=>{ze.current===Ne&&(ze.current=null)});return ze.current=Ne,Ne},[]);Gn.current=pn,_.useEffect(()=>{D&&pn().catch(()=>{})},[D,e,t,n,c,pn]);const Pi=TO({isOpen:D,connectionStatus:G.connectionStatus,conversationId:G.conversationId,messages:G.messages,deliverUserMessageRef:Wr,onWelcomeTimeout:k,welcomeNotExpected:oe,agentJoined:K,welcomeStreaming:G.streamingBlocks.length>0}),Ri=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)return!1;const ye=M.current,Ne=Ge.getStoredConnectOptions();if(!Ne)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{Z.disconnect(),yield Z.connect(Ne)}catch(le){if(Jp(le))return P==null||P.log("🦜 attemptResume: token expired (401) — will start fresh",{error:le instanceof Error?le.message:String(le)}),!1;throw P==null||P.log("🦜 attemptResume: transient connect failure — rethrowing, session kept",{error:le instanceof Error?le.message:String(le)}),le}yield Ge.persistContinuationToken(Z);const Ee=yield Ge.initializeConversation(Z,{createIfMissing:!1});return Ee.outcome==="not-found-or-closed"||!Ee.conversationId?(P==null||P.log("🦜 attemptResume: conversation no longer resumable (closed/not found) — will start fresh"),!1):(Ee.outcome==="unverified-error"&&(P==null||P.log("🦜 attemptResume: resume validation failed transiently — keeping live session, resuming optimistically",{conversationId:Ee.conversationId}),Z.resumeConversation(Ee.conversationId)),P==null||P.log("🦜 attemptResume: resumed conversation on same identity",{conversationId:Ee.conversationId}),I({type:"SET_CONVERSATION_ID",id:Ee.conversationId}),Ee.outcome==="resumed"&&ye===M.current&&Ee.humanHandoff!==void 0&&Xt(Ee.humanHandoff),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ee.outcome!=="resumed"&&Ge.persistConversationId(Ee.conversationId,"resumed"),Dt.current=!1,I({type:"SET_SESSION_EXPIRED",expired:!1}),!0)}),[Ge,P,Xt]),ls=_.useCallback(Z=>Ce(null,null,function*(){var Ne,Ee,le,Le,Be,ht,wt;const ye=Xe.current;if(ye){Z.options.silent||(I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_PROGRESS_MESSAGE",message:""})),Z.sessionContext=JE(Z.sessionContext);try{if(Z.file){const We=yield ZE(Z);if("error"in We){I({type:"SET_SEND_ERROR",error:{text:Z.text,displayContent:Z.displayContent,options:Z.options,sessionContext:Z.sessionContext,file:Z.file,message:We.error}}),(Ne=ne.current)==null||Ne.failure("file_rejected"),(Ee=qe.current)==null||Ee.call(qe,We.error),rn(Z,{outcome:"failure",message:We.error});return}Ds(Z);const Ye=yield ye.sendFile(We.file,Z.text.trim()?{text:Z.text}:void 0);jE((le=ye.conversationId)!=null?le:ge.current.conversationId,Ye,Z.file)}else if(Z.sessionContext){Ds(Z);const We=yield ye.sendMessage(Z.text,Z.sessionContext);In(Z,We,(Le=ye.conversationId)!=null?Le:ge.current.conversationId)}else{Ds(Z);const We=yield ye.sendMessage(Z.text);In(Z,We,(Be=ye.conversationId)!=null?Be:ge.current.conversationId)}wa(Z)}catch(We){(ht=ne.current)==null||ht.failure("send_failed",Ms(We));const Ye=si(We);I({type:"SET_SEND_ERROR",error:{text:Z.text,displayContent:Z.displayContent,options:Z.options,sessionContext:Z.sessionContext,file:Z.file,message:Ye}}),(wt=qe.current)==null||wt.call(qe,We instanceof Error?We.message:String(We)),rn(Z,{outcome:"failure",message:Ye})}}}),[rn,In,wa]),Hd=_.useCallback(Z=>Ce(null,null,function*(){var Ne,Ee,le;const ye=Xe.current;if(!(!ye||Qe.current)){Qe.current=!0,Ot.current=!0;try{if(yield Ri()){Z&&(yield ls(Z));return}P==null||P.log("🦜 recoverExpiredSession: resume failed — starting a new session + conversation"),bt("expired"),Dt.current=!1,I({type:"SET_SESSION_EXPIRED",expired:!1}),I({type:"ADD_MESSAGE",message:{id:crypto.randomUUID(),role:"system",content:V.current.session.sessionEnded,timestamp:new Date().toISOString()}}),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),ye.disconnect(),yield ye.connect(),yield Ge.persistContinuationToken(ye);const Le=yield Tl({routingAttributes:r});if(Le===lu){I({type:"SET_CONNECTION_STATUS",status:"disconnected"});return}const Be=yield ye.createConversation(Le);P==null||P.log("🦜 recoverExpiredSession: new conversation created",{conversationId:Be}),I({type:"SET_CONVERSATION_ID",id:Be}),(Ne=ne.current)==null||Ne.conversationStarted("recovery"),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ge.persistConversationId(Be,"created"),Z&&(Z.completeOnAcknowledgment=!1,yield ls(Z))}catch(Le){(Ee=ne.current)==null||Ee.failure("session_recovery_failed",Ms(Le));const Be=Le instanceof Error?Le.message:String(Le);I({type:"SET_ERROR",error:si(Le)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(le=qe.current)==null||le.call(qe,Be),Z&&rn(Z,{outcome:"failure",message:si(Le)})}finally{Qe.current=!1,Ot.current=!1}}}),[r,Ge,Ri,ls,P,rn,bt,Xt]),nc=_.useRef(Hd);nc.current=Hd;const $d=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z||!ot.current||Qe.current)return;if(!ge.current.conversationId&&!Dt.current){Z.reconnect();return}Qe.current=!0;const ye=Ce(null,null,function*(){try{(yield Ri())||(Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}))}catch(Ne){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"})}finally{Qe.current=!1,de.current=null}});de.current=ye,yield ye}),[Ri]),wi=_.useRef($d);wi.current=$d;const zd=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z||Qe.current)return;const ye=Ge.getStoredConnectOptions(),Ne=ye==null?void 0:ye.continuationToken;if(Ne){Qe.current=!0;try{Z.disconnect(),yield Z.connect({continuationToken:Ne}),yield Ge.persistContinuationToken(Z);const Ee=ge.current.conversationId;Ee&&Z.resumeConversation(Ee)}catch(Ee){if(Jp(Ee)){Dt.current=!0,I({type:"SET_SESSION_EXPIRED",expired:!0}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),I({type:"SET_LOADING",isLoading:!1});return}P==null||P.log("🦜 reconnectOmittingLastEventId: transient connect failure — session kept",{error:Ee instanceof Error?Ee.message:String(Ee)})}finally{Qe.current=!1}}}),[Ge,P]);_.useEffect(()=>{const Z=()=>{const Be=Date.now();Be-Je.current<uO||(Je.current=Be,wi.current())},ye=()=>{if(document.visibilityState==="hidden"){Re.current=Date.now();return}const Be=Xe.current;if(!Be)return;const ht=Re.current?Date.now()-Re.current:0;Re.current=0,(Dt.current||!Be.isConnected||ht>aO)&&Z()},Ne=Be=>{Be.persisted&&Z()},Ee=()=>{Re.current=Date.now()},le=()=>Z(),Le=()=>Z();return document.addEventListener("visibilitychange",ye),window.addEventListener("pageshow",Ne),window.addEventListener("pagehide",Ee),document.addEventListener("resume",le),window.addEventListener("online",Le),()=>{document.removeEventListener("visibilitychange",ye),window.removeEventListener("pageshow",Ne),window.removeEventListener("pagehide",Ee),document.removeEventListener("resume",le),window.removeEventListener("online",Le)}},[]);const rc=_.useCallback((Z,ye)=>Ce(null,null,function*(){var Ee,le,Le,Be,ht,wt,We;const Ne=Xe.current;if(!Ne){rn(Z,{outcome:"failure",message:"Messaging is unavailable"});return}if(Dt.current){yield nc.current(Z);return}try{if(Z.file){const Ye=yield ZE(Z);if("error"in Ye){I({type:"SET_SEND_ERROR",error:ye(Ye.error)}),(Ee=ne.current)==null||Ee.failure("file_rejected"),(le=qe.current)==null||le.call(qe,Ye.error),rn(Z,{outcome:"failure",message:Ye.error});return}Ds(Z);const un=yield Ne.sendFile(Ye.file,Z.text.trim()?{text:Z.text}:void 0);jE((Le=Ne.conversationId)!=null?Le:ge.current.conversationId,un,Z.file)}else if(Z.sessionContext){Ds(Z);const Ye=yield Ne.sendMessage(Z.text,Z.sessionContext);In(Z,Ye,(Be=Ne.conversationId)!=null?Be:ge.current.conversationId)}else{Ds(Z);const Ye=yield Ne.sendMessage(Z.text);In(Z,Ye,(ht=Ne.conversationId)!=null?ht:ge.current.conversationId)}wa(Z)}catch(Ye){if(VE(Ye)){yield nc.current(Z);return}(wt=ne.current)==null||wt.failure("send_failed",Ms(Ye));const un=si(Ye);I({type:"SET_SEND_ERROR",error:ye(un)}),(We=qe.current)==null||We.call(qe,Ye instanceof Error?Ye.message:String(Ye)),rn(Z,{outcome:"failure",message:un})}}),[rn,In,wa]),Vd=_.useCallback(Z=>Ce(null,null,function*(){const ye=de.current;ye&&(yield ye),yield Z()}),[]),Nr=_.useCallback((Z,ye,Ne={},Ee,le,Le=!1)=>new Promise(Be=>{var mn;if(!Xe.current){Be({outcome:"failure",message:"Messaging is unavailable"});return}if(!Z.trim()&&!le){Be({outcome:"failure",message:"Message is empty"});return}const wt=Ne.pageContextDivider,We=!Le&&!le&&wt!==void 0&&!QE(wt.context,Yt.current),Ye=!Le&&wt!==void 0&&!We?pe(B({},Ne),{pageContextDivider:void 0}):Ne;let un=Le&&Ee?JE(Ee):Ee;if(un===void 0&&(un=null,d)){const Tt=Ye.pageContextSnapshot===void 0?Cs():Ye.pageContextSnapshot;un=(mn=DO(Tt,nm()))!=null?mn:null}const cn={};if(Object.assign(cn,{text:Z,displayContent:ye,options:Ye,completeOnAcknowledgment:te.current,sessionContext:un,file:le,resolve:Be,timeoutId:setTimeout(()=>{var Tt;(Tt=ne.current)==null||Tt.failure("send_timeout"),I({type:"SET_AGENT_TYPING",isTyping:!1}),rn(cn,{outcome:"timeout"})},HE)}),vn.current.push(cn),I({type:"CLEAR_SEND_ERROR"}),!Ye.silent){if(!Le){const Tt=crypto.randomUUID();I({type:"ADD_MESSAGE",message:{id:Tt,role:"user",content:ye!=null?ye:Z,timestamp:new Date().toISOString(),pageContextDivider:Ye.pageContextDivider}}),We&&wt&&(Yt.current=wt.context),le&&le.type.startsWith("image/")&&vp(le,{maxDimension:$O,quality:zO}).then(xy).then(Xn=>I({type:"UPDATE_MESSAGE",id:Tt,patch:{attachmentImageUrl:Xn}})).catch(()=>{})}I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_PROGRESS_MESSAGE",message:""})}Vd(()=>rc(cn,Tt=>({text:Z,displayContent:ye,options:Ye,sessionContext:cn.sessionContext,file:le,message:Tt})))}),[rc,Vd,d,rn]);Wr.current=Nr;const so=_.useCallback((Z,ye)=>{var wt;if(!Z.trim())return Promise.resolve({outcome:"failure",message:"Message is empty"});const Ne=Un(ye),Ee=pe(B({},Ne),{displayContent:(wt=Ne.displayContent)!=null?wt:Z});if(!D||!te.current&&!vl(ge.current.messages)){const We=Pi(Z,Ee);return ot.current||pn().catch(()=>{}),D?We:Promise.resolve({outcome:"success"})}const le=kt.current,Le=()=>{const We=()=>le!==kt.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Nr(Z,Ee.displayContent,Ee);return ot.current?We():pn().then(We,Ye=>({outcome:"failure",message:si(Ye)}))},Be=fn.current?fn.current.then(Le):Le(),ht=Be.then(()=>{});return fn.current=ht,ht.finally(()=>{fn.current===ht&&(fn.current=null)}),Be},[Nr,pn,D,Pi,Un]);bi.current=so;const ic=_.useCallback(Z=>{if(!Xe.current)return Promise.resolve({outcome:"failure",message:"Messaging is unavailable"});const{text:Ne,file:Ee,displayContent:le}=Z;if(!Ee)return Ne.trim()?so(Ne):Promise.resolve({outcome:"failure",message:"Message is empty"});const Le=Ne.trim(),Be=(le!=null?le:Ne).trim()||Ee.name,ht={displayContent:Be};if(!D||!te.current&&!vl(ge.current.messages)){const cn=Pi(Le,ht,Ee);return ot.current||pn().catch(()=>{}),D?cn:Promise.resolve({outcome:"success"})}const wt=kt.current,We=()=>{const cn=()=>wt!==kt.current?Promise.resolve({outcome:"failure",message:"Message cancelled"}):Nr(Le,Be,ht,null,Ee);return ot.current?cn():pn().then(cn,mn=>({outcome:"failure",message:si(mn)}))},Ye=fn.current?fn.current.then(We):We(),un=Ye.then(()=>{});return fn.current=un,un.finally(()=>{fn.current===un&&(fn.current=null)}),Ye},[Nr,so,pn,D,Pi]),oc=_.useCallback(Z=>{if(!Xe.current)return;const ye=kt.current,{prompt:Ne,display:Ee}=dO(Z);pn().then(()=>{if(ye===kt.current)return Nr(Ne,Ee)}).catch(()=>{})},[Nr,pn]),qd=_.useCallback(()=>{const Z=Xe.current,ye=ge.current.sendError;if(!Z||!ye)return;const Ne=()=>Ot.current?Promise.resolve({outcome:"failure",message:ye.message}):Nr(ye.text,ye.displayContent,ye.options,ye.sessionContext,ye.file,!0),Ee=fn.current?fn.current.then(Ne):Ne(),le=Ee.then(()=>{});return fn.current=le,le.finally(()=>{fn.current===le&&(fn.current=null)}),Ee},[Nr]),Wd=_.useCallback(()=>{const Z=Xe.current;Z&&(ze.current||(Dt.current=!1,ot.current=!1,j(!1),Z.disconnect(),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),pn().catch(()=>{})))},[pn]),$t=_.useCallback(Z=>{const ye=Xe.current;if(!ye)return Promise.resolve();if(vn.current=[],Yt.current=null,bt(Z),!ot.current)return Ht.current+=1,kt.current+=1,ye.disconnect(),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),Promise.resolve();const Ne=++kt.current;return Dt.current=!1,ce(!1),Ge.clearPersistedConversation("reset"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_LOADING",isLoading:!0}),I({type:"SET_CONNECTION_STATUS",status:"connecting"}),ye.endConversation().then(()=>Ne!==kt.current||Xe.current!==ye?null:(ye.disconnect(),ye.connect().then(()=>ye))).then(Ee=>Ce(null,null,function*(){if(!Ee||Ne!==kt.current||(yield Ge.persistContinuationToken(Ee,()=>Ne===kt.current&&Xe.current===Ee),Ne!==kt.current||Xe.current!==Ee))return null;const le=yield Tl({routingAttributes:r});return le===lu?null:ye.createConversation(le)})).then(Ee=>{var le;!Ee||Ne!==kt.current||Xe.current!==ye||(I({type:"SET_CONVERSATION_ID",id:Ee}),I({type:"SET_CONNECTION_STATUS",status:"connected"}),Ge.persistConversationId(Ee,"created"),(le=ne.current)==null||le.conversationStarted("reset"))}).catch(Ee=>{var le,Le;Ne!==kt.current||Xe.current!==ye||((le=ne.current)==null||le.failure("conversation_create_failed",Ms(Ee)),I({type:"SET_ERROR",error:si(Ee)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Le=qe.current)==null||Le.call(qe,Ee.message))})},[r,Ge,bt,Xt]),sc=_.useCallback(()=>$t("reset"),[$t]);AO(sc),fO({connectionStatus:G.connectionStatus,loading:G.loading,hasMessages:G.messages.length>0,sessionExpired:G.sessionExpired,bootstrapSettled:W,resumeUsedLastEventId:ee,recoverySteps:[zd,()=>$t("resume_timeout")],onExhausted:()=>{var ye,Ne;(ye=ne.current)==null||ye.failure("resume_timeout");const Z=si({type:"network"});I({type:"SET_ERROR",error:Z}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Ne=qe.current)==null||Ne.call(qe,Z)},logger:P,isRecoveryInFlight:()=>Qe.current||de.current!==null});const xa=_.useCallback(()=>Ce(null,null,function*(){var Ee;const Z=Xe.current;if(!Z||!ge.current.conversationId)return;const ye=yield Z.retrieveConversationTranscript(),Ne=URL.createObjectURL(ye);try{const le=document.createElement("a");le.href=Ne,le.download=`transcript-${(Ee=Z.conversationId)!=null?Ee:"conversation"}.pdf`,document.body.appendChild(le),le.click(),le.remove()}finally{URL.revokeObjectURL(Ne)}}),[]),Ta=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)return Promise.resolve();if(vn.current=[],Yt.current=null,bt("ended"),!ot.current)return Ht.current+=1,kt.current+=1,Z.disconnect(),Ge.clearPersistedConversation("ended"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"}),Promise.resolve();const ye=++kt.current;if(Dt.current=!1,ce(!1),it.current)try{yield Promise.race([it.current(ge.current.conversationId),new Promise(Ee=>setTimeout(Ee,UO))])}catch(Ee){P==null||P.error("onEndConversation callback failed",Ee)}Ge.clearPersistedConversation("ended"),Xt(!1),ae(!1),he(!1),I({type:"RESET"}),I({type:"SET_CONNECTION_STATUS",status:"disconnected"});const Ne={id:crypto.randomUUID(),role:"system",content:V.current.session.conversationEnded,timestamp:new Date().toISOString()};return I({type:"ADD_MESSAGE",message:Ne}),ot.current=!1,j(!1),Z.endConversation().then(()=>{ye!==kt.current||Xe.current!==Z||Z.disconnect()}).catch(Ee=>{var le,Le;ye!==kt.current||Xe.current!==Z||((le=ne.current)==null||le.failure("end_conversation_failed",Ms(Ee)),I({type:"SET_ERROR",error:si(Ee)}),I({type:"SET_CONNECTION_STATUS",status:"error"}),(Le=qe.current)==null||Le.call(qe,Ee.message))})}),[P,Ge,ce,bt,Xt]);kO(Ta);const Li=_.useCallback(()=>Ce(null,null,function*(){const Z=Xe.current;if(!Z)throw new Error("getAuthLinkKey called before the messaging client connected");return P==null||P.debug("🦜 getAuthLinkKey: requesting single-use auth link key"),Z.getAuthLinkKey()}),[P]);_.useEffect(()=>{const Z={getAuthLinkKey:Li,sendMessage:(ye,Ne)=>bi.current(ye,Ne)};return CO(Z),()=>NO(Z)},[Li]);const va=G.connectionStatus==="connected"&&G.conversationId!==null;_.useEffect(()=>{ey(va)},[va]),_.useEffect(()=>()=>ey(!1),[]);const Yd=_.useMemo(()=>({connectionStatus:G.connectionStatus,isConnected:va,isAgentTyping:G.isAgentTyping,conversationId:G.conversationId,messages:G.messages,streamingBlocks:G.streamingBlocks,progressMessage:G.progressMessage,progressSteps:G.progressSteps,error:G.error,sendError:G.sendError,canInitialize:!O&&G.error===null,loading:G.loading,humanHandoff:G.humanHandoff,sessionExpired:G.sessionExpired,sendMessage:so,sendFile:ic,addToCart:oc,resetConversation:sc,endConversation:Ta,retryLastMessage:qd,retryConnection:Wd,downloadTranscript:xa,getAuthLinkKey:Li,cartTransport:v,storefrontCartPageUrl:N,directCart:Ju,directCartError:Zu,directCartLoading:ec,loadDirectCart:tc,applyDirectCartChange:ba}),[G,va,O,so,ic,oc,sc,Ta,qd,Wd,xa,Li,v,N,Ju,Zu,ec,tc,ba]);return w.jsx(sl.Provider,{value:ne.current,children:w.jsx(uy.Provider,{value:Yd,children:L})})};var tb=Symbol.for("immer-nothing"),nb=Symbol.for("immer-draftable"),pr=Symbol.for("immer-state");function Ur(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Us=Object.getPrototypeOf;function js(e){return!!e&&!!e[pr]}function Uo(e){var t;return e?rb(e)||Array.isArray(e)||!!e[nb]||!!((t=e.constructor)!=null&&t[nb])||fu(e)||Al(e):!1}var qO=Object.prototype.constructor.toString();function rb(e){if(!e||typeof e!="object")return!1;const t=Us(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)===qO}function _l(e,t){Sl(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Sl(e){const t=e[pr];return t?t.type_:Array.isArray(e)?1:fu(e)?2:Al(e)?3:0}function rm(e,t){return Sl(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ib(e,t,n){const r=Sl(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function WO(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function fu(e){return e instanceof Map}function Al(e){return e instanceof Set}function jo(e){return e.copy_||e.base_}function im(e,t){if(fu(e))return new Map(e);if(Al(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const n=rb(e);if(t===!0||t==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(e);delete r[pr];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const u=i[s],c=r[u];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[u]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[u]})}return Object.create(Us(e),r)}else{const r=Us(e);if(r!==null&&n)return B({},e);const i=Object.create(r);return Object.assign(i,e)}}function om(e,t=!1){return Cl(e)||js(e)||!Uo(e)||(Sl(e)>1&&Object.defineProperties(e,{set:{value:kl},add:{value:kl},clear:{value:kl},delete:{value:kl}}),Object.freeze(e),t&&Object.values(e).forEach(n=>om(n,!0))),e}function kl(){Ur(2)}function Cl(e){return Object.isFrozen(e)}var YO={};function Ho(e){const t=YO[e];return t||Ur(0,e),t}var pu;function ob(){return pu}function GO(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function sb(e,t){t&&(Ho("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function sm(e){am(e),e.drafts_.forEach(XO),e.drafts_=null}function am(e){e===pu&&(pu=e.parent_)}function ab(e){return pu=GO(pu,e)}function XO(e){const t=e[pr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function ub(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[pr].modified_&&(sm(t),Ur(4)),Uo(e)&&(e=Nl(t,e),t.parent_||Il(t,e)),t.patches_&&Ho("Patches").generateReplacementPatches_(n[pr].base_,e,t.patches_,t.inversePatches_)):e=Nl(t,n,[]),sm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==tb?e:void 0}function Nl(e,t,n){if(Cl(t))return t;const r=t[pr];if(!r)return _l(t,(i,s)=>cb(e,r,t,i,s,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Il(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const i=r.copy_;let s=i,u=!1;r.type_===3&&(s=new Set(i),i.clear(),u=!0),_l(s,(c,d)=>cb(e,r,i,c,d,n,u)),Il(e,i,!1),n&&e.patches_&&Ho("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function cb(e,t,n,r,i,s,u){if(js(i)){const c=s&&t&&t.type_!==3&&!rm(t.assigned_,r)?s.concat(r):void 0,d=Nl(e,i,c);if(ib(n,r,d),js(d))e.canAutoFreeze_=!1;else return}else u&&n.add(i);if(Uo(i)&&!Cl(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Nl(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&(fu(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&Il(e,i)}}function Il(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&om(t,n)}function KO(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:ob(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,s=um;n&&(i=[r],s=mu);const{revoke:u,proxy:c}=Proxy.revocable(i,s);return r.draft_=c,r.revoke_=u,c}var um={get(e,t){if(t===pr)return e;const n=jo(e);if(!rm(n,t))return QO(e,n,t);const r=n[t];return e.finalized_||!Uo(r)?r:r===cm(e.base_,t)?(dm(e),e.copy_[t]=fm(r,e)):r},has(e,t){return t in jo(e)},ownKeys(e){return Reflect.ownKeys(jo(e))},set(e,t,n){const r=lb(jo(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const i=cm(jo(e),t),s=i==null?void 0:i[pr];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(WO(n,i)&&(n!==void 0||rm(e.base_,t)))return!0;dm(e),lm(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 cm(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,dm(e),lm(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=jo(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 Us(e.base_)},setPrototypeOf(){Ur(12)}},mu={};_l(um,(e,t)=>{mu[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),mu.deleteProperty=function(e,t){return mu.set.call(this,e,t,void 0)},mu.set=function(e,t,n){return um.set.call(this,e[0],t,n,e[0])};function cm(e,t){const n=e[pr];return(n?jo(n):e)[t]}function QO(e,t,n){var i;const r=lb(t,n);return r?"value"in r?r.value:(i=r.get)==null?void 0:i.call(e.draft_):void 0}function lb(e,t){if(!(t in e))return;let n=Us(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Us(n)}}function lm(e){e.modified_||(e.modified_=!0,e.parent_&&lm(e.parent_))}function dm(e){e.copy_||(e.copy_=im(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var JO=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const s=n;n=t;const u=this;return function(d=s,...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 i;if(Uo(t)){const s=ab(this),u=fm(t,void 0);let c=!0;try{i=n(u),c=!1}finally{c?sm(s):am(s)}return sb(s,r),ub(i,s)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===tb&&(i=void 0),this.autoFreeze_&&om(i,!0),r){const s=[],u=[];Ho("Patches").generateReplacementPatches_(t,i,s,u),r(s,u)}return i}else Ur(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(u,...c)=>this.produceWithPatches(u,d=>t(d,...c));let r,i;return[this.produce(t,n,(u,c)=>{r=u,i=c}),r,i]},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){Uo(e)||Ur(8),js(e)&&(e=ZO(e));const t=ab(this),n=fm(e,void 0);return n[pr].isManual_=!0,am(t),n}finishDraft(e,t){const n=e&&e[pr];(!n||!n.isManual_)&&Ur(9);const{scope_:r}=n;return sb(r,t),ub(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 i=t[n];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}n>-1&&(t=t.slice(n+1));const r=Ho("Patches").applyPatches_;return js(e)?r(e,t):this.produce(e,i=>r(i,t))}};function fm(e,t){const n=fu(e)?Ho("MapSet").proxyMap_(e,t):Al(e)?Ho("MapSet").proxySet_(e,t):KO(e,t);return(t?t.scope_:ob()).drafts_.push(n),n}function ZO(e){return js(e)||Ur(10,e),db(e)}function db(e){if(!Uo(e)||Cl(e))return e;const t=e[pr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=im(e,t.scope_.immer_.useStrictShallowCopy_)}else n=im(e,!0);return _l(n,(r,i)=>{ib(n,r,db(i))}),t&&(t.finalized_=!1),n}var eP=new JO,tP=eP.produce;function nP(e,t,n){var r=_.useMemo(function(){return tP(e)},[e]);return _.useReducer(r,t,n)}const rP=e=>Array.from(new Set((e!=null?e:[]).map(t=>t.trim()).filter(Boolean))),fb=_.createContext(null),pb=_.createContext(null),iP=({children:e,dispatch:t})=>{const n=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_INITIALIZED,payload:x})},[t]),r=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_OPEN,payload:x})},[t]),i=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_INLINE,payload:x})},[t]),s=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ELEMENT_ID,payload:x})},[t]),u=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ENTRY_TYPE,payload:x})},[t]),c=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID,payload:x})},[t]),d=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_USER_PROMPT,payload:x})},[t]),f=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_PARAMS,payload:x})},[t]),m=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE,payload:x})},[t]),h=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE,payload:x})},[t]),y=_.useCallback(x=>{t({type:Ft.SET_PROMPTS_EXTENSION_RESPONSE_LOADING,payload:x})},[t]),E=_.useMemo(()=>({setIsInitialized:n,setIsOpen:r,setIsInline:i,setElementId:s,setEntryType:u,setActivePromptsId:c,setUserPrompt:d,setParams:f,setPromptsMessage:m,setResponseMessage:h,setIsResponseLoading:y}),[n,r,i,s,u,c,d,f,m,h,y]);return w.jsx(pb.Provider,{value:E,children:e})},oP=(e,t)=>{const{type:n,payload:r}=t;switch(n){case Ft.SET_PROMPTS_EXTENSION_INITIALIZED:e.isInitialized=r;break;case Ft.SET_PROMPTS_EXTENSION_OPEN:e.isOpen=r;break;case Ft.SET_PROMPTS_EXTENSION_INLINE:e.isInline=r;break;case Ft.SET_PROMPTS_EXTENSION_ELEMENT_ID:e.elementId=r;break;case Ft.SET_PROMPTS_EXTENSION_ENTRY_TYPE:e.entryType=r;break;case Ft.SET_PROMPTS_EXTENSION_PARAMS:e.params=r;break;case Ft.RESET_PROMPTS_EXTENSION_PARAMS:e.params=null;break;case Ft.SET_PROMPTS_EXTENSION_USER_PROMPT:e.userPrompt=r;break;case Ft.SET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=r;break;case Ft.RESET_PROMPTS_EXTENSION_ACTIVE_PROMPTS_ID:e.activePromptsId=null;break;case Ft.SET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=r;break;case Ft.RESET_PROMPTS_EXTENSION_PROMPTS_MESSAGE:e.promptsMessage=null;break;case Ft.SET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=r;break;case Ft.RESET_PROMPTS_EXTENSION_RESPONSE_MESSAGE:e.responseMessage=null;break;case Ft.SET_PROMPTS_EXTENSION_RESPONSE_LOADING:e.isResponseLoading=r;break}},sP=({promptsConfig:e,children:t})=>{const[n,r]=nP(oP,pe(B(B({},Ty),e||{}),{staticQuestions:rP((e==null?void 0:e.staticQuestions)||[])}));return w.jsx(fb.Provider,{value:n,children:w.jsx(iP,{dispatch:r,children:t})})},aP={productId:fr.productId,pdpLink:fr.pdpLink},mb=_.createContext(aP),uP=({children:e})=>{const[t,n]=_.useState(fr.productId),[r,i]=_.useState(fr.pdpLink);_.useEffect(()=>{const u=({detail:c})=>{if((c==null?void 0:c.property)==="pdp-context"){const d=c.value;n(d.productId),i(d.pdpLink);return}(c==null?void 0:c.property)==="productId"&&n(c.value),(c==null?void 0:c.property)==="pdpLink"&&i(c.value)};return L1(u),()=>{D1(u)}},[]);const s=_.useMemo(()=>({productId:t,pdpLink:r}),[t,r]);return w.jsx(mb.Provider,{value:s,children:e})},hb=({mode:e,apiKey:t,apiToken:n,baseUrl:r,logoUrl:i,headerText:s,headerConfig:u,theme:c,openLinksInNewTab:d,onNavigate:f,globalClassName:m,isDevelopment:h=!1,componentType:y,componentConfig:E,initialEntry:x,entryMessage:A,disclaimerText:k,disclaimerMarkdown:v,clientContext:N,searchPlaceholder:L,searchButtonLabel:P,searchConfig:z,suggestionButtonConfig:D,messageAlignment:q,autoScroll:V,promptsConfig:G,showProductDescription:I,resetConversationMessage:W,conversationHistory:Q,messagingConfig:K,translations:ae,overrides:oe,overridesUrl:he,inlineOverrides:se,__features:ee,children:ce})=>{var Oe,ne,be,_e;const O=h||iC(),j=_.useRef({}),te=_.useRef(!1);te.current||(te.current=!0,j.current=nC({enablePageContext:!!(K!=null&&K.enablePageContext),initialPageContext:K==null?void 0:K.initialPageContext,initialEntry:x,isDevelopment:O}));const M=(Oe=u==null?void 0:u.actions)==null?void 0:Oe.minimize,ge=_.useMemo(()=>M===void 0?E:pe(B({},E),{enableMinimize:yp(M,!!(E!=null&&E.enableMinimize))}),[E,M]);return w.jsx(mC,{translations:ae,children:w.jsx(mI,{mode:e,baseUrl:r,apiKey:t,apiToken:n,logoUrl:i,headerText:s,headerConfig:u,entryMessage:A,theme:c,globalClassName:m,openLinksInNewTab:d,onNavigate:f,searchPlaceholder:L,searchButtonLabel:P,searchConfig:z,suggestionButtonConfig:D,messageAlignment:q,autoScroll:V,showProductDescription:I,componentConfig:ge,clientContext:N,disclaimerMarkdown:v,disclaimerText:k,resetConversationMessage:W,conversationHistory:Q,isDevelopment:O,__features:ee,progressStepsLimit:K==null?void 0:K.progressStepsLimit,routingAttributes:K==null?void 0:K.routingAttributes,enableDownloadTranscript:yp((ne=u==null?void 0:u.actions)==null?void 0:ne.downloadTranscript,(be=K==null?void 0:K.enableDownloadTranscript)!=null?be:!0),enablePageContext:K==null?void 0:K.enablePageContext,enableEscalationToAgent:K==null?void 0:K.enableEscalationToAgent,enableImageUpload:K==null?void 0:K.enableImageUpload,showProductCaptions:K==null?void 0:K.showProductCaptions,connectingMessages:K==null?void 0:K.connectingMessages,children:w.jsx(QC,{entryType:(_e=j.current.entryType)!=null?_e:x==null?void 0:x.type,componentConfig:E,componentType:y,children:w.jsx(uP,{children:w.jsx(sP,{promptsConfig:G,children:w.jsx(cC,{overridesUrl:he,inlineOverrides:se||oe,children:w.jsx(eb,{scrt2Url:(K==null?void 0:K.scrt2Url)||"",orgId:(K==null?void 0:K.orgId)||"",esDeveloperName:(K==null?void 0:K.esDeveloperName)||"",routingAttributes:(K==null?void 0:K.routingAttributes)||{},conversationId:K==null?void 0:K.conversationId,continuationToken:K==null?void 0:K.continuationToken,lastEventId:K==null?void 0:K.lastEventId,capabilitiesVersion:K==null?void 0:K.capabilitiesVersion,enablePageContext:K==null?void 0:K.enablePageContext,enableLogging:O,onProductResult:K==null?void 0:K.onProductResult,onEndConversation:K==null?void 0:K.onEndConversation,onSessionUpdate:K==null?void 0:K.onSessionUpdate,cartTransport:K==null?void 0:K.cartTransport,storefrontCartPageUrl:K==null?void 0:K.storefrontCartPageUrl,children:w.jsx(fC,{children:ce})})})})})})})})};var pm={exports:{}},nr={},mm={exports:{}},hm={};var gb;function cP(){return gb||(gb=1,(function(e){function t(ee,ce){var O=ee.length;ee.push(ce);e:for(;0<O;){var j=O-1>>>1,te=ee[j];if(0<i(te,ce))ee[j]=ce,ee[O]=te,O=j;else break e}}function n(ee){return ee.length===0?null:ee[0]}function r(ee){if(ee.length===0)return null;var ce=ee[0],O=ee.pop();if(O!==ce){ee[0]=O;e:for(var j=0,te=ee.length,M=te>>>1;j<M;){var ge=2*(j+1)-1,Oe=ee[ge],ne=ge+1,be=ee[ne];if(0>i(Oe,O))ne<te&&0>i(be,Oe)?(ee[j]=be,ee[ne]=O,j=ne):(ee[j]=Oe,ee[ge]=O,j=ge);else if(ne<te&&0>i(be,O))ee[j]=be,ee[ne]=O,j=ne;else break e}}return ce}function i(ee,ce){var O=ee.sortIndex-ce.sortIndex;return O!==0?O:ee.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var d=[],f=[],m=1,h=null,y=3,E=!1,x=!1,A=!1,k=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate!="undefined"?setImmediate:null;typeof navigator!="undefined"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function L(ee){for(var ce=n(f);ce!==null;){if(ce.callback===null)r(f);else if(ce.startTime<=ee)r(f),ce.sortIndex=ce.expirationTime,t(d,ce);else break;ce=n(f)}}function P(ee){if(A=!1,L(ee),!x)if(n(d)!==null)x=!0,he(z);else{var ce=n(f);ce!==null&&se(P,ce.startTime-ee)}}function z(ee,ce){x=!1,A&&(A=!1,v(V),V=-1),E=!0;var O=y;try{for(L(ce),h=n(d);h!==null&&(!(h.expirationTime>ce)||ee&&!W());){var j=h.callback;if(typeof j=="function"){h.callback=null,y=h.priorityLevel;var te=j(h.expirationTime<=ce);ce=e.unstable_now(),typeof te=="function"?h.callback=te:h===n(d)&&r(d),L(ce)}else r(d);h=n(d)}if(h!==null)var M=!0;else{var ge=n(f);ge!==null&&se(P,ge.startTime-ce),M=!1}return M}finally{h=null,y=O,E=!1}}var D=!1,q=null,V=-1,G=5,I=-1;function W(){return!(e.unstable_now()-I<G)}function Q(){if(q!==null){var ee=e.unstable_now();I=ee;var ce=!0;try{ce=q(!0,ee)}finally{ce?K():(D=!1,q=null)}}else D=!1}var K;if(typeof N=="function")K=function(){N(Q)};else if(typeof MessageChannel!="undefined"){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=Q,K=function(){oe.postMessage(null)}}else K=function(){k(Q,0)};function he(ee){q=ee,D||(D=!0,K())}function se(ee,ce){V=k(function(){ee(e.unstable_now())},ce)}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(ee){ee.callback=null},e.unstable_continueExecution=function(){x||E||(x=!0,he(z))},e.unstable_forceFrameRate=function(ee){0>ee||125<ee?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):G=0<ee?Math.floor(1e3/ee):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(ee){switch(y){case 1:case 2:case 3:var ce=3;break;default:ce=y}var O=y;y=ce;try{return ee()}finally{y=O}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(ee,ce){switch(ee){case 1:case 2:case 3:case 4:case 5:break;default:ee=3}var O=y;y=ee;try{return ce()}finally{y=O}},e.unstable_scheduleCallback=function(ee,ce,O){var j=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?j+O:j):O=j,ee){case 1:var te=-1;break;case 2:te=250;break;case 5:te=1073741823;break;case 4:te=1e4;break;default:te=5e3}return te=O+te,ee={id:m++,callback:ce,priorityLevel:ee,startTime:O,expirationTime:te,sortIndex:-1},O>j?(ee.sortIndex=O,t(f,ee),n(d)===null&&ee===n(f)&&(A?(v(V),V=-1):A=!0,se(P,O-j))):(ee.sortIndex=te,t(d,ee),x||E||(x=!0,he(z))),ee},e.unstable_shouldYield=W,e.unstable_wrapCallback=function(ee){var ce=y;return function(){var O=y;y=ce;try{return ee.apply(this,arguments)}finally{y=O}}}})(hm)),hm}var yb;function lP(){return yb||(yb=1,mm.exports=cP()),mm.exports}var Eb;function dP(){if(Eb)return nr;Eb=1;var e=Fr(),t=lP();function n(o){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+o,l=1;l<arguments.length;l++)a+="&args[]="+encodeURIComponent(arguments[l]);return"Minified React error #"+o+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function s(o,a){u(o,a),u(o+"Capture",a)}function u(o,a){for(i[o]=a,o=0;o<a.length;o++)r.add(a[o])}var c=!(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={},h={};function y(o){return d.call(h,o)?!0:d.call(m,o)?!1:f.test(o)?h[o]=!0:(m[o]=!0,!1)}function E(o,a,l,p){if(l!==null&&l.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return p?!1:l!==null?!l.acceptsBooleans:(o=o.toLowerCase().slice(0,5),o!=="data-"&&o!=="aria-");default:return!1}}function x(o,a,l,p){if(a===null||typeof a=="undefined"||E(o,a,l,p))return!0;if(p)return!1;if(l!==null)switch(l.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function A(o,a,l,p,b,T,C){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=p,this.attributeNamespace=b,this.mustUseProperty=l,this.propertyName=o,this.type=a,this.sanitizeURL=T,this.removeEmptyString=C}var k={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(o){k[o]=new A(o,0,!1,o,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(o){var a=o[0];k[a]=new A(a,1,!1,o[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(o){k[o]=new A(o,2,!1,o.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(o){k[o]=new A(o,2,!1,o,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(o){k[o]=new A(o,3,!1,o.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(o){k[o]=new A(o,3,!0,o,null,!1,!1)}),["capture","download"].forEach(function(o){k[o]=new A(o,4,!1,o,null,!1,!1)}),["cols","rows","size","span"].forEach(function(o){k[o]=new A(o,6,!1,o,null,!1,!1)}),["rowSpan","start"].forEach(function(o){k[o]=new A(o,5,!1,o.toLowerCase(),null,!1,!1)});var v=/[\-:]([a-z])/g;function N(o){return o[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(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(o){var a=o.replace(v,N);k[a]=new A(a,1,!1,o,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(o){k[o]=new A(o,1,!1,o.toLowerCase(),null,!1,!1)}),k.xlinkHref=new A("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(o){k[o]=new A(o,1,!1,o.toLowerCase(),null,!0,!0)});function L(o,a,l,p){var b=k.hasOwnProperty(a)?k[a]:null;(b!==null?b.type!==0:p||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(x(a,l,b,p)&&(l=null),p||b===null?y(a)&&(l===null?o.removeAttribute(a):o.setAttribute(a,""+l)):b.mustUseProperty?o[b.propertyName]=l===null?b.type===3?!1:"":l:(a=b.attributeName,p=b.attributeNamespace,l===null?o.removeAttribute(a):(b=b.type,l=b===3||b===4&&l===!0?"":""+l,p?o.setAttributeNS(p,a,l):o.setAttribute(a,l))))}var P=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,z=Symbol.for("react.element"),D=Symbol.for("react.portal"),q=Symbol.for("react.fragment"),V=Symbol.for("react.strict_mode"),G=Symbol.for("react.profiler"),I=Symbol.for("react.provider"),W=Symbol.for("react.context"),Q=Symbol.for("react.forward_ref"),K=Symbol.for("react.suspense"),ae=Symbol.for("react.suspense_list"),oe=Symbol.for("react.memo"),he=Symbol.for("react.lazy"),se=Symbol.for("react.offscreen"),ee=Symbol.iterator;function ce(o){return o===null||typeof o!="object"?null:(o=ee&&o[ee]||o["@@iterator"],typeof o=="function"?o:null)}var O=Object.assign,j;function te(o){if(j===void 0)try{throw Error()}catch(l){var a=l.stack.trim().match(/\n( *(at )?)/);j=a&&a[1]||""}return`
17
17
  `+j+o}var M=!1;function ge(o,a){if(!o||M)return"";M=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(fe){var p=fe}Reflect.construct(o,[],a)}else{try{a.call()}catch(fe){p=fe}o.call(a.prototype)}else{try{throw Error()}catch(fe){p=fe}o()}}catch(fe){if(fe&&p&&typeof fe.stack=="string"){for(var b=fe.stack.split(`
18
18
  `),T=p.stack.split(`
19
19
  `),C=b.length-1,H=T.length-1;1<=C&&0<=H&&b[C]!==T[H];)H--;for(;1<=C&&0<=H;C--,H--)if(b[C]!==T[H]){if(C!==1||H!==1)do if(C--,H--,0>H||b[C]!==T[H]){var Y=`
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.60.1",
4
+ "version": "1.60.2",
5
5
  "keywords": [
6
6
  "cimulate",
7
7
  "copilot",