@yellowdotai/yellow-chat-sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +462 -0
- package/dist/index.d.ts +1623 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.js +2 -0
- package/dist/index.umd.js +2 -0
- package/package.json +76 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function t(t,e){return e.forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(s){if("default"!==s&&!(s in t)){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})}),Object.freeze(t)}function e(t,e,s){return{code:t,message:e,details:s?.details,originalError:s?.originalError,timestamp:new Date,recoverable:s?.recoverable??!1}}class s extends Error{constructor(t,e,i){super(e),this.name="YellowChatError",this.code=t,this.details=i?.details,this.recoverable=i?.recoverable??!1,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,s)}toSDKError(){return{code:this.code,message:this.message,details:this.details,originalError:this,timestamp:this.timestamp,recoverable:this.recoverable}}}const i="/api/plugin/bot-load-details",n="/api/plugin/update-user-info",r="/integrations/yellowmessenger/receive",o="/api/plugin/active-ticket-details",a="/api/engagements/inbound/list-campaigns",h="/api/integration/file-upload",c={HOST:"https://app.yellowmessenger.com",XMPP_DOMAIN:"xmpp.yellowmssngr.com",WEBSOCKET_ROUTE:"/websocket/",MAX_RECONNECT_ATTEMPTS:5,RECONNECT_BASE_DELAY:1e3,RECONNECT_MAX_DELAY:3e4,MESSAGE_TIMEOUT:1e4,RATE_LIMIT_WINDOW:6e4,RATE_LIMIT_MAX_MESSAGES:20,PING_INTERVAL:6e4,SOURCE:"yellowmessenger",STORAGE_KEY_PREFIX:"ym_sdk_"};function u(){return Date.now()}function l(){const t="abcdefghijklmnopqrstuvwxyz0123456789";let e="";for(let s=0;s<32;s++)e+=t.charAt(Math.floor(36*Math.random()));return e}const d=new Map;function f(t){return"undefined"==typeof window?d:function(t){try{const e="local"===t?window.localStorage:window.sessionStorage,s="__storage_test__";return e.setItem(s,s),e.removeItem(s),!0}catch{return!1}}(t)?"local"===t?window.localStorage:window.sessionStorage:d}class p{constructor(t={}){const e=t.type??"local";this.prefix=t.prefix??c.STORAGE_KEY_PREFIX,this.storage=f(e)}getKey(t){return`${this.prefix}${t}`}get(t,e){try{const s=this.getKey(t);let i;return i=this.storage instanceof Map?this.storage.get(s)??null:this.storage.getItem(s),null===i?e??null:JSON.parse(i)}catch{return e??null}}set(t,e){try{const s=this.getKey(t),i=JSON.stringify(e);return this.storage instanceof Map?this.storage.set(s,i):this.storage.setItem(s,i),!0}catch{return!1}}remove(t){try{const e=this.getKey(t);return this.storage instanceof Map?this.storage.delete(e):this.storage.removeItem(e),!0}catch{return!1}}has(t){const e=this.getKey(t);return this.storage instanceof Map?this.storage.has(e):null!==this.storage.getItem(e)}clear(){try{if(this.storage instanceof Map)for(const t of this.storage.keys())t.startsWith(this.prefix)&&this.storage.delete(t);else{const t=[];for(let e=0;e<this.storage.length;e++){const s=this.storage.key(e);s&&s.startsWith(this.prefix)&&t.push(s)}t.forEach(t=>{this.storage instanceof Map?this.storage.delete(t):this.storage.removeItem(t)})}return!0}catch{return!1}}}const m=new p({type:"local"});new p({type:"session"});const g="user_id",w="jid";class v{constructor(t){this.timestamps=[],this.maxActions=t?.maxActions??c.RATE_LIMIT_MAX_MESSAGES,this.windowMs=t?.windowMs??c.RATE_LIMIT_WINDOW}canProceed(){return this.cleanup(),this.timestamps.length<this.maxActions}tryAction(){return this.cleanup(),!(this.timestamps.length>=this.maxActions)&&(this.timestamps.push(Date.now()),!0)}getState(){return this.cleanup(),{timestamps:[...this.timestamps],isLimited:this.timestamps.length>=this.maxActions}}getRemainingActions(){return this.cleanup(),Math.max(0,this.maxActions-this.timestamps.length)}getTimeUntilReset(){if(this.cleanup(),this.timestamps.length<this.maxActions)return 0;const t=this.timestamps[0]+this.windowMs;return Math.max(0,t-Date.now())}reset(){this.timestamps=[]}cleanup(){const t=Date.now()-this.windowMs;this.timestamps=this.timestamps.filter(e=>e>t)}}const y={debug:0,info:1,warn:2,error:3,none:4};const b=new class{constructor(){this.config={level:"warn",prefix:"[YellowSDK]",enabled:!1}}configure(t){this.config={...this.config,...t}}enableDebug(){this.config.enabled=!0,this.config.level="debug"}disable(){this.config.enabled=!1}shouldLog(t){return!(!this.config.enabled&&"error"!==t)&&y[t]>=y[this.config.level]}format(t,e){return`${this.config.prefix} ${t}: ${e}`}sanitize(t){if(null==t)return t;if("object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>this.sanitize(t));const e={},s=["ymAuthenticationToken","token","password","secret","apiKey","authorization","cookie","session"];for(const[i,n]of Object.entries(t)){const t=i.toLowerCase();s.some(e=>t.includes(e.toLowerCase()))?e[i]="[REDACTED]":e[i]="object"==typeof n&&null!==n?this.sanitize(n):n}return e}debug(t,e,s){this.shouldLog("debug")&&(void 0!==s?console.debug(this.format(t,e),this.sanitize(s)):console.debug(this.format(t,e)))}info(t,e,s){this.shouldLog("info")&&(void 0!==s?console.info(this.format(t,e),this.sanitize(s)):console.info(this.format(t,e)))}warn(t,e,s){this.shouldLog("warn")&&(void 0!==s?console.warn(this.format(t,e),this.sanitize(s)):console.warn(this.format(t,e)))}error(t,e,s){void 0!==s?console.error(this.format(t,e),this.sanitize(s)):console.error(this.format(t,e))}};class S{constructor(t,e,s){this.cachedBotInfo=null,this.transport=t,this.eventEmitter=e,this.config=s}async loadBotDetails(){this.eventEmitter.emit("bot:loading");const t={bot:this.config.bot,source:this.config.source??"web",subSource:this.config.subSource??"widget",linkType:"web",payload:this.config.payload??{},loadEverywhere:!1};this.config.deviceToken&&(t.deviceToken=this.config.deviceToken),this.config.ymAuthenticationToken&&(t.ymAuthenticationToken=this.config.ymAuthenticationToken),this.config.utmCampaign&&(t.utm_campaign=this.config.utmCampaign),this.config.utmMedium&&(t.utm_medium=this.config.utmMedium),this.config.utmSource&&(t.utm_source=this.config.utmSource);const s=`${i}?bot=${encodeURIComponent(this.config.bot)}`;try{b.debug("BotLoadAPI","Fetching bot details");const i=await this.transport.post(s,t,{headers:{"x-ym-bot-id":this.config.bot}});if(!i.success||!i.data){b.error("BotLoadAPI","Bot load failed");const t=i.error??e("BOT_LOAD_FAILED","Failed to load bot details");throw this.eventEmitter.emit("bot:loadFailed",t),t}const n=i.data;if(!n.success||!n.data){b.error("BotLoadAPI","API returned failure");const t=e("BOT_LOAD_FAILED","Bot load API returned failure");throw this.eventEmitter.emit("bot:loadFailed",t),t}const r=this.transformResponse(n.data);return this.cachedBotInfo=r.botConfig,this.eventEmitter.emit("bot:loaded",r.botConfig),r.welcomeMessages&&r.welcomeMessages.length>0&&this.eventEmitter.emit("bot:welcomeMessages",r.welcomeMessages),r}catch(t){if(b.error("BotLoadAPI","Exception during bot load"),t&&"object"==typeof t&&"code"in t)throw t;const s=e("BOT_LOAD_FAILED",t instanceof Error?t.message:"Failed to load bot details",{originalError:t instanceof Error?t:void 0});throw this.eventEmitter.emit("bot:loadFailed",s),s}}getBotInfo(){return this.cachedBotInfo}transformResponse(t){return{botConfig:{botId:this.config.bot,name:t.botName??"Bot",icon:t.botIcon,botType:t.botType,subscriptionId:t.subscriptionId,useSecureUid:t.useSecureUid,feUID:t.feUID,turnOff:t.turnOff,defaultLanguage:t.defaultLanguage,languages:t.languages,skin:t.skin?{primaryColor:t.skin.primaryColor,secondaryColor:t.skin.secondaryColor,botBubbleColor:t.skin.botBubbleColor,botTextColor:t.skin.botTextColor,userBubbleColor:t.skin.userBubbleColor,userTextColor:t.skin.userTextColor,headerColor:t.skin.headerColor,headerTextColor:t.skin.headerTextColor,fontFamily:t.skin.fontFamily,fontSize:t.skin.fontSize,borderRadius:t.skin.borderRadius,showTyping:t.skin.showTyping,enableSound:t.skin.enableSound,showBranding:t.skin.showBranding}:void 0,features:t.features?{fileUpload:t.features.fileUpload,voiceInput:t.features.voiceInput,locationSharing:t.features.locationSharing,messageHistory:t.features.messageHistory,typingIndicator:t.features.typingIndicator,readReceipts:t.features.readReceipts,pushNotifications:t.features.pushNotifications,liveAgent:t.features.liveAgent,feedback:t.features.feedback,emoji:t.features.emoji,attachments:t.features.attachments,multiLanguage:t.features.multiLanguage}:void 0},welcomeMessages:t.welcomeMessages?.map(t=>({message:t.message,delay:t.delay}))??[],banners:t.banners?.map(t=>({id:t.id,title:t.title,message:t.message,image:t.image,actionUrl:t.actionUrl,actionText:t.actionText,position:t.position,type:t.type,autoDismiss:t.autoDismiss}))}}}class x{constructor(t,e,s){this.transport=t,this.eventEmitter=e,this.config=s}async listCampaigns(t){const e={bot:this.config.bot,uid:t};try{const t=await this.transport.get(a,e);if(!t.success)return b.warn("CampaignAPI","Failed to get campaigns"),{success:!1};const s=t.data||{success:!1},i=s.campaigns||s.data||[];return this.eventEmitter.emit("campaigns:loaded",i),{success:!0,campaigns:i}}catch(t){return b.error("CampaignAPI","Error fetching campaigns"),{success:!1}}}}class E{constructor(t,e,s){this.lastAssignedAgentId=null,this.transport=t,this.eventEmitter=e,this.config=s}resetAgentTracking(){this.lastAssignedAgentId=null}async getActiveTicketDetails(t){const e={uid:t,bot:this.config.bot,source:this.config.source??"yellowmessenger"};try{const t=await this.transport.get(o,e);if(!t.success)return b.warn("TicketAPI","Failed to get active ticket details"),{success:!1};const s=t.data||{success:!1};if(s.isAgentConnected&&s.agentProfile){const t=s.agentProfile.username||s.agentProfile.name||"";t!==this.lastAssignedAgentId&&(this.lastAssignedAgentId=t,this.eventEmitter.emit("agent:assigned",s.agentProfile))}return this.eventEmitter.emit("ticket:details",s),s}catch(t){return b.error("TicketAPI","Error fetching active ticket details"),{success:!1}}}}class M{constructor(t,e,s){this.transport=t,this.eventEmitter=e,this.config=s}async updateUserInfo(t,e){const s="undefined"!=typeof screen&&screen.width>768?"desktop":"mobile",i="undefined"!=typeof navigator?navigator.userAgent:void 0,r="undefined"!=typeof window?window.location.href:void 0,o={bot:this.config.bot,uid:t,source:this.config.source??"yellowmessenger",subSource:this.config.subSource??"widget",payload:this.config.payload,deviceToken:this.config.deviceToken,device:s,ua:i,pageUrl:r,triggerJourney:this.config.triggerJourney,isWelcomeMessagePresent:e?.isWelcomeMessagePresent??!1,shouldRefreshContext:e?.shouldRefreshContext??!1,...e};try{const t=`${n}?bot=${encodeURIComponent(this.config.bot)}`,e=await this.transport.post(t,o,{headers:{"x-ym-bot-id":this.config.bot}});if(!e.success)return b.warn("UserAPI","Failed to update user info"),{success:!1};const s=e.data||{success:!1};return this.eventEmitter.emit("user:infoUpdated",s),s.data?.welcomeMessages&&s.data.welcomeMessages.length>0&&this.eventEmitter.emit("bot:welcomeMessages",s.data.welcomeMessages),s}catch(t){return b.error("UserAPI","Error updating user info"),{success:!1}}}async bulkUpdateMessageStatus(t){if(!t||0===t.length)return!0;const e=t.map(t=>({source:"yellowmessenger",messageId:t.messageId,traceId:t.traceId,eventType:"user_received",timestamp:Date.now()}));try{const s=`/api/status/message/bulk?bot=${encodeURIComponent(this.config.bot)}`;return(await this.transport.post(s,{payload:e},{headers:{"x-ym-bot-id":this.config.bot}})).success?(b.debug("UserAPI",`Marked ${t.length} messages as received`),!0):(b.warn("UserAPI","Failed to update message status"),!1)}catch(t){return b.error("UserAPI","Error updating message status"),!1}}async updateMessageStatus(t,e,s="user_received",i="sandbox"){try{const n=`/api/status/message/${encodeURIComponent(this.config.bot)}?bot=${encodeURIComponent(this.config.bot)}`,r={messageId:t,traceId:e,source:"yellowmessenger",botType:i,eventType:s,timestamp:Date.now()};return(await this.transport.post(n,{payload:r},{headers:{"x-ym-bot-id":this.config.bot,"Content-Type":"application/json"}})).success?(b.debug("UserAPI",`Message ${t} status updated to ${s}`),!0):(b.warn("UserAPI","Failed to update message status"),!1)}catch(t){return b.error("UserAPI","Error updating message status"),!1}}}class A{constructor(t,e){this.reconnectCallback=null,this.currentAttempt=0,this.currentDelay=0,this.reconnectTimer=null,this.isReconnecting=!1,this.isStopped=!1,this.eventEmitter=t,this.config={maxAttempts:e?.maxAttempts??c.MAX_RECONNECT_ATTEMPTS,baseDelay:e?.baseDelay??c.RECONNECT_BASE_DELAY,maxDelay:e?.maxDelay??c.RECONNECT_MAX_DELAY,backoffMultiplier:e?.backoffMultiplier??2,jitter:e?.jitter??!0}}setReconnectCallback(t){this.reconnectCallback=t}startReconnecting(){this.isReconnecting||this.isStopped||(this.isReconnecting=!0,this.currentAttempt=0,this.currentDelay=this.config.baseDelay,this.scheduleReconnect())}stop(){this.isStopped=!0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reset()}resume(){this.isStopped=!1}reset(){this.currentAttempt=0,this.currentDelay=this.config.baseDelay,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}onConnectionSuccess(){this.reset(),this.isStopped=!1}getState(){return{isReconnecting:this.isReconnecting,currentAttempt:this.currentAttempt,maxAttempts:this.config.maxAttempts,nextRetryIn:this.currentDelay}}scheduleReconnect(){if(this.isStopped||!this.isReconnecting)return;if(this.currentAttempt>=this.config.maxAttempts)return this.isReconnecting=!1,void this.eventEmitter.emit("connection:reconnectFailed");this.currentAttempt++;let t=this.currentDelay;if(this.config.jitter){const e=.25*t;t+=Math.random()*e*2-e}this.eventEmitter.emit("connection:reconnecting",{attempt:this.currentAttempt,delay:t}),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},t),this.currentDelay=Math.min(this.currentDelay*this.config.backoffMultiplier,this.config.maxDelay)}async attemptReconnect(){if(!this.isStopped&&this.isReconnecting)if(this.reconnectCallback)try{await this.reconnectCallback()?this.onConnectionSuccess():this.scheduleReconnect()}catch(t){b.error("Reconnect","Reconnect attempt failed"),this.scheduleReconnect()}else b.error("Reconnect","No reconnect callback set")}}class D{constructor(t,e){this.connection=null,this.Strophe=null,this.$msg=null,this.$pres=null,this.handlers={messageHandler:null,presenceHandler:null,pingHandler:null},this.connectionState="disconnected",this.jid=null,this.userId=null,this.pingInterval=null,this.onMessageCallback=null,this.onPresenceCallback=null,this.reconnectTimeout=0,this.reconnectTimer=null,this.userInitiatedDisconnect=!1,this.connectedOnce=!1,this.maxReconnectTimeout=6e4,this.networkListenersAttached=!1,this.eventEmitter=t,this.config=e,this.setupNetworkListeners()}setupNetworkListeners(){"undefined"==typeof window||this.networkListenersAttached||(this.networkListenersAttached=!0,window.addEventListener("offline",()=>{b.debug("XMPP","Network offline detected"),this.eventEmitter.emit("network:offline")}),window.addEventListener("online",()=>{b.debug("XMPP","Network online detected"),this.eventEmitter.emit("network:online"),!this.connectedOnce||this.isConnected()||this.userInitiatedDisconnect||(b.debug("XMPP","Network back online, attempting reconnection..."),this.scheduleReconnect(!0))}),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&(b.debug("XMPP","Tab became visible"),!this.connectedOnce||this.isConnected()||this.userInitiatedDisconnect||(b.debug("XMPP","Tab visible, checking connection..."),this.scheduleReconnect(!0)))}),b.debug("XMPP","Network listeners attached"))}async initialize(){try{const t="undefined"!=typeof window?window:null;if(t?.Strophe)return b.debug("XMPP","Using global Strophe from CDN"),this.Strophe=t.Strophe,this.$msg=t.$msg||null,this.$pres=t.$pres||null,b.debug("XMPP","$msg available:",!!this.$msg),void b.debug("XMPP","$pres available:",!!this.$pres);b.debug("XMPP","Loading Strophe via import");const e=await Promise.resolve().then(function(){return ot});this.Strophe=e.Strophe,this.$msg=e.$msg||null,this.$pres=e.$pres||null}catch(t){throw b.error("XMPP","Failed to load Strophe.js:",t),t}}async connect(t){if(this.Strophe||await this.initialize(),!this.Strophe)throw new Error("Strophe.js not loaded");const e=this.config.xmppDomain??c.XMPP_DOMAIN,s=this.config.websocketRoute??c.WEBSOCKET_ROUTE;let i;i=this.config.xmppHost?this.config.xmppHost.replace("http","ws"):this.config.host&&this.config.host.length>0?this.config.host.replace("http","ws"):"wss://cloud.yellow.ai";const n=`${i}${s}`;b.debug("XMPP","WebSocket URL:",n),this.connection=new this.Strophe.Connection(n),this.userId=t;const r=`webWidget_${Math.floor(1e5+9e5*Math.random())}`;t?(this.jid=`${t}@${e}/${r}`,b.debug("XMPP","Connecting with user JID:",this.jid)):(this.jid=`${e}/${r}`,b.debug("XMPP","Connecting anonymously with JID:",this.jid)),this.setConnectionState("connecting");const o=this.connection.xmlInput?.bind(this.connection);return this.connection.xmlInput=t=>{try{const e=t.getElementsByTagName("jid");if(e.length>0){const t=e[0].textContent?.split("/")[0];if(t){b.debug("XMPP","Captured server JID from stream:",t),this.jid=t;const e=t.split("@")[0];e&&(this.userId=e,b.debug("XMPP","Server assigned userId:",e),this.eventEmitter.emit("connection:uidAssigned",e))}}}catch(t){}o&&o(t)},new Promise((t,e)=>{const s=this.Strophe.Status;this.connection.connect(this.jid,null,i=>{this.handleConnectionStatus(i,s,t,e)})})}handleConnectionStatus(t,e,s,i){switch(t){case e.CONNECTING:this.setConnectionState("connecting");break;case e.CONNECTED:this.setConnectionState("connected"),this.connectedOnce=!0,this.reconnectTimeout=0,this.userInitiatedDisconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);try{const t=this.connection?.jid;t&&(b.debug("XMPP","Server assigned JID:",t),this.jid=t),this.setupHandlers(),this.startPingInterval(),this.sendPresence()}catch(t){b.warn("XMPP","Error during post-connect setup:",t)}s();break;case e.DISCONNECTED:this.setConnectionState("disconnected"),this.cleanup(),this.eventEmitter.emit("connection:disconnected",{code:"DISCONNECTED",message:"Connection closed",wasClean:!0}),!this.userInitiatedDisconnect&&this.connectedOnce&&(b.debug("XMPP","Unexpected disconnect, scheduling reconnect..."),this.scheduleReconnect());break;case e.DISCONNECTING:break;case e.CONNFAIL:this.setConnectionState("failed"),this.cleanup(),this.connectedOnce&&!this.userInitiatedDisconnect?(b.debug("XMPP","Connection failed, scheduling reconnect..."),this.scheduleReconnect()):i(new Error("Connection failed"));break;case e.AUTHFAIL:this.setConnectionState("failed"),this.cleanup(),this.connectedOnce&&!this.userInitiatedDisconnect?(b.debug("XMPP","Auth failed, scheduling reconnect..."),this.scheduleReconnect()):i(new Error("Authentication failed"));break;case e.ERROR:this.setConnectionState("failed"),this.cleanup(),this.connectedOnce&&!this.userInitiatedDisconnect?(b.debug("XMPP","XMPP error, scheduling reconnect..."),this.scheduleReconnect()):i(new Error("XMPP error"));break;case e.CONNTIMEOUT:this.setConnectionState("failed"),this.cleanup(),this.connectedOnce&&!this.userInitiatedDisconnect?(b.debug("XMPP","Connection timeout, scheduling reconnect..."),this.scheduleReconnect()):i(new Error("Connection timeout"))}}disconnect(){if(this.userInitiatedDisconnect=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectTimeout=0,this.connection)try{this.connection.disconnect("User initiated disconnect")}catch{}this.cleanup(),this.setConnectionState("disconnected")}scheduleReconnect(t=!1){if(this.userInitiatedDisconnect)return void b.debug("XMPP","Skipping reconnect - user initiated disconnect");if("connected"===this.connectionState||"connecting"===this.connectionState)return void b.debug("XMPP","Skipping reconnect - already connected/connecting");if("undefined"!=typeof navigator&&!navigator.onLine)return void b.debug("XMPP","Skipping reconnect - network offline");if(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),t)this.reconnectTimeout=0;else{const t=2+Math.random(),e=this.reconnectTimeout*t;this.reconnectTimeout=0===this.reconnectTimeout?1e3+1e3*Math.random():Math.min(e,this.maxReconnectTimeout)}const e=Math.round(this.reconnectTimeout);b.debug("XMPP",`Scheduling reconnect in ${e}ms`),this.setConnectionState("reconnecting"),this.eventEmitter.emit("connection:reconnecting",{attempt:Math.ceil(Math.log2(e/1e3+1)),delay:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.attemptReconnect()},e)}async attemptReconnect(){if(this.userInitiatedDisconnect)b.debug("XMPP","Aborting reconnect - user initiated disconnect");else if("connected"!==this.connectionState)if("undefined"==typeof navigator||navigator.onLine){b.debug("XMPP","Attempting reconnection with userId:",this.userId||"(anonymous)");try{await this.connect(this.userId||""),b.debug("XMPP","Reconnection successful"),this.eventEmitter.emit("connection:reconnected",{userId:this.userId})}catch(t){b.error("XMPP","Reconnection failed:",t),this.scheduleReconnect()}}else b.debug("XMPP","Aborting reconnect - still offline");else b.debug("XMPP","Aborting reconnect - already connected")}async reconnect(){b.debug("XMPP","Manual reconnect requested"),this.userInitiatedDisconnect=!1,this.reconnectTimeout=0,await this.attemptReconnect()}sendMessage(t,e){if(!this.connection)throw new Error("Not connected");if(!this.$msg)throw new Error("Strophe $msg helper not available");b.debug("XMPP","Sending message");const s=this.$msg({to:t,type:"chat",from:this.jid}).c("body").t(e).tree();this.connection.send(s)}sendPresence(){if(!this.connection||!this.$pres)return;const t=this.$pres().tree();this.connection.send(t)}onMessage(t){this.onMessageCallback=t}onPresence(t){this.onPresenceCallback=t}getConnectionState(){return this.connectionState}getJid(){return this.jid}getUserId(){return this.userId}isConnected(){return"connected"===this.connectionState}setupHandlers(){this.connection&&(this.connection.addHandler(t=>(b.error("XMPP","Stream error received:",t.outerHTML||t),this.eventEmitter.emit("connection:error",{code:"STREAM_ERROR",message:"XMPP stream error",details:{stanza:t.outerHTML||String(t)},timestamp:new Date,recoverable:!0}),!0),null,"error"),this.connection.addHandler(t=>(t.getElementsByTagName("error")[0]&&b.error("XMPP","IQ error:",t.outerHTML||t),!0),null,"iq","error"),this.handlers.messageHandler=this.connection.addHandler(t=>{if(this.onMessageCallback)try{this.onMessageCallback(t)}catch(t){b.error("XMPP","Error in message handler:",t)}return!0},null,"message","chat"),this.handlers.presenceHandler=this.connection.addHandler(t=>{if(this.onPresenceCallback)try{this.onPresenceCallback(t)}catch(t){b.error("XMPP","Error in presence handler:",t)}return!0},null,"presence","subscribe"),this.handlers.pingHandler=this.connection.addHandler(t=>(this.handlePing(t),!0),"urn:xmpp:ping","iq"))}handlePing(t){const e=t.getAttribute("id"),s=t.getAttribute("from");e&&s&&this.connection}startPingInterval(){this.stopPingInterval(),this.pingInterval=setInterval(()=>{this.sendPresence()},c.PING_INTERVAL)}stopPingInterval(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}cleanup(){if(this.stopPingInterval(),this.connection){if(this.handlers.messageHandler)try{this.connection.deleteHandler(this.handlers.messageHandler)}catch{}if(this.handlers.presenceHandler)try{this.connection.deleteHandler(this.handlers.presenceHandler)}catch{}if(this.handlers.pingHandler)try{this.connection.deleteHandler(this.handlers.pingHandler)}catch{}}this.handlers={messageHandler:null,presenceHandler:null,pingHandler:null}}setConnectionState(t){const e=this.connectionState;this.connectionState=t,e!==t&&this.eventEmitter.emit("connection:stateChange",t)}}class _{constructor(t,e,s={}){this.userId=null,this.isInitialized=!1,this.networkOnline=!0,this.handleOnline=()=>{this.networkOnline=!0,!this.isConnected()&&this.options.autoReconnect&&(this.reconnectionManager.resume(),this.reconnectionManager.startReconnecting())},this.handleOffline=()=>{this.networkOnline=!1,this.reconnectionManager.stop()},this.eventEmitter=t,this.config=e,this.options={autoReconnect:s.autoReconnect??!0,networkAware:s.networkAware??!0},this.transport=new D(t,e),this.reconnectionManager=new A(t,{maxAttempts:e.reconnectAttempts,baseDelay:e.reconnectBaseDelay,maxDelay:e.reconnectMaxDelay}),this.reconnectionManager.setReconnectCallback(async()=>this.attemptReconnect()),this.options.networkAware&&"undefined"!=typeof window&&this.setupNetworkListeners()}async initialize(){this.isInitialized||(await this.transport.initialize(),this.isInitialized=!0)}async connect(t){this.isInitialized||await this.initialize(),this.userId=t??this.getOrCreateUserId(),this.eventEmitter.emit("connection:connecting");try{await this.transport.connect(this.userId),this.reconnectionManager.onConnectionSuccess(),this.eventEmitter.emit("connection:connected",{userId:this.userId}),m.set(g,this.userId),m.set(w,this.transport.getJid())}catch(t){const s=e("CONNECTION_FAILED",t instanceof Error?t.message:"Connection failed",{originalError:t instanceof Error?t:void 0,recoverable:!0});throw this.eventEmitter.emit("connection:error",s),this.options.autoReconnect&&this.networkOnline&&this.reconnectionManager.startReconnecting(),t}}disconnect(){this.reconnectionManager.stop(),this.transport.disconnect(),this.eventEmitter.emit("connection:disconnected",{code:"USER_INITIATED",message:"User initiated disconnect",wasClean:!0})}getConnectionState(){return this.reconnectionManager.getState().isReconnecting?"reconnecting":this.transport.getConnectionState()}isConnected(){return this.transport.isConnected()}getUserId(){return this.userId??this.transport.getUserId()}getJid(){return this.transport.getJid()}getTransport(){return this.transport}onMessage(t){this.transport.onMessage(t)}onPresence(t){this.transport.onPresence(t)}reconnect(){this.reconnectionManager.resume(),this.reconnectionManager.startReconnecting()}destroy(){this.disconnect(),this.removeNetworkListeners(),this.isInitialized=!1}async attemptReconnect(){if(!this.userId)return!1;try{return await this.transport.connect(this.userId),this.eventEmitter.emit("connection:connected",{userId:this.userId}),!0}catch{return!1}}getOrCreateUserId(){if(this.config.userId)return this.config.userId;const t=m.get(g);return t||`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,10)}`}setupNetworkListeners(){window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline)}removeNetworkListeners(){"undefined"!=typeof window&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline))}}class T{constructor(){this.events=new Map,this.onceHandlers=new WeakSet,this.maxListeners=100}on(t,e){this.events.has(t)||this.events.set(t,new Set);const s=this.events.get(t);return s.size>=this.maxListeners&&b.warn("EventEmitter",`Max listeners exceeded for event "${String(t)}"`),s.add(e),()=>this.off(t,e)}once(t,e){const s=(...i)=>{this.off(t,s),e(...i)};return this.onceHandlers.add(s),this.on(t,s)}off(t,e){const s=this.events.get(t);s&&(s.delete(e),0===s.size&&this.events.delete(t))}emit(t,...e){const s=this.events.get(t);if(s){const i=Array.from(s);for(const s of i)try{s(...e)}catch(e){b.error("EventEmitter",`Error in handler for "${String(t)}"`)}}}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}listenerCount(t){const e=this.events.get(t);return e?e.size:0}eventNames(){return Array.from(this.events.keys())}setMaxListeners(t){this.maxListeners=t}getMaxListeners(){return this.maxListeners}hasListeners(t){return this.listenerCount(t)>0}}class I{constructor(t){this.lastAssignedAgentId=null,this.eventEmitter=t}resetAgentTracking(){this.lastAssignedAgentId=null}parseFromXmpp(t){const e=t.querySelector("body");if(!e||!e.textContent)return null;const s=e.textContent;return this.parse(s)}parse(t){const e=function(t,e){try{return JSON.parse(t)}catch{return e}}(t,null);if(!e)return this.createTextMessage(t);if(0===Object.keys(e).length)return null;if("message-previous-conversation"===e.type||"previous-messages-with-offset"===e.type)return this.handlePreviousConversation(e),null;if("previous-messages-with-offset"===e.event?.code||"message-previous-conversation"===e.event?.code||"fetchPreviousConversation"===e.event?.code||"previousConversation"===e.event?.code)return this.handlePreviousConversationFromEvent(e.event),null;if(void 0!==e.typing)return this.eventEmitter.emit("message:typing",e.typing),null;const s="string"==typeof e.event?e.event:e.event?.code,i="ticket-assigned-agent-profile"===s;if(e.messageAgentProfile||e.agentProfile){const t=e.agentProfile||e.messageAgentProfile,s=this.parseAgentProfile(t);if(s){const t=s.username||s.name||"";if(t!==this.lastAssignedAgentId&&(this.lastAssignedAgentId=t,this.eventEmitter.emit("agent:assigned",s)),i){const t=s.name||"Agent";return{id:String(Date.now()),timestamp:new Date,type:"system",content:{message:`${t} joined the conversation`},sender:"system"}}}if(!i)return null}return e.ticketClosedEvent?(this.eventEmitter.emit("ticket:closed"),this.eventEmitter.emit("agent:left"),this.lastAssignedAgentId=null,{id:String(Date.now()),timestamp:new Date,type:"system",content:{message:"Conversation ended"},sender:"system"}):"ticket-resolved"===s||e.ticketResolvedEvent?(this.eventEmitter.emit("ticket:resolved"),this.eventEmitter.emit("agent:left"),this.lastAssignedAgentId=null,{id:String(Date.now()),timestamp:new Date,type:"system",content:{message:"Ticket has been resolved"},sender:"system"}):(void 0!==e.queuePositionData&&this.eventEmitter.emit("queue:position",{position:e.queuePositionData,message:e.queuePositionMessage}),e.disableInput?this.eventEmitter.emit("ui:hideInput"):e.enableInput&&this.eventEmitter.emit("ui:showInput",{enabled:!0,placeholder:e.disableInputMessage}),e.event?this.handleEvent(e):this.parseMessageContent(e))}parseMessageContent(t){const e=String(t.messageId??t.i??Date.now()),s=t.timestamp?new Date(t.timestamp):new Date,i=t.agentProfile||t.messageAgentProfile?"agent":"bot",{type:n,content:r}=this.determineTypeAndContent(t);if(!n)return null;const o={id:e,timestamp:s,type:n,content:r,sender:i};return t.traceId&&(o.o=t.traceId),o}determineTypeAndContent(t){const e={};if(t.richMessage)return this.parseRichMessage(t.richMessage);if(t.quickReply||t.quickReplies){const s=t.quickReply||t.quickReplies;return e.quickReplies={title:s?.message||s?.title,options:this.parseQuickReplyOptions(s?.options??[])},this.eventEmitter.emit("ui:showQuickReplies",e.quickReplies.options),t.message&&(e.text=t.message),{type:"quickReplies",content:e}}if(t.image)return{type:"image",content:{url:t.image}};if(t.video)return{type:"video",content:{url:t.video,controls:!0,autoplay:!1,loop:!1,muted:!1,downloadable:!0,thumbnail:void 0}};if(t.file){const e=t.options,s="string"==typeof t.file?t.file:t.file.url??"",i=e?.filename||("object"==typeof t.file?t.file.name:null)||this.extractFilename(s),n=this.getFileType(s,i);return"image"===n?{type:"image",content:{url:s}}:"video"===n?{type:"video",content:{url:s,controls:!0,autoplay:!1,loop:!1,muted:!1,downloadable:!0,thumbnail:void 0}}:"audio"===n?{type:"audio",content:{url:s}}:{type:"file",content:{url:s,name:i,size:e?.size??("object"==typeof t.file?t.file.size:void 0),mimeType:e?.mimeType??("object"==typeof t.file?t.file.mimeType:void 0)}}}if(t.location)return{type:"location",content:{latitude:t.location.latitude,longitude:t.location.longitude}};const s=t.message||t.text;return s?{type:"text",content:{message:s}}:{type:null,content:e}}parseRichMessage(t){const e={};return t.cards&&t.cards.length>0?(e.cards=t.cards.map(t=>this.parseCard(t)),this.eventEmitter.emit("ui:showCards",e.cards),{type:"cards",content:e}):t.webView?(e.webView=this.parseWebView(t.webView),this.eventEmitter.emit("ui:showWebView",e.webView),{type:"webView",content:e}):t.webViews&&t.webViews.length>0?(e.webViews=t.webViews.map(t=>this.parseWebView(t)),{type:"webViews",content:e}):t.rating?(e.rating=this.parseRating(t.rating),this.eventEmitter.emit("ui:showRating",e.rating),{type:"rating",content:e}):t.text||t.title?{type:"text",content:{message:t.text||t.title}}:{type:"text",content:e}}parseCard(t){return{title:t.title??t.text??"",description:t.description,image:t.image,url:t.url,actions:t.actions?.map(t=>this.parseCardAction(t))}}parseCardAction(t){return{title:t.title??t.text??t.buttonDefault??"",type:t.type??"postback",url:t.url}}parseWebView(t){return{url:t.url??"",title:t.title,height:t.height??"tall"}}parseRating(t){return{title:t.title,ratingType:t.ratingType??"star"}}parseQuickReplyOptions(t){return t.map(t=>({title:t.title??t.text??"",value:t.value,icon:t.icon}))}parseAgentProfile(t){return t&&"boolean"!=typeof t?{username:t.username??"",name:t.name??t.username??"",profilePicture:t.profile_picture,description:t.description,webrtcUsername:t.webrtc_username,owner:t.owner}:null}createTextMessage(t){return{id:String(Date.now()),timestamp:new Date,type:"text",content:{message:t},sender:"bot"}}handleEvent(t){const e="object"==typeof t.event?t.event:null;return e?.code&&t.message?{id:String(t.messageId??Date.now()),timestamp:new Date,type:"notification",content:{message:t.message},sender:"bot",metadata:{eventCode:e.code,eventData:e.data}}:null}handlePreviousConversation(t){let e=[];if("string"==typeof t.data)try{e=JSON.parse(t.data)}catch{return void b.error("Parser","Failed to parse previous conversation data")}else Array.isArray(t.data)&&(e=t.data);this.emitHistoryEvents(e)}handlePreviousConversationFromEvent(t){let e=[];if("string"==typeof t.data)try{e=JSON.parse(t.data)}catch(t){return void b.error("Parser","Failed to parse event.data as JSON")}else Array.isArray(t.data)&&(e=t.data);this.emitHistoryEvents(e)}emitHistoryEvents(t){const e=t.map(t=>this.cleanHistoryMessage(t));this.eventEmitter.emit("history:previousMessages",e),this.eventEmitter.emit("history:loaded",{messages:e,hasMore:t.length>=50})}cleanHistoryMessage(t){const e=t;let s=e.message,i=null;if("string"==typeof e.message)try{i=JSON.parse(e.message)}catch{}else"object"==typeof e.message&&null!==e.message&&(i=e.message);if(i?.event){const t=i.event,s=t.code,n=t.data;return this.formatSystemEvent(e,s,n)}if(i?.file||e.file){const t=i?.file||e.file,s=i?.options||e.options,n=s?.filename||this.extractFilename(t),r=this.getFileType(t,n);return this.formatAttachmentMessage(e,t,n,r,i)}i&&(s=i.message||i.text||e.message);const n=this.determineSender(e);return{id:e.id||e.i,type:"text",content:{message:s},timestamp:e.timestamp,sender:n}}formatSystemEvent(t,e,s){let i="";switch(e){case"ticket-assigned-agent-profile":i=s?.message||`${s?.agentName||"Agent"} joined the conversation`;break;case"ticket-resolved":i="Ticket has been resolved";break;case"ticket-closed":i="Conversation ended";break;case"agent-away":i=s?.message||"Agent is away";break;case"agent-transferred":i=s?.message||"Transferred to another agent";break;default:i=s?.message||`System: ${e}`}return{id:t.id||t.i,type:"system",content:{message:i},timestamp:t.timestamp,sender:"system"}}formatAttachmentMessage(t,e,s,i,n){const r=this.determineSender(t),o={id:t.id||t.i,type:i,timestamp:t.timestamp,sender:r};switch(i){case"image":case"audio":o.content={url:e};break;case"video":o.content={url:e,controls:!0,autoplay:!1,loop:!1,muted:!1,downloadable:!0};break;default:o.content={url:e,name:s,size:n?.size||void 0}}return o}determineSender(t){const e=!0===t.you||"USER"===t.messageType,s="AGENT"===t.messageType;return e?"user":s?"agent":"bot"}extractFilename(t){try{const e=t.split("/"),s=e[e.length-1];return decodeURIComponent(s.split("?")[0])}catch{return"file"}}getFileType(t,e){const s=t.toLowerCase(),i=e.toLowerCase();return/\.(jpg|jpeg|png|gif|webp|bmp|svg)/.test(i)||/\.(jpg|jpeg|png|gif|webp|bmp|svg)/.test(s)?"image":/\.(mp4|webm|mov|avi|mkv)/.test(i)||/\.(mp4|webm|mov|avi|mkv)/.test(s)?"video":/\.(mp3|wav|ogg|m4a|aac)/.test(i)||/\.(mp3|wav|ogg|m4a|aac)/.test(s)?"audio":"file"}}class C{constructor(t,e,s,i){this.botType="sandbox",this.eventEmitter=t,this.config=e,this.connectionManager=s,this.restTransport=i,this.messageParser=new I(t),this.rateLimiter=new v({maxActions:e.rateLimitMaxMessages??c.RATE_LIMIT_MAX_MESSAGES,windowMs:e.rateLimitWindow??c.RATE_LIMIT_WINDOW}),this.setupMessageHandler()}setBotType(t){this.botType=t,b.debug("MsgHandler"," Bot type set to:",t)}async sendMessage(t,s={}){const i=function(t){if(!t||"string"!=typeof t)return"";let e=t.trim();return e.length>1e4&&(e=e.substring(0,1e4)),e}(t);if(!i)throw e("INVALID_MESSAGE","Message cannot be empty");if(!s.skipRateLimit&&!this.rateLimiter.tryAction()){const t=e("MESSAGE_RATE_LIMITED","Too many messages sent. Please wait.",{recoverable:!0});throw this.eventEmitter.emit("message:failed",{messageId:"",error:t}),t}const n=u(),r=l(),o={message:i,messageId:n,source:this.config.source??c.SOURCE,subSource:this.config.subSource??"widget",pageUrl:"undefined"!=typeof window?window.location.href:void 0,title:s.title};try{return await this.sendViaRest(o),this.eventEmitter.emit("message:sent",{id:String(n),message:i}),{id:String(n),traceId:r,timestamp:new Date}}catch(t){const s=e("MESSAGE_SEND_FAILED",t instanceof Error?t.message:"Failed to send message",{originalError:t instanceof Error?t:void 0});throw this.eventEmitter.emit("message:failed",{messageId:String(n),error:s}),t}}async sendEvent(t,e){b.debug("MsgHandler",`sendEvent called with code: ${t}`);const s=this.connectionManager.getUserId(),i={event:{tabId:`${this.generateRandomId().substring(0,8)}${Date.now()}`,code:t,...e||{}},source:"yellowmessenger",subSource:"sdk",isSensitiveInfo:!1},n=JSON.stringify(i),o=`${s}_${this.generateRandomId()}`,a={from:s,to:this.config.bot,message:n,xmppNotUsed:!0},h=this.botType||"sandbox",c=`${r}?bottype=${h}&bot=${encodeURIComponent(this.config.bot)}`;b.debug("MsgHandler","Sending event via REST",{code:t});try{const t=await this.restTransport.post(c,a,{headers:{"x-ym-trace-id":o,"x-ym-message-origin":"web-widget","x-ym-bot-id":this.config.bot}});b.debug("MsgHandler"," Event REST response:",t)}catch(t){throw b.error("MsgHandler"," Failed to send event:",t),t}}async sendTyping(t){const e={messageId:u(),source:this.config.source??c.SOURCE,subSource:this.config.subSource??"widget",typing:t};try{await this.sendViaRest(e)}catch{}}async sendLocation(t,e){const s=u(),i=l(),n={messageId:s,source:this.config.source??c.SOURCE,subSource:this.config.subSource??"widget",location:{latitude:t,longitude:e}};try{return await this.sendViaRest(n),this.eventEmitter.emit("message:sent",{id:String(s),message:`Location: ${t}, ${e}`}),{id:String(s),traceId:i,timestamp:new Date}}catch(t){throw t}}async sendViaRest(t){const e=this.connectionManager.getUserId(),s={message:t.message,source:this.config.source||"yellowmessenger",subSource:"sdk",messageId:t.messageId,pageUrl:t.pageUrl,isSensitiveInfo:!1},i=JSON.stringify(s),n=`${e}_${this.generateRandomId()}`,o={from:e,to:this.config.bot,message:i,xmppNotUsed:!0},a=this.botType||"sandbox",h=`${r}?bottype=${a}&bot=${encodeURIComponent(this.config.bot)}`;b.debug("MsgHandler","Sending message via REST");const c=await this.restTransport.post(h,o,{headers:{"x-ym-trace-id":n,"x-ym-message-origin":"web-widget","x-ym-bot-id":this.config.bot}});if(b.debug("MsgHandler"," Response:",c),!c.success)throw c.error}generateRandomId(){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";let e="";for(let s=0;s<21;s++)e+=t.charAt(Math.floor(62*Math.random()));return e}setupMessageHandler(){this.connectionManager.onMessage(t=>{try{const e=this.messageParser.parseFromXmpp(t);if(e){if("bot"===e.sender||"agent"===e.sender){this.eventEmitter.emit("message:typing",!1);const t=e.o;e.id&&t&&this.updateMessageStatus(e.id,t,"user_received").catch(t=>{b.warn("MsgHandler","Failed to send message ack:",t)})}const t={id:e.id,timestamp:e.timestamp,type:e.type,content:e.content,sender:e.sender};this.eventEmitter.emit("message:received",t)}}catch(t){b.error("MsgHandler"," Error parsing message:",t)}})}parseMessage(t){return this.messageParser.parse(t)}async updateMessageStatus(t,e,s="user_received"){try{const i=`/api/status/message/${encodeURIComponent(this.config.bot)}?bot=${encodeURIComponent(this.config.bot)}`,n={messageId:t,traceId:e,source:"yellowmessenger",botType:this.botType,eventType:s,timestamp:Date.now()};return!!(await this.restTransport.post(i,{payload:n},{headers:{"x-ym-bot-id":this.config.bot,"Content-Type":"application/json"}})).success&&(b.debug("MsgHandler",`Message ${t} status updated to ${s}`),!0)}catch(t){return b.warn("MsgHandler","Error updating message status"),!1}}}class P{constructor(t){this.config=t,this.baseUrl=t.host??c.HOST,this.defaultHeaders={"Content-Type":"application/json",Accept:"application/json"}}setBotId(t){this.defaultHeaders["x-ym-bot-id"]=t}setAuthToken(t){this.defaultHeaders.Authorization=`Bearer ${t}`}async get(t,e,s){let i=`${this.baseUrl}${t}`;if(e){i+=`?${new URLSearchParams(e).toString()}`}return this.request(i,{...s,method:"GET"})}async post(t,e,s){const i=`${this.baseUrl}${t}`;return this.request(i,{...s,method:"POST",body:e})}async put(t,e,s){const i=`${this.baseUrl}${t}`;return this.request(i,{...s,method:"PUT",body:e})}async delete(t,e){const s=`${this.baseUrl}${t}`;return this.request(s,{...e,method:"DELETE"})}async uploadFile(t,s,i){const n=`${this.baseUrl}${t}`,r=new FormData;if(r.append("file",s),i)for(const[t,e]of Object.entries(i))r.append(t,e);try{const t=await fetch(n,{method:"POST",headers:{...this.getDefaultHeaders()},body:r,credentials:"include"});if(!t.ok)return{success:!1,error:e("FILE_UPLOAD_FAILED",`Upload failed: ${t.status}`)};return{success:!0,data:await t.json()}}catch(t){return{success:!1,error:e("FILE_UPLOAD_FAILED","File upload failed",{originalError:t instanceof Error?t:void 0})}}}async request(t,s={}){const{method:i="GET",headers:n={},body:r,timeout:o=c.MESSAGE_TIMEOUT,withCredentials:a=!0}=s,h=new AbortController,u=setTimeout(()=>h.abort(),o);try{const s={method:i,headers:{...this.getDefaultHeaders(),...n,"x-ym-trace-id":l()},signal:h.signal,credentials:a?"include":"omit"};r&&"GET"!==i&&(s.body=JSON.stringify(r)),b.debug("REST",`${i} request`);const o=await fetch(t,s);if(b.debug("REST",`Response ${o.status}`),clearTimeout(u),!o.ok)return{success:!1,error:e("API_ERROR",`API request failed: ${o.status} ${o.statusText}`,{details:{status:o.status,url:t}})};const c=o.headers.get("content-type");if(!c||!c.includes("application/json"))return{success:!0,data:void 0};return{success:!0,data:await o.json()}}catch(s){return clearTimeout(u),s instanceof Error&&"AbortError"===s.name?{success:!1,error:e("MESSAGE_TIMEOUT","Request timed out",{details:{url:t,timeout:o}})}:{success:!1,error:e("NETWORK_ERROR",s instanceof Error?s.message:"Network request failed",{originalError:s instanceof Error?s:void 0})}}}getDefaultHeaders(){const t={...this.defaultHeaders,"x-ym-message-origin":this.config.source??c.SOURCE};return this.config.bot&&(t["x-ym-bot-id"]=this.config.bot),t}buildUrl(t,e){let s=`${this.baseUrl}${t}`;if(e){const t=new URLSearchParams;for(const[s,i]of Object.entries(e))null!=i&&t.append(s,String(i));const i=t.toString();i&&(s+=`?${i}`)}return s}}const k={host:"https://cloud.yellow.ai",xmppDomain:"xmpp.yellowmssngr.com",websocketRoute:"/websocket/",reconnectAttempts:5,reconnectBaseDelay:1e3,reconnectMaxDelay:3e4,messageTimeout:1e4,rateLimitWindow:6e4,rateLimitMaxMessages:20,source:"yellowmessenger"},N="anon_jid_";class O{constructor(){this.config=null,this.connectionManager=null,this.messageHandler=null,this.restTransport=null,this.botLoadAPI=null,this.ticketAPI=null,this.campaignAPI=null,this.userAPI=null,this.isInitialized=!1,this.botInfo=null,this.storedUid=null,this.authenticatedFeUID=null,this.isReconnecting=!1,this.lastSeenMessageTimestamp=0,this.eventEmitter=new T,this.setupInternalListeners()}getStoredUid(){if("undefined"==typeof window||!window.localStorage)return null;try{const t=N+(this.config?.bot||"");return localStorage.getItem(t)}catch{return null}}storeUid(t){if("undefined"!=typeof window&&window.localStorage)try{const e=N+(this.config?.bot||"");localStorage.setItem(e,t),b.debug("SDK","Stored UID in localStorage")}catch(t){b.warn("SDK","Failed to store UID",t)}}async init(t){if(!t.bot)throw new s("INVALID_CONFIG","Bot ID is required");if(this.config={...k,...t},this.config.debug&&(b.enableDebug(),b.debug("SDK","Debug logging enabled"),b.debug("SDK","Config:",{bot:this.config.bot,host:this.config.host,source:this.config.source||"yellowmessenger"})),this.restTransport=new P(this.config),this.connectionManager=new _(this.eventEmitter,this.config,{autoReconnect:!0,networkAware:!0}),this.messageHandler=new C(this.eventEmitter,this.config,this.connectionManager,this.restTransport),this.botLoadAPI=new S(this.restTransport,this.eventEmitter,this.config),this.ticketAPI=new E(this.restTransport,this.eventEmitter,this.config),this.campaignAPI=new x(this.restTransport,this.eventEmitter,this.config),this.userAPI=new M(this.restTransport,this.eventEmitter,this.config),this.storedUid=this.getStoredUid(),b.debug("SDK","Retrieved stored UID from localStorage"),!this.config.skipBotLoad)try{const t=await this.botLoadAPI.loadBotDetails();this.botInfo=t.botConfig,this.messageHandler&&t.botConfig.botType&&this.messageHandler.setBotType(t.botConfig.botType),this.config.ymAuthenticationToken&&t.botConfig.feUID?(this.authenticatedFeUID=t.botConfig.feUID,b.debug("SDK","ymAuthenticationToken: feUID received from server:",this.authenticatedFeUID)):this.config.ymAuthenticationToken&&b.debug("SDK","ymAuthenticationToken provided but no feUID received from server")}catch(t){throw b.error("SDK","Failed to load bot details",t),new s("BOT_LOAD_FAILED","Failed to load bot details. Cannot proceed.")}this.isInitialized=!0}async connect(t){let e;this.ensureInitialized();const s="syncApi"===this.config.source;s&&t?(e=t,b.debug("SDK","Hybrid mode: using passed userId for ticket continuity:",e),this.authenticatedFeUID&&b.debug("SDK","feUID available but not used in hybrid mode")):this.authenticatedFeUID&&!s?(e=this.authenticatedFeUID,b.debug("SDK","Headless mode: using feUID from ymAuthenticationToken:",e),t&&t!==this.authenticatedFeUID&&b.debug("SDK","Ignoring passed userId, using feUID instead")):(e=t||this.storedUid||void 0,b.debug("SDK","Connecting with UID:",e||"(anonymous)"));this.eventEmitter.on("connection:uidAssigned",e=>{this.authenticatedFeUID||s&&t||e&&e!==this.storedUid&&(b.debug("SDK","Server assigned new UID"),this.storeUid(e),this.storedUid=e)}),await this.connectionManager.connect(e);const i=this.getUserId();i&&this.fetchPostConnectionData(i)}setupInternalListeners(){this.eventEmitter.on("connection:reconnected",async()=>{const t=this.getUserId();t&&(b.debug("SDK","Reconnected, fetching essential data"),this.isReconnecting=!0,await this.fetchPostReconnectionData(t))}),this.eventEmitter.on("history:previousMessages",async t=>{if(!this.isReconnecting||!this.userAPI||!t||0===t.length)return void(t&&t.length>0&&this.updateLastSeenTimestamp(t));const e=t.filter(t=>null!==t&&"object"==typeof t).filter(t=>this.getMessageTimestamp(t)>this.lastSeenMessageTimestamp).filter(t=>t.id||t.messageId||t.i).map(t=>({messageId:String(t.id||t.messageId||t.i),traceId:t.traceId?String(t.traceId):void 0}));if(this.isReconnecting=!1,this.updateLastSeenTimestamp(t),e.length>0){b.debug("SDK",`Marking ${e.length} missed messages as received`);try{await this.userAPI.bulkUpdateMessageStatus(e)}catch(t){b.warn("SDK","Failed to update message status",t)}}})}getMessageTimestamp(t){const e=t.timestamp||t.createdAt||t.time;if(!e)return 0;if("number"==typeof e)return e;if("string"==typeof e){const t=Date.parse(e);return isNaN(t)?0:t}return e instanceof Date?e.getTime():0}updateLastSeenTimestamp(t){let e=this.lastSeenMessageTimestamp;for(const s of t)if(s&&"object"==typeof s){const t=this.getMessageTimestamp(s);t>e&&(e=t)}this.lastSeenMessageTimestamp=e}async fetchPostReconnectionData(t){if(b.debug("SDK","Fetching post-reconnection data"),this.ticketAPI)try{await this.ticketAPI.getActiveTicketDetails(t),b.debug("SDK","Ticket details refreshed after reconnect")}catch(t){b.warn("SDK","Failed to fetch ticket details on reconnect",t)}try{await this.fetchPreviousConversation(),b.debug("SDK","Previous conversation fetch requested after reconnect")}catch(t){b.warn("SDK","Failed to fetch previous conversation on reconnect",t)}if(this.userAPI)try{await this.userAPI.updateUserInfo(t,{shouldRefreshContext:!1,isWelcomeMessagePresent:!0}),b.debug("SDK","User info updated after reconnect")}catch(t){b.warn("SDK","Failed to update user info on reconnect",t)}}async fetchPostConnectionData(t){b.debug("SDK","Fetching post-connection data");const e=[];this.ticketAPI&&e.push(this.ticketAPI.getActiveTicketDetails(t).catch(t=>(b.warn("SDK","Failed to fetch ticket details",t),null))),this.campaignAPI&&e.push(this.campaignAPI.listCampaigns(t).catch(t=>(b.warn("SDK","Failed to fetch campaigns",t),null))),await Promise.allSettled(e),b.debug("SDK","Ticket and campaigns fetched");try{await this.fetchPreviousConversation(),b.debug("SDK","Previous conversation fetch requested")}catch(t){b.warn("SDK","Failed to fetch previous conversation",t)}if(this.userAPI)try{const e="syncApi"===this.config.source||!0===this.config.disableWelcomeMessage;e&&b.debug("SDK","Suppressing welcome messages (hybrid mode or disableWelcomeMessage=true)"),await this.userAPI.updateUserInfo(t,{isWelcomeMessagePresent:e}),b.debug("SDK","User info updated")}catch(t){b.warn("SDK","Failed to update user info",t)}}async fetchPreviousConversation(t=50,e){this.ensureInitialized(),b.debug("SDK","Fetching previous conversation"),await this.messageHandler.sendEvent("fetchPreviousConversation",{limit:t,offset:e||null})}disconnect(){this.connectionManager&&this.connectionManager.disconnect()}async sendMessage(t,e){return this.ensureInitialized(),this.messageHandler.sendMessage(t,e)}async sendEventInternal(t,e){return this.ensureInitialized(),this.messageHandler.sendEvent(t,e)}async sendFile(t){this.ensureInitialized();const i=`file_${Date.now()}`;this.eventEmitter.emit("file:uploadStarted",{fileId:i,fileName:t.name});try{const s=await this.restTransport.uploadFile(h,t,{bot:this.config.bot});if(!s.success||!s.data)throw s.error??e("FILE_UPLOAD_FAILED","Upload failed");return this.eventEmitter.emit("file:uploadCompleted",{fileId:i,file:{url:s.data.url,name:s.data.name,size:s.data.size}}),await this.sendEventInternal("file-upload",{url:s.data.url,name:s.data.name,size:s.data.size}),s.data}catch(t){const n=t instanceof s?t.toSDKError():e("FILE_UPLOAD_FAILED",t instanceof Error?t.message:"Upload failed");throw this.eventEmitter.emit("file:uploadFailed",{fileId:i,error:n}),t}}isConnected(){return this.connectionManager?.isConnected()??!1}getUserId(){return"syncApi"===this.config.source?this.connectionManager?.getUserId()??null:this.authenticatedFeUID?this.authenticatedFeUID:this.connectionManager?.getUserId()??null}getBotInfo(){return this.botInfo}on(t,e){return this.eventEmitter.on(t,e)}off(t,e){this.eventEmitter.off(t,e)}ensureInitialized(){if(!this.isInitialized)throw new s("INVALID_CONFIG","SDK not initialized. Call init() first.")}}function R(){return new O}var $="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function F(t){return t&&t.u&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var L,U,j={exports:{}};var q,H,X={},B={},K={};function W(){if(q)return K;function t(t,e){return void 0===e&&(e=Object),e&&"function"==typeof e.freeze?e.freeze(t):t}q=1;var e=t({HTML:"text/html",isHTML:function(t){return t===e.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),s=t({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(t){return t===s.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});return K.assign=function(t,e){if(null===t||"object"!=typeof t)throw new TypeError("target is not an object");for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=e[s]);return t},K.find=function(t,e,s){if(void 0===s&&(s=Array.prototype),t&&"function"==typeof s.find)return s.find.call(t,e);for(var i=0;i<t.length;i++)if(Object.prototype.hasOwnProperty.call(t,i)){var n=t[i];if(e.call(void 0,n,i,t))return n}},K.freeze=t,K.MIME_TYPE=e,K.NAMESPACE=s,K}function z(){if(H)return B;H=1;var t=W(),e=t.find,s=t.NAMESPACE;function i(t){return""!==t}function n(t,e){return t.hasOwnProperty(e)||(t[e]=!0),t}function r(t){if(!t)return[];var e=function(t){return t?t.split(/[\t\n\f\r ]+/).filter(i):[]}(t);return Object.keys(e.reduce(n,{}))}function o(t,e){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}function a(t,e){var s=t.prototype;if(!(s instanceof e)){function i(){}i.prototype=e.prototype,o(s,i=new i),t.prototype=s=i}s.constructor!=t&&("function"!=typeof t&&console.error("unknown Class:"+t),s.constructor=t)}var h={},c=h.ELEMENT_NODE=1,u=h.ATTRIBUTE_NODE=2,l=h.TEXT_NODE=3,d=h.CDATA_SECTION_NODE=4,f=h.ENTITY_REFERENCE_NODE=5,p=h.ENTITY_NODE=6,m=h.PROCESSING_INSTRUCTION_NODE=7,g=h.COMMENT_NODE=8,w=h.DOCUMENT_NODE=9,v=h.DOCUMENT_TYPE_NODE=10,y=h.DOCUMENT_FRAGMENT_NODE=11,b=h.NOTATION_NODE=12,S={},x={};S.INDEX_SIZE_ERR=(x[1]="Index size error",1),S.DOMSTRING_SIZE_ERR=(x[2]="DOMString size error",2);var E=S.HIERARCHY_REQUEST_ERR=(x[3]="Hierarchy request error",3);S.WRONG_DOCUMENT_ERR=(x[4]="Wrong document",4),S.INVALID_CHARACTER_ERR=(x[5]="Invalid character",5),S.NO_DATA_ALLOWED_ERR=(x[6]="No data allowed",6),S.NO_MODIFICATION_ALLOWED_ERR=(x[7]="No modification allowed",7);var M=S.NOT_FOUND_ERR=(x[8]="Not found",8);S.NOT_SUPPORTED_ERR=(x[9]="Not supported",9);var A=S.INUSE_ATTRIBUTE_ERR=(x[10]="Attribute in use",10);function D(t,e){if(e instanceof Error)var s=e;else s=this,Error.call(this,x[t]),this.message=x[t],Error.captureStackTrace&&Error.captureStackTrace(this,D);return s.code=t,e&&(this.message=this.message+": "+e),s}function _(){}function T(t,e){this.l=t,this.m=e,I(this)}function I(t){var e=t.l.v||t.l.ownerDocument.v;if(t.v!=e){var s=t.m(t.l);yt(t,"length",s.length),o(s,t),t.v=e}}function C(){}function P(t,e){for(var s=t.length;s--;)if(t[s]===e)return s}function k(t,e,i,n){if(n?e[P(e,n)]=i:e[e.length++]=i,t){i.ownerElement=t;var r=t.ownerDocument;r&&(n&&U(r,t,n),function(t,e,i){t&&t.v++;var n=i.namespaceURI;n===s.XMLNS&&(e.S[i.prefix?i.localName:""]=i.value)}(r,t,i))}}function N(t,e,s){var i=P(e,s);if(!(i>=0))throw new D(M,new Error(t.tagName+"@"+s));for(var n=e.length-1;i<n;)e[i]=e[++i];if(e.length=n,t){var r=t.ownerDocument;r&&(U(r,t,s),s.ownerElement=null)}}function O(){}function R(){}function $(t){return("<"==t?"<":">"==t&&">")||"&"==t&&"&"||'"'==t&&"""||"&#"+t.charCodeAt()+";"}function F(t,e){if(e(t))return!0;if(t=t.firstChild)do{if(F(t,e))return!0}while(t=t.nextSibling)}function L(){this.ownerDocument=this}function U(t,e,i,n){t&&t.v++,i.namespaceURI===s.XMLNS&&delete e.S[i.prefix?i.localName:""]}function j(t,e,s){if(t&&t.v){t.v++;var i=e.childNodes;if(s)i[i.length++]=s;else{for(var n=e.firstChild,r=0;n;)i[r++]=n,n=n.nextSibling;i.length=r,delete i[i.length]}}}function q(t,e){var s=e.previousSibling,i=e.nextSibling;return s?s.nextSibling=i:t.firstChild=i,i?i.previousSibling=s:t.lastChild=s,e.parentNode=null,e.previousSibling=null,e.nextSibling=null,j(t.ownerDocument,t),e}function X(t){return t&&t.nodeType===R.DOCUMENT_TYPE_NODE}function K(t){return t&&t.nodeType===R.ELEMENT_NODE}function z(t){return t&&t.nodeType===R.TEXT_NODE}function J(t,s){var i=t.childNodes||[];if(e(i,K)||X(s))return!1;var n=e(i,X);return!(s&&n&&i.indexOf(n)>i.indexOf(s))}function G(t,s){var i=t.childNodes||[];if(e(i,function(t){return K(t)&&t!==s}))return!1;var n=e(i,X);return!(s&&n&&i.indexOf(n)>i.indexOf(s))}function V(t,e,s){if(!function(t){return t&&(t.nodeType===R.DOCUMENT_NODE||t.nodeType===R.DOCUMENT_FRAGMENT_NODE||t.nodeType===R.ELEMENT_NODE)}(t))throw new D(E,"Unexpected parent node type "+t.nodeType);if(s&&s.parentNode!==t)throw new D(M,"child not in parent");if(!function(t){return t&&(K(t)||z(t)||X(t)||t.nodeType===R.DOCUMENT_FRAGMENT_NODE||t.nodeType===R.COMMENT_NODE||t.nodeType===R.PROCESSING_INSTRUCTION_NODE)}(e)||X(e)&&t.nodeType!==R.DOCUMENT_NODE)throw new D(E,"Unexpected node type "+e.nodeType+" for parent node type "+t.nodeType)}function Y(t,s,i){var n=t.childNodes||[],r=s.childNodes||[];if(s.nodeType===R.DOCUMENT_FRAGMENT_NODE){var o=r.filter(K);if(o.length>1||e(r,z))throw new D(E,"More than one element or text in fragment");if(1===o.length&&!J(t,i))throw new D(E,"Element in fragment can not be inserted before doctype")}if(K(s)&&!J(t,i))throw new D(E,"Only one element can be added and only after doctype");if(X(s)){if(e(n,X))throw new D(E,"Only one doctype is allowed");var a=e(n,K);if(i&&n.indexOf(a)<n.indexOf(i))throw new D(E,"Doctype can only be inserted before an element");if(!i&&a)throw new D(E,"Doctype can not be appended since element is present")}}function Q(t,s,i){var n=t.childNodes||[],r=s.childNodes||[];if(s.nodeType===R.DOCUMENT_FRAGMENT_NODE){var o=r.filter(K);if(o.length>1||e(r,z))throw new D(E,"More than one element or text in fragment");if(1===o.length&&!G(t,i))throw new D(E,"Element in fragment can not be inserted before doctype")}if(K(s)&&!G(t,i))throw new D(E,"Only one element can be added and only after doctype");if(X(s)){function h(t){return X(t)&&t!==i}if(e(n,h))throw new D(E,"Only one doctype is allowed");var a=e(n,K);if(i&&n.indexOf(a)<n.indexOf(i))throw new D(E,"Doctype can only be inserted before an element")}}function Z(t,e,s,i){V(t,e,s),t.nodeType===R.DOCUMENT_NODE&&(i||Y)(t,e,s);var n=e.parentNode;if(n&&n.removeChild(e),e.nodeType===y){var r=e.firstChild;if(null==r)return e;var o=e.lastChild}else r=o=e;var a=s?s.previousSibling:t.lastChild;r.previousSibling=a,o.nextSibling=s,a?a.nextSibling=r:t.firstChild=r,null==s?t.lastChild=o:s.previousSibling=o;do{r.parentNode=t}while(r!==o&&(r=r.nextSibling));return j(t.ownerDocument||t,t),e.nodeType==y&&(e.firstChild=e.lastChild=null),e}function tt(){this.S={}}function et(){}function st(){}function it(){}function nt(){}function rt(){}function ot(){}function at(){}function ht(){}function ct(){}function ut(){}function lt(){}function dt(){}function ft(t,e){var s=[],i=9==this.nodeType&&this.documentElement||this,n=i.prefix,r=i.namespaceURI;if(r&&null==n&&null==(n=i.lookupPrefix(r)))var o=[{namespace:r,prefix:null}];return gt(this,s,t,e,o),s.join("")}function pt(t,e,i){var n=t.prefix||"",r=t.namespaceURI;if(!r)return!1;if("xml"===n&&r===s.XML||r===s.XMLNS)return!1;for(var o=i.length;o--;){var a=i[o];if(a.prefix===n)return a.namespace!==r}return!0}function mt(t,e,s){t.push(" ",e,'="',s.replace(/[<>&"\t\n\r]/g,$),'"')}function gt(t,e,i,n,r){if(r||(r=[]),n){if(!(t=n(t)))return;if("string"==typeof t)return void e.push(t)}switch(t.nodeType){case c:var o=t.attributes,a=o.length,h=t.firstChild,p=t.tagName,b=p;if(!(i=s.isHTML(t.namespaceURI)||i)&&!t.prefix&&t.namespaceURI){for(var S,x=0;x<o.length;x++)if("xmlns"===o.item(x).name){S=o.item(x).value;break}if(!S)for(var E=r.length-1;E>=0;E--){if(""===(M=r[E]).prefix&&M.namespace===t.namespaceURI){S=M.namespace;break}}if(S!==t.namespaceURI)for(E=r.length-1;E>=0;E--){var M;if((M=r[E]).namespace===t.namespaceURI){M.prefix&&(b=M.prefix+":"+p);break}}}e.push("<",b);for(var A=0;A<a;A++){"xmlns"==(D=o.item(A)).prefix?r.push({prefix:D.localName,namespace:D.value}):"xmlns"==D.nodeName&&r.push({prefix:"",namespace:D.value})}for(A=0;A<a;A++){var D,_,T;if(pt(D=o.item(A),0,r))mt(e,(_=D.prefix||"")?"xmlns:"+_:"xmlns",T=D.namespaceURI),r.push({prefix:_,namespace:T});gt(D,e,i,n,r)}if(p===b&&pt(t,0,r))mt(e,(_=t.prefix||"")?"xmlns:"+_:"xmlns",T=t.namespaceURI),r.push({prefix:_,namespace:T});if(h||i&&!/^(?:meta|link|img|br|hr|input)$/i.test(p)){if(e.push(">"),i&&/^script$/i.test(p))for(;h;)h.data?e.push(h.data):gt(h,e,i,n,r.slice()),h=h.nextSibling;else for(;h;)gt(h,e,i,n,r.slice()),h=h.nextSibling;e.push("</",b,">")}else e.push("/>");return;case w:case y:for(h=t.firstChild;h;)gt(h,e,i,n,r.slice()),h=h.nextSibling;return;case u:return mt(e,t.name,t.value);case l:return e.push(t.data.replace(/[<&>]/g,$));case d:return e.push("<![CDATA[",t.data,"]]>");case g:return e.push("\x3c!--",t.data,"--\x3e");case v:var I=t.publicId,C=t.systemId;if(e.push("<!DOCTYPE ",t.name),I)e.push(" PUBLIC ",I),C&&"."!=C&&e.push(" ",C),e.push(">");else if(C&&"."!=C)e.push(" SYSTEM ",C,">");else{var P=t.internalSubset;P&&e.push(" [",P,"]"),e.push(">")}return;case m:return e.push("<?",t.target," ",t.data,"?>");case f:return e.push("&",t.nodeName,";");default:e.push("??",t.nodeName)}}function wt(t,e,s){var i;switch(e.nodeType){case c:(i=e.cloneNode(!1)).ownerDocument=t;case y:break;case u:s=!0}if(i||(i=e.cloneNode(!1)),i.ownerDocument=t,i.parentNode=null,s)for(var n=e.firstChild;n;)i.appendChild(wt(t,n,s)),n=n.nextSibling;return i}function vt(t,e,s){var i=new e.constructor;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=e[n];"object"!=typeof r&&r!=i[n]&&(i[n]=r)}switch(e.childNodes&&(i.childNodes=new _),i.ownerDocument=t,i.nodeType){case c:var o=e.attributes,a=i.attributes=new C,h=o.length;a.M=i;for(var l=0;l<h;l++)i.setAttributeNode(vt(t,o.item(l),!0));break;case u:s=!0}if(s)for(var d=e.firstChild;d;)i.appendChild(vt(t,d,s)),d=d.nextSibling;return i}function yt(t,e,s){t[e]=s}S.INVALID_STATE_ERR=(x[11]="Invalid state",11),S.SYNTAX_ERR=(x[12]="Syntax error",12),S.INVALID_MODIFICATION_ERR=(x[13]="Invalid modification",13),S.NAMESPACE_ERR=(x[14]="Invalid namespace",14),S.INVALID_ACCESS_ERR=(x[15]="Invalid access",15),D.prototype=Error.prototype,o(S,D),_.prototype={length:0,item:function(t){return this[t]||null},toString:function(t,e){for(var s=[],i=0;i<this.length;i++)gt(this[i],s,t,e);return s.join("")},filter:function(t){return Array.prototype.filter.call(this,t)},indexOf:function(t){return Array.prototype.indexOf.call(this,t)}},T.prototype.item=function(t){return I(this),this[t]},a(T,_),C.prototype={length:0,item:_.prototype.item,getNamedItem:function(t){for(var e=this.length;e--;){var s=this[e];if(s.nodeName==t)return s}},setNamedItem:function(t){var e=t.ownerElement;if(e&&e!=this.M)throw new D(A);var s=this.getNamedItem(t.nodeName);return k(this.M,this,t,s),s},setNamedItemNS:function(t){var e,s=t.ownerElement;if(s&&s!=this.M)throw new D(A);return e=this.getNamedItemNS(t.namespaceURI,t.localName),k(this.M,this,t,e),e},removeNamedItem:function(t){var e=this.getNamedItem(t);return N(this.M,this,e),e},removeNamedItemNS:function(t,e){var s=this.getNamedItemNS(t,e);return N(this.M,this,s),s},getNamedItemNS:function(t,e){for(var s=this.length;s--;){var i=this[s];if(i.localName==e&&i.namespaceURI==t)return i}return null}},O.prototype={hasFeature:function(t,e){return!0},createDocument:function(t,e,s){var i=new L;if(i.implementation=this,i.childNodes=new _,i.doctype=s||null,s&&i.appendChild(s),e){var n=i.createElementNS(t,e);i.appendChild(n)}return i},createDocumentType:function(t,e,s){var i=new ot;return i.name=t,i.nodeName=t,i.publicId=e||"",i.systemId=s||"",i}},R.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(t,e){return Z(this,t,e)},replaceChild:function(t,e){Z(this,t,e,Q),e&&this.removeChild(e)},removeChild:function(t){return q(this,t)},appendChild:function(t){return this.insertBefore(t,null)},hasChildNodes:function(){return null!=this.firstChild},cloneNode:function(t){return vt(this.ownerDocument||this,this,t)},normalize:function(){for(var t=this.firstChild;t;){var e=t.nextSibling;e&&e.nodeType==l&&t.nodeType==l?(this.removeChild(e),t.appendData(e.data)):(t.normalize(),t=e)}},isSupported:function(t,e){return this.ownerDocument.implementation.hasFeature(t,e)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(t){for(var e=this;e;){var s=e.S;if(s)for(var i in s)if(Object.prototype.hasOwnProperty.call(s,i)&&s[i]===t)return i;e=e.nodeType==u?e.ownerDocument:e.parentNode}return null},lookupNamespaceURI:function(t){for(var e=this;e;){var s=e.S;if(s&&Object.prototype.hasOwnProperty.call(s,t))return s[t];e=e.nodeType==u?e.ownerDocument:e.parentNode}return null},isDefaultNamespace:function(t){return null==this.lookupPrefix(t)}},o(h,R),o(h,R.prototype),L.prototype={nodeName:"#document",nodeType:w,doctype:null,documentElement:null,v:1,insertBefore:function(t,e){if(t.nodeType==y){for(var s=t.firstChild;s;){var i=s.nextSibling;this.insertBefore(s,e),s=i}return t}return Z(this,t,e),t.ownerDocument=this,null===this.documentElement&&t.nodeType===c&&(this.documentElement=t),t},removeChild:function(t){return this.documentElement==t&&(this.documentElement=null),q(this,t)},replaceChild:function(t,e){Z(this,t,e,Q),t.ownerDocument=this,e&&this.removeChild(e),K(t)&&(this.documentElement=t)},importNode:function(t,e){return wt(this,t,e)},getElementById:function(t){var e=null;return F(this.documentElement,function(s){if(s.nodeType==c&&s.getAttribute("id")==t)return e=s,!0}),e},getElementsByClassName:function(t){var e=r(t);return new T(this,function(s){var i=[];return e.length>0&&F(s.documentElement,function(n){if(n!==s&&n.nodeType===c){var o=n.getAttribute("class");if(o){var a=t===o;if(!a){var h=r(o);a=e.every((u=h,function(t){return u&&-1!==u.indexOf(t)}))}a&&i.push(n)}}var u}),i})},createElement:function(t){var e=new tt;return e.ownerDocument=this,e.nodeName=t,e.tagName=t,e.localName=t,e.childNodes=new _,(e.attributes=new C).M=e,e},createDocumentFragment:function(){var t=new ut;return t.ownerDocument=this,t.childNodes=new _,t},createTextNode:function(t){var e=new it;return e.ownerDocument=this,e.appendData(t),e},createComment:function(t){var e=new nt;return e.ownerDocument=this,e.appendData(t),e},createCDATASection:function(t){var e=new rt;return e.ownerDocument=this,e.appendData(t),e},createProcessingInstruction:function(t,e){var s=new lt;return s.ownerDocument=this,s.tagName=s.target=t,s.nodeValue=s.data=e,s},createAttribute:function(t){var e=new et;return e.ownerDocument=this,e.name=t,e.nodeName=t,e.localName=t,e.specified=!0,e},createEntityReference:function(t){var e=new ct;return e.ownerDocument=this,e.nodeName=t,e},createElementNS:function(t,e){var s=new tt,i=e.split(":"),n=s.attributes=new C;return s.childNodes=new _,s.ownerDocument=this,s.nodeName=e,s.tagName=e,s.namespaceURI=t,2==i.length?(s.prefix=i[0],s.localName=i[1]):s.localName=e,n.M=s,s},createAttributeNS:function(t,e){var s=new et,i=e.split(":");return s.ownerDocument=this,s.nodeName=e,s.name=e,s.namespaceURI=t,s.specified=!0,2==i.length?(s.prefix=i[0],s.localName=i[1]):s.localName=e,s}},a(L,R),tt.prototype={nodeType:c,hasAttribute:function(t){return null!=this.getAttributeNode(t)},getAttribute:function(t){var e=this.getAttributeNode(t);return e&&e.value||""},getAttributeNode:function(t){return this.attributes.getNamedItem(t)},setAttribute:function(t,e){var s=this.ownerDocument.createAttribute(t);s.value=s.nodeValue=""+e,this.setAttributeNode(s)},removeAttribute:function(t){var e=this.getAttributeNode(t);e&&this.removeAttributeNode(e)},appendChild:function(t){return t.nodeType===y?this.insertBefore(t,null):function(t,e){return e.parentNode&&e.parentNode.removeChild(e),e.parentNode=t,e.previousSibling=t.lastChild,e.nextSibling=null,e.previousSibling?e.previousSibling.nextSibling=e:t.firstChild=e,t.lastChild=e,j(t.ownerDocument,t,e),e}(this,t)},setAttributeNode:function(t){return this.attributes.setNamedItem(t)},setAttributeNodeNS:function(t){return this.attributes.setNamedItemNS(t)},removeAttributeNode:function(t){return this.attributes.removeNamedItem(t.nodeName)},removeAttributeNS:function(t,e){var s=this.getAttributeNodeNS(t,e);s&&this.removeAttributeNode(s)},hasAttributeNS:function(t,e){return null!=this.getAttributeNodeNS(t,e)},getAttributeNS:function(t,e){var s=this.getAttributeNodeNS(t,e);return s&&s.value||""},setAttributeNS:function(t,e,s){var i=this.ownerDocument.createAttributeNS(t,e);i.value=i.nodeValue=""+s,this.setAttributeNode(i)},getAttributeNodeNS:function(t,e){return this.attributes.getNamedItemNS(t,e)},getElementsByTagName:function(t){return new T(this,function(e){var s=[];return F(e,function(i){i===e||i.nodeType!=c||"*"!==t&&i.tagName!=t||s.push(i)}),s})},getElementsByTagNameNS:function(t,e){return new T(this,function(s){var i=[];return F(s,function(n){n===s||n.nodeType!==c||"*"!==t&&n.namespaceURI!==t||"*"!==e&&n.localName!=e||i.push(n)}),i})}},L.prototype.getElementsByTagName=tt.prototype.getElementsByTagName,L.prototype.getElementsByTagNameNS=tt.prototype.getElementsByTagNameNS,a(tt,R),et.prototype.nodeType=u,a(et,R),st.prototype={data:"",substringData:function(t,e){return this.data.substring(t,t+e)},appendData:function(t){t=this.data+t,this.nodeValue=this.data=t,this.length=t.length},insertData:function(t,e){this.replaceData(t,0,e)},appendChild:function(t){throw new Error(x[E])},deleteData:function(t,e){this.replaceData(t,e,"")},replaceData:function(t,e,s){s=this.data.substring(0,t)+s+this.data.substring(t+e),this.nodeValue=this.data=s,this.length=s.length}},a(st,R),it.prototype={nodeName:"#text",nodeType:l,splitText:function(t){var e=this.data,s=e.substring(t);e=e.substring(0,t),this.data=this.nodeValue=e,this.length=e.length;var i=this.ownerDocument.createTextNode(s);return this.parentNode&&this.parentNode.insertBefore(i,this.nextSibling),i}},a(it,st),nt.prototype={nodeName:"#comment",nodeType:g},a(nt,st),rt.prototype={nodeName:"#cdata-section",nodeType:d},a(rt,st),ot.prototype.nodeType=v,a(ot,R),at.prototype.nodeType=b,a(at,R),ht.prototype.nodeType=p,a(ht,R),ct.prototype.nodeType=f,a(ct,R),ut.prototype.nodeName="#document-fragment",ut.prototype.nodeType=y,a(ut,R),lt.prototype.nodeType=m,a(lt,R),dt.prototype.serializeToString=function(t,e,s){return ft.call(t,e,s)},R.prototype.toString=ft;try{if(Object.defineProperty){function bt(t){switch(t.nodeType){case c:case y:var e=[];for(t=t.firstChild;t;)7!==t.nodeType&&8!==t.nodeType&&e.push(bt(t)),t=t.nextSibling;return e.join("");default:return t.nodeValue}}Object.defineProperty(T.prototype,"length",{get:function(){return I(this),this.$$length}}),Object.defineProperty(R.prototype,"textContent",{get:function(){return bt(this)},set:function(t){switch(this.nodeType){case c:case y:for(;this.firstChild;)this.removeChild(this.firstChild);(t||String(t))&&this.appendChild(this.ownerDocument.createTextNode(t));break;default:this.data=t,this.value=t,this.nodeValue=t}}}),yt=function(t,e,s){t["$$"+e]=s}}}catch(St){}return B.DocumentType=ot,B.DOMException=D,B.DOMImplementation=O,B.Element=tt,B.Node=R,B.NodeList=_,B.XMLSerializer=dt,B}var J,G={},V={};function Y(){return J||(J=1,t=V,e=W().freeze,t.XML_ENTITIES=e({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),t.HTML_ENTITIES=e({lt:"<",gt:">",amp:"&",quot:'"',apos:"'",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",times:"×",divide:"÷",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",euro:"€",trade:"™",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"}),t.entityMap=t.HTML_ENTITIES),V;var t,e}var Q,Z,tt,et={};function st(){if(Q)return et;Q=1;var t=W().NAMESPACE,e=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,s=new RegExp("[\\-\\.0-9"+e.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),i=new RegExp("^"+e.source+s.source+"*(?::"+e.source+s.source+"*)?$");function n(t,e){this.message=t,this.locator=e,Error.captureStackTrace&&Error.captureStackTrace(this,n)}function r(){}function o(t,e){return e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber,e}function a(e,s,i,n,r,o){function a(t,e,s){i.attributeNames.hasOwnProperty(t)&&o.fatalError("Attribute "+t+" redefined"),i.addValue(t,e.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,r),s)}for(var h,c=++s,u=0;;){var l=e.charAt(c);switch(l){case"=":if(1===u)h=e.slice(s,c),u=3;else{if(2!==u)throw new Error("attribute equal must after attrName");u=3}break;case"'":case'"':if(3===u||1===u){if(1===u&&(o.warning('attribute value must after "="'),h=e.slice(s,c)),s=c+1,!((c=e.indexOf(l,s))>0))throw new Error("attribute value no end '"+l+"' match");a(h,d=e.slice(s,c),s-1),u=5}else{if(4!=u)throw new Error('attribute value must after "="');a(h,d=e.slice(s,c),s),o.warning('attribute "'+h+'" missed start quot('+l+")!!"),s=c+1,u=5}break;case"/":switch(u){case 0:i.setTagName(e.slice(s,c));case 5:case 6:case 7:u=7,i.closed=!0;case 4:case 1:break;case 2:i.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),0==u&&i.setTagName(e.slice(s,c)),c;case">":switch(u){case 0:i.setTagName(e.slice(s,c));case 5:case 6:case 7:break;case 4:case 1:"/"===(d=e.slice(s,c)).slice(-1)&&(i.closed=!0,d=d.slice(0,-1));case 2:2===u&&(d=h),4==u?(o.warning('attribute "'+d+'" missed quot(")!'),a(h,d,s)):(t.isHTML(n[""])&&d.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+d+'" missed value!! "'+d+'" instead!!'),a(d,d,s));break;case 3:throw new Error("attribute value missed!!")}return c;case"":l=" ";default:if(l<=" ")switch(u){case 0:i.setTagName(e.slice(s,c)),u=6;break;case 1:h=e.slice(s,c),u=2;break;case 4:var d=e.slice(s,c);o.warning('attribute "'+d+'" missed quot(")!!'),a(h,d,s);case 5:u=6}else switch(u){case 2:i.tagName,t.isHTML(n[""])&&h.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+h+'" missed value!! "'+h+'" instead2!!'),a(h,h,s),s=c,u=1;break;case 5:o.warning('attribute space is required"'+h+'"!!');case 6:u=1,s=c;break;case 3:u=4,s=c;break;case 7:throw new Error("elements closed character '/' and '>' must be connected to")}}c++}}function h(e,s,i){for(var n=e.tagName,r=null,o=e.length;o--;){var a=e[o],h=a.qName,c=a.value;if((p=h.indexOf(":"))>0)var u=a.prefix=h.slice(0,p),d=h.slice(p+1),f="xmlns"===u&&d;else d=h,u=null,f="xmlns"===h&&"";a.localName=d,!1!==f&&(null==r&&(r={},l(i,i={})),i[f]=r[f]=c,a.uri=t.XMLNS,s.startPrefixMapping(f,c))}for(o=e.length;o--;){(u=(a=e[o]).prefix)&&("xml"===u&&(a.uri=t.XML),"xmlns"!==u&&(a.uri=i[u||""]))}var p;(p=n.indexOf(":"))>0?(u=e.prefix=n.slice(0,p),d=e.localName=n.slice(p+1)):(u=null,d=e.localName=n);var m=e.uri=i[u||""];if(s.startElement(m,d,n,e),!e.closed)return e.currentNSMap=i,e.localNSMap=r,!0;if(s.endElement(m,d,n),r)for(u in r)Object.prototype.hasOwnProperty.call(r,u)&&s.endPrefixMapping(u)}function c(t,e,s,i,n){if(/^(?:script|textarea)$/i.test(s)){var r=t.indexOf("</"+s+">",e),o=t.substring(e+1,r);if(/[&<]/.test(o))return/^script$/i.test(s)?(n.characters(o,0,o.length),r):(o=o.replace(/&#?\w+;/g,i),n.characters(o,0,o.length),r)}return e+1}function u(t,e,s,i){var n=i[s];return null==n&&((n=t.lastIndexOf("</"+s+">"))<e&&(n=t.lastIndexOf("</"+s)),i[s]=n),n<e}function l(t,e){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}function d(t,e,s,i){if("-"===t.charAt(e+2))return"-"===t.charAt(e+3)?(n=t.indexOf("--\x3e",e+4))>e?(s.comment(t,e+4,n-e-4),n+3):(i.error("Unclosed comment"),-1):-1;if("CDATA["==t.substr(e+3,6)){var n=t.indexOf("]]>",e+9);return s.startCDATA(),s.characters(t,e+9,n-e-9),s.endCDATA(),n+3}var r=function(t,e){var s,i=[],n=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;n.lastIndex=e,n.exec(t);for(;s=n.exec(t);)if(i.push(s),s[1])return i}(t,e),o=r.length;if(o>1&&/!doctype/i.test(r[0][0])){var a=r[1][0],h=!1,c=!1;o>3&&(/^public$/i.test(r[2][0])?(h=r[3][0],c=o>4&&r[4][0]):/^system$/i.test(r[2][0])&&(c=r[3][0]));var u=r[o-1];return s.startDTD(a,h,c),s.endDTD(),u.index+u[0].length}return-1}function f(t,e,s){var i=t.indexOf("?>",e);if(i){var n=t.substring(e,i).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return n?(n[0].length,s.processingInstruction(n[1],n[2]),i+2):-1}return-1}function p(){this.attributeNames={}}return n.prototype=new Error,n.prototype.name=n.name,r.prototype={parse:function(e,s,i){var r=this.domBuilder;r.startDocument(),l(s,s={}),function(e,s,i,r,l){function m(t){if(t>65535){var e=55296+((t-=65536)>>10),s=56320+(1023&t);return String.fromCharCode(e,s)}return String.fromCharCode(t)}function g(t){var e=t.slice(1,-1);return Object.hasOwnProperty.call(i,e)?i[e]:"#"===e.charAt(0)?m(parseInt(e.substr(1).replace("x","0x"))):(l.error("entity not found:"+t),t)}function w(t){if(t>A){var s=e.substring(A,t).replace(/&#?\w+;/g,g);x&&v(A),r.characters(s,0,t-A),A=t}}function v(t,s){for(;t>=b&&(s=S.exec(e));)y=s.index,b=y+s[0].length,x.lineNumber++;x.columnNumber=t-y+1}var y=0,b=0,S=/.*(?:\r\n?|\n)|.*$/g,x=r.locator,E=[{currentNSMap:s}],M={},A=0;for(;;){try{var D=e.indexOf("<",A);if(D<0){if(!e.substr(A).match(/^\s*$/)){var _=r.doc,T=_.createTextNode(e.substr(A));_.appendChild(T),r.currentElement=T}return}switch(D>A&&w(D),e.charAt(D+1)){case"/":var I=e.indexOf(">",D+3),C=e.substring(D+2,I).replace(/[ \t\n\r]+$/g,""),P=E.pop();I<0?(C=e.substring(D+2).replace(/[\s<].*/,""),l.error("end tag name: "+C+" is not complete:"+P.tagName),I=D+1+C.length):C.match(/\s</)&&(C=C.replace(/[\s<].*/,""),l.error("end tag name: "+C+" maybe not complete"),I=D+1+C.length);var k=P.localNSMap,N=P.tagName==C;if(N||P.tagName&&P.tagName.toLowerCase()==C.toLowerCase()){if(r.endElement(P.uri,P.localName,C),k)for(var O in k)Object.prototype.hasOwnProperty.call(k,O)&&r.endPrefixMapping(O);N||l.fatalError("end tag name: "+C+" is not match the current start tagName:"+P.tagName)}else E.push(P);I++;break;case"?":x&&v(D),I=f(e,D,r);break;case"!":x&&v(D),I=d(e,D,r,l);break;default:x&&v(D);var R=new p,$=E[E.length-1].currentNSMap,F=(I=a(e,D,R,$,g,l),R.length);if(!R.closed&&u(e,I,R.tagName,M)&&(R.closed=!0,i.nbsp||l.warning("unclosed xml attribute")),x&&F){for(var L=o(x,{}),U=0;U<F;U++){var j=R[U];v(j.offset),j.locator=o(x,{})}r.locator=L,h(R,r,$)&&E.push(R),r.locator=x}else h(R,r,$)&&E.push(R);t.isHTML(R.uri)&&!R.closed?I=c(e,I,R.tagName,g,r):I++}}catch(t){if(t instanceof n)throw t;l.error("element parse error: "+t),I=-1}I>A?A=I:w(Math.max(D,A)+1)}}(e,s,i,r,this.errorHandler),r.endDocument()}},p.prototype={setTagName:function(t){if(!i.test(t))throw new Error("invalid tagName:"+t);this.tagName=t},addValue:function(t,e,s){if(!i.test(t))throw new Error("invalid attribute:"+t);this.attributeNames[t]=this.length,this[this.length++]={qName:t,value:e,offset:s}},length:0,getLocalName:function(t){return this[t].localName},getLocator:function(t){return this[t].locator},getQName:function(t){return this[t].qName},getURI:function(t){return this[t].uri},getValue:function(t){return this[t].value}},et.XMLReader=r,et.ParseError=n,et}function it(){if(Z)return G;Z=1;var t=W(),e=z(),s=Y(),i=st(),n=e.DOMImplementation,r=t.NAMESPACE,o=i.ParseError,a=i.XMLReader;function h(t){return t.replace(/\r[\n\u0085]/g,"\n").replace(/[\r\u0085\u2028]/g,"\n")}function c(t){this.options=t||{locator:{}}}function u(){this.cdata=!1}function l(t,e){e.lineNumber=t.lineNumber,e.columnNumber=t.columnNumber}function d(t){if(t)return"\n@"+(t.systemId||"")+"#[line:"+t.lineNumber+",col:"+t.columnNumber+"]"}function f(t,e,s){return"string"==typeof t?t.substr(e,s):t.length>=e+s||e?new java.lang.String(t,e,s)+"":t}function p(t,e){t.currentElement?t.currentElement.appendChild(e):t.doc.appendChild(e)}return c.prototype.parseFromString=function(t,e){var i=this.options,n=new a,o=i.domBuilder||new u,c=i.errorHandler,l=i.locator,f=i.xmlns||{},p=/\/x?html?$/.test(e),m=p?s.HTML_ENTITIES:s.XML_ENTITIES;l&&o.setDocumentLocator(l),n.errorHandler=function(t,e,s){if(!t){if(e instanceof u)return e;t=e}var i={},n=t instanceof Function;function r(e){var r=t[e];!r&&n&&(r=2==t.length?function(s){t(e,s)}:t),i[e]=r&&function(t){r("[xmldom "+e+"]\t"+t+d(s))}||function(){}}return s=s||{},r("warning"),r("error"),r("fatalError"),i}(c,o,l),n.domBuilder=i.domBuilder||o,p&&(f[""]=r.HTML),f.xml=f.xml||r.XML;var g=i.normalizeLineEndings||h;return t&&"string"==typeof t?n.parse(g(t),f,m):n.errorHandler.error("invalid doc source"),o.doc},u.prototype={startDocument:function(){this.doc=(new n).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(t,e,s,i){var n=this.doc,r=n.createElementNS(t,s||e),o=i.length;p(this,r),this.currentElement=r,this.locator&&l(this.locator,r);for(var a=0;a<o;a++){t=i.getURI(a);var h=i.getValue(a),c=(s=i.getQName(a),n.createAttributeNS(t,s));this.locator&&l(i.getLocator(a),c),c.value=c.nodeValue=h,r.setAttributeNode(c)}},endElement:function(t,e,s){var i=this.currentElement;i.tagName,this.currentElement=i.parentNode},startPrefixMapping:function(t,e){},endPrefixMapping:function(t){},processingInstruction:function(t,e){var s=this.doc.createProcessingInstruction(t,e);this.locator&&l(this.locator,s),p(this,s)},ignorableWhitespace:function(t,e,s){},characters:function(t,e,s){if(t=f.apply(this,arguments)){if(this.cdata)var i=this.doc.createCDATASection(t);else i=this.doc.createTextNode(t);this.currentElement?this.currentElement.appendChild(i):/^\s*$/.test(t)&&this.doc.appendChild(i),this.locator&&l(this.locator,i)}},skippedEntity:function(t){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(t){(this.locator=t)&&(t.lineNumber=0)},comment:function(t,e,s){t=f.apply(this,arguments);var i=this.doc.createComment(t);this.locator&&l(this.locator,i),p(this,i)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(t,e,s){var i=this.doc.implementation;if(i&&i.createDocumentType){var n=i.createDocumentType(t,e,s);this.locator&&l(this.locator,n),p(this,n),this.doc.doctype=n}},warning:function(t){console.warn("[xmldom warning]\t"+t,d(this.locator))},error:function(t){console.error("[xmldom error]\t"+t,d(this.locator))},fatalError:function(t){throw new o(t,this.locator)}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(t){u.prototype[t]=function(){return null}}),G.A=u,G.normalizeLineEndings=h,G.DOMParser=c,G}function nt(){if(tt)return X;tt=1;var t=z();return X.DOMImplementation=t.DOMImplementation,X.XMLSerializer=t.XMLSerializer,X.DOMParser=it().DOMParser,X}!function(t){var e=void 0!==$?$:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function s(){let t=e.WebSocket;if(void 0===t)try{t=U?L:(U=1,L=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")})}catch(t){throw new Error('You must install the "ws" package to use Strophe in nodejs.')}return t}const i=s();function n(){let t=e.DOMParser;if(void 0===t)try{t=nt().DOMParser}catch(t){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return t}const r=n();function o(){const t=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(let e=0;e<t.length;e++)try{return new ActiveXObject(t[e])}catch(t){}}function a(){if("undefined"==typeof document)try{return(new(0,nt().DOMImplementation)).createDocument("jabber:client","strophe",null)}catch(t){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}if(void 0===document.implementation.createDocument||document.implementation.createDocument&&document.documentMode&&document.documentMode<10){const t=o();return t.appendChild(t.createElement("strophe")),t}return document.implementation.createDocument("jabber:client","strophe",null)}var h=Object.freeze({__proto__:null,WebSocket:i,DOMParser:r,getDummyXMLDOMDocument:a});const c={HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},u={tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"]},l={ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12},d={BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},f={DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},p={NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11};function m(t){let e="";const s=t.length;for(let i=0;i<s;i++){const s=t.charCodeAt(i);s>=0&&s<=127?e+=t.charAt(i):s>2047?(e+=String.fromCharCode(224|s>>12&15),e+=String.fromCharCode(128|s>>6&63),e+=String.fromCharCode(128|63&s)):(e+=String.fromCharCode(192|s>>6&31),e+=String.fromCharCode(128|63&s))}return e}function g(t,e){const s=new Uint8Array(t),i=new Uint8Array(e),n=new Uint8Array(t.byteLength);for(let e=0;e<t.byteLength;e++)n[e]=s[e]^i[e];return n.buffer}function w(t){let e="";const s=new Uint8Array(t),i=s.byteLength;for(let t=0;t<i;t++)e+=String.fromCharCode(s[t]);return btoa(e)}function v(t){var e;return null===(e=Uint8Array.from(atob(t),t=>t.charCodeAt(0)))||void 0===e?void 0:e.buffer}function y(t){return new TextEncoder("utf-8").encode(t).buffer}function b(t){"undefined"==typeof document&&Dt.log(Dt.LogLevel.ERROR,"addCookies: not adding any cookies, since there's no document object"),t=t||{};for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let s="",i="",n="";const r=t[e],o="object"==typeof r,a=escape(unescape(o?r.value:r));o&&(s=r.expires?";expires="+r.expires:"",i=r.domain?";domain="+r.domain:"",n=r.path?";path="+r.path:""),document.cookie=e+"="+a+s+i+n}}let S=null;function x(){return S||(S=a()),S}function E(t){return x().createTextNode(t)}function M(t){let e;return r?e=(new r).parseFromString(t,"text/xml"):(e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t)),e}function A(t){if(!t)return null;const e=x().createElement(t);for(let t=1;t<arguments.length;t++){const s=arguments[t];if(s)if("string"==typeof s||"number"==typeof s)e.appendChild(E(s));else if("object"==typeof s&&"function"==typeof s.sort)for(let t=0;t<s.length;t++){const i=s[t];"object"==typeof i&&"function"==typeof i.sort&&void 0!==i[1]&&null!==i[1]&&e.setAttribute(i[0],i[1])}else if("object"==typeof s)for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&void 0!==s[t]&&null!==s[t]&&e.setAttribute(t,s[t])}return e}function D(t){for(let e=0;e<u.tags.length;e++)if(t===u.tags[e])return!0;return!1}function _(t,e){if(void 0!==u.attributes[t]&&u.attributes[t].length>0)for(let s=0;s<u.attributes[t].length;s++)if(e===u.attributes[t][s])return!0;return!1}function T(t){for(let e=0;e<u.css.length;e++)if(t===u.css[e])return!0;return!1}function I(t){let e;if(t.nodeType===p.NORMAL){const s=t.nodeName.toLowerCase();if(D(s))try{e=A(s);for(let i=0;i<u.attributes[s].length;i++){const n=u.attributes[s][i];let r=t.getAttribute(n);if(null!=r&&""!==r&&!1!==r&&0!==r)if("style"===n&&"object"==typeof r&&void 0!==r.cssText&&(r=r.cssText),"style"===n){const t=[],s=r.split(";");for(let e=0;e<s.length;e++){const i=s[e].split(":"),n=i[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(T(n)){const e=i[1].replace(/^\s*/,"").replace(/\s*$/,"");t.push(n+": "+e)}}t.length>0&&(r=t.join("; "),e.setAttribute(n,r))}else e.setAttribute(n,r)}for(let s=0;s<t.childNodes.length;s++)e.appendChild(I(t.childNodes[s]))}catch(t){e=E("")}else{e=x().createDocumentFragment();for(let s=0;s<t.childNodes.length;s++)e.appendChild(I(t.childNodes[s]))}}else if(t.nodeType===p.FRAGMENT){e=x().createDocumentFragment();for(let s=0;s<t.childNodes.length;s++)e.appendChild(I(t.childNodes[s]))}else t.nodeType===p.TEXT&&(e=E(t.nodeValue));return e}function C(t){let e;if(t.nodeType===p.NORMAL){e=A(t.tagName);for(let s=0;s<t.attributes.length;s++)e.setAttribute(t.attributes[s].nodeName,t.attributes[s].value);for(let s=0;s<t.childNodes.length;s++)e.appendChild(C(t.childNodes[s]))}else t.nodeType===p.TEXT&&(e=x().createTextNode(t.nodeValue));return e}function P(t){return t=(t=(t=(t=(t=t.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,""")}function k(t){return t=(t=(t=(t=(t=t.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"')}function N(t){if(!t)return null;"function"==typeof t.tree&&(t=t.tree());const e=[...Array(t.attributes.length).keys()].map(e=>t.attributes[e].nodeName);e.sort();let s=e.reduce((e,s)=>`${e} ${s}="${P(t.attributes.getNamedItem(s).value)}"`,`<${t.nodeName}`);if(t.childNodes.length>0){s+=">";for(let e=0;e<t.childNodes.length;e++){const i=t.childNodes[e];switch(i.nodeType){case p.NORMAL:s+=N(i);break;case p.TEXT:s+=P(i.nodeValue);break;case p.CDATA:s+="<![CDATA["+i.nodeValue+"]]>"}}s+="</"+t.nodeName+">"}else s+="/>";return s}function O(t,e,s){for(let i=0;i<t.childNodes.length;i++){const n=t.childNodes[i];n.nodeType!==p.NORMAL||e&&!this.isTagEqual(n,e)||s(n)}}function R(t,e){return t.tagName===e}function F(t){var e;if(!t)return null;let s="";null!==(e=t.childNodes)&&void 0!==e&&e.length||t.nodeType!==p.TEXT||(s+=t.nodeValue);for(let e=0;null!==(i=e<(null===(n=t.childNodes)||void 0===n?void 0:n.length))&&void 0!==i&&i;e++){var i,n;t.childNodes[e].nodeType===p.TEXT&&(s+=t.childNodes[e].nodeValue)}return P(s)}function j(t){return"string"!=typeof t?t:t.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40")}function q(t){return"string"!=typeof t?t:t.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")}function H(t){return t.indexOf("@")<0?null:t.split("@")[0]}function X(t){const e=K(t);if(e.indexOf("@")<0)return e;{const t=e.split("@");return t.splice(0,1),t.join("@")}}function B(t){if(!t)return null;const e=t.split("/");return e.length<2?null:(e.splice(0,1),e.join("/"))}function K(t){return t?t.split("/")[0]:null}const W={utf16to8:m,xorArrayBuffers:g,arrayBufToBase64:w,base64ToArrayBuf:v,stringToArrayBuf:y,addCookies:b};var z=Object.freeze({__proto__:null,utf16to8:m,xorArrayBuffers:g,arrayBufToBase64:w,base64ToArrayBuf:v,stringToArrayBuf:y,addCookies:b,xmlGenerator:x,xmlTextNode:E,xmlHtmlNode:M,xmlElement:A,validTag:D,validAttribute:_,validCSS:T,createHtml:I,copyElement:C,xmlescape:P,xmlunescape:k,serialize:N,forEachChild:O,isTagEqual:R,getText:F,escapeNode:j,unescapeNode:q,getNodeFromJid:H,getDomainFromJid:X,getResourceFromJid:B,getBareJidFromJid:K,default:W});function J(t,e){return new Q(t,e)}function G(t){return new Q("message",t)}function V(t){return new Q("iq",t)}function Y(t){return new Q("presence",t)}class Q{constructor(t,e){"presence"!==t&&"message"!==t&&"iq"!==t||(e&&!e.xmlns?e.xmlns=c.CLIENT:e||(e={xmlns:c.CLIENT})),this.nodeTree=A(t,e),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return N(this.nodeTree)}up(){return this.node=this.node.parentNode,this}root(){return this.node=this.nodeTree,this}attrs(t){for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(void 0===t[e]?this.node.removeAttribute(e):this.node.setAttribute(e,t[e]));return this}c(t,e,s){const i=A(t,e,s);return this.node.appendChild(i),"string"!=typeof s&&"number"!=typeof s&&(this.node=i),this}cnode(t){let e;const s=x();try{e=void 0!==s.importNode}catch(t){e=!1}const i=e?s.importNode(t,!0):C(t);return this.node.appendChild(i),this.node=i,this}t(t){const e=E(t);return this.node.appendChild(e),this}h(t){const e=x().createElement("body");e.innerHTML=t;const s=I(e);for(;s.childNodes.length>0;)this.node.appendChild(s.childNodes[0]);return this}}class Z{constructor(t,e,s,i,n,r,o){this.handler=t,this.ns=e,this.name=s,this.type=i,this.id=n,this.options=o||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(Dt.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=r?K(r):null:this.from=r,this.user=!0}getNamespace(t){let e=t.getAttribute("xmlns");return e&&this.options.ignoreNamespaceFragment&&(e=e.split("#")[0]),e}namespaceMatch(t){let e=!1;return!this.ns||(O(t,null,t=>{this.getNamespace(t)===this.ns&&(e=!0)}),e||this.getNamespace(t)===this.ns)}isMatch(t){let e=t.getAttribute("from");this.options.matchBareFromJid&&(e=K(e));const s=t.getAttribute("type");return!(!this.namespaceMatch(t)||this.name&&!Dt.isTagEqual(t,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(s):s!==this.type)||this.id&&t.getAttribute("id")!==this.id||this.from&&e!==this.from)}run(t){let e=null;try{e=this.handler(t)}catch(t){throw Dt.D(t),t}return e}toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}}class tt{constructor(t,e){this.period=t,this.handler=e,this.lastCalled=(new Date).getTime(),this.user=!0}run(){return this.lastCalled=(new Date).getTime(),this.handler()}reset(){this.lastCalled=(new Date).getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}}function et(t){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");if((t=(t=`${t}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(t=t.replace(/==?$/,"")),t.length%4==1||/[^+/0-9A-Za-z]/.test(t))return null;let e="",s=0,i=0;for(let n=0;n<t.length;n++)s<<=6,s|=it(t[n]),i+=6,24===i&&(e+=String.fromCharCode((16711680&s)>>16),e+=String.fromCharCode((65280&s)>>8),e+=String.fromCharCode(255&s),s=i=0);return 12===i?(s>>=4,e+=String.fromCharCode(s)):18===i&&(s>>=2,e+=String.fromCharCode((65280&s)>>8),e+=String.fromCharCode(255&s)),e}const st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function it(t){const e=st.indexOf(t);return e<0?void 0:e}function rt(t){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");let e;for(t=`${t}`,e=0;e<t.length;e++)if(t.charCodeAt(e)>255)return null;let s="";for(e=0;e<t.length;e+=3){const i=[void 0,void 0,void 0,void 0];i[0]=t.charCodeAt(e)>>2,i[1]=(3&t.charCodeAt(e))<<4,t.length>e+1&&(i[1]|=t.charCodeAt(e+1)>>4,i[2]=(15&t.charCodeAt(e+1))<<2),t.length>e+2&&(i[2]|=t.charCodeAt(e+2)>>6,i[3]=63&t.charCodeAt(e+2));for(let t=0;t<i.length;t++)void 0===i[t]?s+="=":s+=at(i[t])}return s}const ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function at(t){if(t>=0&&t<64)return ot[t]}var ht={atob:et,btoa:rt};class ct{constructor(t,e){this.service=t,this.options=e||{},this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this.T=null,this.I=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this.C=[],this.P=0,this.k=null,this.N=null,this.O=null,this.maxRetries=5,this.T=setTimeout(()=>this.R(),100),b(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new Z(t=>this.send(V({type:"error",id:t.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:Dt.NS.STANZAS})),null,"iq",["get","set"]);for(const t in Dt.$)if(Object.prototype.hasOwnProperty.call(Dt.$,t)){const e=function(){};e.prototype=Dt.$[t],this[t]=new e,this[t].init(this)}}setProtocol(){const t=this.options.protocol||"";this.options.worker?this.F=new Dt.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===t.indexOf("ws")?this.F=new Dt.Websocket(this):this.F=new Dt.Bosh(this)}reset(){this.F.L(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this.C=[],this.U=[],this.P=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(t){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)});return"string"==typeof t||"number"==typeof t?e+":"+t:e+""}addProtocolErrorHandler(t,e,s){this.protocolErrorHandlers[t][e]=s}connect(t,e,s,i,n,r,o){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:3e3;this.jid=t,this.authzid=Dt.getBareJidFromJid(this.jid),this.authcid=o||Dt.getNodeFromJid(this.jid),this.pass=e,this.scram_keys=null,this.connect_callback=s,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=a,this.domain=Dt.getDomainFromJid(this.jid),this.j(l.CONNECTING,null),this.F.q(i,n,r)}attach(t,e,s,i,n,r,o){if(this.F.H)return this.F.H(t,e,s,i,n,r,o);{const t=new Error('The "attach" method is not available for your connection protocol');throw t.name="StropheSessionError",t}}restore(t,e,s,i,n){if(!this.X()){const t=new Error('The "restore" method can only be used with a BOSH connection.');throw t.name="StropheSessionError",t}this.F.B(t,e,s,i,n)}X(){if(this.F instanceof Dt.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(t){return!1}return!0}return!1}xmlInput(t){}xmlOutput(t){}rawInput(t){}rawOutput(t){}nextValidRid(t){}send(t){if(null!==t){if("function"==typeof t.sort)for(let e=0;e<t.length;e++)this.K(t[e]);else"function"==typeof t.tree?this.K(t.tree()):this.K(t);this.F.W()}}flush(){clearTimeout(this.T),this.R()}sendPresence(t,e,s,i){let n=null;"function"==typeof t.tree&&(t=t.tree());let r=t.getAttribute("id");if(r||(r=this.getUniqueId("sendPresence"),t.setAttribute("id",r)),"function"==typeof e||"function"==typeof s){const t=this.addHandler(t=>{n&&this.deleteTimedHandler(n),"error"===t.getAttribute("type")?s&&s(t):e&&e(t)},null,"presence",null,r);i&&(n=this.addTimedHandler(i,()=>(this.deleteHandler(t),s&&s(null),!1)))}return this.send(t),r}sendIQ(t,e,s,i){let n=null;"function"==typeof t.tree&&(t=t.tree());let r=t.getAttribute("id");if(r||(r=this.getUniqueId("sendIQ"),t.setAttribute("id",r)),"function"==typeof e||"function"==typeof s){const t=this.addHandler(t=>{n&&this.deleteTimedHandler(n);const i=t.getAttribute("type");if("result"===i)e&&e(t);else{if("error"!==i){const t=new Error(`Got bad IQ type of ${i}`);throw t.name="StropheError",t}s&&s(t)}},null,"iq",["error","result"],r);i&&(n=this.addTimedHandler(i,()=>(this.deleteHandler(t),s&&s(null),!1)))}return this.send(t),r}K(t){if(null===t||!t.tagName||!t.childNodes){const t=new Error("Cannot queue non-DOMElement.");throw t.name="StropheError",t}this.C.push(t)}J(){this.C.push("restart"),this.F.J(),this.T=setTimeout(()=>this.R(),100)}addTimedHandler(t,e){const s=new Dt.TimedHandler(t,e);return this.addTimeds.push(s),s}deleteTimedHandler(t){this.removeTimeds.push(t)}addHandler(t,e,s,i,n,r,o){const a=new Z(t,e,s,i,n,r,o);return this.addHandlers.push(a),a}deleteHandler(t){this.removeHandlers.push(t);const e=this.addHandlers.indexOf(t);e>=0&&this.addHandlers.splice(e,1)}registerSASLMechanisms(t){this.mechanisms={},(t=t||[Dt.SASLAnonymous,Dt.SASLExternal,Dt.SASLOAuthBearer,Dt.SASLXOAuth2,Dt.SASLPlain,Dt.SASLSHA1,Dt.SASLSHA256,Dt.SASLSHA384,Dt.SASLSHA512]).forEach(t=>this.registerSASLMechanism(t))}registerSASLMechanism(t){const e=new t;this.mechanisms[e.mechname]=e}disconnect(t){if(this.j(l.DISCONNECTING,t),t?Dt.warn("Disconnect was called because: "+t):Dt.info("Disconnect was called"),this.connected){let t=!1;this.disconnecting=!0,this.authenticated&&(t=Y({xmlns:Dt.NS.CLIENT,type:"unavailable"})),this.I=this.G(this.disconnection_timeout,this.V.bind(this)),this.F.Y(t)}else Dt.warn("Disconnect was called before Strophe connected to the server"),this.F.Z(),this.tt()}j(t,e,s){for(const s in Dt.$)if(Object.prototype.hasOwnProperty.call(Dt.$,s)){const i=this[s];if(i.statusChanged)try{i.statusChanged(t,e)}catch(t){Dt.error(`${s} plugin caused an exception changing status: ${t}`)}}if(this.connect_callback)try{this.connect_callback(t,e,s)}catch(t){Dt.D(t),Dt.error(`User connection callback caused an exception: ${t}`)}}tt(t){"number"==typeof this.T&&clearTimeout(this.T),null!==this.I&&(this.deleteTimedHandler(this.I),this.I=null),Dt.debug("_doDisconnect was called"),this.F.tt(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.j(l.DISCONNECTED,t),this.connected=!1}et(t,e){const s=this.F.st(t);if(null===s)return;for(this.xmlInput!==Dt.Connection.prototype.xmlInput&&(s.nodeName===this.F.strip&&s.childNodes.length?this.xmlInput(s.childNodes[0]):this.xmlInput(s)),this.rawInput!==Dt.Connection.prototype.rawInput&&(e?this.rawInput(e):this.rawInput(Dt.serialize(s)));this.removeHandlers.length>0;){const t=this.removeHandlers.pop(),e=this.handlers.indexOf(t);e>=0&&this.handlers.splice(e,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this.F.it())return void this.tt();const i=s.getAttribute("type");if(null!==i&&"terminate"===i){if(this.disconnecting)return;let t=s.getAttribute("condition");const e=s.getElementsByTagName("conflict");return null!==t?("remote-stream-error"===t&&e.length>0&&(t="conflict"),this.j(l.CONNFAIL,t)):this.j(l.CONNFAIL,Dt.ErrorCondition.UNKOWN_REASON),void this.tt(t)}Dt.forEachChild(s,null,t=>{const e=[];this.handlers=this.handlers.reduce((s,i)=>{try{!i.isMatch(t)||!this.authenticated&&i.user?s.push(i):(i.run(t)&&s.push(i),e.push(i))}catch(t){Dt.warn("Removing Strophe handlers due to uncaught exception: "+t.message)}return s},[]),!e.length&&this.iqFallbackHandler.isMatch(t)&&this.iqFallbackHandler.run(t)})}nt(t,e,s){let i,n;Dt.debug("_connect_cb was called"),this.connected=!0;try{i=this.F.st(t)}catch(t){if(t.name!==Dt.ErrorCondition.BAD_FORMAT)throw t;this.j(l.CONNFAIL,Dt.ErrorCondition.BAD_FORMAT),this.tt(Dt.ErrorCondition.BAD_FORMAT)}if(!i)return;if(this.xmlInput!==Dt.Connection.prototype.xmlInput&&(i.nodeName===this.F.strip&&i.childNodes.length?this.xmlInput(i.childNodes[0]):this.xmlInput(i)),this.rawInput!==Dt.Connection.prototype.rawInput&&(s?this.rawInput(s):this.rawInput(Dt.serialize(i))),this.F.nt(i)===l.CONNFAIL)return;if(n=i.getElementsByTagNameNS?i.getElementsByTagNameNS(Dt.NS.STREAM,"features").length>0:i.getElementsByTagName("stream:features").length>0||i.getElementsByTagName("features").length>0,!n)return void this.F.rt(e);const r=Array.from(i.getElementsByTagName("mechanism")).map(t=>this.mechanisms[t.textContent]).filter(t=>t);0!==r.length||0!==i.getElementsByTagName("auth").length?!1!==this.do_authentication&&this.authenticate(r):this.F.rt(e)}sortMechanismsByPriority(t){for(let e=0;e<t.length-1;++e){let s=e;for(let i=e+1;i<t.length;++i)t[i].priority>t[s].priority&&(s=i);if(s!==e){const i=t[e];t[e]=t[s],t[s]=i}}return t}authenticate(t){this.ot(t)||this.ht()}ot(t){t=this.sortMechanismsByPriority(t||[]);let e=!1;for(let s=0;s<t.length;++s){if(!t[s].test(this))continue;this.k=this.ct(this.ut.bind(this),null,"success",null,null),this.N=this.ct(this.dt.bind(this),null,"failure",null,null),this.O=this.ct(this.ft.bind(this),null,"challenge",null,null),this.wt=t[s],this.wt.onStart(this);const i=J("auth",{xmlns:Dt.NS.SASL,mechanism:this.wt.mechname});if(this.wt.isClientFirst){const t=this.wt.clientChallenge(this);i.t(ht.btoa(t))}this.send(i.tree()),e=!0;break}return e}async ft(t){const e=ht.atob(F(t)),s=await this.wt.onChallenge(this,e),i=J("response",{xmlns:Dt.NS.SASL});return""!==s&&i.t(ht.btoa(s)),this.send(i.tree()),!0}ht(){null===Dt.getNodeFromJid(this.jid)?(this.j(l.CONNFAIL,Dt.ErrorCondition.MISSING_JID_NODE),this.disconnect(Dt.ErrorCondition.MISSING_JID_NODE)):(this.j(l.AUTHENTICATING,null),this.ct(this.vt.bind(this),null,null,null,"_auth_1"),this.send(V({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:Dt.NS.AUTH}).c("username",{}).t(Dt.getNodeFromJid(this.jid)).tree()))}vt(t){const e=V({type:"set",id:"_auth_2"}).c("query",{xmlns:Dt.NS.AUTH}).c("username",{}).t(Dt.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return Dt.getResourceFromJid(this.jid)||(this.jid=Dt.getBareJidFromJid(this.jid)+"/strophe"),e.up().c("resource",{}).t(Dt.getResourceFromJid(this.jid)),this.ct(this.yt.bind(this),null,null,null,"_auth_2"),this.send(e.tree()),!1}ut(t){if(this._["server-signature"]){let e;const s=/([a-z]+)=([^,]+)(,|$)/,i=ht.atob(F(t)).match(s);if("v"===i[1]&&(e=i[2]),e!==this._["server-signature"])return this.deleteHandler(this.N),this.N=null,this.O&&(this.deleteHandler(this.O),this.O=null),this._={},this.dt(null)}Dt.info("SASL authentication succeeded."),this._.keys&&(this.scram_keys=this._.keys),this.wt&&this.wt.onSuccess(),this.deleteHandler(this.N),this.N=null,this.O&&(this.deleteHandler(this.O),this.O=null);const e=[],s=(t,e)=>{for(;t.length;)this.deleteHandler(t.pop());return this.bt(e),!1};return e.push(this.ct(t=>s(e,t),null,"stream:features",null,null)),e.push(this.ct(t=>s(e,t),Dt.NS.STREAM,"features",null,null)),this.J(),!1}bt(t){this.features=t;for(let e=0;e<t.childNodes.length;e++){const s=t.childNodes[e];"bind"===s.nodeName&&(this.do_bind=!0),"session"===s.nodeName&&(this.do_session=!0)}return this.do_bind?(this.options.explicitResourceBinding?this.j(l.BINDREQUIRED,null):this.bind(),!1):(this.j(l.AUTHFAIL,null),!1)}bind(){if(!this.do_bind)return void Dt.log(Dt.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');this.ct(this.St.bind(this),null,null,null,"_bind_auth_2");const t=Dt.getResourceFromJid(this.jid);t?this.send(V({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Dt.NS.BIND}).c("resource",{}).t(t).tree()):this.send(V({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Dt.NS.BIND}).tree())}St(t){if("error"===t.getAttribute("type")){let e;return Dt.warn("Resource binding failed."),t.getElementsByTagName("conflict").length>0&&(e=Dt.ErrorCondition.CONFLICT),this.j(l.AUTHFAIL,e,t),!1}const e=t.getElementsByTagName("bind");if(!(e.length>0))return Dt.warn("Resource binding failed."),this.j(l.AUTHFAIL,null,t),!1;{const t=e[0].getElementsByTagName("jid");t.length>0&&(this.authenticated=!0,this.jid=F(t[0]),this.do_session?this.xt():this.j(l.CONNECTED,null))}}xt(){if(!this.do_session)throw new Error(`Strophe.Connection.prototype._establishSession called but apparently ${Dt.NS.SESSION} wasn't advertised by the server`);this.ct(this.Et.bind(this),null,null,null,"_session_auth_2"),this.send(V({type:"set",id:"_session_auth_2"}).c("session",{xmlns:Dt.NS.SESSION}).tree())}Et(t){if("result"===t.getAttribute("type"))this.authenticated=!0,this.j(l.CONNECTED,null);else if("error"===t.getAttribute("type"))return this.authenticated=!1,Dt.warn("Session creation failed."),this.j(l.AUTHFAIL,null,t),!1;return!1}dt(t){return this.k&&(this.deleteHandler(this.k),this.k=null),this.O&&(this.deleteHandler(this.O),this.O=null),this.wt&&this.wt.onFailure(),this.j(l.AUTHFAIL,null,t),!1}yt(t){return"result"===t.getAttribute("type")?(this.authenticated=!0,this.j(l.CONNECTED,null)):"error"===t.getAttribute("type")&&(this.j(l.AUTHFAIL,null,t),this.disconnect("authentication failed")),!1}G(t,e){const s=new tt(t,e);return s.user=!1,this.addTimeds.push(s),s}ct(t,e,s,i,n){const r=new Z(t,e,s,i,n);return r.user=!1,this.addHandlers.push(r),r}V(){return Dt.debug("_onDisconnectTimeout was called"),this.j(l.CONNTIMEOUT,null),this.F.V(),this.tt(),!1}R(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){const t=this.removeTimeds.pop(),e=this.timedHandlers.indexOf(t);e>=0&&this.timedHandlers.splice(e,1)}const t=(new Date).getTime(),e=[];for(let s=0;s<this.timedHandlers.length;s++){const i=this.timedHandlers[s];!this.authenticated&&i.user||(i.lastCalled+i.period-t<=0?i.run()&&e.push(i):e.push(i))}this.timedHandlers=e,clearTimeout(this.T),this.F.R(),this.connected&&(this.T=setTimeout(()=>this.R(),100))}}class ut{constructor(t,e,s){this.mechname=t,this.isClientFirst=e,this.priority=s}test(){return!0}onStart(t){this.Mt=t}onChallenge(t,e){throw new Error("You should implement challenge handling!")}clientChallenge(t){if(!this.isClientFirst)throw new Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(t)}onFailure(){this.Mt=null}onSuccess(){this.Mt=null}}class lt extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ANONYMOUS",arguments.length>1&&void 0!==arguments[1]&&arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:20)}test(t){return null===t.authcid}}class dt extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"EXTERNAL",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:10)}onChallenge(t){return t.authcid===t.authzid?"":t.authzid}}class ft extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"OAUTHBEARER",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:40)}test(t){return null!==t.pass}onChallenge(t){let e="n,";return null!==t.authcid&&(e=e+"a="+t.authzid),e+=",",e+="",e+="auth=Bearer ",e+=t.pass,e+="",e+="",W.utf16to8(e)}}class pt extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"PLAIN",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:50)}test(t){return null!==t.authcid}onChallenge(t){const{authcid:e,authzid:s,domain:i,pass:n}=t;if(!i)throw new Error("SASLPlain onChallenge: domain is not defined!");let r=s!==`${e}@${i}`?s:"";return r+="\0",r+=e,r+="\0",r+=n,W.utf16to8(r)}}async function mt(t,e,s){const i=await crypto.subtle.importKey("raw",await crypto.subtle.digest(s,e),{name:"HMAC",hash:s},!1,["sign"]),n=await crypto.subtle.sign("HMAC",i,W.stringToArrayBuf(t));return W.xorArrayBuffers(e,n)}function gt(t){let e,s,i;const n=/([a-z]+)=([^,]+)(,|$)/;for(;t.match(n);){const r=t.match(n);switch(t=t.replace(r[0],""),r[1]){case"r":e=r[2];break;case"s":s=W.base64ToArrayBuf(r[2]);break;case"i":i=parseInt(r[2],10);break;default:return}}if(isNaN(i)||i<4096)Dt.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(s)return{nonce:e,salt:s,iter:i};Dt.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}async function wt(t,e,s,i,n){const r=await crypto.subtle.deriveBits({name:"PBKDF2",salt:e,iterations:s,hash:{name:i}},await crypto.subtle.importKey("raw",W.stringToArrayBuf(t),"PBKDF2",!1,["deriveBits"]),n),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:i},!1,["sign"]);return{ck:await crypto.subtle.sign("HMAC",o,W.stringToArrayBuf("Client Key")),sk:await crypto.subtle.sign("HMAC",o,W.stringToArrayBuf("Server Key"))}}async function vt(t,e,s){const i=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:s},!1,["sign"]);return crypto.subtle.sign("HMAC",i,W.stringToArrayBuf(t))}function yt(){const t=new Uint8Array(16);return W.arrayBufToBase64(crypto.getRandomValues(t).buffer)}const bt={async scramResponse(t,e,s,i){var n,r,o;const a=t._.cnonce,h=gt(e);if(!h&&(null==h?void 0:h.nonce.slice(0,a.length))!==a)return Dt.warn("Failing SCRAM authentication because server supplied incorrect nonce."),t._={},t.dt();let c,u;if((null===(n=t.pass)||void 0===n?void 0:n.name)===s&&(null===(r=t.pass)||void 0===r?void 0:r.salt)===W.arrayBufToBase64(h.salt)&&(null===(o=t.pass)||void 0===o?void 0:o.iter)===h.iter)c=W.base64ToArrayBuf(t.pass.ck),u=W.base64ToArrayBuf(t.pass.sk);else{if(!("string"==typeof t.pass||t.pass instanceof String))return t.dt();{const e=await wt(t.pass,h.salt,h.iter,s,i);c=e.ck,u=e.sk}}const l=t._["client-first-message-bare"],d=e,f=`c=biws,r=${h.nonce}`,p=`${l},${d},${f}`,m=await mt(p,c,s),g=await vt(p,u,s);return t._["server-signature"]=W.arrayBufToBase64(g),t._.keys={name:s,iter:h.iter,salt:W.arrayBufToBase64(h.salt),ck:W.arrayBufToBase64(c),sk:W.arrayBufToBase64(u)},`${f},p=${W.arrayBufToBase64(m)}`},clientChallenge(t,e){const s=e||yt(),i=`n=${t.authcid},r=${s}`;return t._.cnonce=s,t._["client-first-message-bare"]=i,`n,,${i}`}};class St extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-1",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:60)}test(t){return null!==t.authcid}async onChallenge(t,e){return await bt.scramResponse(t,e,"SHA-1",160)}clientChallenge(t,e){return bt.clientChallenge(t,e)}}class xt extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-256",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:70)}test(t){return null!==t.authcid}async onChallenge(t,e){return await bt.scramResponse(t,e,"SHA-256",256)}clientChallenge(t,e){return bt.clientChallenge(t,e)}}class Et extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-384",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:71)}test(t){return null!==t.authcid}async onChallenge(t,e){return await bt.scramResponse(t,e,"SHA-384",384)}clientChallenge(t,e){return bt.clientChallenge(t,e)}}class Mt extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-512",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:72)}test(t){return null!==t.authcid}async onChallenge(t,e){return await bt.scramResponse(t,e,"SHA-512",512)}clientChallenge(t,e){return bt.clientChallenge(t,e)}}class At extends ut{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"X-OAUTH2",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:30)}test(t){return null!==t.pass}onChallenge(t){let e="\0";return null!==t.authcid&&(e+=t.authzid),e+="\0",e+=t.pass,W.utf16to8(e)}}const Dt={VERSION:"1.6.1",Builder:Q,Connection:ct,ElementType:p,ErrorCondition:d,Handler:Z,LogLevel:f,NS:c,SASLMechanism:ut,Status:l,TimedHandler:tt,...z,XHTML:{...u,validTag:D,validCSS:T,validAttribute:_},addNamespace(t,e){Dt.NS[t]=e},D(t){void 0!==t.stack&&Dt.fatal(t.stack),t.sourceURL?Dt.fatal("error: "+this.handler+" "+t.sourceURL+":"+t.line+" - "+t.name+": "+t.message):t.fileName?Dt.fatal("error: "+this.handler+" "+t.fileName+":"+t.lineNumber+" - "+t.name+": "+t.message):Dt.fatal("error: "+t.message)},log(t,e){var s;t===this.LogLevel.FATAL&&(null===(s=console)||void 0===s||s.error(e))},debug(t){this.log(this.LogLevel.DEBUG,t)},info(t){this.log(this.LogLevel.INFO,t)},warn(t){this.log(this.LogLevel.WARN,t)},error(t){this.log(this.LogLevel.ERROR,t)},fatal(t){this.log(this.LogLevel.FATAL,t)},At:0,$:{},addConnectionPlugin(t,e){Dt.$[t]=e}};Dt.SASLAnonymous=lt,Dt.SASLPlain=pt,Dt.SASLSHA1=St,Dt.SASLSHA256=xt,Dt.SASLSHA384=Et,Dt.SASLSHA512=Mt,Dt.SASLOAuthBearer=ft,Dt.SASLExternal=dt,Dt.SASLXOAuth2=At;var _t={Strophe:Dt,$build:J,$iq:V,$msg:G,$pres:Y};Dt.Request=class{constructor(t,e,s,i){this.id=++Dt.At,this.xmlData=t,this.data=Dt.serialize(t),this.origFunc=e,this.func=e,this.rid=s,this.date=NaN,this.sends=i||0,this.abort=!1,this.dead=null,this.age=function(){return this.date?(new Date-this.date)/1e3:0},this.timeDead=function(){return this.dead?(new Date-this.dead)/1e3:0},this.xhr=this.Dt()}getResponse(){let t=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){if(t=this.xhr.responseXML.documentElement,"parsererror"===t.tagName)throw Dt.error("invalid response received"),Dt.error("responseText: "+this.xhr.responseText),Dt.error("responseXML: "+Dt.serialize(this.xhr.responseXML)),new Error("parsererror")}else if(this.xhr.responseText){var e;Dt.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),t=(new r).parseFromString(this.xhr.responseText,"application/xml").documentElement;const s=null===(e=t)||void 0===e?void 0:e.querySelector("parsererror");if(!t||s){s&&(Dt.error("invalid response received: "+s.textContent),Dt.error("responseText: "+this.xhr.responseText));const t=new Error;throw t.name=Dt.ErrorCondition.BAD_FORMAT,t}}return t}Dt(){let t=null;return globalThis.XMLHttpRequest?(t=new XMLHttpRequest,t.overrideMimeType&&t.overrideMimeType("text/xml; charset=utf-8")):globalThis.ActiveXObject&&(t=new ActiveXObject("Microsoft.XMLHTTP")),t.onreadystatechange=this.func.bind(null,this),t}},Dt.Bosh=class t{constructor(t){this._t=t,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.lastResponseHeaders=null,this.U=[]}Tt(){const t=J("body",{rid:this.rid++,xmlns:Dt.NS.HTTPBIND});return null!==this.sid&&t.attrs({sid:this.sid}),this._t.options.keepalive&&this._t.X()&&this.It(),t}L(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._t.X()&&sessionStorage.removeItem("strophe-bosh-session"),this._t.nextValidRid(this.rid)}q(t,e,s){this.wait=t||this.wait,this.hold=e||this.hold,this.errors=0;const i=this.Tt().attrs({to:this._t.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Dt.NS.BOSH});s&&i.attrs({route:s});const n=this._t.nt;this.U.push(new Dt.Request(i.tree(),this.Ct.bind(this,n.bind(this._t)),i.tree().getAttribute("rid"))),this.Pt()}H(t,e,s,i,n,r,o){this._t.jid=t,this.sid=e,this.rid=s,this._t.connect_callback=i,this._t.domain=Dt.getDomainFromJid(this._t.jid),this._t.authenticated=!0,this._t.connected=!0,this.wait=n||this.wait,this.hold=r||this.hold,this.window=o||this.window,this._t.j(Dt.Status.ATTACHED,null)}B(t,e,s,i,n){const r=JSON.parse(sessionStorage.getItem("strophe-bosh-session"));if(!(null!=r&&r.rid&&r.sid&&r.jid&&(null==t||Dt.getBareJidFromJid(r.jid)===Dt.getBareJidFromJid(t)||null===Dt.getNodeFromJid(t)&&Dt.getDomainFromJid(r.jid)===t))){const t=new Error("_restore: no restoreable session.");throw t.name="StropheSessionError",t}this._t.restored=!0,this.H(r.jid,r.sid,r.rid,e,s,i,n)}It(){this._t.authenticated?this._t.jid&&this.rid&&this.sid&&sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._t.jid,rid:this.rid,sid:this.sid})):sessionStorage.removeItem("strophe-bosh-session")}nt(t){const e=t.getAttribute("type");if(null!==e&&"terminate"===e){let e=t.getAttribute("condition");Dt.error("BOSH-Connection failed: "+e);const s=t.getElementsByTagName("conflict");return null!==e?("remote-stream-error"===e&&s.length>0&&(e="conflict"),this._t.j(Dt.Status.CONNFAIL,e)):this._t.j(Dt.Status.CONNFAIL,"unknown"),this._t.tt(e),Dt.Status.CONNFAIL}this.sid||(this.sid=t.getAttribute("sid"));const s=t.getAttribute("requests");s&&(this.window=parseInt(s,10));const i=t.getAttribute("hold");i&&(this.hold=parseInt(i,10));const n=t.getAttribute("wait");n&&(this.wait=parseInt(n,10));const r=t.getAttribute("inactivity");r&&(this.inactivity=parseInt(r,10))}Y(t){this.kt(t)}tt(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._t.X()&&sessionStorage.removeItem("strophe-bosh-session"),this._t.nextValidRid(this.rid)}it(){return 0===this.U.length}Nt(e){const s=t.Ot(e),i=this._t.protocolErrorHandlers.HTTP[s];i&&i.call(this,s)}Rt(t){this.errors++,Dt.warn("request errored, status: "+t+", number of errors: "+this.errors),this.errors>4&&this._t.V()}rt(t){Dt.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),t=t?t.bind(this._t):this._t.nt.bind(this._t);const e=this.Tt();this.U.push(new Dt.Request(e.tree(),this.Ct.bind(this,t),e.tree().getAttribute("rid"))),this.Pt()}V(){this.Z()}Z(){for(;this.U.length>0;){const t=this.U.pop();t.abort=!0,t.xhr.abort(),t.xhr.onreadystatechange=function(){}}}R(){const t=this._t.C;if(this._t.authenticated&&0===this.U.length&&0===t.length&&!this._t.disconnecting&&(Dt.debug("no requests during idle cycle, sending blank request"),t.push(null)),!this._t.paused){if(this.U.length<2&&t.length>0){const e=this.Tt();for(let s=0;s<t.length;s++)null!==t[s]&&("restart"===t[s]?e.attrs({to:this._t.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Dt.NS.BOSH}):e.cnode(t[s]).up());delete this._t.C,this._t.C=[],this.U.push(new Dt.Request(e.tree(),this.Ct.bind(this,this._t.et.bind(this._t)),e.tree().getAttribute("rid"))),this.Pt()}if(this.U.length>0){const t=this.U[0].age();null!==this.U[0].dead&&this.U[0].timeDead()>Math.floor(Dt.SECONDARY_TIMEOUT*this.wait)&&this.Pt(),t>Math.floor(Dt.TIMEOUT*this.wait)&&(Dt.warn("Request "+this.U[0].id+" timed out, over "+Math.floor(Dt.TIMEOUT*this.wait)+" seconds since last activity"),this.Pt())}}}static Ot(t,e){let s;if(4===t.xhr.readyState)try{s=t.xhr.status}catch(t){Dt.error("Caught an error while retrieving a request's status, reqStatus: "+s)}return void 0===s&&(s="number"==typeof e?e:0),s}Ct(e,s){if(Dt.debug("request id "+s.id+"."+s.sends+" state changed to "+s.xhr.readyState),s.abort)return void(s.abort=!1);if(4!==s.xhr.readyState)return;const i=t.Ot(s);if(this.lastResponseHeaders=s.xhr.getAllResponseHeaders(),this._t.disconnecting&&i>=400)return this.Rt(i),void this.Nt(s);const n=this.U[0]===s,r=this.U[1]===s,o=i>0&&i<500,a=s.sends>this._t.maxRetries;(o||a)&&(this.$t(s),Dt.debug("request id "+s.id+" should now be removed")),200===i?((r||n&&this.U.length>0&&this.U[0].age()>Math.floor(Dt.SECONDARY_TIMEOUT*this.wait))&&this.Ft(0),this._t.nextValidRid(Number(s.rid)+1),Dt.debug("request id "+s.id+"."+s.sends+" got 200"),e(s),this.errors=0):0===i||i>=400&&i<600||i>=12e3?(Dt.error("request id "+s.id+"."+s.sends+" error "+i+" happened"),this.Rt(i),this.Nt(s),i>=400&&i<500&&(this._t.j(Dt.Status.DISCONNECTING,null),this._t.tt())):Dt.error("request id "+s.id+"."+s.sends+" error "+i+" happened"),o||a?a&&!this._t.connected&&this._t.j(Dt.Status.CONNFAIL,"giving-up"):this.Pt()}Lt(e){let s=this.U[e];const i=t.Ot(s,-1);if(s.sends>this._t.maxRetries)return void this._t.V();const n=s.age(),r=!isNaN(n)&&n>Math.floor(Dt.TIMEOUT*this.wait),o=null!==s.dead&&s.timeDead()>Math.floor(Dt.SECONDARY_TIMEOUT*this.wait),a=4===s.xhr.readyState&&(i<1||i>=500);if((r||o||a)&&(o&&Dt.error(`Request ${this.U[e].id} timed out (secondary), restarting`),s.abort=!0,s.xhr.abort(),s.xhr.onreadystatechange=function(){},this.U[e]=new Dt.Request(s.xmlData,s.origFunc,s.rid,s.sends),s=this.U[e]),0===s.xhr.readyState){Dt.debug("request id "+s.id+"."+s.sends+" posting");try{const t=this._t.options.contentType||"text/xml; charset=utf-8";s.xhr.open("POST",this._t.service,!this._t.options.sync),void 0!==s.xhr.setRequestHeader&&s.xhr.setRequestHeader("Content-Type",t),this._t.options.withCredentials&&(s.xhr.withCredentials=!0)}catch(t){return Dt.error("XHR open failed: "+t.toString()),this._t.connected||this._t.j(Dt.Status.CONNFAIL,"bad-service"),void this._t.disconnect()}const t=()=>{if(s.date=new Date,this._t.options.customHeaders){const t=this._t.options.customHeaders;for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&s.xhr.setRequestHeader(e,t[e])}s.xhr.send(s.data)};if(s.sends>1){const e=1e3*Math.min(Math.floor(Dt.TIMEOUT*this.wait),Math.pow(s.sends,3));setTimeout(function(){t()},e)}else t();s.sends++,this._t.xmlOutput!==Dt.Connection.prototype.xmlOutput&&(s.xmlData.nodeName===this.strip&&s.xmlData.childNodes.length?this._t.xmlOutput(s.xmlData.childNodes[0]):this._t.xmlOutput(s.xmlData)),this._t.rawOutput!==Dt.Connection.prototype.rawOutput&&this._t.rawOutput(s.data)}else Dt.debug("_processRequest: "+(0===e?"first":"second")+" request has readyState of "+s.xhr.readyState)}$t(t){Dt.debug("removing request");for(let e=this.U.length-1;e>=0;e--)t===this.U[e]&&this.U.splice(e,1);t.xhr.onreadystatechange=function(){},this.Pt()}Ft(t){const e=this.U[t];null===e.dead&&(e.dead=new Date),this.Lt(t)}st(t){try{return t.getResponse()}catch(t){if("parsererror"!==t.message)throw t;this._t.disconnect("strophe-parsererror")}}kt(t){Dt.debug("_sendTerminate was called");const e=this.Tt().attrs({type:"terminate"});t&&e.cnode(t.tree());const s=new Dt.Request(e.tree(),this.Ct.bind(this,this._t.et.bind(this._t)),e.tree().getAttribute("rid"));this.U.push(s),this.Pt()}W(){clearTimeout(this._t.T),this.Pt(),this._t.T=setTimeout(()=>this._t.R(),100)}J(){this.Pt(),clearTimeout(this._t.T)}Pt(){this.U?Dt.debug("_throttledRequestHandler called with "+this.U.length+" requests"):Dt.debug("_throttledRequestHandler called with undefined requests"),this.U&&0!==this.U.length&&(this.U.length>0&&this.Lt(0),this.U.length>1&&Math.abs(this.U[0].rid-this.U[1].rid)<this.window&&this.Lt(1))}},Dt.Bosh.prototype.strip=null,Dt.Websocket=class{constructor(t){this._t=t,this.strip="wrapper";const e=t.service;if(0!==e.indexOf("ws:")&&0!==e.indexOf("wss:")){let s="";"ws"===t.options.protocol&&"https:"!==location.protocol?s+="ws":s+="wss",s+="://"+location.host,0!==e.indexOf("/")?s+=location.pathname+e:s+=e,t.service=s}}Ut(){return J("open",{xmlns:Dt.NS.FRAMING,to:this._t.domain,version:"1.0"})}jt(t,e){let s;if(s=t.getElementsByTagNameNS?t.getElementsByTagNameNS(Dt.NS.STREAM,"error"):t.getElementsByTagName("stream:error"),0===s.length)return!1;const i=s[0];let n="",r="";const o="urn:ietf:params:xml:ns:xmpp-streams";for(let t=0;t<i.childNodes.length;t++){const e=i.childNodes[t];if(e.getAttribute("xmlns")!==o)break;"text"===e.nodeName?r=e.textContent:n=e.nodeName}let a="WebSocket stream error: ";return a+=n||"unknown",r&&(a+=" - "+r),Dt.error(a),this._t.j(e,n),this._t.tt(),!0}L(){}q(){this.qt(),this.socket=new i(this._t.service,"xmpp"),this.socket.onopen=()=>this.Ht(),this.socket.onerror=t=>this.Xt(t),this.socket.onclose=t=>this.Bt(t),this.socket.onmessage=t=>this.Kt(t)}nt(t){if(this.jt(t,Dt.Status.CONNFAIL))return Dt.Status.CONNFAIL}Wt(t){let e=!1;const s=t.getAttribute("xmlns");"string"!=typeof s?e="Missing xmlns in <open />":s!==Dt.NS.FRAMING&&(e="Wrong xmlns in <open />: "+s);const i=t.getAttribute("version");return"string"!=typeof i?e="Missing version in <open />":"1.0"!==i&&(e="Wrong version in <open />: "+i),!e||(this._t.j(Dt.Status.CONNFAIL,e),this._t.tt(),!1)}Kt(t){if(0===t.data.indexOf("<open ")||0===t.data.indexOf("<?xml")){const e=t.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===e)return;const s=(new r).parseFromString(e,"text/xml").documentElement;this._t.xmlInput(s),this._t.rawInput(t.data),this.Wt(s)&&this.nt(s)}else if(0===t.data.indexOf("<close ")){const e=(new r).parseFromString(t.data,"text/xml").documentElement;this._t.xmlInput(e),this._t.rawInput(t.data);const s=e.getAttribute("see-other-uri");if(s){const t=this._t.service;(t.indexOf("wss:")>=0&&s.indexOf("wss:")>=0||t.indexOf("ws:")>=0)&&(this._t.j(Dt.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._t.reset(),this._t.service=s,this.q())}else this._t.j(Dt.Status.CONNFAIL,"Received closing stream"),this._t.tt()}else{this.zt();const e=this.Jt(t.data),s=(new r).parseFromString(e,"text/xml").documentElement;this._t.nt(s,null,t.data)}}zt(){this.socket.onmessage=t=>this.Gt(t)}Y(t){if(this.socket&&this.socket.readyState!==i.CLOSED){t&&this._t.send(t);const e=J("close",{xmlns:Dt.NS.FRAMING});this._t.xmlOutput(e.tree());const s=Dt.serialize(e);this._t.rawOutput(s);try{this.socket.send(s)}catch(t){Dt.warn("Couldn't send <close /> tag.")}}setTimeout(()=>this._t.tt(),0)}tt(){Dt.debug("WebSockets _doDisconnect was called"),this.qt()}Jt(t){return"<wrapper>"+t+"</wrapper>"}qt(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(t){Dt.debug(t.message)}this.socket=null}it(){return!0}Bt(t){this._t.connected&&!this._t.disconnecting?(Dt.error("Websocket closed unexpectedly"),this._t.tt()):t&&1006===t.code&&!this._t.connected&&this.socket?(Dt.error("Websocket closed unexcectedly"),this._t.j(Dt.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._t.tt()):Dt.debug("Websocket closed")}rt(t){Dt.error("Server did not offer a supported authentication mechanism"),this._t.j(Dt.Status.CONNFAIL,Dt.ErrorCondition.NO_AUTH_MECH),t&&t.call(this._t),this._t.tt()}V(){}Z(){}Xt(t){Dt.error("Websocket error "+JSON.stringify(t)),this._t.j(Dt.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this.Y()}R(){const t=this._t.C;if(t.length>0&&!this._t.paused){for(let e=0;e<t.length;e++)if(null!==t[e]){let s;s="restart"===t[e]?this.Ut().tree():t[e];const i=Dt.serialize(s);this._t.xmlOutput(s),this._t.rawOutput(i),this.socket.send(i)}this._t.C=[]}}Gt(t){let e;const s='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(t.data===s)return this._t.rawInput(s),this._t.xmlInput(t),void(this._t.disconnecting||this._t.tt());if(0===t.data.search("<open ")){if(e=(new r).parseFromString(t.data,"text/xml").documentElement,!this.Wt(e))return}else{const s=this.Jt(t.data);e=(new r).parseFromString(s,"text/xml").documentElement}return this.jt(e,Dt.Status.ERROR)?void 0:this._t.disconnecting&&"presence"===e.firstChild.nodeName&&"unavailable"===e.firstChild.getAttribute("type")?(this._t.xmlInput(e),void this._t.rawInput(Dt.serialize(e))):void this._t.et(e,t.data)}Ht(){Dt.debug("Websocket open");const t=this.Ut();this._t.xmlOutput(t.tree());const e=Dt.serialize(t);this._t.rawOutput(e),this.socket.send(e)}st(t){return t}W(){this._t.flush()}J(){clearTimeout(this._t.T),this._t.R.bind(this._t)()}};const Tt={};Tt.debug=Dt.LogLevel.DEBUG,Tt.info=Dt.LogLevel.INFO,Tt.warn=Dt.LogLevel.WARN,Tt.error=Dt.LogLevel.ERROR,Tt.fatal=Dt.LogLevel.FATAL,Dt.WorkerWebsocket=class extends Dt.Websocket{constructor(t){super(t),this._t=t,this.worker=new SharedWorker(this._t.options.worker,"Strophe XMPP Connection"),this.worker.onerror=t=>{var e;null===(e=console)||void 0===e||e.error(t),Dt.log(Dt.LogLevel.ERROR,`Shared Worker Error: ${t}`)}}get socket(){return{send:t=>this.worker.port.postMessage(["send",t])}}q(){this.Vt=t=>this.Kt(t),this.worker.port.start(),this.worker.port.onmessage=t=>this.Yt(t),this.worker.port.postMessage(["_connect",this._t.service,this._t.jid])}H(t){this.Vt=t=>this.Gt(t),this._t.connect_callback=t,this.worker.port.start(),this.worker.port.onmessage=t=>this.Yt(t),this.worker.port.postMessage(["_attach",this._t.service])}Qt(t,e){t===Dt.Status.ATTACHED?(this._t.jid=e,this._t.authenticated=!0,this._t.connected=!0,this._t.restored=!0,this._t.j(Dt.Status.ATTACHED)):t===Dt.Status.ATTACHFAIL&&(this._t.authenticated=!1,this._t.connected=!1,this._t.restored=!1,this._t.j(Dt.Status.ATTACHFAIL))}Y(t,e){e&&this._t.send(e);const s=J("close",{xmlns:Dt.NS.FRAMING});this._t.xmlOutput(s.tree());const i=Dt.serialize(s);this._t.rawOutput(i),this.worker.port.postMessage(["send",i]),this._t.tt()}Bt(t){this._t.connected&&!this._t.disconnecting?(Dt.error("Websocket closed unexpectedly"),this._t.tt()):t&&1006===t.code&&!this._t.connected?(Dt.error("Websocket closed unexcectedly"),this._t.j(Dt.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._t.tt()):Dt.debug("Websocket closed")}qt(){this.worker.port.postMessage(["_closeSocket"])}zt(){this.Vt=t=>this.Gt(t)}Yt(t){const{data:e}=t,s=e[0];if("_onMessage"===s)this.Vt(e[1]);else if(s in this)try{this[s].apply(this,t.data.slice(1))}catch(t){Dt.log(Dt.LogLevel.ERROR,t)}else if("log"===s){const t=e[1],s=e[2];Dt.log(Tt[t],s)}else Dt.log(Dt.LogLevel.ERROR,`Found unhandled service worker message: ${e}`)}},e.$build=_t.$build,e.$iq=_t.$iq,e.$msg=_t.$msg,e.$pres=_t.$pres,e.Strophe=_t.Strophe,e.Strophe.shims=h,t.$build=J,t.$iq=V,t.$msg=G,t.$pres=Y,t.Strophe=Dt,Object.defineProperty(t,"u",{value:!0})}(j.exports);var rt=j.exports,ot=t({__proto__:null,default:F(rt)},[rt]);export{O as YellowChat,s as YellowChatError,e as createSDKError,R as createYellowChat,O as default};
|
|
2
|
+
//# sourceMappingURL=index.esm.js.map
|